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": "r : Bool\nwithBorder =\n True\n\n\npaths =\n --[ \"Glueck\", \"Liebe\", \"Geld\", \"Erfolg\" ]\n [ \"Fortune\", \"L", "end": 1211, "score": 0.9837386608, "start": 1205, "tag": "NAME", "value": "Glueck" }, { "context": "ithBorder =\n True\n\n\npaths =\n --[ \"Glueck\", \"Liebe\", \"Geld\", \"Erfolg\" ]\n [ \"Fortune\", \"Love\", \"Mo", "end": 1220, "score": 0.9784834981, "start": 1215, "tag": "NAME", "value": "Liebe" }, { "context": " =\n True\n\n\npaths =\n --[ \"Glueck\", \"Liebe\", \"Geld\", \"Erfolg\" ]\n [ \"Fortune\", \"Love\", \"Money\", \"S", "end": 1228, "score": 0.7692285776, "start": 1224, "tag": "NAME", "value": "Geld" }, { "context": "\", \"Protection\", \"Energy\", \"Divination\" ]\n\n\n\n--[ \"Gegenwart\", \"Ziel\", \"Kraft\", \"Bedeutung\", \"Dankbarkeit\", \"W", "end": 1440, "score": 0.9986867309, "start": 1431, "tag": "NAME", "value": "Gegenwart" }, { "context": "n\", \"Energy\", \"Divination\" ]\n\n\n\n--[ \"Gegenwart\", \"Ziel\", \"Kraft\", \"Bedeutung\", \"Dankbarkeit\", \"Werte\", \"", "end": 1448, "score": 0.9970245957, "start": 1444, "tag": "NAME", "value": "Ziel" }, { "context": "bebe\"\n , \"aeiaei\"\n , \"aeiou\"\n ]--}\n{--[ \"Gegenwart\"\n , \"Ziel\"\n , \"Werte\"\n , \"Kr", "end": 1647, "score": 0.9984072447, "start": 1638, "tag": "NAME", "value": "Gegenwart" }, { "context": " , \"aeiou\"\n ]--}\n{--[ \"Gegenwart\"\n , \"Ziel\"\n , \"Werte\"\n , \"Kraft\"\n , \"B", "end": 1664, "score": 0.992384553, "start": 1660, "tag": "NAME", "value": "Ziel" }, { "context": " , \"Kraft\"\n , \"Bedeutung\"\n , \"Dankbarkeit\"\n , \"Gedanken\"\n , \"Zukunft\"\n ", "end": 1746, "score": 0.9997380376, "start": 1736, "tag": "NAME", "value": "ankbarkeit" }, { "context": " , \"Bedeutung\"\n , \"Dankbarkeit\"\n , \"Gedanken\"\n , \"Zukunft\"\n ]--}\n---------------", "end": 1767, "score": 0.9994195104, "start": 1759, "tag": "NAME", "value": "Gedanken" }, { "context": " , \"Dankbarkeit\"\n , \"Gedanken\"\n , \"Zukunft\"\n ]--}\n-----------------------------------", "end": 1787, "score": 0.9992567301, "start": 1780, "tag": "NAME", "value": "Zukunft" }, { "context": "eticMind\"\n , label = Element.text \"DI Lucas Payr\"\n }\n , Element", "end": 6278, "score": 0.9956952333, "start": 6276, "tag": "NAME", "value": "DI" }, { "context": "icMind\"\n , label = Element.text \"DI Lucas Payr\"\n }\n , Element.text \".\"\n ", "end": 6289, "score": 0.8938903213, "start": 6279, "tag": "NAME", "value": "Lucas Payr" } ]
src/SigilGenerator.elm
Orasund/hermeticMind
1
module SigilGenerator exposing (..) import Browser import Data.Alphabet as Alphabet import Data.Card exposing (description) import Element exposing (Element) import Element.Background as Background import Element.Font as Font import Html exposing (Html) import List.Extra as List import View.Color as Color import View.Sigil as Sigil exposing (SigilSort(..)) import Widget import Widget.Customize as Customize import Widget.Material as Material import Widget.Material.Typography as Typography -------------------------------------------------------------------------------- -- Config -------------------------------------------------------------------------------- sigilSort : SigilSort sigilSort = MagicSquareSigil --BraidSigil -- zoom : number zoom = 2 --4 radius : number radius = 60 size : number size = radius * 4 width : number width = size height : Float height = size --size * 1.25 withCircle : Bool withCircle = True interactive : Bool interactive = True debugMode : Bool debugMode = False withRunes : Bool withRunes = True withText : Bool withText = True withBorder : Bool withBorder = True paths = --[ "Glueck", "Liebe", "Geld", "Erfolg" ] [ "Fortune", "Love", "Money", "Success", "Health", "Protection", "Energy", "Divination", "Fortune", "Love", "Money", "Success", "Health", "Protection", "Energy", "Divination" ] --[ "Gegenwart", "Ziel", "Kraft", "Bedeutung", "Dankbarkeit", "Werte", "Gedanken", "Zukunft" ] {--[ "teat" , "aaaasssd" , "bede" , "uede" , "ebebebebe" , "aeiaei" , "aeiou" ]--} {--[ "Gegenwart" , "Ziel" , "Werte" , "Kraft" , "Bedeutung" , "Dankbarkeit" , "Gedanken" , "Zukunft" ]--} -------------------------------------------------------------------------------- -- Model -------------------------------------------------------------------------------- type alias Model = { string : String , isGerman : Bool } init : () -> ( Model, Cmd Msg ) init () = ( { string = "" , isGerman = False } , Cmd.none ) -------------------------------------------------------------------------------- -- Update -------------------------------------------------------------------------------- type Msg = ChangedText String | SetField (Model -> Model) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ChangedText string -> ( { model | string = string }, Cmd.none ) SetField fun -> ( fun model, Cmd.none ) -------------------------------------------------------------------------------- -- Subscriptions -------------------------------------------------------------------------------- subscriptions : Model -> Sub Msg subscriptions _ = Sub.none -------------------------------------------------------------------------------- -- View -------------------------------------------------------------------------------- switch : { description : String , onPress : Model -> Model , active : Bool } -> Element Msg switch { description, onPress, active } = [ Element.text description , Widget.switch (Material.switch Material.defaultPalette) { description = description , onPress = onPress |> SetField |> Just , active = active } ] |> Element.row [ Element.spacing 4 ] view : Model -> Html Msg view model = let viewFun = Sigil.view { width = width , height = height , radius = radius , zoom = zoom , asAlphabet = if model.isGerman then Alphabet.german else Alphabet.english , withCircle = withCircle , debugMode = debugMode , withRunes = withRunes , withText = withText , withBorder = withBorder , fillColor = "white" --Color.dark -- , strokeColor = "black" --Color.primary --Color.light -- , sort = sigilSort , lineWidth = 4 , strokeWidth = 1 } in if interactive then [ "Sigil Generator" |> Element.text |> Element.el Typography.h6 |> Widget.asItem , Widget.fullBleedItem (Material.fullBleedItem Material.defaultPalette) { text = "Write a single word into the input field." , onPress = Nothing , icon = always Element.none } , Widget.textInput (Material.textInput Material.defaultPalette) { chips = [] , text = model.string , placeholder = Nothing , label = "Word" , onChange = ChangedText } |> Widget.asItem , Widget.divider (Material.fullBleedDivider Material.defaultPalette) , [ switch { description = "is German" , onPress = \m -> { m | isGerman = not model.isGerman } , active = model.isGerman } ] |> Element.wrappedRow [ Element.width <| Element.fill ] |> Widget.asItem , Widget.divider (Material.fullBleedDivider Material.defaultPalette) , viewFun model.string |> Element.html |> Element.el [ Element.centerX ] |> Widget.asItem , Widget.divider (Material.fullBleedDivider Material.defaultPalette) , [ Element.text "This work is licensed under a " , Element.link [ Font.underline, Font.color <| Element.rgb255 100 80 146 ] { url = "https://creativecommons.org/licenses/by-nc/4.0/" , label = Element.text "Creative Commons Attribution-NonCommercial 4.0 International License" } , Element.text " by " , Element.link [ Font.underline, Font.color <| Element.rgb255 100 80 146 ] { url = "https://www.etsy.com/shop/HermeticMind" , label = Element.text "DI Lucas Payr" } , Element.text "." ] |> Element.paragraph [] |> Widget.asItem ] |> Widget.itemList (Material.cardColumn Material.defaultPalette |> Customize.elementColumn [ Element.width <| Element.px <| round <| zoom * width * 1.5 , Element.centerX , Element.centerY ] |> Customize.mapContent (Customize.element [ Element.width <| Element.px <| round <| zoom * width * 1.5 ] ) ) |> Element.layout [ Background.color <| Element.rgb255 64 64 64 ] else paths |> List.map viewFun |> Html.div [] main : Program () Model Msg main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions }
56986
module SigilGenerator exposing (..) import Browser import Data.Alphabet as Alphabet import Data.Card exposing (description) import Element exposing (Element) import Element.Background as Background import Element.Font as Font import Html exposing (Html) import List.Extra as List import View.Color as Color import View.Sigil as Sigil exposing (SigilSort(..)) import Widget import Widget.Customize as Customize import Widget.Material as Material import Widget.Material.Typography as Typography -------------------------------------------------------------------------------- -- Config -------------------------------------------------------------------------------- sigilSort : SigilSort sigilSort = MagicSquareSigil --BraidSigil -- zoom : number zoom = 2 --4 radius : number radius = 60 size : number size = radius * 4 width : number width = size height : Float height = size --size * 1.25 withCircle : Bool withCircle = True interactive : Bool interactive = True debugMode : Bool debugMode = False withRunes : Bool withRunes = True withText : Bool withText = True withBorder : Bool withBorder = True paths = --[ "<NAME>", "<NAME>", "<NAME>", "Erfolg" ] [ "Fortune", "Love", "Money", "Success", "Health", "Protection", "Energy", "Divination", "Fortune", "Love", "Money", "Success", "Health", "Protection", "Energy", "Divination" ] --[ "<NAME>", "<NAME>", "Kraft", "Bedeutung", "Dankbarkeit", "Werte", "Gedanken", "Zukunft" ] {--[ "teat" , "aaaasssd" , "bede" , "uede" , "ebebebebe" , "aeiaei" , "aeiou" ]--} {--[ "<NAME>" , "<NAME>" , "Werte" , "Kraft" , "Bedeutung" , "D<NAME>" , "<NAME>" , "<NAME>" ]--} -------------------------------------------------------------------------------- -- Model -------------------------------------------------------------------------------- type alias Model = { string : String , isGerman : Bool } init : () -> ( Model, Cmd Msg ) init () = ( { string = "" , isGerman = False } , Cmd.none ) -------------------------------------------------------------------------------- -- Update -------------------------------------------------------------------------------- type Msg = ChangedText String | SetField (Model -> Model) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ChangedText string -> ( { model | string = string }, Cmd.none ) SetField fun -> ( fun model, Cmd.none ) -------------------------------------------------------------------------------- -- Subscriptions -------------------------------------------------------------------------------- subscriptions : Model -> Sub Msg subscriptions _ = Sub.none -------------------------------------------------------------------------------- -- View -------------------------------------------------------------------------------- switch : { description : String , onPress : Model -> Model , active : Bool } -> Element Msg switch { description, onPress, active } = [ Element.text description , Widget.switch (Material.switch Material.defaultPalette) { description = description , onPress = onPress |> SetField |> Just , active = active } ] |> Element.row [ Element.spacing 4 ] view : Model -> Html Msg view model = let viewFun = Sigil.view { width = width , height = height , radius = radius , zoom = zoom , asAlphabet = if model.isGerman then Alphabet.german else Alphabet.english , withCircle = withCircle , debugMode = debugMode , withRunes = withRunes , withText = withText , withBorder = withBorder , fillColor = "white" --Color.dark -- , strokeColor = "black" --Color.primary --Color.light -- , sort = sigilSort , lineWidth = 4 , strokeWidth = 1 } in if interactive then [ "Sigil Generator" |> Element.text |> Element.el Typography.h6 |> Widget.asItem , Widget.fullBleedItem (Material.fullBleedItem Material.defaultPalette) { text = "Write a single word into the input field." , onPress = Nothing , icon = always Element.none } , Widget.textInput (Material.textInput Material.defaultPalette) { chips = [] , text = model.string , placeholder = Nothing , label = "Word" , onChange = ChangedText } |> Widget.asItem , Widget.divider (Material.fullBleedDivider Material.defaultPalette) , [ switch { description = "is German" , onPress = \m -> { m | isGerman = not model.isGerman } , active = model.isGerman } ] |> Element.wrappedRow [ Element.width <| Element.fill ] |> Widget.asItem , Widget.divider (Material.fullBleedDivider Material.defaultPalette) , viewFun model.string |> Element.html |> Element.el [ Element.centerX ] |> Widget.asItem , Widget.divider (Material.fullBleedDivider Material.defaultPalette) , [ Element.text "This work is licensed under a " , Element.link [ Font.underline, Font.color <| Element.rgb255 100 80 146 ] { url = "https://creativecommons.org/licenses/by-nc/4.0/" , label = Element.text "Creative Commons Attribution-NonCommercial 4.0 International License" } , Element.text " by " , Element.link [ Font.underline, Font.color <| Element.rgb255 100 80 146 ] { url = "https://www.etsy.com/shop/HermeticMind" , label = Element.text "<NAME> <NAME>" } , Element.text "." ] |> Element.paragraph [] |> Widget.asItem ] |> Widget.itemList (Material.cardColumn Material.defaultPalette |> Customize.elementColumn [ Element.width <| Element.px <| round <| zoom * width * 1.5 , Element.centerX , Element.centerY ] |> Customize.mapContent (Customize.element [ Element.width <| Element.px <| round <| zoom * width * 1.5 ] ) ) |> Element.layout [ Background.color <| Element.rgb255 64 64 64 ] else paths |> List.map viewFun |> Html.div [] main : Program () Model Msg main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions }
true
module SigilGenerator exposing (..) import Browser import Data.Alphabet as Alphabet import Data.Card exposing (description) import Element exposing (Element) import Element.Background as Background import Element.Font as Font import Html exposing (Html) import List.Extra as List import View.Color as Color import View.Sigil as Sigil exposing (SigilSort(..)) import Widget import Widget.Customize as Customize import Widget.Material as Material import Widget.Material.Typography as Typography -------------------------------------------------------------------------------- -- Config -------------------------------------------------------------------------------- sigilSort : SigilSort sigilSort = MagicSquareSigil --BraidSigil -- zoom : number zoom = 2 --4 radius : number radius = 60 size : number size = radius * 4 width : number width = size height : Float height = size --size * 1.25 withCircle : Bool withCircle = True interactive : Bool interactive = True debugMode : Bool debugMode = False withRunes : Bool withRunes = True withText : Bool withText = True withBorder : Bool withBorder = True paths = --[ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "Erfolg" ] [ "Fortune", "Love", "Money", "Success", "Health", "Protection", "Energy", "Divination", "Fortune", "Love", "Money", "Success", "Health", "Protection", "Energy", "Divination" ] --[ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "Kraft", "Bedeutung", "Dankbarkeit", "Werte", "Gedanken", "Zukunft" ] {--[ "teat" , "aaaasssd" , "bede" , "uede" , "ebebebebe" , "aeiaei" , "aeiou" ]--} {--[ "PI:NAME:<NAME>END_PI" , "PI:NAME:<NAME>END_PI" , "Werte" , "Kraft" , "Bedeutung" , "DPI:NAME:<NAME>END_PI" , "PI:NAME:<NAME>END_PI" , "PI:NAME:<NAME>END_PI" ]--} -------------------------------------------------------------------------------- -- Model -------------------------------------------------------------------------------- type alias Model = { string : String , isGerman : Bool } init : () -> ( Model, Cmd Msg ) init () = ( { string = "" , isGerman = False } , Cmd.none ) -------------------------------------------------------------------------------- -- Update -------------------------------------------------------------------------------- type Msg = ChangedText String | SetField (Model -> Model) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ChangedText string -> ( { model | string = string }, Cmd.none ) SetField fun -> ( fun model, Cmd.none ) -------------------------------------------------------------------------------- -- Subscriptions -------------------------------------------------------------------------------- subscriptions : Model -> Sub Msg subscriptions _ = Sub.none -------------------------------------------------------------------------------- -- View -------------------------------------------------------------------------------- switch : { description : String , onPress : Model -> Model , active : Bool } -> Element Msg switch { description, onPress, active } = [ Element.text description , Widget.switch (Material.switch Material.defaultPalette) { description = description , onPress = onPress |> SetField |> Just , active = active } ] |> Element.row [ Element.spacing 4 ] view : Model -> Html Msg view model = let viewFun = Sigil.view { width = width , height = height , radius = radius , zoom = zoom , asAlphabet = if model.isGerman then Alphabet.german else Alphabet.english , withCircle = withCircle , debugMode = debugMode , withRunes = withRunes , withText = withText , withBorder = withBorder , fillColor = "white" --Color.dark -- , strokeColor = "black" --Color.primary --Color.light -- , sort = sigilSort , lineWidth = 4 , strokeWidth = 1 } in if interactive then [ "Sigil Generator" |> Element.text |> Element.el Typography.h6 |> Widget.asItem , Widget.fullBleedItem (Material.fullBleedItem Material.defaultPalette) { text = "Write a single word into the input field." , onPress = Nothing , icon = always Element.none } , Widget.textInput (Material.textInput Material.defaultPalette) { chips = [] , text = model.string , placeholder = Nothing , label = "Word" , onChange = ChangedText } |> Widget.asItem , Widget.divider (Material.fullBleedDivider Material.defaultPalette) , [ switch { description = "is German" , onPress = \m -> { m | isGerman = not model.isGerman } , active = model.isGerman } ] |> Element.wrappedRow [ Element.width <| Element.fill ] |> Widget.asItem , Widget.divider (Material.fullBleedDivider Material.defaultPalette) , viewFun model.string |> Element.html |> Element.el [ Element.centerX ] |> Widget.asItem , Widget.divider (Material.fullBleedDivider Material.defaultPalette) , [ Element.text "This work is licensed under a " , Element.link [ Font.underline, Font.color <| Element.rgb255 100 80 146 ] { url = "https://creativecommons.org/licenses/by-nc/4.0/" , label = Element.text "Creative Commons Attribution-NonCommercial 4.0 International License" } , Element.text " by " , Element.link [ Font.underline, Font.color <| Element.rgb255 100 80 146 ] { url = "https://www.etsy.com/shop/HermeticMind" , label = Element.text "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" } , Element.text "." ] |> Element.paragraph [] |> Widget.asItem ] |> Widget.itemList (Material.cardColumn Material.defaultPalette |> Customize.elementColumn [ Element.width <| Element.px <| round <| zoom * width * 1.5 , Element.centerX , Element.centerY ] |> Customize.mapContent (Customize.element [ Element.width <| Element.px <| round <| zoom * width * 1.5 ] ) ) |> Element.layout [ Background.color <| Element.rgb255 64 64 64 ] else paths |> List.map viewFun |> Html.div [] main : Program () Model Msg main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions }
elm
[ { "context": "{-\nCopyright 2020 Morgan Stanley\n\nLicensed under the Apache License, Version 2.0 (", "end": 32, "score": 0.9997890592, "start": 18, "tag": "NAME", "value": "Morgan Stanley" } ]
src/Morphir/Sample/LCR/Flows.elm
maoo/morphir-examples
0
{- 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 Morphir.Sample.LCR.Flows exposing (..) import Morphir.SDK.Basics exposing (Decimal) import Date exposing (Date, Interval(..), Unit(..)) import Morphir.Sample.LCR.Basics exposing (..) import Morphir.Sample.LCR.Counterparty exposing (CounterpartyId) import Morphir.Sample.LCR.Product exposing (ProductId) import Morphir.Sample.LCR.MaturityBucket as MB type alias BusinessDate = Date type alias ReportingEntity = Entity type alias Flow = { amount : Decimal , assetType : AssetCategoryCodes , businessDate : BusinessDate , collateralClass : AssetCategoryCodes , counterpartyId : CounterpartyId , currency : Currency , fed5GCode : Fed5GCode , insured : InsuranceType , isTreasuryControl : Bool , isUnencumbered : Bool , maturityDate : Date , effectiveMaturityDate : Date , productId : ProductId }
57584
{- 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 Morphir.Sample.LCR.Flows exposing (..) import Morphir.SDK.Basics exposing (Decimal) import Date exposing (Date, Interval(..), Unit(..)) import Morphir.Sample.LCR.Basics exposing (..) import Morphir.Sample.LCR.Counterparty exposing (CounterpartyId) import Morphir.Sample.LCR.Product exposing (ProductId) import Morphir.Sample.LCR.MaturityBucket as MB type alias BusinessDate = Date type alias ReportingEntity = Entity type alias Flow = { amount : Decimal , assetType : AssetCategoryCodes , businessDate : BusinessDate , collateralClass : AssetCategoryCodes , counterpartyId : CounterpartyId , currency : Currency , fed5GCode : Fed5GCode , insured : InsuranceType , isTreasuryControl : Bool , isUnencumbered : Bool , maturityDate : Date , effectiveMaturityDate : Date , productId : ProductId }
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 Morphir.Sample.LCR.Flows exposing (..) import Morphir.SDK.Basics exposing (Decimal) import Date exposing (Date, Interval(..), Unit(..)) import Morphir.Sample.LCR.Basics exposing (..) import Morphir.Sample.LCR.Counterparty exposing (CounterpartyId) import Morphir.Sample.LCR.Product exposing (ProductId) import Morphir.Sample.LCR.MaturityBucket as MB type alias BusinessDate = Date type alias ReportingEntity = Entity type alias Flow = { amount : Decimal , assetType : AssetCategoryCodes , businessDate : BusinessDate , collateralClass : AssetCategoryCodes , counterpartyId : CounterpartyId , currency : Currency , fed5GCode : Fed5GCode , insured : InsuranceType , isTreasuryControl : Bool , isUnencumbered : Bool , maturityDate : Date , effectiveMaturityDate : Date , productId : ProductId }
elm
[ { "context": "del : Model\ninitialModel = \n {\n name = \"Anonymous\"\n , gameNumber = 1\n , entries = []\n ", "end": 772, "score": 0.6057933569, "start": 763, "tag": "NAME", "value": "Anonymous" }, { "context": "fo\", class \"classy\"]\n-- [ playerInfoText \"mike\" 3]\n\nviewPlayer name gameNumber = \n h2 [id \"in", "end": 5583, "score": 0.8329127431, "start": 5579, "tag": "NAME", "value": "mike" } ]
starter-project/bingo/RenderHtml.elm
bikash119/elm-pragma
0
module RenderHtml exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing(onClick, onInput) import List exposing (sortBy ) import Random import Http import Json.Decode as Decode exposing (Decoder, field, succeed) import Json.Encode as Encode --MODEL type GameState = EditMode | Playing type alias Score = { id : Int , name : String , score : Int } type alias Entry = { id : Int , phrase : String , points : Int , marked : Bool } type alias Model = { name : String , gameNumber : Int , entries : List Entry , alertMessage: Maybe String , nameInput: String , gameState: GameState } initialModel : Model initialModel = { name = "Anonymous" , gameNumber = 1 , entries = [] , alertMessage = Nothing , nameInput = "" , gameState = EditMode } --update type Msg = NewGame | Mark Int | Sort | NewRandom Int | NewEntries (Result Http.Error (List Entry)) | CloseAlert | ShareScore | NewScore (Result Http.Error Score) | SetNameInput String | SaveName | CancelName | SwitchGameState GameState allEntriesMarked : List Entry -> Bool allEntriesMarked entries = let marked e = e.marked in List.all marked entries update : Msg -> Model -> ( Model, Cmd Msg) update msg model = case msg of SwitchGameState state -> ( {model | gameState = state}, Cmd.none ) SaveName -> ( { model | name = model.nameInput , nameInput = "" , gameState = Playing}, Cmd.none) CancelName -> ( { model | nameInput = "" ,gameState = EditMode}, Cmd.none ) SetNameInput value -> ( {model | nameInput = value } , Cmd.none) ShareScore -> (model, postScore model) NewScore ( Ok score) -> let message = "Your score of" ++ (toString score.score) ++ " was successfully shared" in ( { model | alertMessage = Just message} , Cmd.none) NewScore ( Err error) -> let message = "Error posting your " ++ (toString error) in ( { model | alertMessage = Just message} , Cmd.none) NewGame -> ({ model | gameNumber = model.gameNumber + 1}, getEntries ) Mark id -> let markEntry e = if e.id == id then { e | marked = (not e.marked) } else e in ({ model | entries = List.map markEntry model.entries}, Cmd.none) Sort -> let sortByPoints e = e.points in ( { model | entries = List.sortBy sortByPoints model.entries }, Cmd.none ) NewRandom randomNumber -> ( { model | gameNumber = randomNumber } , Cmd.none) NewEntries (Ok randomEntries) -> ({model | entries = randomEntries}, Cmd.none ) NewEntries (Err error) -> let errorMessage = case error of Http.NetworkError -> "Is the server running" Http.BadStatus response -> (toString response.status) Http.BadPayload message _-> "Decoding failed" ++ message _ -> (toString error) in ( {model | alertMessage = Just errorMessage }, Cmd.none) closeAlert -> ( { model | alertMessage = Nothing}, Cmd.none ) --DECODERS / ENCODERS entryDecoder : Decoder Entry entryDecoder = Decode.map4 Entry (field "id" Decode.int) (field "phrase" Decode.string) (field "points" Decode.int) (succeed False) scoreDecoder = Decode.map3 Score (field "id" Decode.int) (field "name" Decode.string) (field "score" Decode.int) encodeScore : Model -> Encode.Value encodeScore model = Encode.object [ ("name", Encode.string model.name) , ("score" , Encode.int (totalPoints model.entries)) ] --COMMAND generateRandomNumber : Cmd Msg generateRandomNumber = Random.generate (\num -> NewRandom num) (Random.int 1 100) entriesUrl : String entriesUrl = "http://localhost:3000/random-entries" postScore : Model -> Cmd Msg postScore model = let url = "http://localhost:3000/scores" body = encodeScore model |> Http.jsonBody request = Http.post url body scoreDecoder in Http.send NewScore request getEntries : Cmd Msg getEntries = -- Http.send NewEntries (Http.getString entriesUrl) (Decode.list entryDecoder) |> Http.get entriesUrl |> Http.send NewEntries hasZeroScore : Model -> Bool hasZeroScore model = -- case totalPoints model.entries of -- 0 -> -- True -- _ -> -- False totalPoints model.entries == 0 --VIEW -- main = -- -- Html.h2 [ attributes ] [ child node] -- h2 [id "info", class "classy"] -- [ playerInfoText "mike" 3] viewPlayer name gameNumber = h2 [id "info", class "classy"] [ a [ href "#", onClick ( SwitchGameState EditMode)] [ text name ] , text (" - Game #" ++ (toString gameNumber)) ] --viewHeader, viewFooter, view are definitions as they do not take any value. You can't have a function with zero arguments in Elm viewHeader title= header [] [ h1 [] [ text title]] viewFooter = footer [] [ a [ href "http://elm-lang.org" ] [ text "Powered by me"] ] viewEntryItem : Entry -> Html.Html Msg viewEntryItem entry = li [ classList [ ("marked" , entry.marked) ] ,onClick (Mark entry.id) ] [ span [ class "phrase" ] [text entry.phrase] , span [ class "points" ] [text (toString entry.points)] ] totalPoints : List Entry -> Int totalPoints entries = let squares x = x*x in entries |> List.filter .marked |> List.map .points |> List.foldl (+) 0 viewScore : Int -> Html.Html msg viewScore totalPoints = div [ class "score" ] [ span [ class "label" ] [ text "Score"] , span [ class "value" ] [ text (toString totalPoints) ] ] viewEntries : List Entry -> Html.Html Msg viewEntries entries = entries |> List.map viewEntryItem |> ul [] view : Model -> Html.Html Msg view model = div [ class "content"] [ viewHeader "Buzzword Bingo" , viewPlayer model.name model.gameNumber , viewNameInput model , viewAlertMessage model.alertMessage , viewEntries model.entries , viewScore (totalPoints model.entries) , div [ class "button-group"] [ button [ onClick NewGame ] [text "NewGame"] , button [ onClick Sort ] [ text "Sort" ] , button [ onClick ShareScore, disabled (hasZeroScore model) ] [ text "Share Score"] ] , div [ class "debug"] [ text (toString model) ] , viewFooter ] viewNameInput : Model -> Html Msg viewNameInput model = case model.gameState of EditMode -> div [ class "name-input" ] [ input [ type_ "text" , placeholder "who's playing?" , autofocus True , onInput SetNameInput , value model.nameInput ] [] , button [ onClick SaveName, disabled (String.isEmpty model.nameInput || String.length model.nameInput < 3)] [ text "Save"] , button [ onClick CancelName ] [ text "Cancel"] ] Playing -> text "" viewAlertMessage : Maybe String -> Html Msg viewAlertMessage alertMessage = case alertMessage of Just message -> div [ class "alert" ] [ span [ class "close", onClick CloseAlert ] [ text "X"] , text message ] Nothing -> text "" -- main = -- update NewGame initialModel -- |> view main : Program Never Model Msg main = Html.program { init = ( initialModel, getEntries ) , view = view , update = update , subscriptions = (\_ -> Sub.none) }
59141
module RenderHtml exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing(onClick, onInput) import List exposing (sortBy ) import Random import Http import Json.Decode as Decode exposing (Decoder, field, succeed) import Json.Encode as Encode --MODEL type GameState = EditMode | Playing type alias Score = { id : Int , name : String , score : Int } type alias Entry = { id : Int , phrase : String , points : Int , marked : Bool } type alias Model = { name : String , gameNumber : Int , entries : List Entry , alertMessage: Maybe String , nameInput: String , gameState: GameState } initialModel : Model initialModel = { name = "<NAME>" , gameNumber = 1 , entries = [] , alertMessage = Nothing , nameInput = "" , gameState = EditMode } --update type Msg = NewGame | Mark Int | Sort | NewRandom Int | NewEntries (Result Http.Error (List Entry)) | CloseAlert | ShareScore | NewScore (Result Http.Error Score) | SetNameInput String | SaveName | CancelName | SwitchGameState GameState allEntriesMarked : List Entry -> Bool allEntriesMarked entries = let marked e = e.marked in List.all marked entries update : Msg -> Model -> ( Model, Cmd Msg) update msg model = case msg of SwitchGameState state -> ( {model | gameState = state}, Cmd.none ) SaveName -> ( { model | name = model.nameInput , nameInput = "" , gameState = Playing}, Cmd.none) CancelName -> ( { model | nameInput = "" ,gameState = EditMode}, Cmd.none ) SetNameInput value -> ( {model | nameInput = value } , Cmd.none) ShareScore -> (model, postScore model) NewScore ( Ok score) -> let message = "Your score of" ++ (toString score.score) ++ " was successfully shared" in ( { model | alertMessage = Just message} , Cmd.none) NewScore ( Err error) -> let message = "Error posting your " ++ (toString error) in ( { model | alertMessage = Just message} , Cmd.none) NewGame -> ({ model | gameNumber = model.gameNumber + 1}, getEntries ) Mark id -> let markEntry e = if e.id == id then { e | marked = (not e.marked) } else e in ({ model | entries = List.map markEntry model.entries}, Cmd.none) Sort -> let sortByPoints e = e.points in ( { model | entries = List.sortBy sortByPoints model.entries }, Cmd.none ) NewRandom randomNumber -> ( { model | gameNumber = randomNumber } , Cmd.none) NewEntries (Ok randomEntries) -> ({model | entries = randomEntries}, Cmd.none ) NewEntries (Err error) -> let errorMessage = case error of Http.NetworkError -> "Is the server running" Http.BadStatus response -> (toString response.status) Http.BadPayload message _-> "Decoding failed" ++ message _ -> (toString error) in ( {model | alertMessage = Just errorMessage }, Cmd.none) closeAlert -> ( { model | alertMessage = Nothing}, Cmd.none ) --DECODERS / ENCODERS entryDecoder : Decoder Entry entryDecoder = Decode.map4 Entry (field "id" Decode.int) (field "phrase" Decode.string) (field "points" Decode.int) (succeed False) scoreDecoder = Decode.map3 Score (field "id" Decode.int) (field "name" Decode.string) (field "score" Decode.int) encodeScore : Model -> Encode.Value encodeScore model = Encode.object [ ("name", Encode.string model.name) , ("score" , Encode.int (totalPoints model.entries)) ] --COMMAND generateRandomNumber : Cmd Msg generateRandomNumber = Random.generate (\num -> NewRandom num) (Random.int 1 100) entriesUrl : String entriesUrl = "http://localhost:3000/random-entries" postScore : Model -> Cmd Msg postScore model = let url = "http://localhost:3000/scores" body = encodeScore model |> Http.jsonBody request = Http.post url body scoreDecoder in Http.send NewScore request getEntries : Cmd Msg getEntries = -- Http.send NewEntries (Http.getString entriesUrl) (Decode.list entryDecoder) |> Http.get entriesUrl |> Http.send NewEntries hasZeroScore : Model -> Bool hasZeroScore model = -- case totalPoints model.entries of -- 0 -> -- True -- _ -> -- False totalPoints model.entries == 0 --VIEW -- main = -- -- Html.h2 [ attributes ] [ child node] -- h2 [id "info", class "classy"] -- [ playerInfoText "<NAME>" 3] viewPlayer name gameNumber = h2 [id "info", class "classy"] [ a [ href "#", onClick ( SwitchGameState EditMode)] [ text name ] , text (" - Game #" ++ (toString gameNumber)) ] --viewHeader, viewFooter, view are definitions as they do not take any value. You can't have a function with zero arguments in Elm viewHeader title= header [] [ h1 [] [ text title]] viewFooter = footer [] [ a [ href "http://elm-lang.org" ] [ text "Powered by me"] ] viewEntryItem : Entry -> Html.Html Msg viewEntryItem entry = li [ classList [ ("marked" , entry.marked) ] ,onClick (Mark entry.id) ] [ span [ class "phrase" ] [text entry.phrase] , span [ class "points" ] [text (toString entry.points)] ] totalPoints : List Entry -> Int totalPoints entries = let squares x = x*x in entries |> List.filter .marked |> List.map .points |> List.foldl (+) 0 viewScore : Int -> Html.Html msg viewScore totalPoints = div [ class "score" ] [ span [ class "label" ] [ text "Score"] , span [ class "value" ] [ text (toString totalPoints) ] ] viewEntries : List Entry -> Html.Html Msg viewEntries entries = entries |> List.map viewEntryItem |> ul [] view : Model -> Html.Html Msg view model = div [ class "content"] [ viewHeader "Buzzword Bingo" , viewPlayer model.name model.gameNumber , viewNameInput model , viewAlertMessage model.alertMessage , viewEntries model.entries , viewScore (totalPoints model.entries) , div [ class "button-group"] [ button [ onClick NewGame ] [text "NewGame"] , button [ onClick Sort ] [ text "Sort" ] , button [ onClick ShareScore, disabled (hasZeroScore model) ] [ text "Share Score"] ] , div [ class "debug"] [ text (toString model) ] , viewFooter ] viewNameInput : Model -> Html Msg viewNameInput model = case model.gameState of EditMode -> div [ class "name-input" ] [ input [ type_ "text" , placeholder "who's playing?" , autofocus True , onInput SetNameInput , value model.nameInput ] [] , button [ onClick SaveName, disabled (String.isEmpty model.nameInput || String.length model.nameInput < 3)] [ text "Save"] , button [ onClick CancelName ] [ text "Cancel"] ] Playing -> text "" viewAlertMessage : Maybe String -> Html Msg viewAlertMessage alertMessage = case alertMessage of Just message -> div [ class "alert" ] [ span [ class "close", onClick CloseAlert ] [ text "X"] , text message ] Nothing -> text "" -- main = -- update NewGame initialModel -- |> view main : Program Never Model Msg main = Html.program { init = ( initialModel, getEntries ) , view = view , update = update , subscriptions = (\_ -> Sub.none) }
true
module RenderHtml exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing(onClick, onInput) import List exposing (sortBy ) import Random import Http import Json.Decode as Decode exposing (Decoder, field, succeed) import Json.Encode as Encode --MODEL type GameState = EditMode | Playing type alias Score = { id : Int , name : String , score : Int } type alias Entry = { id : Int , phrase : String , points : Int , marked : Bool } type alias Model = { name : String , gameNumber : Int , entries : List Entry , alertMessage: Maybe String , nameInput: String , gameState: GameState } initialModel : Model initialModel = { name = "PI:NAME:<NAME>END_PI" , gameNumber = 1 , entries = [] , alertMessage = Nothing , nameInput = "" , gameState = EditMode } --update type Msg = NewGame | Mark Int | Sort | NewRandom Int | NewEntries (Result Http.Error (List Entry)) | CloseAlert | ShareScore | NewScore (Result Http.Error Score) | SetNameInput String | SaveName | CancelName | SwitchGameState GameState allEntriesMarked : List Entry -> Bool allEntriesMarked entries = let marked e = e.marked in List.all marked entries update : Msg -> Model -> ( Model, Cmd Msg) update msg model = case msg of SwitchGameState state -> ( {model | gameState = state}, Cmd.none ) SaveName -> ( { model | name = model.nameInput , nameInput = "" , gameState = Playing}, Cmd.none) CancelName -> ( { model | nameInput = "" ,gameState = EditMode}, Cmd.none ) SetNameInput value -> ( {model | nameInput = value } , Cmd.none) ShareScore -> (model, postScore model) NewScore ( Ok score) -> let message = "Your score of" ++ (toString score.score) ++ " was successfully shared" in ( { model | alertMessage = Just message} , Cmd.none) NewScore ( Err error) -> let message = "Error posting your " ++ (toString error) in ( { model | alertMessage = Just message} , Cmd.none) NewGame -> ({ model | gameNumber = model.gameNumber + 1}, getEntries ) Mark id -> let markEntry e = if e.id == id then { e | marked = (not e.marked) } else e in ({ model | entries = List.map markEntry model.entries}, Cmd.none) Sort -> let sortByPoints e = e.points in ( { model | entries = List.sortBy sortByPoints model.entries }, Cmd.none ) NewRandom randomNumber -> ( { model | gameNumber = randomNumber } , Cmd.none) NewEntries (Ok randomEntries) -> ({model | entries = randomEntries}, Cmd.none ) NewEntries (Err error) -> let errorMessage = case error of Http.NetworkError -> "Is the server running" Http.BadStatus response -> (toString response.status) Http.BadPayload message _-> "Decoding failed" ++ message _ -> (toString error) in ( {model | alertMessage = Just errorMessage }, Cmd.none) closeAlert -> ( { model | alertMessage = Nothing}, Cmd.none ) --DECODERS / ENCODERS entryDecoder : Decoder Entry entryDecoder = Decode.map4 Entry (field "id" Decode.int) (field "phrase" Decode.string) (field "points" Decode.int) (succeed False) scoreDecoder = Decode.map3 Score (field "id" Decode.int) (field "name" Decode.string) (field "score" Decode.int) encodeScore : Model -> Encode.Value encodeScore model = Encode.object [ ("name", Encode.string model.name) , ("score" , Encode.int (totalPoints model.entries)) ] --COMMAND generateRandomNumber : Cmd Msg generateRandomNumber = Random.generate (\num -> NewRandom num) (Random.int 1 100) entriesUrl : String entriesUrl = "http://localhost:3000/random-entries" postScore : Model -> Cmd Msg postScore model = let url = "http://localhost:3000/scores" body = encodeScore model |> Http.jsonBody request = Http.post url body scoreDecoder in Http.send NewScore request getEntries : Cmd Msg getEntries = -- Http.send NewEntries (Http.getString entriesUrl) (Decode.list entryDecoder) |> Http.get entriesUrl |> Http.send NewEntries hasZeroScore : Model -> Bool hasZeroScore model = -- case totalPoints model.entries of -- 0 -> -- True -- _ -> -- False totalPoints model.entries == 0 --VIEW -- main = -- -- Html.h2 [ attributes ] [ child node] -- h2 [id "info", class "classy"] -- [ playerInfoText "PI:NAME:<NAME>END_PI" 3] viewPlayer name gameNumber = h2 [id "info", class "classy"] [ a [ href "#", onClick ( SwitchGameState EditMode)] [ text name ] , text (" - Game #" ++ (toString gameNumber)) ] --viewHeader, viewFooter, view are definitions as they do not take any value. You can't have a function with zero arguments in Elm viewHeader title= header [] [ h1 [] [ text title]] viewFooter = footer [] [ a [ href "http://elm-lang.org" ] [ text "Powered by me"] ] viewEntryItem : Entry -> Html.Html Msg viewEntryItem entry = li [ classList [ ("marked" , entry.marked) ] ,onClick (Mark entry.id) ] [ span [ class "phrase" ] [text entry.phrase] , span [ class "points" ] [text (toString entry.points)] ] totalPoints : List Entry -> Int totalPoints entries = let squares x = x*x in entries |> List.filter .marked |> List.map .points |> List.foldl (+) 0 viewScore : Int -> Html.Html msg viewScore totalPoints = div [ class "score" ] [ span [ class "label" ] [ text "Score"] , span [ class "value" ] [ text (toString totalPoints) ] ] viewEntries : List Entry -> Html.Html Msg viewEntries entries = entries |> List.map viewEntryItem |> ul [] view : Model -> Html.Html Msg view model = div [ class "content"] [ viewHeader "Buzzword Bingo" , viewPlayer model.name model.gameNumber , viewNameInput model , viewAlertMessage model.alertMessage , viewEntries model.entries , viewScore (totalPoints model.entries) , div [ class "button-group"] [ button [ onClick NewGame ] [text "NewGame"] , button [ onClick Sort ] [ text "Sort" ] , button [ onClick ShareScore, disabled (hasZeroScore model) ] [ text "Share Score"] ] , div [ class "debug"] [ text (toString model) ] , viewFooter ] viewNameInput : Model -> Html Msg viewNameInput model = case model.gameState of EditMode -> div [ class "name-input" ] [ input [ type_ "text" , placeholder "who's playing?" , autofocus True , onInput SetNameInput , value model.nameInput ] [] , button [ onClick SaveName, disabled (String.isEmpty model.nameInput || String.length model.nameInput < 3)] [ text "Save"] , button [ onClick CancelName ] [ text "Cancel"] ] Playing -> text "" viewAlertMessage : Maybe String -> Html Msg viewAlertMessage alertMessage = case alertMessage of Just message -> div [ class "alert" ] [ span [ class "close", onClick CloseAlert ] [ text "X"] , text message ] Nothing -> text "" -- main = -- update NewGame initialModel -- |> view main : Program Never Model Msg main = Html.program { init = ( initialModel, getEntries ) , view = view , update = update , subscriptions = (\_ -> Sub.none) }
elm
[ { "context": "d email\" <|\n \\() ->\n [ \"test@outlook.com\", \"gmail@gmail.com\", \"yahoo.com\", \"inbox.com\", \"@", "end": 587, "score": 0.9999166727, "start": 571, "tag": "EMAIL", "value": "test@outlook.com" }, { "context": " \\() ->\n [ \"test@outlook.com\", \"gmail@gmail.com\", \"yahoo.com\", \"inbox.com\", \"@me.com\", \"mail.net\"", "end": 606, "score": 0.9999140501, "start": 591, "tag": "EMAIL", "value": "gmail@gmail.com" }, { "context": "com\", \"gmail@gmail.com\", \"yahoo.com\", \"inbox.com\", \"@me.com\", \"mail.net\", \"aol.com\", \"hotmail.com\" ]\n ", "end": 634, "score": 0.486073792, "start": 634, "tag": "USERNAME", "value": "" } ]
tests/Tests.elm
polyfish42/Quizlet
2
module Tests exposing (..) import Test exposing (..) import Expect import Fuzz exposing (list, int, tuple, string) import Navigation import String import Quizlet exposing (totalScore, onBlacklist) all : Test all = describe "Quizlet Functions Tests" [ fuzz int "Calculates Score" <| \num -> let score = num in Expect.equal (totalScore score) (num + 20) , test "Validate ones are a blacklisted email" <| \() -> [ "test@outlook.com", "gmail@gmail.com", "yahoo.com", "inbox.com", "@me.com", "mail.net", "aol.com", "hotmail.com" ] |> List.map onBlacklist |> Expect.equal [ True, True, True, True, True, False, True, True ] ]
49953
module Tests exposing (..) import Test exposing (..) import Expect import Fuzz exposing (list, int, tuple, string) import Navigation import String import Quizlet exposing (totalScore, onBlacklist) all : Test all = describe "Quizlet Functions Tests" [ fuzz int "Calculates Score" <| \num -> let score = num in Expect.equal (totalScore score) (num + 20) , test "Validate ones are a blacklisted email" <| \() -> [ "<EMAIL>", "<EMAIL>", "yahoo.com", "inbox.com", "@me.com", "mail.net", "aol.com", "hotmail.com" ] |> List.map onBlacklist |> Expect.equal [ True, True, True, True, True, False, True, True ] ]
true
module Tests exposing (..) import Test exposing (..) import Expect import Fuzz exposing (list, int, tuple, string) import Navigation import String import Quizlet exposing (totalScore, onBlacklist) all : Test all = describe "Quizlet Functions Tests" [ fuzz int "Calculates Score" <| \num -> let score = num in Expect.equal (totalScore score) (num + 20) , test "Validate ones are a blacklisted email" <| \() -> [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "yahoo.com", "inbox.com", "@me.com", "mail.net", "aol.com", "hotmail.com" ] |> List.map onBlacklist |> Expect.equal [ True, True, True, True, True, False, True, True ] ]
elm
[ { "context": "- Graphing.elm\n-- A simple library for graphing\n-- C. Moresco (moresco.cm@gmail.com)\n-- 2016\n\nmodule Graphing \n", "end": 62, "score": 0.9998751879, "start": 52, "tag": "NAME", "value": "C. Moresco" }, { "context": "m\n-- A simple library for graphing\n-- C. Moresco (moresco.cm@gmail.com)\n-- 2016\n\nmodule Graphing \n (Graph, ToPlot, pl", "end": 84, "score": 0.999930501, "start": 64, "tag": "EMAIL", "value": "moresco.cm@gmail.com" } ]
Graphing.elm
catherinemoresco/elm-fourier-tutorial
1
-- Graphing.elm -- A simple library for graphing -- C. Moresco (moresco.cm@gmail.com) -- 2016 module Graphing (Graph, ToPlot, plotType, GraphAttributes, wrapData, wrapFunc, graph, defaultGraph, defaultPlot) where import List import String import Color import Svg import Signal import Svg.Attributes exposing (..) import Html exposing (Html) import Animation exposing (..) import Time exposing (second) {-| A graph will be an SVG element, which is backed by `Svg.Svg` in `evancz/elm-svg` -} type alias Graph = Svg.Svg type alias Coords = (Float, Float) type ToPlot = Func (Float -> Float) | Data (List Coords) type DataPlot = Scatter | Impulse | Line type alias GraphAttributes = { width: Int, height: Int, ticks: Int, margin: Int, xInterval: (Float, Float), yInterval: (Float, Float), backgroundColor: String, axisColor: String, axisWidth: Int, xTicksEvery: Float, yTicksEvery: Float, xUnits: String, yUnits: String } type alias PlotAttributes = { strokeColor: String, dotColor: String, strokeWidth: String, plotType: DataPlot } {-| Main function for a simple graph. Takes an x-interval, a y-interval, and a function or set of points -} graph : List (ToPlot, PlotAttributes) -> GraphAttributes -> Html graph toGraph graphAttrs = let graphSvg toGraph= case toGraph of (Func function, plotAttrs) -> Svg.g [transform <| translate graphAttrs] [funcPlot graphAttrs plotAttrs function] (Data coords, plotAttrs) -> Svg.g [transform <| translate graphAttrs] [dataField graphAttrs plotAttrs coords] in Svg.svg [width <| toString graphAttrs.width, height <| toString graphAttrs.height] (List.append [xAxis graphAttrs, yAxis graphAttrs, xTicks graphAttrs, yTicks graphAttrs] (List.map graphSvg toGraph)) translate : GraphAttributes -> String translate graphAttrs = String.concat [ "translate(", toString graphAttrs.margin, " ", toString graphAttrs.margin, ")"] xAxis : GraphAttributes -> Svg.Svg xAxis graphStyles = let bottom = graphStyles.height - graphStyles.margin top = graphStyles.margin left = graphStyles.margin right = graphStyles.width - graphStyles.margin in Svg.line [x1 <| toString graphStyles.margin, y1 <| toString bottom, x2 <| toString right, y2 <| toString bottom, stroke graphStyles.axisColor, strokeWidth <| toString graphStyles.axisWidth ] [] yAxis : GraphAttributes -> Svg.Svg yAxis graphStyles = let bottom = graphStyles.height - graphStyles.margin top = graphStyles.margin left = graphStyles.margin right = graphStyles.width - graphStyles.margin in Svg.line [x1 <|toString left, y1 <| toString bottom, x2 <| toString left, y2 <| toString top, stroke graphStyles.axisColor, strokeWidth <| toString graphStyles.axisWidth ] [] xTicks : GraphAttributes -> Svg.Svg xTicks ga = let (xmin, xmax) = ga.xInterval in let numticks = floor <| (xmax - xmin)/ga.xTicksEvery in let step = (toFloat ga.width - 2 * (toFloat ga.margin))/ (toFloat numticks) in let bottom = ga.height - ga.margin top = ga.margin left = ga.margin right = ga.width - ga.margin in let lines = List.map (\x -> Svg.line [ x1 <| toString <| x * step + toFloat left , y1 <| toString (bottom + 5) , x2 <| toString <| x * step + toFloat left , y2 <| toString (bottom - 5) , stroke ga.axisColor , strokeWidth <| toString ga.axisWidth] []) <| List.map toFloat [1..numticks] labels = List.map (\k -> Svg.text' [ x <| toString <| k * step + toFloat left + 3 , y <| toString (bottom + 15) , fontFamily "monospace" ] [Svg.text <| String.concat [toString <| (k * ga.xTicksEvery) + xmin, ga.xUnits]]) <| List.map toFloat [1..numticks] in Svg.g [] <| List.append lines labels yTicks : GraphAttributes -> Svg.Svg yTicks ga = let (ymin, ymax) = ga.yInterval in let numticks = floor <| (ymax - ymin)/ga.yTicksEvery in let step = (toFloat ga.height - 2 * (toFloat ga.margin))/ ((ymax - ymin)/ga.yTicksEvery) in let bottom = ga.height - ga.margin top = ga.margin left = ga.margin right = ga.width - ga.margin in let lines = List.map (\x -> Svg.line [ x1 <| toString <| toFloat left - 5 , y1 <| toString <| toFloat bottom - x * step , x2 <| toString <| toFloat left + 5 , y2 <| toString <| toFloat bottom - x * step , stroke ga.axisColor , strokeWidth <| toString ga.axisWidth] []) <| List.map toFloat [1..numticks] labels = List.map (\k -> Svg.text' [ y <| toString <| toFloat bottom + 5 - k * step , x <| toString (left - 10) , textAnchor "end" , fontFamily "monospace" ] [Svg.text <| toString <| (k * ga.yTicksEvery) + ymin]) <| List.map toFloat [1..numticks] in Svg.g [] <| List.append lines labels {-| Functions for a scatter plot -} dataField : GraphAttributes -> PlotAttributes -> List Coords -> Svg.Svg dataField ga pa data = let w = ga.width - 2*ga.margin h = ga.height - 2*ga.margin newCoords = List.map (convertCoords ga.xInterval ga.yInterval (w, h)) data in let (lines, dots) = case pa.plotType of Scatter -> ([], (makeDots (w, h) newCoords pa)) Impulse -> (makeImpulses (w, h) newCoords pa, (makeDots (w, h) newCoords pa)) Line -> ([pathFromCoords pa newCoords], []) in Svg.g [] <| List.concat [lines, dots] makeDots : (Float, Float) -> List Coords -> PlotAttributes -> List Svg.Svg makeDots dimensions data pa = let makeDot (x, y) = Svg.circle [cx <| toString x, cy <| toString y, r "5", fill pa.dotColor] [] in List.map makeDot data makeImpulses : (Float, Float) -> List Coords -> PlotAttributes -> List Svg.Svg makeImpulses dimensions data pa = let makeImpulse (x, y) = pathFromCoords pa [(x, y), (x, snd dimensions)] in List.map makeImpulse data {-| Functions for plotting a continuous function -} funcPlot : GraphAttributes -> PlotAttributes -> (Float -> Float) -> Svg.Svg funcPlot ga pa func = let w = ga.width - 2*ga.margin h = ga.height - 2*ga.margin in Svg.g [] [makePath ga pa (w, h) func] makePath : GraphAttributes -> PlotAttributes -> (Float, Float) -> (Float -> Float) -> Svg.Svg makePath ga pa (w, h) func = let samples = linearSpace ga.xInterval 700 in let coordinates = List.map2 (,) samples (List.map func samples) in pathFromCoords pa <| List.map (convertCoords ga.xInterval ga.yInterval (w, h)) coordinates pathFromCoords : PlotAttributes -> List Coords -> Svg.Svg pathFromCoords pa coords = let addPt samples = case samples of [] -> "" (x, y)::xs -> String.concat [" L", toString x, " ", toString y, " ", addPt xs] in let (x, y) = case coords of [] -> (0, 0) c::cs -> c in Svg.path [d (String.concat ["M", toString x, " ", toString y, addPt (List.drop 1 coords)]), stroke pa.strokeColor, strokeWidth pa.strokeWidth, fill "none"] [] {-| Input an (xmin, xmax), (ymin, ymax), (width, height), and coords for a new set of coords Used to convert data coordinates to pixel coordinates-} convertCoords : (Float, Float) -> (Float, Float) -> (Float, Float) -> Coords -> Coords convertCoords (xMin, xMax) (yMin, yMax) (width, height) (x, y) = (lerp xMin x xMax 0 width, lerp yMax y yMin 0 height) linearSpace : (Float, Float) -> Float -> List Float linearSpace (min, max) numPoints = let size = max - min stepSize = size / numPoints in List.map (\x -> x * stepSize + min) [0..(numPoints - 1)] {-| Linear interpolation -} lerp : Float -> Float -> Float -> Float -> Float -> Float lerp x0 x x1 y0 y1 = y0 + (y1 - y0)*((x - x0)/(x1 - x0)) defaultGraph : GraphAttributes defaultGraph = {width=400, height=400, ticks=0, backgroundColor="#f5f5f5", axisColor="#555", margin=25, xInterval=(0, 10), yInterval=(0, 10), axisWidth = 2, xTicksEvery = 1, yTicksEvery = 1, xUnits="", yUnits="" } defaultPlot : PlotAttributes defaultPlot = {strokeColor="#000", strokeWidth="2px", plotType=Impulse, dotColor="#000" } wrapData : List Coords -> ToPlot wrapData data = Data data wrapFunc : (Float -> Float) -> ToPlot wrapFunc func = Func func plotType : String -> DataPlot plotType x = if x == "impulse" then Impulse else if x == "scatter" then Scatter else if x == "line" then Line else Debug.crash "that's not a plot type!" {-| Some defualt constants -} defaultMax : Float defaultMax = 100 {-| Animations -} radiusAnimation : Animation radiusAnimation = animation 0 |> Animation.from 0 |> Animation.to 10 |> duration (4*second) clock : Signal Time.Time clock = Signal.foldp (+) 0 (Time.fps 40) radius : Signal Float radius = Signal.map (\x -> animate x radiusAnimation) clock
4452
-- Graphing.elm -- A simple library for graphing -- <NAME> (<EMAIL>) -- 2016 module Graphing (Graph, ToPlot, plotType, GraphAttributes, wrapData, wrapFunc, graph, defaultGraph, defaultPlot) where import List import String import Color import Svg import Signal import Svg.Attributes exposing (..) import Html exposing (Html) import Animation exposing (..) import Time exposing (second) {-| A graph will be an SVG element, which is backed by `Svg.Svg` in `evancz/elm-svg` -} type alias Graph = Svg.Svg type alias Coords = (Float, Float) type ToPlot = Func (Float -> Float) | Data (List Coords) type DataPlot = Scatter | Impulse | Line type alias GraphAttributes = { width: Int, height: Int, ticks: Int, margin: Int, xInterval: (Float, Float), yInterval: (Float, Float), backgroundColor: String, axisColor: String, axisWidth: Int, xTicksEvery: Float, yTicksEvery: Float, xUnits: String, yUnits: String } type alias PlotAttributes = { strokeColor: String, dotColor: String, strokeWidth: String, plotType: DataPlot } {-| Main function for a simple graph. Takes an x-interval, a y-interval, and a function or set of points -} graph : List (ToPlot, PlotAttributes) -> GraphAttributes -> Html graph toGraph graphAttrs = let graphSvg toGraph= case toGraph of (Func function, plotAttrs) -> Svg.g [transform <| translate graphAttrs] [funcPlot graphAttrs plotAttrs function] (Data coords, plotAttrs) -> Svg.g [transform <| translate graphAttrs] [dataField graphAttrs plotAttrs coords] in Svg.svg [width <| toString graphAttrs.width, height <| toString graphAttrs.height] (List.append [xAxis graphAttrs, yAxis graphAttrs, xTicks graphAttrs, yTicks graphAttrs] (List.map graphSvg toGraph)) translate : GraphAttributes -> String translate graphAttrs = String.concat [ "translate(", toString graphAttrs.margin, " ", toString graphAttrs.margin, ")"] xAxis : GraphAttributes -> Svg.Svg xAxis graphStyles = let bottom = graphStyles.height - graphStyles.margin top = graphStyles.margin left = graphStyles.margin right = graphStyles.width - graphStyles.margin in Svg.line [x1 <| toString graphStyles.margin, y1 <| toString bottom, x2 <| toString right, y2 <| toString bottom, stroke graphStyles.axisColor, strokeWidth <| toString graphStyles.axisWidth ] [] yAxis : GraphAttributes -> Svg.Svg yAxis graphStyles = let bottom = graphStyles.height - graphStyles.margin top = graphStyles.margin left = graphStyles.margin right = graphStyles.width - graphStyles.margin in Svg.line [x1 <|toString left, y1 <| toString bottom, x2 <| toString left, y2 <| toString top, stroke graphStyles.axisColor, strokeWidth <| toString graphStyles.axisWidth ] [] xTicks : GraphAttributes -> Svg.Svg xTicks ga = let (xmin, xmax) = ga.xInterval in let numticks = floor <| (xmax - xmin)/ga.xTicksEvery in let step = (toFloat ga.width - 2 * (toFloat ga.margin))/ (toFloat numticks) in let bottom = ga.height - ga.margin top = ga.margin left = ga.margin right = ga.width - ga.margin in let lines = List.map (\x -> Svg.line [ x1 <| toString <| x * step + toFloat left , y1 <| toString (bottom + 5) , x2 <| toString <| x * step + toFloat left , y2 <| toString (bottom - 5) , stroke ga.axisColor , strokeWidth <| toString ga.axisWidth] []) <| List.map toFloat [1..numticks] labels = List.map (\k -> Svg.text' [ x <| toString <| k * step + toFloat left + 3 , y <| toString (bottom + 15) , fontFamily "monospace" ] [Svg.text <| String.concat [toString <| (k * ga.xTicksEvery) + xmin, ga.xUnits]]) <| List.map toFloat [1..numticks] in Svg.g [] <| List.append lines labels yTicks : GraphAttributes -> Svg.Svg yTicks ga = let (ymin, ymax) = ga.yInterval in let numticks = floor <| (ymax - ymin)/ga.yTicksEvery in let step = (toFloat ga.height - 2 * (toFloat ga.margin))/ ((ymax - ymin)/ga.yTicksEvery) in let bottom = ga.height - ga.margin top = ga.margin left = ga.margin right = ga.width - ga.margin in let lines = List.map (\x -> Svg.line [ x1 <| toString <| toFloat left - 5 , y1 <| toString <| toFloat bottom - x * step , x2 <| toString <| toFloat left + 5 , y2 <| toString <| toFloat bottom - x * step , stroke ga.axisColor , strokeWidth <| toString ga.axisWidth] []) <| List.map toFloat [1..numticks] labels = List.map (\k -> Svg.text' [ y <| toString <| toFloat bottom + 5 - k * step , x <| toString (left - 10) , textAnchor "end" , fontFamily "monospace" ] [Svg.text <| toString <| (k * ga.yTicksEvery) + ymin]) <| List.map toFloat [1..numticks] in Svg.g [] <| List.append lines labels {-| Functions for a scatter plot -} dataField : GraphAttributes -> PlotAttributes -> List Coords -> Svg.Svg dataField ga pa data = let w = ga.width - 2*ga.margin h = ga.height - 2*ga.margin newCoords = List.map (convertCoords ga.xInterval ga.yInterval (w, h)) data in let (lines, dots) = case pa.plotType of Scatter -> ([], (makeDots (w, h) newCoords pa)) Impulse -> (makeImpulses (w, h) newCoords pa, (makeDots (w, h) newCoords pa)) Line -> ([pathFromCoords pa newCoords], []) in Svg.g [] <| List.concat [lines, dots] makeDots : (Float, Float) -> List Coords -> PlotAttributes -> List Svg.Svg makeDots dimensions data pa = let makeDot (x, y) = Svg.circle [cx <| toString x, cy <| toString y, r "5", fill pa.dotColor] [] in List.map makeDot data makeImpulses : (Float, Float) -> List Coords -> PlotAttributes -> List Svg.Svg makeImpulses dimensions data pa = let makeImpulse (x, y) = pathFromCoords pa [(x, y), (x, snd dimensions)] in List.map makeImpulse data {-| Functions for plotting a continuous function -} funcPlot : GraphAttributes -> PlotAttributes -> (Float -> Float) -> Svg.Svg funcPlot ga pa func = let w = ga.width - 2*ga.margin h = ga.height - 2*ga.margin in Svg.g [] [makePath ga pa (w, h) func] makePath : GraphAttributes -> PlotAttributes -> (Float, Float) -> (Float -> Float) -> Svg.Svg makePath ga pa (w, h) func = let samples = linearSpace ga.xInterval 700 in let coordinates = List.map2 (,) samples (List.map func samples) in pathFromCoords pa <| List.map (convertCoords ga.xInterval ga.yInterval (w, h)) coordinates pathFromCoords : PlotAttributes -> List Coords -> Svg.Svg pathFromCoords pa coords = let addPt samples = case samples of [] -> "" (x, y)::xs -> String.concat [" L", toString x, " ", toString y, " ", addPt xs] in let (x, y) = case coords of [] -> (0, 0) c::cs -> c in Svg.path [d (String.concat ["M", toString x, " ", toString y, addPt (List.drop 1 coords)]), stroke pa.strokeColor, strokeWidth pa.strokeWidth, fill "none"] [] {-| Input an (xmin, xmax), (ymin, ymax), (width, height), and coords for a new set of coords Used to convert data coordinates to pixel coordinates-} convertCoords : (Float, Float) -> (Float, Float) -> (Float, Float) -> Coords -> Coords convertCoords (xMin, xMax) (yMin, yMax) (width, height) (x, y) = (lerp xMin x xMax 0 width, lerp yMax y yMin 0 height) linearSpace : (Float, Float) -> Float -> List Float linearSpace (min, max) numPoints = let size = max - min stepSize = size / numPoints in List.map (\x -> x * stepSize + min) [0..(numPoints - 1)] {-| Linear interpolation -} lerp : Float -> Float -> Float -> Float -> Float -> Float lerp x0 x x1 y0 y1 = y0 + (y1 - y0)*((x - x0)/(x1 - x0)) defaultGraph : GraphAttributes defaultGraph = {width=400, height=400, ticks=0, backgroundColor="#f5f5f5", axisColor="#555", margin=25, xInterval=(0, 10), yInterval=(0, 10), axisWidth = 2, xTicksEvery = 1, yTicksEvery = 1, xUnits="", yUnits="" } defaultPlot : PlotAttributes defaultPlot = {strokeColor="#000", strokeWidth="2px", plotType=Impulse, dotColor="#000" } wrapData : List Coords -> ToPlot wrapData data = Data data wrapFunc : (Float -> Float) -> ToPlot wrapFunc func = Func func plotType : String -> DataPlot plotType x = if x == "impulse" then Impulse else if x == "scatter" then Scatter else if x == "line" then Line else Debug.crash "that's not a plot type!" {-| Some defualt constants -} defaultMax : Float defaultMax = 100 {-| Animations -} radiusAnimation : Animation radiusAnimation = animation 0 |> Animation.from 0 |> Animation.to 10 |> duration (4*second) clock : Signal Time.Time clock = Signal.foldp (+) 0 (Time.fps 40) radius : Signal Float radius = Signal.map (\x -> animate x radiusAnimation) clock
true
-- Graphing.elm -- A simple library for graphing -- PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) -- 2016 module Graphing (Graph, ToPlot, plotType, GraphAttributes, wrapData, wrapFunc, graph, defaultGraph, defaultPlot) where import List import String import Color import Svg import Signal import Svg.Attributes exposing (..) import Html exposing (Html) import Animation exposing (..) import Time exposing (second) {-| A graph will be an SVG element, which is backed by `Svg.Svg` in `evancz/elm-svg` -} type alias Graph = Svg.Svg type alias Coords = (Float, Float) type ToPlot = Func (Float -> Float) | Data (List Coords) type DataPlot = Scatter | Impulse | Line type alias GraphAttributes = { width: Int, height: Int, ticks: Int, margin: Int, xInterval: (Float, Float), yInterval: (Float, Float), backgroundColor: String, axisColor: String, axisWidth: Int, xTicksEvery: Float, yTicksEvery: Float, xUnits: String, yUnits: String } type alias PlotAttributes = { strokeColor: String, dotColor: String, strokeWidth: String, plotType: DataPlot } {-| Main function for a simple graph. Takes an x-interval, a y-interval, and a function or set of points -} graph : List (ToPlot, PlotAttributes) -> GraphAttributes -> Html graph toGraph graphAttrs = let graphSvg toGraph= case toGraph of (Func function, plotAttrs) -> Svg.g [transform <| translate graphAttrs] [funcPlot graphAttrs plotAttrs function] (Data coords, plotAttrs) -> Svg.g [transform <| translate graphAttrs] [dataField graphAttrs plotAttrs coords] in Svg.svg [width <| toString graphAttrs.width, height <| toString graphAttrs.height] (List.append [xAxis graphAttrs, yAxis graphAttrs, xTicks graphAttrs, yTicks graphAttrs] (List.map graphSvg toGraph)) translate : GraphAttributes -> String translate graphAttrs = String.concat [ "translate(", toString graphAttrs.margin, " ", toString graphAttrs.margin, ")"] xAxis : GraphAttributes -> Svg.Svg xAxis graphStyles = let bottom = graphStyles.height - graphStyles.margin top = graphStyles.margin left = graphStyles.margin right = graphStyles.width - graphStyles.margin in Svg.line [x1 <| toString graphStyles.margin, y1 <| toString bottom, x2 <| toString right, y2 <| toString bottom, stroke graphStyles.axisColor, strokeWidth <| toString graphStyles.axisWidth ] [] yAxis : GraphAttributes -> Svg.Svg yAxis graphStyles = let bottom = graphStyles.height - graphStyles.margin top = graphStyles.margin left = graphStyles.margin right = graphStyles.width - graphStyles.margin in Svg.line [x1 <|toString left, y1 <| toString bottom, x2 <| toString left, y2 <| toString top, stroke graphStyles.axisColor, strokeWidth <| toString graphStyles.axisWidth ] [] xTicks : GraphAttributes -> Svg.Svg xTicks ga = let (xmin, xmax) = ga.xInterval in let numticks = floor <| (xmax - xmin)/ga.xTicksEvery in let step = (toFloat ga.width - 2 * (toFloat ga.margin))/ (toFloat numticks) in let bottom = ga.height - ga.margin top = ga.margin left = ga.margin right = ga.width - ga.margin in let lines = List.map (\x -> Svg.line [ x1 <| toString <| x * step + toFloat left , y1 <| toString (bottom + 5) , x2 <| toString <| x * step + toFloat left , y2 <| toString (bottom - 5) , stroke ga.axisColor , strokeWidth <| toString ga.axisWidth] []) <| List.map toFloat [1..numticks] labels = List.map (\k -> Svg.text' [ x <| toString <| k * step + toFloat left + 3 , y <| toString (bottom + 15) , fontFamily "monospace" ] [Svg.text <| String.concat [toString <| (k * ga.xTicksEvery) + xmin, ga.xUnits]]) <| List.map toFloat [1..numticks] in Svg.g [] <| List.append lines labels yTicks : GraphAttributes -> Svg.Svg yTicks ga = let (ymin, ymax) = ga.yInterval in let numticks = floor <| (ymax - ymin)/ga.yTicksEvery in let step = (toFloat ga.height - 2 * (toFloat ga.margin))/ ((ymax - ymin)/ga.yTicksEvery) in let bottom = ga.height - ga.margin top = ga.margin left = ga.margin right = ga.width - ga.margin in let lines = List.map (\x -> Svg.line [ x1 <| toString <| toFloat left - 5 , y1 <| toString <| toFloat bottom - x * step , x2 <| toString <| toFloat left + 5 , y2 <| toString <| toFloat bottom - x * step , stroke ga.axisColor , strokeWidth <| toString ga.axisWidth] []) <| List.map toFloat [1..numticks] labels = List.map (\k -> Svg.text' [ y <| toString <| toFloat bottom + 5 - k * step , x <| toString (left - 10) , textAnchor "end" , fontFamily "monospace" ] [Svg.text <| toString <| (k * ga.yTicksEvery) + ymin]) <| List.map toFloat [1..numticks] in Svg.g [] <| List.append lines labels {-| Functions for a scatter plot -} dataField : GraphAttributes -> PlotAttributes -> List Coords -> Svg.Svg dataField ga pa data = let w = ga.width - 2*ga.margin h = ga.height - 2*ga.margin newCoords = List.map (convertCoords ga.xInterval ga.yInterval (w, h)) data in let (lines, dots) = case pa.plotType of Scatter -> ([], (makeDots (w, h) newCoords pa)) Impulse -> (makeImpulses (w, h) newCoords pa, (makeDots (w, h) newCoords pa)) Line -> ([pathFromCoords pa newCoords], []) in Svg.g [] <| List.concat [lines, dots] makeDots : (Float, Float) -> List Coords -> PlotAttributes -> List Svg.Svg makeDots dimensions data pa = let makeDot (x, y) = Svg.circle [cx <| toString x, cy <| toString y, r "5", fill pa.dotColor] [] in List.map makeDot data makeImpulses : (Float, Float) -> List Coords -> PlotAttributes -> List Svg.Svg makeImpulses dimensions data pa = let makeImpulse (x, y) = pathFromCoords pa [(x, y), (x, snd dimensions)] in List.map makeImpulse data {-| Functions for plotting a continuous function -} funcPlot : GraphAttributes -> PlotAttributes -> (Float -> Float) -> Svg.Svg funcPlot ga pa func = let w = ga.width - 2*ga.margin h = ga.height - 2*ga.margin in Svg.g [] [makePath ga pa (w, h) func] makePath : GraphAttributes -> PlotAttributes -> (Float, Float) -> (Float -> Float) -> Svg.Svg makePath ga pa (w, h) func = let samples = linearSpace ga.xInterval 700 in let coordinates = List.map2 (,) samples (List.map func samples) in pathFromCoords pa <| List.map (convertCoords ga.xInterval ga.yInterval (w, h)) coordinates pathFromCoords : PlotAttributes -> List Coords -> Svg.Svg pathFromCoords pa coords = let addPt samples = case samples of [] -> "" (x, y)::xs -> String.concat [" L", toString x, " ", toString y, " ", addPt xs] in let (x, y) = case coords of [] -> (0, 0) c::cs -> c in Svg.path [d (String.concat ["M", toString x, " ", toString y, addPt (List.drop 1 coords)]), stroke pa.strokeColor, strokeWidth pa.strokeWidth, fill "none"] [] {-| Input an (xmin, xmax), (ymin, ymax), (width, height), and coords for a new set of coords Used to convert data coordinates to pixel coordinates-} convertCoords : (Float, Float) -> (Float, Float) -> (Float, Float) -> Coords -> Coords convertCoords (xMin, xMax) (yMin, yMax) (width, height) (x, y) = (lerp xMin x xMax 0 width, lerp yMax y yMin 0 height) linearSpace : (Float, Float) -> Float -> List Float linearSpace (min, max) numPoints = let size = max - min stepSize = size / numPoints in List.map (\x -> x * stepSize + min) [0..(numPoints - 1)] {-| Linear interpolation -} lerp : Float -> Float -> Float -> Float -> Float -> Float lerp x0 x x1 y0 y1 = y0 + (y1 - y0)*((x - x0)/(x1 - x0)) defaultGraph : GraphAttributes defaultGraph = {width=400, height=400, ticks=0, backgroundColor="#f5f5f5", axisColor="#555", margin=25, xInterval=(0, 10), yInterval=(0, 10), axisWidth = 2, xTicksEvery = 1, yTicksEvery = 1, xUnits="", yUnits="" } defaultPlot : PlotAttributes defaultPlot = {strokeColor="#000", strokeWidth="2px", plotType=Impulse, dotColor="#000" } wrapData : List Coords -> ToPlot wrapData data = Data data wrapFunc : (Float -> Float) -> ToPlot wrapFunc func = Func func plotType : String -> DataPlot plotType x = if x == "impulse" then Impulse else if x == "scatter" then Scatter else if x == "line" then Line else Debug.crash "that's not a plot type!" {-| Some defualt constants -} defaultMax : Float defaultMax = 100 {-| Animations -} radiusAnimation : Animation radiusAnimation = animation 0 |> Animation.from 0 |> Animation.to 10 |> duration (4*second) clock : Signal Time.Time clock = Signal.foldp (+) 0 (Time.fps 40) radius : Signal Float radius = Signal.map (\x -> animate x radiusAnimation) clock
elm
[ { "context": "\": \"email\",\n \"value\": \"something@example.com\",\n \"title\": \"The Field", "end": 4355, "score": 0.9999194145, "start": 4334, "tag": "EMAIL", "value": "something@example.com" }, { "context": " \"email\"\n (Just \"something@example.com\")\n (Just \"The Fiel", "end": 4782, "score": 0.9999204874, "start": 4761, "tag": "EMAIL", "value": "something@example.com" } ]
tests/Siren/DecodeTests.elm
tomphp/elm-siren
1
module Siren.DecodeTests exposing (..) import Dict import Expect import Json.Decode exposing (decodeString) import Result import Set import Siren.Decode exposing (..) import Siren.Entity exposing (..) import Siren.Value exposing (Value(..)) import Test exposing (..) all : Test all = describe "Siren.Decode" [ valueTests , linkTests , actionFieldTests , actionTests , entityLinkTests , entityTests , decodeJsonTests ] valueTests : Test valueTests = describe "value" [ test "It can decode a string" <| \() -> Expect.equal (Ok <| StringValue "string-value") (decodeString value "\"string-value\"") , test "It can decode an integer" <| \() -> Expect.equal (Ok <| IntValue 101) (decodeString value "101") , test "It can decode a float" <| \() -> Expect.equal (Ok <| FloatValue 1.01) (decodeString value "1.01") , test "It can decode a boolean" <| \() -> Expect.equal (Ok <| BoolValue True) (decodeString value "true") , test "It can decode a null" <| \() -> Expect.equal (Ok NullValue) (decodeString value "null") ] linkTests : Test linkTests = describe "link" [ test "It decodes a link with minimum details" <| \() -> let json = """ { "rel": ["rel1", "rel2"], "href": "http://example.com/api/entities/123" } """ in Expect.equal (Ok <| Link (Set.fromList [ "rel1", "rel2" ]) Set.empty "http://example.com/api/entities/123" Nothing Nothing ) (decodeString link json) , test "It decodes a link with all details" <| \() -> let json = """ { "rel": ["rel1", "rel2"], "class": ["class1", "class2"], "href": "http://example.com/api/entities/123", "title": "A Link", "type": "example/type" } """ in Expect.equal (Ok <| Link (Set.fromList [ "rel1", "rel2" ]) (Set.fromList [ "class1", "class2" ]) "http://example.com/api/entities/123" (Just "A Link") (Just "example/type") ) (decodeString link json) ] actionFieldTests : Test actionFieldTests = describe "actionField" [ test "It decodes a field with minimum details" <| \() -> let json = "{\"name\": \"the-field\"}" in Expect.equal (Ok <| Field "the-field" Set.empty "text" Nothing Nothing ) (decodeString actionField json) , test "It decodes a field with all details" <| \() -> let json = """ { "name": "the-field", "class": ["the-class"], "type": "email", "value": "something@example.com", "title": "The Field" } """ in Expect.equal (Ok <| Field "the-field" (Set.singleton "the-class") "email" (Just "something@example.com") (Just "The Field") ) (decodeString actionField json) ] actionTests : Test actionTests = describe "action" [ test "It decodes an action with minimum details" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com/api/entities/456" } """ in Expect.equal (Ok <| Action "action-name" "http://example.com/api/entities/456" Set.empty "GET" Nothing [] ) (decodeString action json) , test "It decodes an action with minimum details" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com/api/entities/456" } """ in Expect.equal (Ok <| Action "action-name" "http://example.com/api/entities/456" Set.empty "GET" Nothing [] ) (decodeString action json) , test "It decodes an action with full details" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com", "class": ["action-class"], "method": "POST", "title": "The Action" } """ in Expect.equal (Ok <| Action "action-name" "http://example.com" (Set.singleton "action-class") "POST" (Just "The Action") [] ) (decodeString action json) , test "It decodes an action with fields" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com/api/entities/456", "fields": [ {"name": "field-name"} ] } """ in Expect.equal (Ok <| [ Field "field-name" Set.empty "text" Nothing Nothing ] ) (decodeString action json |> Result.map .fields) ] entityLinkTests : Test entityLinkTests = describe "entityLink" [ test "It decodes an entityLink with minimum details" <| \() -> Expect.equal (Ok <| EmbeddedLink { rels = Set.empty , classes = Set.empty , href = "http://example.com/api/entities/55" , mediaType = Nothing , title = Nothing } ) (decodeString entityLink "{\"href\": \"http://example.com/api/entities/55\"}") , test "It decodes an entityLink all details" <| \() -> let json = """ { "rel": ["the-rel"], "class": ["the-class"], "href": "http://example.com/api/entities/77", "type": "the-type", "title": "The Title" } """ in Expect.equal (Ok <| EmbeddedLink { rels = Set.singleton "the-rel" , classes = Set.singleton "the-class" , href = "http://example.com/api/entities/77" , mediaType = Just "the-type" , title = Just "The Title" } ) (decodeString entityLink json) ] entityTests : Test entityTests = describe "entity" [ test "It decodes an entity with minimum details" <| \() -> Expect.equal (Ok <| Entity Set.empty Set.empty Dict.empty [] [] [] ) (decodeString entity "{}") , test "It decodes an entity all details" <| \() -> let json = """ { "rel": ["the-rel"], "class": ["the-class"], "properties": {"the-property": "the-value"}, "links": [{ "rel": ["link-rel"], "href": "http://example.com/api/entities" }], "actions": [{ "name": "action-name", "href": "http://example.com/api/entities/123" }] } """ in Expect.equal (Ok <| Entity (Set.singleton "the-rel") (Set.singleton "the-class") (Dict.singleton "the-property" (StringValue "the-value")) [ Link (Set.singleton "link-rel") Set.empty "http://example.com/api/entities" Nothing Nothing ] [] [ Action "action-name" "http://example.com/api/entities/123" Set.empty "GET" Nothing [] ] ) (decodeString entity json) , test "It decodes an entity with an embedded entity" <| \() -> let json = """ { "entities": [ {"class": ["embedded"]} ] } """ in Expect.equal (Ok <| { rels = Set.empty , classes = Set.empty , properties = Dict.empty , links = [] , entities = [ EmbeddedRepresentation { rels = Set.empty , classes = Set.singleton "embedded" , properties = Dict.empty , links = [] , entities = [] , actions = [] } ] , actions = [] } ) (decodeString entity json) , test "It decodes an entity with an embedded entity link" <| \() -> let json = """ { "entities": [ {"href": "http://example.com/embedded"} ] } """ in Expect.equal (Ok <| { rels = Set.empty , classes = Set.empty , properties = Dict.empty , links = [] , entities = [ EmbeddedLink { rels = Set.empty , classes = Set.empty , href = "http://example.com/embedded" , mediaType = Nothing , title = Nothing } ] , actions = [] } ) (decodeString entity json) ] decodeJsonTests : Test decodeJsonTests = describe "decodeJson" [ test "It decodes an entity" <| \() -> let json = """ { "rel": ["the-rel"], "class": ["the-class"], "properties": {"the-property": "the-value"}, "links": [{ "rel": ["link-rel"], "href": "http://example.com/api/entities" }], "actions": [{ "name": "action-name", "href": "http://example.com/api/entities/123" }] } """ in Expect.equal (decodeString entity json) (decodeJson json) ]
15632
module Siren.DecodeTests exposing (..) import Dict import Expect import Json.Decode exposing (decodeString) import Result import Set import Siren.Decode exposing (..) import Siren.Entity exposing (..) import Siren.Value exposing (Value(..)) import Test exposing (..) all : Test all = describe "Siren.Decode" [ valueTests , linkTests , actionFieldTests , actionTests , entityLinkTests , entityTests , decodeJsonTests ] valueTests : Test valueTests = describe "value" [ test "It can decode a string" <| \() -> Expect.equal (Ok <| StringValue "string-value") (decodeString value "\"string-value\"") , test "It can decode an integer" <| \() -> Expect.equal (Ok <| IntValue 101) (decodeString value "101") , test "It can decode a float" <| \() -> Expect.equal (Ok <| FloatValue 1.01) (decodeString value "1.01") , test "It can decode a boolean" <| \() -> Expect.equal (Ok <| BoolValue True) (decodeString value "true") , test "It can decode a null" <| \() -> Expect.equal (Ok NullValue) (decodeString value "null") ] linkTests : Test linkTests = describe "link" [ test "It decodes a link with minimum details" <| \() -> let json = """ { "rel": ["rel1", "rel2"], "href": "http://example.com/api/entities/123" } """ in Expect.equal (Ok <| Link (Set.fromList [ "rel1", "rel2" ]) Set.empty "http://example.com/api/entities/123" Nothing Nothing ) (decodeString link json) , test "It decodes a link with all details" <| \() -> let json = """ { "rel": ["rel1", "rel2"], "class": ["class1", "class2"], "href": "http://example.com/api/entities/123", "title": "A Link", "type": "example/type" } """ in Expect.equal (Ok <| Link (Set.fromList [ "rel1", "rel2" ]) (Set.fromList [ "class1", "class2" ]) "http://example.com/api/entities/123" (Just "A Link") (Just "example/type") ) (decodeString link json) ] actionFieldTests : Test actionFieldTests = describe "actionField" [ test "It decodes a field with minimum details" <| \() -> let json = "{\"name\": \"the-field\"}" in Expect.equal (Ok <| Field "the-field" Set.empty "text" Nothing Nothing ) (decodeString actionField json) , test "It decodes a field with all details" <| \() -> let json = """ { "name": "the-field", "class": ["the-class"], "type": "email", "value": "<EMAIL>", "title": "The Field" } """ in Expect.equal (Ok <| Field "the-field" (Set.singleton "the-class") "email" (Just "<EMAIL>") (Just "The Field") ) (decodeString actionField json) ] actionTests : Test actionTests = describe "action" [ test "It decodes an action with minimum details" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com/api/entities/456" } """ in Expect.equal (Ok <| Action "action-name" "http://example.com/api/entities/456" Set.empty "GET" Nothing [] ) (decodeString action json) , test "It decodes an action with minimum details" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com/api/entities/456" } """ in Expect.equal (Ok <| Action "action-name" "http://example.com/api/entities/456" Set.empty "GET" Nothing [] ) (decodeString action json) , test "It decodes an action with full details" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com", "class": ["action-class"], "method": "POST", "title": "The Action" } """ in Expect.equal (Ok <| Action "action-name" "http://example.com" (Set.singleton "action-class") "POST" (Just "The Action") [] ) (decodeString action json) , test "It decodes an action with fields" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com/api/entities/456", "fields": [ {"name": "field-name"} ] } """ in Expect.equal (Ok <| [ Field "field-name" Set.empty "text" Nothing Nothing ] ) (decodeString action json |> Result.map .fields) ] entityLinkTests : Test entityLinkTests = describe "entityLink" [ test "It decodes an entityLink with minimum details" <| \() -> Expect.equal (Ok <| EmbeddedLink { rels = Set.empty , classes = Set.empty , href = "http://example.com/api/entities/55" , mediaType = Nothing , title = Nothing } ) (decodeString entityLink "{\"href\": \"http://example.com/api/entities/55\"}") , test "It decodes an entityLink all details" <| \() -> let json = """ { "rel": ["the-rel"], "class": ["the-class"], "href": "http://example.com/api/entities/77", "type": "the-type", "title": "The Title" } """ in Expect.equal (Ok <| EmbeddedLink { rels = Set.singleton "the-rel" , classes = Set.singleton "the-class" , href = "http://example.com/api/entities/77" , mediaType = Just "the-type" , title = Just "The Title" } ) (decodeString entityLink json) ] entityTests : Test entityTests = describe "entity" [ test "It decodes an entity with minimum details" <| \() -> Expect.equal (Ok <| Entity Set.empty Set.empty Dict.empty [] [] [] ) (decodeString entity "{}") , test "It decodes an entity all details" <| \() -> let json = """ { "rel": ["the-rel"], "class": ["the-class"], "properties": {"the-property": "the-value"}, "links": [{ "rel": ["link-rel"], "href": "http://example.com/api/entities" }], "actions": [{ "name": "action-name", "href": "http://example.com/api/entities/123" }] } """ in Expect.equal (Ok <| Entity (Set.singleton "the-rel") (Set.singleton "the-class") (Dict.singleton "the-property" (StringValue "the-value")) [ Link (Set.singleton "link-rel") Set.empty "http://example.com/api/entities" Nothing Nothing ] [] [ Action "action-name" "http://example.com/api/entities/123" Set.empty "GET" Nothing [] ] ) (decodeString entity json) , test "It decodes an entity with an embedded entity" <| \() -> let json = """ { "entities": [ {"class": ["embedded"]} ] } """ in Expect.equal (Ok <| { rels = Set.empty , classes = Set.empty , properties = Dict.empty , links = [] , entities = [ EmbeddedRepresentation { rels = Set.empty , classes = Set.singleton "embedded" , properties = Dict.empty , links = [] , entities = [] , actions = [] } ] , actions = [] } ) (decodeString entity json) , test "It decodes an entity with an embedded entity link" <| \() -> let json = """ { "entities": [ {"href": "http://example.com/embedded"} ] } """ in Expect.equal (Ok <| { rels = Set.empty , classes = Set.empty , properties = Dict.empty , links = [] , entities = [ EmbeddedLink { rels = Set.empty , classes = Set.empty , href = "http://example.com/embedded" , mediaType = Nothing , title = Nothing } ] , actions = [] } ) (decodeString entity json) ] decodeJsonTests : Test decodeJsonTests = describe "decodeJson" [ test "It decodes an entity" <| \() -> let json = """ { "rel": ["the-rel"], "class": ["the-class"], "properties": {"the-property": "the-value"}, "links": [{ "rel": ["link-rel"], "href": "http://example.com/api/entities" }], "actions": [{ "name": "action-name", "href": "http://example.com/api/entities/123" }] } """ in Expect.equal (decodeString entity json) (decodeJson json) ]
true
module Siren.DecodeTests exposing (..) import Dict import Expect import Json.Decode exposing (decodeString) import Result import Set import Siren.Decode exposing (..) import Siren.Entity exposing (..) import Siren.Value exposing (Value(..)) import Test exposing (..) all : Test all = describe "Siren.Decode" [ valueTests , linkTests , actionFieldTests , actionTests , entityLinkTests , entityTests , decodeJsonTests ] valueTests : Test valueTests = describe "value" [ test "It can decode a string" <| \() -> Expect.equal (Ok <| StringValue "string-value") (decodeString value "\"string-value\"") , test "It can decode an integer" <| \() -> Expect.equal (Ok <| IntValue 101) (decodeString value "101") , test "It can decode a float" <| \() -> Expect.equal (Ok <| FloatValue 1.01) (decodeString value "1.01") , test "It can decode a boolean" <| \() -> Expect.equal (Ok <| BoolValue True) (decodeString value "true") , test "It can decode a null" <| \() -> Expect.equal (Ok NullValue) (decodeString value "null") ] linkTests : Test linkTests = describe "link" [ test "It decodes a link with minimum details" <| \() -> let json = """ { "rel": ["rel1", "rel2"], "href": "http://example.com/api/entities/123" } """ in Expect.equal (Ok <| Link (Set.fromList [ "rel1", "rel2" ]) Set.empty "http://example.com/api/entities/123" Nothing Nothing ) (decodeString link json) , test "It decodes a link with all details" <| \() -> let json = """ { "rel": ["rel1", "rel2"], "class": ["class1", "class2"], "href": "http://example.com/api/entities/123", "title": "A Link", "type": "example/type" } """ in Expect.equal (Ok <| Link (Set.fromList [ "rel1", "rel2" ]) (Set.fromList [ "class1", "class2" ]) "http://example.com/api/entities/123" (Just "A Link") (Just "example/type") ) (decodeString link json) ] actionFieldTests : Test actionFieldTests = describe "actionField" [ test "It decodes a field with minimum details" <| \() -> let json = "{\"name\": \"the-field\"}" in Expect.equal (Ok <| Field "the-field" Set.empty "text" Nothing Nothing ) (decodeString actionField json) , test "It decodes a field with all details" <| \() -> let json = """ { "name": "the-field", "class": ["the-class"], "type": "email", "value": "PI:EMAIL:<EMAIL>END_PI", "title": "The Field" } """ in Expect.equal (Ok <| Field "the-field" (Set.singleton "the-class") "email" (Just "PI:EMAIL:<EMAIL>END_PI") (Just "The Field") ) (decodeString actionField json) ] actionTests : Test actionTests = describe "action" [ test "It decodes an action with minimum details" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com/api/entities/456" } """ in Expect.equal (Ok <| Action "action-name" "http://example.com/api/entities/456" Set.empty "GET" Nothing [] ) (decodeString action json) , test "It decodes an action with minimum details" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com/api/entities/456" } """ in Expect.equal (Ok <| Action "action-name" "http://example.com/api/entities/456" Set.empty "GET" Nothing [] ) (decodeString action json) , test "It decodes an action with full details" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com", "class": ["action-class"], "method": "POST", "title": "The Action" } """ in Expect.equal (Ok <| Action "action-name" "http://example.com" (Set.singleton "action-class") "POST" (Just "The Action") [] ) (decodeString action json) , test "It decodes an action with fields" <| \() -> let json = """ { "name": "action-name", "href": "http://example.com/api/entities/456", "fields": [ {"name": "field-name"} ] } """ in Expect.equal (Ok <| [ Field "field-name" Set.empty "text" Nothing Nothing ] ) (decodeString action json |> Result.map .fields) ] entityLinkTests : Test entityLinkTests = describe "entityLink" [ test "It decodes an entityLink with minimum details" <| \() -> Expect.equal (Ok <| EmbeddedLink { rels = Set.empty , classes = Set.empty , href = "http://example.com/api/entities/55" , mediaType = Nothing , title = Nothing } ) (decodeString entityLink "{\"href\": \"http://example.com/api/entities/55\"}") , test "It decodes an entityLink all details" <| \() -> let json = """ { "rel": ["the-rel"], "class": ["the-class"], "href": "http://example.com/api/entities/77", "type": "the-type", "title": "The Title" } """ in Expect.equal (Ok <| EmbeddedLink { rels = Set.singleton "the-rel" , classes = Set.singleton "the-class" , href = "http://example.com/api/entities/77" , mediaType = Just "the-type" , title = Just "The Title" } ) (decodeString entityLink json) ] entityTests : Test entityTests = describe "entity" [ test "It decodes an entity with minimum details" <| \() -> Expect.equal (Ok <| Entity Set.empty Set.empty Dict.empty [] [] [] ) (decodeString entity "{}") , test "It decodes an entity all details" <| \() -> let json = """ { "rel": ["the-rel"], "class": ["the-class"], "properties": {"the-property": "the-value"}, "links": [{ "rel": ["link-rel"], "href": "http://example.com/api/entities" }], "actions": [{ "name": "action-name", "href": "http://example.com/api/entities/123" }] } """ in Expect.equal (Ok <| Entity (Set.singleton "the-rel") (Set.singleton "the-class") (Dict.singleton "the-property" (StringValue "the-value")) [ Link (Set.singleton "link-rel") Set.empty "http://example.com/api/entities" Nothing Nothing ] [] [ Action "action-name" "http://example.com/api/entities/123" Set.empty "GET" Nothing [] ] ) (decodeString entity json) , test "It decodes an entity with an embedded entity" <| \() -> let json = """ { "entities": [ {"class": ["embedded"]} ] } """ in Expect.equal (Ok <| { rels = Set.empty , classes = Set.empty , properties = Dict.empty , links = [] , entities = [ EmbeddedRepresentation { rels = Set.empty , classes = Set.singleton "embedded" , properties = Dict.empty , links = [] , entities = [] , actions = [] } ] , actions = [] } ) (decodeString entity json) , test "It decodes an entity with an embedded entity link" <| \() -> let json = """ { "entities": [ {"href": "http://example.com/embedded"} ] } """ in Expect.equal (Ok <| { rels = Set.empty , classes = Set.empty , properties = Dict.empty , links = [] , entities = [ EmbeddedLink { rels = Set.empty , classes = Set.empty , href = "http://example.com/embedded" , mediaType = Nothing , title = Nothing } ] , actions = [] } ) (decodeString entity json) ] decodeJsonTests : Test decodeJsonTests = describe "decodeJson" [ test "It decodes an entity" <| \() -> let json = """ { "rel": ["the-rel"], "class": ["the-class"], "properties": {"the-property": "the-value"}, "links": [{ "rel": ["link-rel"], "href": "http://example.com/api/entities" }], "actions": [{ "name": "action-name", "href": "http://example.com/api/entities/123" }] } """ in Expect.equal (decodeString entity json) (decodeJson json) ]
elm
[ { "context": "as User =\n { username : String\n , password : String\n , loggedIn : Bool\n , churches : List Churc", "end": 345, "score": 0.8838391304, "start": 339, "tag": "PASSWORD", "value": "String" }, { "context": " , br [] []\n , label [ for \"middlename\" ] [ text \"Middle Name:\" ]\n ", "end": 2713, "score": 0.6197375059, "start": 2709, "tag": "NAME", "value": "midd" }, { "context": "bmit Login ]\n [ div [] [ text \"Username\", input [ id \"username\", type_ \"text\", inputTextS", "end": 3572, "score": 0.9577474594, "start": 3564, "tag": "USERNAME", "value": "Username" }, { "context": " [ div [] [ text \"Username\", input [ id \"username\", type_ \"text\", inputTextStyle, onInput Username ", "end": 3595, "score": 0.9992601275, "start": 3587, "tag": "USERNAME", "value": "username" }, { "context": "rname ] [] ]\n , div [] [ text \"Password\", input [ id \"password\", type_ \"password\", inputT", "end": 3697, "score": 0.7660118341, "start": 3689, "tag": "PASSWORD", "value": "Password" }, { "context": " , div [] [ text \"Password\", input [ id \"password\", type_ \"password\", inputTextStyle, onInput Passw", "end": 3720, "score": 0.6885770559, "start": 3712, "tag": "PASSWORD", "value": "password" }, { "context": "Username name ->\n ( { user | username = name }, Cmd.none )\n\n Password password ->\n ", "end": 5170, "score": 0.7874528766, "start": 5166, "tag": "USERNAME", "value": "name" }, { "context": "word password ->\n ( { user | password = password }, Cmd.none )\n\n Login ->\n ( use", "end": 5257, "score": 0.9958860278, "start": 5249, "tag": "PASSWORD", "value": "password" } ]
web/src/Login.elm
bijoythomas/dswa-cwc-hs
0
module Login exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onSubmit, onInput, onClick) import LoginStyle exposing (..) import Http import Json.Decode as Decode exposing (..) import Json.Encode as Encode exposing (..) type alias User = { username : String , password : String , loggedIn : Bool , churches : List Church , errorMsg : String } type alias Model = User type alias Church = { venue : Int , church : String } churchDecoder : Decoder Church churchDecoder = Decode.map2 Church (field "venue" Decode.int) (field "church" Decode.string) --(field "region" Decode.string) churchListDecoder : Decoder (List Church) churchListDecoder = Decode.list churchDecoder initialUser : User initialUser = User "" "" False [] "" init : ( User, Cmd Msg ) init = ( initialUser, Cmd.none ) type Msg = Username String | Password String | Login | LogOut | HandleLoginResponse (Result Http.Error (List Church)) churchMenu church = option [ Html.Attributes.value (toString church.church) ] [ text (toString church.church) ] churchesMenu : List Church -> List (Html msg) churchesMenu list = List.map (\church -> option [ Html.Attributes.value church.church ] [ text church.church ] ) list listToMenu : List (List String) -> List (Html msg) listToMenu list = let toSelectOption : List String -> List (Html msg) -> List (Html msg) toSelectOption xs acc = case xs of b :: bs -> (option [ Html.Attributes.value b ] [ text b ]) :: acc _ -> acc in List.foldr toSelectOption [] list categoiesMenu = listToMenu [ [ "Bible Quiz", "BQ" ] , [ "Story", "ST" ] , [ "Poetry", "PE" ] , [ "Drawing", "DR" ] , [ "Essay", "ES" ] ] view : User -> Html Msg view user = let -- If there is an error on authentication, show the error alert showError : String showError = if String.isEmpty user.errorMsg then "hidden" else "" -- If the user is logged in, show a greeting; else show login form content = if user.loggedIn then [ Html.form [ registrationFormStyle ] [ label [ for "firsname" ] [ text "First Name:" ] , input [ type_ "text", name "firsname", required True ] [] , br [] [] , label [ for "middlename" ] [ text "Middle Name:" ] , input [ type_ "text", name "middlename", required True ] [] , br [] [] , label [ for "lastname" ] [ text "Last Name:" ] , input [ type_ "text", name "lastname", required True ] [] , br [] [] , label [ for "church" ] [ text "Church:" ] , select [ name "church" ] (churchesMenu user.churches) , br [] [] , label [ for "category" ] [ text "Category:" ] , select [ name "category" ] categoiesMenu ] ] else [ div [ class showError ] [ text user.errorMsg ] , Html.form [ loginFormStyle, onSubmit Login ] [ div [] [ text "Username", input [ id "username", type_ "text", inputTextStyle, onInput Username ] [] ] , div [] [ text "Password", input [ id "password", type_ "password", inputTextStyle, onInput Password ] [] ] , div [] [ button [ buttonStyle ] [ text "Login" ] ] ] ] in div [] content loginUrl : String loginUrl = "/login" userEncoder : User -> Encode.Value userEncoder user = Encode.object [ ( "username", Encode.string user.username ) , ( "password", Encode.string user.password ) ] handleLoginResponse : User -> Result Http.Error (List Church) -> ( User, Cmd Msg ) handleLoginResponse user result = case result of Ok [] -> ( { user | loggedIn = False, churches = [], password = "", errorMsg = "Invalid username/password" }, Cmd.none ) Ok (x :: xs) -> ( { user | loggedIn = True, churches = x :: xs, password = "", errorMsg = "" }, Cmd.none ) Err error -> ( { user | errorMsg = (toString error) }, Cmd.none ) authUser : User -> String -> Http.Request (List Church) authUser user apiUrl = let body = user |> userEncoder |> Http.jsonBody in Http.post loginUrl body churchListDecoder authUserCmd : User -> String -> Cmd Msg authUserCmd user apiUrl = Http.send HandleLoginResponse (authUser user apiUrl) update : Msg -> User -> ( User, Cmd Msg ) update message user = case message of Username name -> ( { user | username = name }, Cmd.none ) Password password -> ( { user | password = password }, Cmd.none ) Login -> ( user, authUserCmd user loginUrl ) LogOut -> ( { user | username = "", password = "", loggedIn = False }, Cmd.none ) HandleLoginResponse result -> handleLoginResponse user result main : Program Never Model Msg main = Html.program { init = init , update = update , subscriptions = \_ -> Sub.none , view = view }
57981
module Login exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onSubmit, onInput, onClick) import LoginStyle exposing (..) import Http import Json.Decode as Decode exposing (..) import Json.Encode as Encode exposing (..) type alias User = { username : String , password : <PASSWORD> , loggedIn : Bool , churches : List Church , errorMsg : String } type alias Model = User type alias Church = { venue : Int , church : String } churchDecoder : Decoder Church churchDecoder = Decode.map2 Church (field "venue" Decode.int) (field "church" Decode.string) --(field "region" Decode.string) churchListDecoder : Decoder (List Church) churchListDecoder = Decode.list churchDecoder initialUser : User initialUser = User "" "" False [] "" init : ( User, Cmd Msg ) init = ( initialUser, Cmd.none ) type Msg = Username String | Password String | Login | LogOut | HandleLoginResponse (Result Http.Error (List Church)) churchMenu church = option [ Html.Attributes.value (toString church.church) ] [ text (toString church.church) ] churchesMenu : List Church -> List (Html msg) churchesMenu list = List.map (\church -> option [ Html.Attributes.value church.church ] [ text church.church ] ) list listToMenu : List (List String) -> List (Html msg) listToMenu list = let toSelectOption : List String -> List (Html msg) -> List (Html msg) toSelectOption xs acc = case xs of b :: bs -> (option [ Html.Attributes.value b ] [ text b ]) :: acc _ -> acc in List.foldr toSelectOption [] list categoiesMenu = listToMenu [ [ "Bible Quiz", "BQ" ] , [ "Story", "ST" ] , [ "Poetry", "PE" ] , [ "Drawing", "DR" ] , [ "Essay", "ES" ] ] view : User -> Html Msg view user = let -- If there is an error on authentication, show the error alert showError : String showError = if String.isEmpty user.errorMsg then "hidden" else "" -- If the user is logged in, show a greeting; else show login form content = if user.loggedIn then [ Html.form [ registrationFormStyle ] [ label [ for "firsname" ] [ text "First Name:" ] , input [ type_ "text", name "firsname", required True ] [] , br [] [] , label [ for "<NAME>lename" ] [ text "Middle Name:" ] , input [ type_ "text", name "middlename", required True ] [] , br [] [] , label [ for "lastname" ] [ text "Last Name:" ] , input [ type_ "text", name "lastname", required True ] [] , br [] [] , label [ for "church" ] [ text "Church:" ] , select [ name "church" ] (churchesMenu user.churches) , br [] [] , label [ for "category" ] [ text "Category:" ] , select [ name "category" ] categoiesMenu ] ] else [ div [ class showError ] [ text user.errorMsg ] , Html.form [ loginFormStyle, onSubmit Login ] [ div [] [ text "Username", input [ id "username", type_ "text", inputTextStyle, onInput Username ] [] ] , div [] [ text "<PASSWORD>", input [ id "<PASSWORD>", type_ "password", inputTextStyle, onInput Password ] [] ] , div [] [ button [ buttonStyle ] [ text "Login" ] ] ] ] in div [] content loginUrl : String loginUrl = "/login" userEncoder : User -> Encode.Value userEncoder user = Encode.object [ ( "username", Encode.string user.username ) , ( "password", Encode.string user.password ) ] handleLoginResponse : User -> Result Http.Error (List Church) -> ( User, Cmd Msg ) handleLoginResponse user result = case result of Ok [] -> ( { user | loggedIn = False, churches = [], password = "", errorMsg = "Invalid username/password" }, Cmd.none ) Ok (x :: xs) -> ( { user | loggedIn = True, churches = x :: xs, password = "", errorMsg = "" }, Cmd.none ) Err error -> ( { user | errorMsg = (toString error) }, Cmd.none ) authUser : User -> String -> Http.Request (List Church) authUser user apiUrl = let body = user |> userEncoder |> Http.jsonBody in Http.post loginUrl body churchListDecoder authUserCmd : User -> String -> Cmd Msg authUserCmd user apiUrl = Http.send HandleLoginResponse (authUser user apiUrl) update : Msg -> User -> ( User, Cmd Msg ) update message user = case message of Username name -> ( { user | username = name }, Cmd.none ) Password password -> ( { user | password = <PASSWORD> }, Cmd.none ) Login -> ( user, authUserCmd user loginUrl ) LogOut -> ( { user | username = "", password = "", loggedIn = False }, Cmd.none ) HandleLoginResponse result -> handleLoginResponse user result main : Program Never Model Msg main = Html.program { init = init , update = update , subscriptions = \_ -> Sub.none , view = view }
true
module Login exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onSubmit, onInput, onClick) import LoginStyle exposing (..) import Http import Json.Decode as Decode exposing (..) import Json.Encode as Encode exposing (..) type alias User = { username : String , password : PI:PASSWORD:<PASSWORD>END_PI , loggedIn : Bool , churches : List Church , errorMsg : String } type alias Model = User type alias Church = { venue : Int , church : String } churchDecoder : Decoder Church churchDecoder = Decode.map2 Church (field "venue" Decode.int) (field "church" Decode.string) --(field "region" Decode.string) churchListDecoder : Decoder (List Church) churchListDecoder = Decode.list churchDecoder initialUser : User initialUser = User "" "" False [] "" init : ( User, Cmd Msg ) init = ( initialUser, Cmd.none ) type Msg = Username String | Password String | Login | LogOut | HandleLoginResponse (Result Http.Error (List Church)) churchMenu church = option [ Html.Attributes.value (toString church.church) ] [ text (toString church.church) ] churchesMenu : List Church -> List (Html msg) churchesMenu list = List.map (\church -> option [ Html.Attributes.value church.church ] [ text church.church ] ) list listToMenu : List (List String) -> List (Html msg) listToMenu list = let toSelectOption : List String -> List (Html msg) -> List (Html msg) toSelectOption xs acc = case xs of b :: bs -> (option [ Html.Attributes.value b ] [ text b ]) :: acc _ -> acc in List.foldr toSelectOption [] list categoiesMenu = listToMenu [ [ "Bible Quiz", "BQ" ] , [ "Story", "ST" ] , [ "Poetry", "PE" ] , [ "Drawing", "DR" ] , [ "Essay", "ES" ] ] view : User -> Html Msg view user = let -- If there is an error on authentication, show the error alert showError : String showError = if String.isEmpty user.errorMsg then "hidden" else "" -- If the user is logged in, show a greeting; else show login form content = if user.loggedIn then [ Html.form [ registrationFormStyle ] [ label [ for "firsname" ] [ text "First Name:" ] , input [ type_ "text", name "firsname", required True ] [] , br [] [] , label [ for "PI:NAME:<NAME>END_PIlename" ] [ text "Middle Name:" ] , input [ type_ "text", name "middlename", required True ] [] , br [] [] , label [ for "lastname" ] [ text "Last Name:" ] , input [ type_ "text", name "lastname", required True ] [] , br [] [] , label [ for "church" ] [ text "Church:" ] , select [ name "church" ] (churchesMenu user.churches) , br [] [] , label [ for "category" ] [ text "Category:" ] , select [ name "category" ] categoiesMenu ] ] else [ div [ class showError ] [ text user.errorMsg ] , Html.form [ loginFormStyle, onSubmit Login ] [ div [] [ text "Username", input [ id "username", type_ "text", inputTextStyle, onInput Username ] [] ] , div [] [ text "PI:PASSWORD:<PASSWORD>END_PI", input [ id "PI:PASSWORD:<PASSWORD>END_PI", type_ "password", inputTextStyle, onInput Password ] [] ] , div [] [ button [ buttonStyle ] [ text "Login" ] ] ] ] in div [] content loginUrl : String loginUrl = "/login" userEncoder : User -> Encode.Value userEncoder user = Encode.object [ ( "username", Encode.string user.username ) , ( "password", Encode.string user.password ) ] handleLoginResponse : User -> Result Http.Error (List Church) -> ( User, Cmd Msg ) handleLoginResponse user result = case result of Ok [] -> ( { user | loggedIn = False, churches = [], password = "", errorMsg = "Invalid username/password" }, Cmd.none ) Ok (x :: xs) -> ( { user | loggedIn = True, churches = x :: xs, password = "", errorMsg = "" }, Cmd.none ) Err error -> ( { user | errorMsg = (toString error) }, Cmd.none ) authUser : User -> String -> Http.Request (List Church) authUser user apiUrl = let body = user |> userEncoder |> Http.jsonBody in Http.post loginUrl body churchListDecoder authUserCmd : User -> String -> Cmd Msg authUserCmd user apiUrl = Http.send HandleLoginResponse (authUser user apiUrl) update : Msg -> User -> ( User, Cmd Msg ) update message user = case message of Username name -> ( { user | username = name }, Cmd.none ) Password password -> ( { user | password = PI:PASSWORD:<PASSWORD>END_PI }, Cmd.none ) Login -> ( user, authUserCmd user loginUrl ) LogOut -> ( { user | username = "", password = "", loggedIn = False }, Cmd.none ) HandleLoginResponse result -> handleLoginResponse user result main : Program Never Model Msg main = Html.program { init = init , update = update , subscriptions = \_ -> Sub.none , view = view }
elm
[ { "context": "t\", False )\n , ( \"accountKey\", \"Account key\", \"MXFPDkaN4KBT\", True )\n , ( \"container\", \"Share name\", \"musi", "end": 1029, "score": 0.9964492321, "start": 1017, "tag": "KEY", "value": "MXFPDkaN4KBT" } ]
src/App/Sources/Services/AzureFile.elm
AdrianoFerrari/diffuse
0
module Sources.Services.AzureFile exposing (..) {-| Microsoft Azure File Service. Resources: - <https://docs.microsoft.com/en-us/rest/api/storageservices/file-service-rest-api> -} import Date exposing (Date) import Dict import Http import Sources.Pick import Sources.Services.Azure.Authorization exposing (..) import Sources.Services.Azure.FileParser as Parser import Sources.Services.Azure.FileMarker as FileMarker exposing (MarkerItem(..)) import Sources.Services.Utils exposing (cleanPath, noPrep) import Sources.Processing.Types exposing (..) import Sources.Types exposing (SourceData) import Time -- Properties -- 📟 defaults = { directoryPath = "/" , name = "Music from Azure File Storage" } {-| The list of properties we need from the user. Tuple: (property, label, placeholder, isPassword) Will be used for the forms. -} properties : List ( String, String, String, Bool ) properties = [ ( "accountName", "Account name", "myaccount", False ) , ( "accountKey", "Account key", "MXFPDkaN4KBT", True ) , ( "container", "Share name", "music", False ) , ( "directoryPath", "Directory (aka. Prefix)", defaults.directoryPath, False ) , ( "name", "Label", defaults.name, False ) ] {-| Initial data set. -} initialData : SourceData initialData = Dict.fromList [ ( "accountName", "" ) , ( "accountKey", "" ) , ( "container", "" ) , ( "directoryPath", defaults.directoryPath ) , ( "name", defaults.name ) ] -- Preparation prepare : String -> SourceData -> Marker -> Maybe (Http.Request String) prepare _ _ _ = Nothing -- Tree {-| Create a directory tree. List all the tracks in the container. Or a specific directory in the container. -} makeTree : SourceData -> Marker -> Date -> (Result Http.Error String -> Msg) -> Cmd Msg makeTree srcData marker currentDate resultMsg = let directoryPathFromSrcData = srcData |> Dict.get "directoryPath" |> Maybe.withDefault defaults.directoryPath |> cleanPath baseParams = [ ( "maxresults", "1000" ) ] ( directoryPath, params ) = case FileMarker.takeOne marker of Just (Directory directory) -> (,) directory [] Just (Param param) -> (,) param.directory [ ( "marker", param.marker ) ] _ -> (,) directoryPathFromSrcData [] url = presignedUrl File List Get 1 currentDate srcData directoryPath (baseParams ++ params) in url |> Http.getString |> Http.send resultMsg {-| Re-export parser functions. -} parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse = noPrep parseTreeResponse : String -> Marker -> TreeAnswer Marker parseTreeResponse = Parser.parseTreeResponse parseErrorResponse : String -> 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. (!) Creates a presigned url that's valid for 48 hours -} makeTrackUrl : Date -> SourceData -> HttpMethod -> String -> String makeTrackUrl currentDate srcData method pathToFile = presignedUrl File Read Get 48 currentDate srcData pathToFile []
32706
module Sources.Services.AzureFile exposing (..) {-| Microsoft Azure File Service. Resources: - <https://docs.microsoft.com/en-us/rest/api/storageservices/file-service-rest-api> -} import Date exposing (Date) import Dict import Http import Sources.Pick import Sources.Services.Azure.Authorization exposing (..) import Sources.Services.Azure.FileParser as Parser import Sources.Services.Azure.FileMarker as FileMarker exposing (MarkerItem(..)) import Sources.Services.Utils exposing (cleanPath, noPrep) import Sources.Processing.Types exposing (..) import Sources.Types exposing (SourceData) import Time -- Properties -- 📟 defaults = { directoryPath = "/" , name = "Music from Azure File Storage" } {-| The list of properties we need from the user. Tuple: (property, label, placeholder, isPassword) Will be used for the forms. -} properties : List ( String, String, String, Bool ) properties = [ ( "accountName", "Account name", "myaccount", False ) , ( "accountKey", "Account key", "<KEY>", True ) , ( "container", "Share name", "music", False ) , ( "directoryPath", "Directory (aka. Prefix)", defaults.directoryPath, False ) , ( "name", "Label", defaults.name, False ) ] {-| Initial data set. -} initialData : SourceData initialData = Dict.fromList [ ( "accountName", "" ) , ( "accountKey", "" ) , ( "container", "" ) , ( "directoryPath", defaults.directoryPath ) , ( "name", defaults.name ) ] -- Preparation prepare : String -> SourceData -> Marker -> Maybe (Http.Request String) prepare _ _ _ = Nothing -- Tree {-| Create a directory tree. List all the tracks in the container. Or a specific directory in the container. -} makeTree : SourceData -> Marker -> Date -> (Result Http.Error String -> Msg) -> Cmd Msg makeTree srcData marker currentDate resultMsg = let directoryPathFromSrcData = srcData |> Dict.get "directoryPath" |> Maybe.withDefault defaults.directoryPath |> cleanPath baseParams = [ ( "maxresults", "1000" ) ] ( directoryPath, params ) = case FileMarker.takeOne marker of Just (Directory directory) -> (,) directory [] Just (Param param) -> (,) param.directory [ ( "marker", param.marker ) ] _ -> (,) directoryPathFromSrcData [] url = presignedUrl File List Get 1 currentDate srcData directoryPath (baseParams ++ params) in url |> Http.getString |> Http.send resultMsg {-| Re-export parser functions. -} parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse = noPrep parseTreeResponse : String -> Marker -> TreeAnswer Marker parseTreeResponse = Parser.parseTreeResponse parseErrorResponse : String -> 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. (!) Creates a presigned url that's valid for 48 hours -} makeTrackUrl : Date -> SourceData -> HttpMethod -> String -> String makeTrackUrl currentDate srcData method pathToFile = presignedUrl File Read Get 48 currentDate srcData pathToFile []
true
module Sources.Services.AzureFile exposing (..) {-| Microsoft Azure File Service. Resources: - <https://docs.microsoft.com/en-us/rest/api/storageservices/file-service-rest-api> -} import Date exposing (Date) import Dict import Http import Sources.Pick import Sources.Services.Azure.Authorization exposing (..) import Sources.Services.Azure.FileParser as Parser import Sources.Services.Azure.FileMarker as FileMarker exposing (MarkerItem(..)) import Sources.Services.Utils exposing (cleanPath, noPrep) import Sources.Processing.Types exposing (..) import Sources.Types exposing (SourceData) import Time -- Properties -- 📟 defaults = { directoryPath = "/" , name = "Music from Azure File Storage" } {-| The list of properties we need from the user. Tuple: (property, label, placeholder, isPassword) Will be used for the forms. -} properties : List ( String, String, String, Bool ) properties = [ ( "accountName", "Account name", "myaccount", False ) , ( "accountKey", "Account key", "PI:KEY:<KEY>END_PI", True ) , ( "container", "Share name", "music", False ) , ( "directoryPath", "Directory (aka. Prefix)", defaults.directoryPath, False ) , ( "name", "Label", defaults.name, False ) ] {-| Initial data set. -} initialData : SourceData initialData = Dict.fromList [ ( "accountName", "" ) , ( "accountKey", "" ) , ( "container", "" ) , ( "directoryPath", defaults.directoryPath ) , ( "name", defaults.name ) ] -- Preparation prepare : String -> SourceData -> Marker -> Maybe (Http.Request String) prepare _ _ _ = Nothing -- Tree {-| Create a directory tree. List all the tracks in the container. Or a specific directory in the container. -} makeTree : SourceData -> Marker -> Date -> (Result Http.Error String -> Msg) -> Cmd Msg makeTree srcData marker currentDate resultMsg = let directoryPathFromSrcData = srcData |> Dict.get "directoryPath" |> Maybe.withDefault defaults.directoryPath |> cleanPath baseParams = [ ( "maxresults", "1000" ) ] ( directoryPath, params ) = case FileMarker.takeOne marker of Just (Directory directory) -> (,) directory [] Just (Param param) -> (,) param.directory [ ( "marker", param.marker ) ] _ -> (,) directoryPathFromSrcData [] url = presignedUrl File List Get 1 currentDate srcData directoryPath (baseParams ++ params) in url |> Http.getString |> Http.send resultMsg {-| Re-export parser functions. -} parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse = noPrep parseTreeResponse : String -> Marker -> TreeAnswer Marker parseTreeResponse = Parser.parseTreeResponse parseErrorResponse : String -> 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. (!) Creates a presigned url that's valid for 48 hours -} makeTrackUrl : Date -> SourceData -> HttpMethod -> String -> String makeTrackUrl currentDate srcData method pathToFile = presignedUrl File Read Get 48 currentDate srcData pathToFile []
elm
[ { "context": " Useful for testing with Test.\n\nCopyright (c) 2016 Robin Luiten\n\n-}\n\nimport Date exposing (Date)\nimport Test expo", "end": 98, "score": 0.9998381734, "start": 86, "tag": "NAME", "value": "Robin Luiten" } ]
tests/TestUtils.elm
AdrianRibao/elm-date-extra
81
module TestUtils exposing (..) {-| Useful for testing with Test. Copyright (c) 2016 Robin Luiten -} import Date exposing (Date) import Test exposing (..) import Expect import String import Time exposing (Time) import Date.Extra.Core as Core import Date.Extra.Create as Create import Date.Extra.Format as Format import Date.Extra.Utils as DateUtils import Date.Extra.Config.Config_en_au as Config import Tuple config = Config.config dateStr = Format.isoString {-| Helper for testing Date transform functions without offset. -} assertDateFunc : String -> String -> (Date -> Date) -> (() -> Expect.Expectation) assertDateFunc inputDateStr expectedDateStr dateFunc = let -- inputDate = DateUtils.unsafeFromString inputDateStr inputDate = fudgeDate inputDateStr outputDate = dateFunc inputDate expectedDate = DateUtils.unsafeFromString expectedDateStr -- _ = Debug.log "assertDateFunc " -- ( "inputDate", inputDateStr, Format.isoStringNoOffset inputDate, Date.toTime inputDate -- , "expectedDate", expectedDateStr -- , "outputDate", Format.isoStringNoOffset outputDate, Date.toTime outputDate -- ) in \() -> Expect.equal expectedDateStr (Format.isoStringNoOffset outputDate) {-| Helper for testing Date transform functions, including offset. -} assertDateFuncOffset : String -> String -> (Date -> Date) -> (() -> Expect.Expectation) assertDateFuncOffset inputDateStr expectedDateStr dateFunc = let -- inputDate = DateUtils.unsafeFromString inputDateStr inputDate = fudgeDate inputDateStr outputDate = dateFunc inputDate -- _ = Debug.log "assertDateFunc " -- ( "inputDate", inputDateStr, Format.isoString inputDate, Date.toTime inputDate -- , "expectedDate", expectedDateStr -- , "outputDate", Format.isoString outputDate, Date.toTime outputDate -- ) in \() -> Expect.equal expectedDateStr (Format.isoString outputDate) debugDumpDateFunc expectedDate testDate dateFunc = let _ = Debug.log ("expectedDate") ( expectedDate , Result.map Core.toTime (Date.fromString expectedDate) , Result.map Format.isoString (Date.fromString expectedDate) ) _ = Debug.log ("testDate, toTime testDate") ( dateStr testDate , Date.toTime testDate ) _ = Debug.log ("dateFunc testDate, toTime dateFunc testDate") ( dateStr (dateFunc testDate) , Date.toTime (dateFunc testDate) ) in True {-| Helper to compare Results with an offset on there Ok value. Initially created for makeDateTicksTest2. -} assertResultEqualWithOffset : Result String Float -> Result String Float -> Int -> (() -> Expect.Expectation) assertResultEqualWithOffset expected test offset = \() -> case expected of Ok expectedTicks -> case test of Ok testTicks -> let _ = Debug.log ("ooo") (expectedTicks - testTicks) in Expect.equal expectedTicks (testTicks + (toFloat offset)) Err msg -> let _ = Debug.log ("assertResultEqualWithOffset Err ") (msg) in Expect.fail msg Err msg -> let _ = Debug.log ("assertResultEqualWithOffset Err ") (msg) in Expect.fail msg logResultDate : String -> Result String Date -> Bool logResultDate str result = case result of Ok date -> let _ = Debug.log (str) (Format.utcIsoString date) in False Err msg -> let _ = Debug.log (str) ("Err " ++ msg) in False logDate : Date -> Date logDate date = let _ = Debug.log ("logDate") (Format.utcIsoString date) in date {-| Return min and max zone offsets in current zone. As a rule (fst (getZoneOffsets year)) will return standard timezoneOffset for local zone as per referenced information. <http://stackoverflow.com/questions/11887934/check-if-daylight-saving-time-is-in-effect-and-if-it-is-for-how-many-hours/11888430#11888430> -} getZoneOffsets : Int -> ( Int, Int ) getZoneOffsets year = let jan01offset = Create.dateFromFields year Date.Jan 1 0 0 0 0 |> Create.getTimezoneOffset jul01offset = Create.dateFromFields year Date.Jun 1 0 0 0 0 |> Create.getTimezoneOffset minOffset = min jan01offset jul01offset maxOffset = max jan01offset jul01offset -- _ = Debug.log "isOffset" (minOffset, maxOffset, jan01offset, jul01offset) in ( minOffset, maxOffset ) {-| firefox wont parse "2016/06/05 04:03:02.111" it really requires "2016-06-05T04:03:02.111+1000" with local offset to get right offset we need a date to start with so we convert str into date with out milliseconds then again with milliseconds and right format with offset. -} fudgeDate : String -> Date fudgeDate str = -- let -- _ = Debug.log "fudgeDate" str -- in case String.split "." str of _ :: [] -> -- no "." so no milliseconds so dont do tricky DateUtils.unsafeFromString str beforeDot :: afterDot -> -- afterDot maybe .XXX or .XXX-Offset so check for + or - of offset and do nothing let strAfterDot = String.concat afterDot in if String.contains "+" strAfterDot || String.contains "-" strAfterDot then DateUtils.unsafeFromString str else let date = DateUtils.unsafeFromString beforeDot newStr = String.concat [ Format.format config Format.isoFormat date , "." , strAfterDot , Format.format config "%z" date ] -- _ = Debug.log "fudgeDate newStr" newStr in DateUtils.unsafeFromString newStr [] -> DateUtils.unsafeFromString str {-| Given a year and list of offset and test data only run tests that matche the minimum and maximum time zone offset of for that test. -} describeOffsetTests : String -> Int -> List ( ( Int, Int ), () -> Test ) -> Test describeOffsetTests description year candidateTests = let -- currentOffsetFilter : ( ( Int, Int ), () -> Test ) -> Maybe Test currentOffsetFilter ( offsets, test ) = if (getZoneOffsets year) == offsets then Just (test ()) else let firstInt tuple = " " ++ (toString <| Tuple.first tuple) secondInt tuple = " " ++ (toString <| Tuple.second tuple) uniqueDescripton = (description ++ (firstInt offsets) ++ (secondInt offsets)) in Just (dummyPassingTest uniqueDescripton) in describe description <| List.append (List.filterMap currentOffsetFilter candidateTests) [ test ("Passing test to make suite not fail if empty for " ++ description) <| (\_ -> Expect.pass) ] dummyPassingTest : String -> Test dummyPassingTest description = test ("Dummy passing test" ++ description) <| \_ -> Expect.true "Dummy passing test" True
30356
module TestUtils exposing (..) {-| Useful for testing with Test. Copyright (c) 2016 <NAME> -} import Date exposing (Date) import Test exposing (..) import Expect import String import Time exposing (Time) import Date.Extra.Core as Core import Date.Extra.Create as Create import Date.Extra.Format as Format import Date.Extra.Utils as DateUtils import Date.Extra.Config.Config_en_au as Config import Tuple config = Config.config dateStr = Format.isoString {-| Helper for testing Date transform functions without offset. -} assertDateFunc : String -> String -> (Date -> Date) -> (() -> Expect.Expectation) assertDateFunc inputDateStr expectedDateStr dateFunc = let -- inputDate = DateUtils.unsafeFromString inputDateStr inputDate = fudgeDate inputDateStr outputDate = dateFunc inputDate expectedDate = DateUtils.unsafeFromString expectedDateStr -- _ = Debug.log "assertDateFunc " -- ( "inputDate", inputDateStr, Format.isoStringNoOffset inputDate, Date.toTime inputDate -- , "expectedDate", expectedDateStr -- , "outputDate", Format.isoStringNoOffset outputDate, Date.toTime outputDate -- ) in \() -> Expect.equal expectedDateStr (Format.isoStringNoOffset outputDate) {-| Helper for testing Date transform functions, including offset. -} assertDateFuncOffset : String -> String -> (Date -> Date) -> (() -> Expect.Expectation) assertDateFuncOffset inputDateStr expectedDateStr dateFunc = let -- inputDate = DateUtils.unsafeFromString inputDateStr inputDate = fudgeDate inputDateStr outputDate = dateFunc inputDate -- _ = Debug.log "assertDateFunc " -- ( "inputDate", inputDateStr, Format.isoString inputDate, Date.toTime inputDate -- , "expectedDate", expectedDateStr -- , "outputDate", Format.isoString outputDate, Date.toTime outputDate -- ) in \() -> Expect.equal expectedDateStr (Format.isoString outputDate) debugDumpDateFunc expectedDate testDate dateFunc = let _ = Debug.log ("expectedDate") ( expectedDate , Result.map Core.toTime (Date.fromString expectedDate) , Result.map Format.isoString (Date.fromString expectedDate) ) _ = Debug.log ("testDate, toTime testDate") ( dateStr testDate , Date.toTime testDate ) _ = Debug.log ("dateFunc testDate, toTime dateFunc testDate") ( dateStr (dateFunc testDate) , Date.toTime (dateFunc testDate) ) in True {-| Helper to compare Results with an offset on there Ok value. Initially created for makeDateTicksTest2. -} assertResultEqualWithOffset : Result String Float -> Result String Float -> Int -> (() -> Expect.Expectation) assertResultEqualWithOffset expected test offset = \() -> case expected of Ok expectedTicks -> case test of Ok testTicks -> let _ = Debug.log ("ooo") (expectedTicks - testTicks) in Expect.equal expectedTicks (testTicks + (toFloat offset)) Err msg -> let _ = Debug.log ("assertResultEqualWithOffset Err ") (msg) in Expect.fail msg Err msg -> let _ = Debug.log ("assertResultEqualWithOffset Err ") (msg) in Expect.fail msg logResultDate : String -> Result String Date -> Bool logResultDate str result = case result of Ok date -> let _ = Debug.log (str) (Format.utcIsoString date) in False Err msg -> let _ = Debug.log (str) ("Err " ++ msg) in False logDate : Date -> Date logDate date = let _ = Debug.log ("logDate") (Format.utcIsoString date) in date {-| Return min and max zone offsets in current zone. As a rule (fst (getZoneOffsets year)) will return standard timezoneOffset for local zone as per referenced information. <http://stackoverflow.com/questions/11887934/check-if-daylight-saving-time-is-in-effect-and-if-it-is-for-how-many-hours/11888430#11888430> -} getZoneOffsets : Int -> ( Int, Int ) getZoneOffsets year = let jan01offset = Create.dateFromFields year Date.Jan 1 0 0 0 0 |> Create.getTimezoneOffset jul01offset = Create.dateFromFields year Date.Jun 1 0 0 0 0 |> Create.getTimezoneOffset minOffset = min jan01offset jul01offset maxOffset = max jan01offset jul01offset -- _ = Debug.log "isOffset" (minOffset, maxOffset, jan01offset, jul01offset) in ( minOffset, maxOffset ) {-| firefox wont parse "2016/06/05 04:03:02.111" it really requires "2016-06-05T04:03:02.111+1000" with local offset to get right offset we need a date to start with so we convert str into date with out milliseconds then again with milliseconds and right format with offset. -} fudgeDate : String -> Date fudgeDate str = -- let -- _ = Debug.log "fudgeDate" str -- in case String.split "." str of _ :: [] -> -- no "." so no milliseconds so dont do tricky DateUtils.unsafeFromString str beforeDot :: afterDot -> -- afterDot maybe .XXX or .XXX-Offset so check for + or - of offset and do nothing let strAfterDot = String.concat afterDot in if String.contains "+" strAfterDot || String.contains "-" strAfterDot then DateUtils.unsafeFromString str else let date = DateUtils.unsafeFromString beforeDot newStr = String.concat [ Format.format config Format.isoFormat date , "." , strAfterDot , Format.format config "%z" date ] -- _ = Debug.log "fudgeDate newStr" newStr in DateUtils.unsafeFromString newStr [] -> DateUtils.unsafeFromString str {-| Given a year and list of offset and test data only run tests that matche the minimum and maximum time zone offset of for that test. -} describeOffsetTests : String -> Int -> List ( ( Int, Int ), () -> Test ) -> Test describeOffsetTests description year candidateTests = let -- currentOffsetFilter : ( ( Int, Int ), () -> Test ) -> Maybe Test currentOffsetFilter ( offsets, test ) = if (getZoneOffsets year) == offsets then Just (test ()) else let firstInt tuple = " " ++ (toString <| Tuple.first tuple) secondInt tuple = " " ++ (toString <| Tuple.second tuple) uniqueDescripton = (description ++ (firstInt offsets) ++ (secondInt offsets)) in Just (dummyPassingTest uniqueDescripton) in describe description <| List.append (List.filterMap currentOffsetFilter candidateTests) [ test ("Passing test to make suite not fail if empty for " ++ description) <| (\_ -> Expect.pass) ] dummyPassingTest : String -> Test dummyPassingTest description = test ("Dummy passing test" ++ description) <| \_ -> Expect.true "Dummy passing test" True
true
module TestUtils exposing (..) {-| Useful for testing with Test. Copyright (c) 2016 PI:NAME:<NAME>END_PI -} import Date exposing (Date) import Test exposing (..) import Expect import String import Time exposing (Time) import Date.Extra.Core as Core import Date.Extra.Create as Create import Date.Extra.Format as Format import Date.Extra.Utils as DateUtils import Date.Extra.Config.Config_en_au as Config import Tuple config = Config.config dateStr = Format.isoString {-| Helper for testing Date transform functions without offset. -} assertDateFunc : String -> String -> (Date -> Date) -> (() -> Expect.Expectation) assertDateFunc inputDateStr expectedDateStr dateFunc = let -- inputDate = DateUtils.unsafeFromString inputDateStr inputDate = fudgeDate inputDateStr outputDate = dateFunc inputDate expectedDate = DateUtils.unsafeFromString expectedDateStr -- _ = Debug.log "assertDateFunc " -- ( "inputDate", inputDateStr, Format.isoStringNoOffset inputDate, Date.toTime inputDate -- , "expectedDate", expectedDateStr -- , "outputDate", Format.isoStringNoOffset outputDate, Date.toTime outputDate -- ) in \() -> Expect.equal expectedDateStr (Format.isoStringNoOffset outputDate) {-| Helper for testing Date transform functions, including offset. -} assertDateFuncOffset : String -> String -> (Date -> Date) -> (() -> Expect.Expectation) assertDateFuncOffset inputDateStr expectedDateStr dateFunc = let -- inputDate = DateUtils.unsafeFromString inputDateStr inputDate = fudgeDate inputDateStr outputDate = dateFunc inputDate -- _ = Debug.log "assertDateFunc " -- ( "inputDate", inputDateStr, Format.isoString inputDate, Date.toTime inputDate -- , "expectedDate", expectedDateStr -- , "outputDate", Format.isoString outputDate, Date.toTime outputDate -- ) in \() -> Expect.equal expectedDateStr (Format.isoString outputDate) debugDumpDateFunc expectedDate testDate dateFunc = let _ = Debug.log ("expectedDate") ( expectedDate , Result.map Core.toTime (Date.fromString expectedDate) , Result.map Format.isoString (Date.fromString expectedDate) ) _ = Debug.log ("testDate, toTime testDate") ( dateStr testDate , Date.toTime testDate ) _ = Debug.log ("dateFunc testDate, toTime dateFunc testDate") ( dateStr (dateFunc testDate) , Date.toTime (dateFunc testDate) ) in True {-| Helper to compare Results with an offset on there Ok value. Initially created for makeDateTicksTest2. -} assertResultEqualWithOffset : Result String Float -> Result String Float -> Int -> (() -> Expect.Expectation) assertResultEqualWithOffset expected test offset = \() -> case expected of Ok expectedTicks -> case test of Ok testTicks -> let _ = Debug.log ("ooo") (expectedTicks - testTicks) in Expect.equal expectedTicks (testTicks + (toFloat offset)) Err msg -> let _ = Debug.log ("assertResultEqualWithOffset Err ") (msg) in Expect.fail msg Err msg -> let _ = Debug.log ("assertResultEqualWithOffset Err ") (msg) in Expect.fail msg logResultDate : String -> Result String Date -> Bool logResultDate str result = case result of Ok date -> let _ = Debug.log (str) (Format.utcIsoString date) in False Err msg -> let _ = Debug.log (str) ("Err " ++ msg) in False logDate : Date -> Date logDate date = let _ = Debug.log ("logDate") (Format.utcIsoString date) in date {-| Return min and max zone offsets in current zone. As a rule (fst (getZoneOffsets year)) will return standard timezoneOffset for local zone as per referenced information. <http://stackoverflow.com/questions/11887934/check-if-daylight-saving-time-is-in-effect-and-if-it-is-for-how-many-hours/11888430#11888430> -} getZoneOffsets : Int -> ( Int, Int ) getZoneOffsets year = let jan01offset = Create.dateFromFields year Date.Jan 1 0 0 0 0 |> Create.getTimezoneOffset jul01offset = Create.dateFromFields year Date.Jun 1 0 0 0 0 |> Create.getTimezoneOffset minOffset = min jan01offset jul01offset maxOffset = max jan01offset jul01offset -- _ = Debug.log "isOffset" (minOffset, maxOffset, jan01offset, jul01offset) in ( minOffset, maxOffset ) {-| firefox wont parse "2016/06/05 04:03:02.111" it really requires "2016-06-05T04:03:02.111+1000" with local offset to get right offset we need a date to start with so we convert str into date with out milliseconds then again with milliseconds and right format with offset. -} fudgeDate : String -> Date fudgeDate str = -- let -- _ = Debug.log "fudgeDate" str -- in case String.split "." str of _ :: [] -> -- no "." so no milliseconds so dont do tricky DateUtils.unsafeFromString str beforeDot :: afterDot -> -- afterDot maybe .XXX or .XXX-Offset so check for + or - of offset and do nothing let strAfterDot = String.concat afterDot in if String.contains "+" strAfterDot || String.contains "-" strAfterDot then DateUtils.unsafeFromString str else let date = DateUtils.unsafeFromString beforeDot newStr = String.concat [ Format.format config Format.isoFormat date , "." , strAfterDot , Format.format config "%z" date ] -- _ = Debug.log "fudgeDate newStr" newStr in DateUtils.unsafeFromString newStr [] -> DateUtils.unsafeFromString str {-| Given a year and list of offset and test data only run tests that matche the minimum and maximum time zone offset of for that test. -} describeOffsetTests : String -> Int -> List ( ( Int, Int ), () -> Test ) -> Test describeOffsetTests description year candidateTests = let -- currentOffsetFilter : ( ( Int, Int ), () -> Test ) -> Maybe Test currentOffsetFilter ( offsets, test ) = if (getZoneOffsets year) == offsets then Just (test ()) else let firstInt tuple = " " ++ (toString <| Tuple.first tuple) secondInt tuple = " " ++ (toString <| Tuple.second tuple) uniqueDescripton = (description ++ (firstInt offsets) ++ (secondInt offsets)) in Just (dummyPassingTest uniqueDescripton) in describe description <| List.append (List.filterMap currentOffsetFilter candidateTests) [ test ("Passing test to make suite not fail if empty for " ++ description) <| (\_ -> Expect.pass) ] dummyPassingTest : String -> Test dummyPassingTest description = test ("Dummy passing test" ++ description) <| \_ -> Expect.true "Dummy passing test" True
elm
[ { "context": "or blue\n\n\nmain : Element\nmain =\n T.fromString \"Hello World\"\n |> makeBlue\n |> T.italic\n ", "end": 218, "score": 0.9745914936, "start": 207, "tag": "NAME", "value": "Hello World" } ]
HelloWorld3.elm
grzegorzbalcerek/ElmByExample
43
module HelloWorld3 where import Color exposing (blue) import Graphics.Element exposing (..) import Text as T makeBlue : T.Text -> T.Text makeBlue = T.color blue main : Element main = T.fromString "Hello World" |> makeBlue |> T.italic |> T.bold |> T.height 60 |> leftAligned
47725
module HelloWorld3 where import Color exposing (blue) import Graphics.Element exposing (..) import Text as T makeBlue : T.Text -> T.Text makeBlue = T.color blue main : Element main = T.fromString "<NAME>" |> makeBlue |> T.italic |> T.bold |> T.height 60 |> leftAligned
true
module HelloWorld3 where import Color exposing (blue) import Graphics.Element exposing (..) import Text as T makeBlue : T.Text -> T.Text makeBlue = T.color blue main : Element main = T.fromString "PI:NAME:<NAME>END_PI" |> makeBlue |> T.italic |> T.bold |> T.height 60 |> leftAligned
elm
[ { "context": " offHandItem : Maybe Item\n }\n\nlily =\n { name = \"Lily\"\n , class = Paladin\n , race = Human\n , mainIte", "end": 521, "score": 0.9993247986, "start": 517, "tag": "NAME", "value": "Lily" }, { "context": "\n , offHandItem = Nothing\n }\n\nmax =\n { name = \"Max\"\n , class = Mage\n , race = HalfElf\n , mainItem", "end": 703, "score": 0.9998489618, "start": 700, "tag": "NAME", "value": "Max" } ]
exercises/elm3.elm
wayfinderio/intro-to-fp
2
-- Copy paste this into Try Elm (http://elm-lang.org/try) and fill in the missing parts import Html exposing (text) type Class = Fighter | Paladin | Ranger | Mage | Cleric | Druid | Thief | Bard type Race = Dwarf | Elf | Gnome | HalfElf | Halfling | Human type alias Item = { name : String , itemType : ItemType } type ItemType = Weapon | Shield | Other type alias Character = { name : String , class : Class , race : Race , mainItem : Maybe Item , offHandItem : Maybe Item } lily = { name = "Lily" , class = Paladin , race = Human , mainItem = Just { name = "+1 Sword of smiting" , itemType = Weapon } , offHandItem = Nothing } max = { name = "Max" , class = Mage , race = HalfElf , mainItem = Just { name = "Wizardly wand of wizardry" , itemType = Weapon } , offHandItem = Just { name = "Book of spells" , itemType = Other } } showClass : Class -> String showClass class = ? showRace : Race -> String showRace race = ? showItem : Item -> String showItem item = ? -- Title formats the details of a character, for example for lily it would return -- Lily is a Human Paladin who carries a weapon: +1 Sword of smiting and nothing else title : Character -> String title character = ? main = title lily |> text
12141
-- Copy paste this into Try Elm (http://elm-lang.org/try) and fill in the missing parts import Html exposing (text) type Class = Fighter | Paladin | Ranger | Mage | Cleric | Druid | Thief | Bard type Race = Dwarf | Elf | Gnome | HalfElf | Halfling | Human type alias Item = { name : String , itemType : ItemType } type ItemType = Weapon | Shield | Other type alias Character = { name : String , class : Class , race : Race , mainItem : Maybe Item , offHandItem : Maybe Item } lily = { name = "<NAME>" , class = Paladin , race = Human , mainItem = Just { name = "+1 Sword of smiting" , itemType = Weapon } , offHandItem = Nothing } max = { name = "<NAME>" , class = Mage , race = HalfElf , mainItem = Just { name = "Wizardly wand of wizardry" , itemType = Weapon } , offHandItem = Just { name = "Book of spells" , itemType = Other } } showClass : Class -> String showClass class = ? showRace : Race -> String showRace race = ? showItem : Item -> String showItem item = ? -- Title formats the details of a character, for example for lily it would return -- Lily is a Human Paladin who carries a weapon: +1 Sword of smiting and nothing else title : Character -> String title character = ? main = title lily |> text
true
-- Copy paste this into Try Elm (http://elm-lang.org/try) and fill in the missing parts import Html exposing (text) type Class = Fighter | Paladin | Ranger | Mage | Cleric | Druid | Thief | Bard type Race = Dwarf | Elf | Gnome | HalfElf | Halfling | Human type alias Item = { name : String , itemType : ItemType } type ItemType = Weapon | Shield | Other type alias Character = { name : String , class : Class , race : Race , mainItem : Maybe Item , offHandItem : Maybe Item } lily = { name = "PI:NAME:<NAME>END_PI" , class = Paladin , race = Human , mainItem = Just { name = "+1 Sword of smiting" , itemType = Weapon } , offHandItem = Nothing } max = { name = "PI:NAME:<NAME>END_PI" , class = Mage , race = HalfElf , mainItem = Just { name = "Wizardly wand of wizardry" , itemType = Weapon } , offHandItem = Just { name = "Book of spells" , itemType = Other } } showClass : Class -> String showClass class = ? showRace : Race -> String showRace race = ? showItem : Item -> String showItem item = ? -- Title formats the details of a character, for example for lily it would return -- Lily is a Human Paladin who carries a weapon: +1 Sword of smiting and nothing else title : Character -> String title character = ? main = title lily |> text
elm
[ { "context": ")\n , ( [ \"name\" ], String \"Alyss Hambrick\" )\n , ( [ \"address\", \"city", "end": 3110, "score": 0.9998980165, "start": 3096, "tag": "NAME", "value": "Alyss Hambrick" }, { "context": " ],\n \"alive\": true,\n \"name\": \"Alyss Hambrick\",\n \"address\": {\n \"city\": \"San J", "end": 3876, "score": 0.9999005198, "start": 3862, "tag": "NAME", "value": "Alyss Hambrick" }, { "context": "live\", Boolean True )\n , ( \"name\", String \"Alyss Hambrick\" )\n , ( \"address\"\n , Object\n ", "end": 4219, "score": 0.9998998046, "start": 4205, "tag": "NAME", "value": "Alyss Hambrick" } ]
tests/Tests/JsonTree.elm
MichaelCombs28/json-tree
0
module Tests.JsonTree exposing (suite, testJSON) import Dict import Expect exposing (Expectation) import Fuzz exposing (Fuzzer, int, list, string) import Json.Decode import Json.Encode import Json.Tree exposing (Tree(..)) import Test exposing (..) suite : Test suite = describe "Test cases for json-tree" [ test "Test decode" <| \_ -> Json.Decode.decodeString Json.Tree.decode testJSON |> Result.mapError Json.Decode.errorToString |> fromResult jsonTree , test "Test encode" <| \_ -> Json.Tree.encode (Json.Tree.Array [ jsonElement ]) |> Json.Encode.encode 4 |> Expect.equal testJSON , test "Test get normal field" <| \_ -> Json.Tree.get [ "id" ] jsonElement |> fromResult (Number 1) , test "Test get nested field" <| \_ -> Json.Tree.get [ "address", "city" ] jsonElement |> fromResult (String "San Jose") , test "Test get within array" <| \_ -> Json.Tree.get [ "0", "interests", "1" ] jsonTree |> fromResult (String "programming") , test "Test put within object." <| \_ -> Json.Tree.put [ "0", "interests", "0" ] (String "cars") jsonTree |> Result.andThen (Json.Tree.get [ "0", "interests", "0" ]) |> fromResult (String "cars") , test "Test height" <| \_ -> Json.Tree.height jsonTree |> Expect.equal 4 , test "Test traverse" <| \_ -> Json.Tree.traverse jsonTree |> Expect.equal [ [] , [ "0" ] , [ "0", "id" ] , [ "0", "interests" ] , [ "0", "interests", "0" ] , [ "0", "interests", "1" ] , [ "0", "alive" ] , [ "0", "name" ] , [ "0", "address" ] , [ "0", "address", "city" ] , [ "0", "address", "street" ] ] , test "Test fold" <| \_ -> let transform queue node acc = if Json.Tree.isObject node || Json.Tree.isArray node || Json.Tree.isNull node then acc else Dict.insert queue node acc expectation = [ ( [ "id" ], Number 1 ) , ( [ "interests", "0" ], String "school" ) , ( [ "interests", "1" ], String "programming" ) , ( [ "alive" ], Boolean True ) , ( [ "name" ], String "Alyss Hambrick" ) , ( [ "address", "city" ], String "San Jose" ) , ( [ "address", "street" ], String "900 South 1st" ) ] |> Dict.fromList in Json.Tree.foldl transform Dict.empty jsonElement |> Expect.equal expectation ] fromResult : a -> Result String a -> Expectation fromResult expectation result = case result of Ok a -> Expect.equal expectation a Err e -> Expect.fail e testJSON : String testJSON = """[ { "id": 1, "interests": [ "school", "programming" ], "alive": true, "name": "Alyss Hambrick", "address": { "city": "San Jose", "street": "900 South 1st" } } ]""" jsonElement : Tree jsonElement = Object [ ( "id", Number 1 ) , ( "interests", Array [ String "school", String "programming" ] ) , ( "alive", Boolean True ) , ( "name", String "Alyss Hambrick" ) , ( "address" , Object [ ( "city", String "San Jose" ) , ( "street", String "900 South 1st" ) ] ) ] jsonTree : Tree jsonTree = Array [ jsonElement ]
55176
module Tests.JsonTree exposing (suite, testJSON) import Dict import Expect exposing (Expectation) import Fuzz exposing (Fuzzer, int, list, string) import Json.Decode import Json.Encode import Json.Tree exposing (Tree(..)) import Test exposing (..) suite : Test suite = describe "Test cases for json-tree" [ test "Test decode" <| \_ -> Json.Decode.decodeString Json.Tree.decode testJSON |> Result.mapError Json.Decode.errorToString |> fromResult jsonTree , test "Test encode" <| \_ -> Json.Tree.encode (Json.Tree.Array [ jsonElement ]) |> Json.Encode.encode 4 |> Expect.equal testJSON , test "Test get normal field" <| \_ -> Json.Tree.get [ "id" ] jsonElement |> fromResult (Number 1) , test "Test get nested field" <| \_ -> Json.Tree.get [ "address", "city" ] jsonElement |> fromResult (String "San Jose") , test "Test get within array" <| \_ -> Json.Tree.get [ "0", "interests", "1" ] jsonTree |> fromResult (String "programming") , test "Test put within object." <| \_ -> Json.Tree.put [ "0", "interests", "0" ] (String "cars") jsonTree |> Result.andThen (Json.Tree.get [ "0", "interests", "0" ]) |> fromResult (String "cars") , test "Test height" <| \_ -> Json.Tree.height jsonTree |> Expect.equal 4 , test "Test traverse" <| \_ -> Json.Tree.traverse jsonTree |> Expect.equal [ [] , [ "0" ] , [ "0", "id" ] , [ "0", "interests" ] , [ "0", "interests", "0" ] , [ "0", "interests", "1" ] , [ "0", "alive" ] , [ "0", "name" ] , [ "0", "address" ] , [ "0", "address", "city" ] , [ "0", "address", "street" ] ] , test "Test fold" <| \_ -> let transform queue node acc = if Json.Tree.isObject node || Json.Tree.isArray node || Json.Tree.isNull node then acc else Dict.insert queue node acc expectation = [ ( [ "id" ], Number 1 ) , ( [ "interests", "0" ], String "school" ) , ( [ "interests", "1" ], String "programming" ) , ( [ "alive" ], Boolean True ) , ( [ "name" ], String "<NAME>" ) , ( [ "address", "city" ], String "San Jose" ) , ( [ "address", "street" ], String "900 South 1st" ) ] |> Dict.fromList in Json.Tree.foldl transform Dict.empty jsonElement |> Expect.equal expectation ] fromResult : a -> Result String a -> Expectation fromResult expectation result = case result of Ok a -> Expect.equal expectation a Err e -> Expect.fail e testJSON : String testJSON = """[ { "id": 1, "interests": [ "school", "programming" ], "alive": true, "name": "<NAME>", "address": { "city": "San Jose", "street": "900 South 1st" } } ]""" jsonElement : Tree jsonElement = Object [ ( "id", Number 1 ) , ( "interests", Array [ String "school", String "programming" ] ) , ( "alive", Boolean True ) , ( "name", String "<NAME>" ) , ( "address" , Object [ ( "city", String "San Jose" ) , ( "street", String "900 South 1st" ) ] ) ] jsonTree : Tree jsonTree = Array [ jsonElement ]
true
module Tests.JsonTree exposing (suite, testJSON) import Dict import Expect exposing (Expectation) import Fuzz exposing (Fuzzer, int, list, string) import Json.Decode import Json.Encode import Json.Tree exposing (Tree(..)) import Test exposing (..) suite : Test suite = describe "Test cases for json-tree" [ test "Test decode" <| \_ -> Json.Decode.decodeString Json.Tree.decode testJSON |> Result.mapError Json.Decode.errorToString |> fromResult jsonTree , test "Test encode" <| \_ -> Json.Tree.encode (Json.Tree.Array [ jsonElement ]) |> Json.Encode.encode 4 |> Expect.equal testJSON , test "Test get normal field" <| \_ -> Json.Tree.get [ "id" ] jsonElement |> fromResult (Number 1) , test "Test get nested field" <| \_ -> Json.Tree.get [ "address", "city" ] jsonElement |> fromResult (String "San Jose") , test "Test get within array" <| \_ -> Json.Tree.get [ "0", "interests", "1" ] jsonTree |> fromResult (String "programming") , test "Test put within object." <| \_ -> Json.Tree.put [ "0", "interests", "0" ] (String "cars") jsonTree |> Result.andThen (Json.Tree.get [ "0", "interests", "0" ]) |> fromResult (String "cars") , test "Test height" <| \_ -> Json.Tree.height jsonTree |> Expect.equal 4 , test "Test traverse" <| \_ -> Json.Tree.traverse jsonTree |> Expect.equal [ [] , [ "0" ] , [ "0", "id" ] , [ "0", "interests" ] , [ "0", "interests", "0" ] , [ "0", "interests", "1" ] , [ "0", "alive" ] , [ "0", "name" ] , [ "0", "address" ] , [ "0", "address", "city" ] , [ "0", "address", "street" ] ] , test "Test fold" <| \_ -> let transform queue node acc = if Json.Tree.isObject node || Json.Tree.isArray node || Json.Tree.isNull node then acc else Dict.insert queue node acc expectation = [ ( [ "id" ], Number 1 ) , ( [ "interests", "0" ], String "school" ) , ( [ "interests", "1" ], String "programming" ) , ( [ "alive" ], Boolean True ) , ( [ "name" ], String "PI:NAME:<NAME>END_PI" ) , ( [ "address", "city" ], String "San Jose" ) , ( [ "address", "street" ], String "900 South 1st" ) ] |> Dict.fromList in Json.Tree.foldl transform Dict.empty jsonElement |> Expect.equal expectation ] fromResult : a -> Result String a -> Expectation fromResult expectation result = case result of Ok a -> Expect.equal expectation a Err e -> Expect.fail e testJSON : String testJSON = """[ { "id": 1, "interests": [ "school", "programming" ], "alive": true, "name": "PI:NAME:<NAME>END_PI", "address": { "city": "San Jose", "street": "900 South 1st" } } ]""" jsonElement : Tree jsonElement = Object [ ( "id", Number 1 ) , ( "interests", Array [ String "school", String "programming" ] ) , ( "alive", Boolean True ) , ( "name", String "PI:NAME:<NAME>END_PI" ) , ( "address" , Object [ ( "city", String "San Jose" ) , ( "street", String "900 South 1st" ) ] ) ] jsonTree : Tree jsonTree = Array [ jsonElement ]
elm
[ { "context": "s on User {\n id\n email\n firstName\n lastName\n handle\n ava", "end": 902, "score": 0.634446919, "start": 893, "tag": "NAME", "value": "firstName" }, { "context": " id\n email\n firstName\n lastName\n handle\n avatarUrl\n ti", "end": 921, "score": 0.9379181266, "start": 913, "tag": "NAME", "value": "lastName" } ]
assets/elm/src/User.elm
mindriot101/level
928
module User exposing (User, avatar, avatarUrl, decoder, displayName, email, firstName, fragment, handle, hasChosenHandle, hasPassword, id, isDemo, lastName, timeZone) import Avatar import GraphQL exposing (Fragment) import Html exposing (Html) import Id exposing (Id) import Json.Decode as Decode exposing (Decoder, bool, fail, field, int, maybe, string, succeed) import Json.Decode.Pipeline as Pipeline exposing (required) -- TYPES type User = User Data type alias Data = { id : Id , email : String , firstName : String , lastName : String , handle : String , avatarUrl : Maybe String , timeZone : String , isDemo : Bool , hasPassword : Bool , hasChosenHandle : Bool , fetchedAt : Int } fragment : Fragment fragment = GraphQL.toFragment """ fragment UserFields on User { id email firstName lastName handle avatarUrl timeZone isDemo hasPassword hasChosenHandle fetchedAt } """ [] -- ACCESSORS id : User -> Id id (User data) = data.id email : User -> String email (User data) = data.email firstName : User -> String firstName (User data) = data.firstName lastName : User -> String lastName (User data) = data.lastName handle : User -> String handle (User data) = data.handle timeZone : User -> String timeZone (User data) = data.timeZone avatarUrl : User -> Maybe String avatarUrl (User data) = data.avatarUrl displayName : User -> String displayName (User data) = data.firstName ++ " " ++ data.lastName avatar : Avatar.Size -> User -> Html msg avatar size (User data) = Avatar.personAvatar size data isDemo : User -> Bool isDemo (User data) = data.isDemo hasPassword : User -> Bool hasPassword (User data) = data.hasPassword hasChosenHandle : User -> Bool hasChosenHandle (User data) = data.hasChosenHandle -- DECODERS decoder : Decoder User decoder = Decode.map User (Decode.succeed Data |> required "id" Id.decoder |> required "email" string |> required "firstName" string |> required "lastName" string |> required "handle" string |> required "avatarUrl" (maybe string) |> required "timeZone" string |> required "isDemo" bool |> required "hasPassword" bool |> required "hasChosenHandle" bool |> required "fetchedAt" int )
31176
module User exposing (User, avatar, avatarUrl, decoder, displayName, email, firstName, fragment, handle, hasChosenHandle, hasPassword, id, isDemo, lastName, timeZone) import Avatar import GraphQL exposing (Fragment) import Html exposing (Html) import Id exposing (Id) import Json.Decode as Decode exposing (Decoder, bool, fail, field, int, maybe, string, succeed) import Json.Decode.Pipeline as Pipeline exposing (required) -- TYPES type User = User Data type alias Data = { id : Id , email : String , firstName : String , lastName : String , handle : String , avatarUrl : Maybe String , timeZone : String , isDemo : Bool , hasPassword : Bool , hasChosenHandle : Bool , fetchedAt : Int } fragment : Fragment fragment = GraphQL.toFragment """ fragment UserFields on User { id email <NAME> <NAME> handle avatarUrl timeZone isDemo hasPassword hasChosenHandle fetchedAt } """ [] -- ACCESSORS id : User -> Id id (User data) = data.id email : User -> String email (User data) = data.email firstName : User -> String firstName (User data) = data.firstName lastName : User -> String lastName (User data) = data.lastName handle : User -> String handle (User data) = data.handle timeZone : User -> String timeZone (User data) = data.timeZone avatarUrl : User -> Maybe String avatarUrl (User data) = data.avatarUrl displayName : User -> String displayName (User data) = data.firstName ++ " " ++ data.lastName avatar : Avatar.Size -> User -> Html msg avatar size (User data) = Avatar.personAvatar size data isDemo : User -> Bool isDemo (User data) = data.isDemo hasPassword : User -> Bool hasPassword (User data) = data.hasPassword hasChosenHandle : User -> Bool hasChosenHandle (User data) = data.hasChosenHandle -- DECODERS decoder : Decoder User decoder = Decode.map User (Decode.succeed Data |> required "id" Id.decoder |> required "email" string |> required "firstName" string |> required "lastName" string |> required "handle" string |> required "avatarUrl" (maybe string) |> required "timeZone" string |> required "isDemo" bool |> required "hasPassword" bool |> required "hasChosenHandle" bool |> required "fetchedAt" int )
true
module User exposing (User, avatar, avatarUrl, decoder, displayName, email, firstName, fragment, handle, hasChosenHandle, hasPassword, id, isDemo, lastName, timeZone) import Avatar import GraphQL exposing (Fragment) import Html exposing (Html) import Id exposing (Id) import Json.Decode as Decode exposing (Decoder, bool, fail, field, int, maybe, string, succeed) import Json.Decode.Pipeline as Pipeline exposing (required) -- TYPES type User = User Data type alias Data = { id : Id , email : String , firstName : String , lastName : String , handle : String , avatarUrl : Maybe String , timeZone : String , isDemo : Bool , hasPassword : Bool , hasChosenHandle : Bool , fetchedAt : Int } fragment : Fragment fragment = GraphQL.toFragment """ fragment UserFields on User { id email PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI handle avatarUrl timeZone isDemo hasPassword hasChosenHandle fetchedAt } """ [] -- ACCESSORS id : User -> Id id (User data) = data.id email : User -> String email (User data) = data.email firstName : User -> String firstName (User data) = data.firstName lastName : User -> String lastName (User data) = data.lastName handle : User -> String handle (User data) = data.handle timeZone : User -> String timeZone (User data) = data.timeZone avatarUrl : User -> Maybe String avatarUrl (User data) = data.avatarUrl displayName : User -> String displayName (User data) = data.firstName ++ " " ++ data.lastName avatar : Avatar.Size -> User -> Html msg avatar size (User data) = Avatar.personAvatar size data isDemo : User -> Bool isDemo (User data) = data.isDemo hasPassword : User -> Bool hasPassword (User data) = data.hasPassword hasChosenHandle : User -> Bool hasChosenHandle (User data) = data.hasChosenHandle -- DECODERS decoder : Decoder User decoder = Decode.map User (Decode.succeed Data |> required "id" Id.decoder |> required "email" string |> required "firstName" string |> required "lastName" string |> required "handle" string |> required "avatarUrl" (maybe string) |> required "timeZone" string |> required "isDemo" bool |> required "hasPassword" bool |> required "hasChosenHandle" bool |> required "fetchedAt" int )
elm
[ { "context": "ple for HtmlTemplate module.\n-- Copyright (c) 2017 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n", "end": 162, "score": 0.9998688698, "start": 148, "tag": "NAME", "value": "Bill St. Clair" }, { "context": "ate module.\n-- Copyright (c) 2017 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n-- Distributed under th", "end": 185, "score": 0.9999330044, "start": 164, "tag": "EMAIL", "value": "billstclair@gmail.com" } ]
examples/template.elm
billstclair/elm-html-template
6
---------------------------------------------------------------------- -- -- template.elm -- Example for HtmlTemplate module. -- Copyright (c) 2017 Bill St. Clair <billstclair@gmail.com> -- Some rights reserved. -- Distributed under the MIT License -- See LICENSE.txt -- ---------------------------------------------------------------------- module Main exposing (..) import HtmlTemplate exposing ( makeLoaders, insertFunctions, insertMessages , addPageProcessors , getExtra, setExtra, getDicts , addOutstandingPagesAndTemplates , loadPage, receivePage, loadTemplate, receiveTemplate , loadOutstandingPageOrTemplate , maybeLoadOutstandingPageOrTemplate , getPage, setPage, removePage , getTemplate , getAtom, setAtom, setAtoms, getDictsAtom , clearPages , render, eval , cantFuncall ) import HtmlTemplate.EncodeDecode exposing ( decodeAtom, encodeAtom, customEncodeAtom ) import HtmlTemplate.Types exposing ( Loaders, Atom(..), Dicts ) import HtmlTemplate.PlayDiv exposing ( PlayState, emptyPlayState , playDivFunction , Update, playStringUpdate, updatePlayState ) import Html exposing ( Html, Attribute , div, p, text, a, textarea, pre ) import Html.Attributes as Attributes exposing ( style, href, rows, cols, class ) import Html.Events exposing ( onClick, onInput ) import Http log = Debug.log main = Html.program { init = init , view = view , update = update , subscriptions = (\x -> Sub.none) } type alias Model = { loaders: Loaders Msg Extra , page: Maybe String , pendingPage : Maybe String , playState : PlayState Msg , error : Maybe String } templateDirs : List String templateDirs = [ "default", "black", "red" ] settingsFile : String settingsFile = "settings" settingsPageName : String settingsPageName = "_settings" indexTemplate : String indexTemplate = "index" pageTemplate : String pageTemplate = "page" nodeTemplate : String nodeTemplate = "node" initialTemplates : List String initialTemplates = [ pageTemplate, indexTemplate, nodeTemplate ] indexPage : String indexPage = "index" initialPages : List String initialPages = [ settingsPageName, indexPage ] postTemplate : String postTemplate = "post" templateFileType : String templateFileType = ".json" templateFilename : String -> String templateFilename name = name ++ templateFileType gotoPageFunction : List (Atom Msg) -> d -> Msg gotoPageFunction args _ = case args of [StringAtom page] -> GotoPage page _ -> SetError <| "Can't go to page: " ++ (toString args) messages : List (String, List (Atom Msg) -> Dicts Msg -> Msg) messages = [ ( "gotoPage", gotoPageFunction ) ] pageLinkFunction : List (Atom Msg) -> d -> Atom Msg pageLinkFunction args _ = case normalizePageLinkArgs args of Just ( page, title ) -> HtmlAtom <| a [ href "#" , onClick <| GotoPage page ] [ text title ] _ -> cantFuncall "pageLink" args normalizePageLinkArgs : List (Atom Msg) -> Maybe (String, String) normalizePageLinkArgs atom = case atom of [ StringAtom page ] -> Just (page, page) [ StringAtom page, StringAtom title ] -> Just (page, title) _ -> Nothing functions : List (String, List (Atom Msg) -> Dicts Msg -> Atom Msg) functions = [ ( "pageLink", pageLinkFunction ) ] type alias Extra = { templateDir : String } initialExtra : Extra initialExtra = { templateDir = "default" } pageProcessors : List (String, String -> Atom Msg -> Loaders Msg Extra -> Loaders Msg Extra) pageProcessors = [ ( settingsPageName, installSettings ) , ( "", add_page_Property ) ] initialLoaders : Loaders Msg Extra initialLoaders = makeLoaders fetchTemplate fetchPage initialExtra |> insertFunctions functions |> insertMessages messages |> addPageProcessors pageProcessors |> addOutstandingPagesAndTemplates initialPages initialTemplates --- --- init --- init : ( Model, Cmd Msg) init = let (model, _) = updatePlayString (playStringUpdate "\"Hello HtmlTemplate!\"") { loaders = initialLoaders , page = Nothing , pendingPage = Just indexPage , playState = emptyPlayState , error = Nothing } in ( model , loadOutstandingPageOrTemplate model.loaders ) -- Store just-loaded "settings" plist as an atom, and remove it as a page. -- The pages reference it as "$settings.<property>". installSettings : String -> Atom Msg -> Loaders Msg Extra -> Loaders Msg Extra installSettings name settings loaders = setAtom settingsFile settings <| removePage name loaders -- The value of most pages is a plist processed by the "node" template. -- This adds the page's own name to its plist when it's loaded. add_page_Property : String -> Atom Msg -> Loaders Msg Extra -> Loaders Msg Extra add_page_Property name page loaders = case page of PListAtom plist -> setPage name (PListAtom <| ("page", StringAtom name) :: plist) loaders _ -> loaders type Msg = TemplateFetchDone String (Loaders Msg Extra) (Result Http.Error String) | PageFetchDone String (Loaders Msg Extra) (Result Http.Error String) | GotoPage String | UpdatePlayState Update | SetError String fetchUrl : String -> ((Result Http.Error String) -> Msg) -> Cmd Msg fetchUrl url wrapper = Http.send wrapper <| httpGetString (log "Getting URL" url) httpGetString : String -> Http.Request String httpGetString url = Http.request { method = "GET" , headers = [ Http.header "Cache-control" "no-cache" ] , url = url , body = Http.emptyBody , expect = Http.expectString , timeout = Nothing , withCredentials = False } templateDir : Loaders Msg Extra -> String templateDir loaders = .templateDir <| getExtra loaders fetchTemplate : String -> Loaders Msg Extra -> Cmd Msg fetchTemplate name loaders = let filename = templateFilename name url = "template/" ++ (templateDir loaders) ++ "/" ++ filename in fetchUrl url <| TemplateFetchDone name loaders fetchPage : String -> Loaders Msg Extra -> Cmd Msg fetchPage name loaders = let url = if name == settingsPageName then templateFilename settingsFile else "page/" ++ (templateFilename name) in fetchUrl url <| PageFetchDone name loaders --- --- update --- update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of TemplateFetchDone name loaders result -> templateFetchDone name loaders result model PageFetchDone name loaders result -> pageFetchDone name loaders result model GotoPage page -> gotoPage page model UpdatePlayState update -> updatePlayString update model SetError message -> ( { model | error = Just message } , Cmd.none ) gotoPage : String -> Model -> ( Model, Cmd Msg ) gotoPage page model = let m = { model | error = Nothing , pendingPage = Just page } in ( m , fetchPage page <| clearPages model.loaders ) templateFetchDone : String -> Loaders Msg Extra -> Result Http.Error String -> Model -> ( Model, Cmd Msg ) templateFetchDone name loaders result model = case result of Err err -> ( { model | error = Just <| "Error fetching template " ++ name ++ ": " ++ (toString err) } , Cmd.none ) Ok json -> case receiveTemplate name json loaders of Err msg -> ( { model | loaders = loaders , error = Just <| "While parsing template \"" ++ name ++ "\": " ++ msg } , Cmd.none ) Ok loaders2 -> continueLoading loaders2 model continueLoading : Loaders Msg Extra -> Model -> ( Model, Cmd Msg ) continueLoading loaders model = case maybeLoadOutstandingPageOrTemplate loaders of Just cmd -> -- Do NOT update model.loaders yet, or the screen flashes ( model, cmd ) Nothing -> let m = { model | loaders = loaders } in ( case m.pendingPage of Nothing -> m Just page -> { m | page = Just page , pendingPage = Nothing , loaders = case m.page of Nothing -> loaders Just referer -> setAtom "referer" (StringAtom referer) loaders } , Cmd.none ) pageFetchDone : String -> Loaders Msg Extra -> Result Http.Error String -> Model -> ( Model, Cmd Msg ) pageFetchDone name loaders result model = case result of Err err -> ( { model | error = Just <| "Error fetching page " ++ name ++ ": " ++ (toString err) } , Cmd.none ) Ok json -> case receivePage name json loaders of Err msg -> ( { model | error = Just <| ("While loading page \"" ++ name ++ "\": " ++ msg) } , Cmd.none ) Ok loaders2 -> continueLoading loaders2 model updatePlayString : Update -> Model -> ( Model, Cmd Msg ) updatePlayString update model = ( { model | playState = updatePlayState update model.loaders model.playState } , Cmd.none ) --- --- view ---- view : Model -> Html Msg view model = div [] [ case model.error of Just err -> p [ style [ ( "color", "red" ) ] ] [ text err ] Nothing -> text "" , case model.page of Nothing -> text "" Just page -> let loaders = insertFunctions [ ( "playDiv" , playDivFunction UpdatePlayState model.playState ) ] model.loaders template = pageTemplate content = (LookupTemplateAtom <| if page == "index" then indexTemplate else nodeTemplate ) in case getTemplate template loaders of Nothing -> dictsDiv "Template" template loaders Just tmpl -> case getPage page loaders of Nothing -> dictsDiv "Page" page loaders Just atom -> let loaders2 = setAtoms [ ("node", atom) , ("content", content) , ("page", StringAtom page) ] loaders in render tmpl loaders2 ] dictsDiv : String -> String -> Loaders Msg Extra -> Html Msg dictsDiv thing page loaders = div [] [ p [] [ text <| thing ++ " not found: " ++ page ] , p [] [ a [ href "template/" ] [ text "template/"] ] , p [] [ text "dicts:" , br , text <| toString <| getDicts loaders ] ] br : Html Msg br = Html.br [] []
54311
---------------------------------------------------------------------- -- -- template.elm -- Example for HtmlTemplate module. -- Copyright (c) 2017 <NAME> <<EMAIL>> -- Some rights reserved. -- Distributed under the MIT License -- See LICENSE.txt -- ---------------------------------------------------------------------- module Main exposing (..) import HtmlTemplate exposing ( makeLoaders, insertFunctions, insertMessages , addPageProcessors , getExtra, setExtra, getDicts , addOutstandingPagesAndTemplates , loadPage, receivePage, loadTemplate, receiveTemplate , loadOutstandingPageOrTemplate , maybeLoadOutstandingPageOrTemplate , getPage, setPage, removePage , getTemplate , getAtom, setAtom, setAtoms, getDictsAtom , clearPages , render, eval , cantFuncall ) import HtmlTemplate.EncodeDecode exposing ( decodeAtom, encodeAtom, customEncodeAtom ) import HtmlTemplate.Types exposing ( Loaders, Atom(..), Dicts ) import HtmlTemplate.PlayDiv exposing ( PlayState, emptyPlayState , playDivFunction , Update, playStringUpdate, updatePlayState ) import Html exposing ( Html, Attribute , div, p, text, a, textarea, pre ) import Html.Attributes as Attributes exposing ( style, href, rows, cols, class ) import Html.Events exposing ( onClick, onInput ) import Http log = Debug.log main = Html.program { init = init , view = view , update = update , subscriptions = (\x -> Sub.none) } type alias Model = { loaders: Loaders Msg Extra , page: Maybe String , pendingPage : Maybe String , playState : PlayState Msg , error : Maybe String } templateDirs : List String templateDirs = [ "default", "black", "red" ] settingsFile : String settingsFile = "settings" settingsPageName : String settingsPageName = "_settings" indexTemplate : String indexTemplate = "index" pageTemplate : String pageTemplate = "page" nodeTemplate : String nodeTemplate = "node" initialTemplates : List String initialTemplates = [ pageTemplate, indexTemplate, nodeTemplate ] indexPage : String indexPage = "index" initialPages : List String initialPages = [ settingsPageName, indexPage ] postTemplate : String postTemplate = "post" templateFileType : String templateFileType = ".json" templateFilename : String -> String templateFilename name = name ++ templateFileType gotoPageFunction : List (Atom Msg) -> d -> Msg gotoPageFunction args _ = case args of [StringAtom page] -> GotoPage page _ -> SetError <| "Can't go to page: " ++ (toString args) messages : List (String, List (Atom Msg) -> Dicts Msg -> Msg) messages = [ ( "gotoPage", gotoPageFunction ) ] pageLinkFunction : List (Atom Msg) -> d -> Atom Msg pageLinkFunction args _ = case normalizePageLinkArgs args of Just ( page, title ) -> HtmlAtom <| a [ href "#" , onClick <| GotoPage page ] [ text title ] _ -> cantFuncall "pageLink" args normalizePageLinkArgs : List (Atom Msg) -> Maybe (String, String) normalizePageLinkArgs atom = case atom of [ StringAtom page ] -> Just (page, page) [ StringAtom page, StringAtom title ] -> Just (page, title) _ -> Nothing functions : List (String, List (Atom Msg) -> Dicts Msg -> Atom Msg) functions = [ ( "pageLink", pageLinkFunction ) ] type alias Extra = { templateDir : String } initialExtra : Extra initialExtra = { templateDir = "default" } pageProcessors : List (String, String -> Atom Msg -> Loaders Msg Extra -> Loaders Msg Extra) pageProcessors = [ ( settingsPageName, installSettings ) , ( "", add_page_Property ) ] initialLoaders : Loaders Msg Extra initialLoaders = makeLoaders fetchTemplate fetchPage initialExtra |> insertFunctions functions |> insertMessages messages |> addPageProcessors pageProcessors |> addOutstandingPagesAndTemplates initialPages initialTemplates --- --- init --- init : ( Model, Cmd Msg) init = let (model, _) = updatePlayString (playStringUpdate "\"Hello HtmlTemplate!\"") { loaders = initialLoaders , page = Nothing , pendingPage = Just indexPage , playState = emptyPlayState , error = Nothing } in ( model , loadOutstandingPageOrTemplate model.loaders ) -- Store just-loaded "settings" plist as an atom, and remove it as a page. -- The pages reference it as "$settings.<property>". installSettings : String -> Atom Msg -> Loaders Msg Extra -> Loaders Msg Extra installSettings name settings loaders = setAtom settingsFile settings <| removePage name loaders -- The value of most pages is a plist processed by the "node" template. -- This adds the page's own name to its plist when it's loaded. add_page_Property : String -> Atom Msg -> Loaders Msg Extra -> Loaders Msg Extra add_page_Property name page loaders = case page of PListAtom plist -> setPage name (PListAtom <| ("page", StringAtom name) :: plist) loaders _ -> loaders type Msg = TemplateFetchDone String (Loaders Msg Extra) (Result Http.Error String) | PageFetchDone String (Loaders Msg Extra) (Result Http.Error String) | GotoPage String | UpdatePlayState Update | SetError String fetchUrl : String -> ((Result Http.Error String) -> Msg) -> Cmd Msg fetchUrl url wrapper = Http.send wrapper <| httpGetString (log "Getting URL" url) httpGetString : String -> Http.Request String httpGetString url = Http.request { method = "GET" , headers = [ Http.header "Cache-control" "no-cache" ] , url = url , body = Http.emptyBody , expect = Http.expectString , timeout = Nothing , withCredentials = False } templateDir : Loaders Msg Extra -> String templateDir loaders = .templateDir <| getExtra loaders fetchTemplate : String -> Loaders Msg Extra -> Cmd Msg fetchTemplate name loaders = let filename = templateFilename name url = "template/" ++ (templateDir loaders) ++ "/" ++ filename in fetchUrl url <| TemplateFetchDone name loaders fetchPage : String -> Loaders Msg Extra -> Cmd Msg fetchPage name loaders = let url = if name == settingsPageName then templateFilename settingsFile else "page/" ++ (templateFilename name) in fetchUrl url <| PageFetchDone name loaders --- --- update --- update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of TemplateFetchDone name loaders result -> templateFetchDone name loaders result model PageFetchDone name loaders result -> pageFetchDone name loaders result model GotoPage page -> gotoPage page model UpdatePlayState update -> updatePlayString update model SetError message -> ( { model | error = Just message } , Cmd.none ) gotoPage : String -> Model -> ( Model, Cmd Msg ) gotoPage page model = let m = { model | error = Nothing , pendingPage = Just page } in ( m , fetchPage page <| clearPages model.loaders ) templateFetchDone : String -> Loaders Msg Extra -> Result Http.Error String -> Model -> ( Model, Cmd Msg ) templateFetchDone name loaders result model = case result of Err err -> ( { model | error = Just <| "Error fetching template " ++ name ++ ": " ++ (toString err) } , Cmd.none ) Ok json -> case receiveTemplate name json loaders of Err msg -> ( { model | loaders = loaders , error = Just <| "While parsing template \"" ++ name ++ "\": " ++ msg } , Cmd.none ) Ok loaders2 -> continueLoading loaders2 model continueLoading : Loaders Msg Extra -> Model -> ( Model, Cmd Msg ) continueLoading loaders model = case maybeLoadOutstandingPageOrTemplate loaders of Just cmd -> -- Do NOT update model.loaders yet, or the screen flashes ( model, cmd ) Nothing -> let m = { model | loaders = loaders } in ( case m.pendingPage of Nothing -> m Just page -> { m | page = Just page , pendingPage = Nothing , loaders = case m.page of Nothing -> loaders Just referer -> setAtom "referer" (StringAtom referer) loaders } , Cmd.none ) pageFetchDone : String -> Loaders Msg Extra -> Result Http.Error String -> Model -> ( Model, Cmd Msg ) pageFetchDone name loaders result model = case result of Err err -> ( { model | error = Just <| "Error fetching page " ++ name ++ ": " ++ (toString err) } , Cmd.none ) Ok json -> case receivePage name json loaders of Err msg -> ( { model | error = Just <| ("While loading page \"" ++ name ++ "\": " ++ msg) } , Cmd.none ) Ok loaders2 -> continueLoading loaders2 model updatePlayString : Update -> Model -> ( Model, Cmd Msg ) updatePlayString update model = ( { model | playState = updatePlayState update model.loaders model.playState } , Cmd.none ) --- --- view ---- view : Model -> Html Msg view model = div [] [ case model.error of Just err -> p [ style [ ( "color", "red" ) ] ] [ text err ] Nothing -> text "" , case model.page of Nothing -> text "" Just page -> let loaders = insertFunctions [ ( "playDiv" , playDivFunction UpdatePlayState model.playState ) ] model.loaders template = pageTemplate content = (LookupTemplateAtom <| if page == "index" then indexTemplate else nodeTemplate ) in case getTemplate template loaders of Nothing -> dictsDiv "Template" template loaders Just tmpl -> case getPage page loaders of Nothing -> dictsDiv "Page" page loaders Just atom -> let loaders2 = setAtoms [ ("node", atom) , ("content", content) , ("page", StringAtom page) ] loaders in render tmpl loaders2 ] dictsDiv : String -> String -> Loaders Msg Extra -> Html Msg dictsDiv thing page loaders = div [] [ p [] [ text <| thing ++ " not found: " ++ page ] , p [] [ a [ href "template/" ] [ text "template/"] ] , p [] [ text "dicts:" , br , text <| toString <| getDicts loaders ] ] br : Html Msg br = Html.br [] []
true
---------------------------------------------------------------------- -- -- template.elm -- Example for HtmlTemplate module. -- 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 Main exposing (..) import HtmlTemplate exposing ( makeLoaders, insertFunctions, insertMessages , addPageProcessors , getExtra, setExtra, getDicts , addOutstandingPagesAndTemplates , loadPage, receivePage, loadTemplate, receiveTemplate , loadOutstandingPageOrTemplate , maybeLoadOutstandingPageOrTemplate , getPage, setPage, removePage , getTemplate , getAtom, setAtom, setAtoms, getDictsAtom , clearPages , render, eval , cantFuncall ) import HtmlTemplate.EncodeDecode exposing ( decodeAtom, encodeAtom, customEncodeAtom ) import HtmlTemplate.Types exposing ( Loaders, Atom(..), Dicts ) import HtmlTemplate.PlayDiv exposing ( PlayState, emptyPlayState , playDivFunction , Update, playStringUpdate, updatePlayState ) import Html exposing ( Html, Attribute , div, p, text, a, textarea, pre ) import Html.Attributes as Attributes exposing ( style, href, rows, cols, class ) import Html.Events exposing ( onClick, onInput ) import Http log = Debug.log main = Html.program { init = init , view = view , update = update , subscriptions = (\x -> Sub.none) } type alias Model = { loaders: Loaders Msg Extra , page: Maybe String , pendingPage : Maybe String , playState : PlayState Msg , error : Maybe String } templateDirs : List String templateDirs = [ "default", "black", "red" ] settingsFile : String settingsFile = "settings" settingsPageName : String settingsPageName = "_settings" indexTemplate : String indexTemplate = "index" pageTemplate : String pageTemplate = "page" nodeTemplate : String nodeTemplate = "node" initialTemplates : List String initialTemplates = [ pageTemplate, indexTemplate, nodeTemplate ] indexPage : String indexPage = "index" initialPages : List String initialPages = [ settingsPageName, indexPage ] postTemplate : String postTemplate = "post" templateFileType : String templateFileType = ".json" templateFilename : String -> String templateFilename name = name ++ templateFileType gotoPageFunction : List (Atom Msg) -> d -> Msg gotoPageFunction args _ = case args of [StringAtom page] -> GotoPage page _ -> SetError <| "Can't go to page: " ++ (toString args) messages : List (String, List (Atom Msg) -> Dicts Msg -> Msg) messages = [ ( "gotoPage", gotoPageFunction ) ] pageLinkFunction : List (Atom Msg) -> d -> Atom Msg pageLinkFunction args _ = case normalizePageLinkArgs args of Just ( page, title ) -> HtmlAtom <| a [ href "#" , onClick <| GotoPage page ] [ text title ] _ -> cantFuncall "pageLink" args normalizePageLinkArgs : List (Atom Msg) -> Maybe (String, String) normalizePageLinkArgs atom = case atom of [ StringAtom page ] -> Just (page, page) [ StringAtom page, StringAtom title ] -> Just (page, title) _ -> Nothing functions : List (String, List (Atom Msg) -> Dicts Msg -> Atom Msg) functions = [ ( "pageLink", pageLinkFunction ) ] type alias Extra = { templateDir : String } initialExtra : Extra initialExtra = { templateDir = "default" } pageProcessors : List (String, String -> Atom Msg -> Loaders Msg Extra -> Loaders Msg Extra) pageProcessors = [ ( settingsPageName, installSettings ) , ( "", add_page_Property ) ] initialLoaders : Loaders Msg Extra initialLoaders = makeLoaders fetchTemplate fetchPage initialExtra |> insertFunctions functions |> insertMessages messages |> addPageProcessors pageProcessors |> addOutstandingPagesAndTemplates initialPages initialTemplates --- --- init --- init : ( Model, Cmd Msg) init = let (model, _) = updatePlayString (playStringUpdate "\"Hello HtmlTemplate!\"") { loaders = initialLoaders , page = Nothing , pendingPage = Just indexPage , playState = emptyPlayState , error = Nothing } in ( model , loadOutstandingPageOrTemplate model.loaders ) -- Store just-loaded "settings" plist as an atom, and remove it as a page. -- The pages reference it as "$settings.<property>". installSettings : String -> Atom Msg -> Loaders Msg Extra -> Loaders Msg Extra installSettings name settings loaders = setAtom settingsFile settings <| removePage name loaders -- The value of most pages is a plist processed by the "node" template. -- This adds the page's own name to its plist when it's loaded. add_page_Property : String -> Atom Msg -> Loaders Msg Extra -> Loaders Msg Extra add_page_Property name page loaders = case page of PListAtom plist -> setPage name (PListAtom <| ("page", StringAtom name) :: plist) loaders _ -> loaders type Msg = TemplateFetchDone String (Loaders Msg Extra) (Result Http.Error String) | PageFetchDone String (Loaders Msg Extra) (Result Http.Error String) | GotoPage String | UpdatePlayState Update | SetError String fetchUrl : String -> ((Result Http.Error String) -> Msg) -> Cmd Msg fetchUrl url wrapper = Http.send wrapper <| httpGetString (log "Getting URL" url) httpGetString : String -> Http.Request String httpGetString url = Http.request { method = "GET" , headers = [ Http.header "Cache-control" "no-cache" ] , url = url , body = Http.emptyBody , expect = Http.expectString , timeout = Nothing , withCredentials = False } templateDir : Loaders Msg Extra -> String templateDir loaders = .templateDir <| getExtra loaders fetchTemplate : String -> Loaders Msg Extra -> Cmd Msg fetchTemplate name loaders = let filename = templateFilename name url = "template/" ++ (templateDir loaders) ++ "/" ++ filename in fetchUrl url <| TemplateFetchDone name loaders fetchPage : String -> Loaders Msg Extra -> Cmd Msg fetchPage name loaders = let url = if name == settingsPageName then templateFilename settingsFile else "page/" ++ (templateFilename name) in fetchUrl url <| PageFetchDone name loaders --- --- update --- update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of TemplateFetchDone name loaders result -> templateFetchDone name loaders result model PageFetchDone name loaders result -> pageFetchDone name loaders result model GotoPage page -> gotoPage page model UpdatePlayState update -> updatePlayString update model SetError message -> ( { model | error = Just message } , Cmd.none ) gotoPage : String -> Model -> ( Model, Cmd Msg ) gotoPage page model = let m = { model | error = Nothing , pendingPage = Just page } in ( m , fetchPage page <| clearPages model.loaders ) templateFetchDone : String -> Loaders Msg Extra -> Result Http.Error String -> Model -> ( Model, Cmd Msg ) templateFetchDone name loaders result model = case result of Err err -> ( { model | error = Just <| "Error fetching template " ++ name ++ ": " ++ (toString err) } , Cmd.none ) Ok json -> case receiveTemplate name json loaders of Err msg -> ( { model | loaders = loaders , error = Just <| "While parsing template \"" ++ name ++ "\": " ++ msg } , Cmd.none ) Ok loaders2 -> continueLoading loaders2 model continueLoading : Loaders Msg Extra -> Model -> ( Model, Cmd Msg ) continueLoading loaders model = case maybeLoadOutstandingPageOrTemplate loaders of Just cmd -> -- Do NOT update model.loaders yet, or the screen flashes ( model, cmd ) Nothing -> let m = { model | loaders = loaders } in ( case m.pendingPage of Nothing -> m Just page -> { m | page = Just page , pendingPage = Nothing , loaders = case m.page of Nothing -> loaders Just referer -> setAtom "referer" (StringAtom referer) loaders } , Cmd.none ) pageFetchDone : String -> Loaders Msg Extra -> Result Http.Error String -> Model -> ( Model, Cmd Msg ) pageFetchDone name loaders result model = case result of Err err -> ( { model | error = Just <| "Error fetching page " ++ name ++ ": " ++ (toString err) } , Cmd.none ) Ok json -> case receivePage name json loaders of Err msg -> ( { model | error = Just <| ("While loading page \"" ++ name ++ "\": " ++ msg) } , Cmd.none ) Ok loaders2 -> continueLoading loaders2 model updatePlayString : Update -> Model -> ( Model, Cmd Msg ) updatePlayString update model = ( { model | playState = updatePlayState update model.loaders model.playState } , Cmd.none ) --- --- view ---- view : Model -> Html Msg view model = div [] [ case model.error of Just err -> p [ style [ ( "color", "red" ) ] ] [ text err ] Nothing -> text "" , case model.page of Nothing -> text "" Just page -> let loaders = insertFunctions [ ( "playDiv" , playDivFunction UpdatePlayState model.playState ) ] model.loaders template = pageTemplate content = (LookupTemplateAtom <| if page == "index" then indexTemplate else nodeTemplate ) in case getTemplate template loaders of Nothing -> dictsDiv "Template" template loaders Just tmpl -> case getPage page loaders of Nothing -> dictsDiv "Page" page loaders Just atom -> let loaders2 = setAtoms [ ("node", atom) , ("content", content) , ("page", StringAtom page) ] loaders in render tmpl loaders2 ] dictsDiv : String -> String -> Loaders Msg Extra -> Html Msg dictsDiv thing page loaders = div [] [ p [] [ text <| thing ++ " not found: " ++ page ] , p [] [ a [ href "template/" ] [ text "template/"] ] , p [] [ text "dicts:" , br , text <| toString <| getDicts loaders ] ] br : Html Msg br = Html.br [] []
elm
[ { "context": "et\"\n\n\npasswordEmail : String\npasswordEmail =\n \"password/email\"\n\n\npasswordReset : String -> String\npasswor", "end": 515, "score": 0.8781424761, "start": 507, "tag": "PASSWORD", "value": "password" }, { "context": "swordEmail : String\npasswordEmail =\n \"password/email\"\n\n\npasswordReset : String -> String\npasswordReset", "end": 521, "score": 0.6906183362, "start": 516, "tag": "PASSWORD", "value": "email" }, { "context": "n\n\n\npasswordUpdate : String\npasswordUpdate =\n \"password/reset\"\n\n\nverificationNotice : String\nverificationNotice", "end": 713, "score": 0.7777266502, "start": 699, "tag": "PASSWORD", "value": "password/reset" } ]
resources/elm/laravel-elm-stuff/Routes.elm
loganhenson/laravel-elm-todomvc
0
port module Routes exposing (..) -- Do not edit this file manually. import Json.Decode exposing (Value) port get : String -> Cmd msg port post : Value -> Cmd msg port patch : Value -> Cmd msg port delete : String -> Cmd msg welcome : String welcome = "/" login : String login = "login" logout : String logout = "logout" register : String register = "register" passwordRequest : String passwordRequest = "password/reset" passwordEmail : String passwordEmail = "password/email" passwordReset : String -> String passwordReset token = "password/reset/{token}" |> String.replace "{token}" token passwordUpdate : String passwordUpdate = "password/reset" verificationNotice : String verificationNotice = "email/verify" verificationVerify : String -> String -> String verificationVerify id hash = "email/verify/{id}/{hash}" |> String.replace "{id}" id |> String.replace "{hash}" hash verificationResend : String verificationResend = "email/resend" home : String home = "home" todosStore : String todosStore = "todos" todosDestroy : String -> String todosDestroy id = "todos/{id}" |> String.replace "{id}" id todosUpdate : String -> String todosUpdate id = "todos/{id}" |> String.replace "{id}" id todosToggleAll : String todosToggleAll = "todos/toggle-all" todosDeleteComplete : String todosDeleteComplete = "todos/delete-complete"
28945
port module Routes exposing (..) -- Do not edit this file manually. import Json.Decode exposing (Value) port get : String -> Cmd msg port post : Value -> Cmd msg port patch : Value -> Cmd msg port delete : String -> Cmd msg welcome : String welcome = "/" login : String login = "login" logout : String logout = "logout" register : String register = "register" passwordRequest : String passwordRequest = "password/reset" passwordEmail : String passwordEmail = "<PASSWORD>/<PASSWORD>" passwordReset : String -> String passwordReset token = "password/reset/{token}" |> String.replace "{token}" token passwordUpdate : String passwordUpdate = "<PASSWORD>" verificationNotice : String verificationNotice = "email/verify" verificationVerify : String -> String -> String verificationVerify id hash = "email/verify/{id}/{hash}" |> String.replace "{id}" id |> String.replace "{hash}" hash verificationResend : String verificationResend = "email/resend" home : String home = "home" todosStore : String todosStore = "todos" todosDestroy : String -> String todosDestroy id = "todos/{id}" |> String.replace "{id}" id todosUpdate : String -> String todosUpdate id = "todos/{id}" |> String.replace "{id}" id todosToggleAll : String todosToggleAll = "todos/toggle-all" todosDeleteComplete : String todosDeleteComplete = "todos/delete-complete"
true
port module Routes exposing (..) -- Do not edit this file manually. import Json.Decode exposing (Value) port get : String -> Cmd msg port post : Value -> Cmd msg port patch : Value -> Cmd msg port delete : String -> Cmd msg welcome : String welcome = "/" login : String login = "login" logout : String logout = "logout" register : String register = "register" passwordRequest : String passwordRequest = "password/reset" passwordEmail : String passwordEmail = "PI:PASSWORD:<PASSWORD>END_PI/PI:PASSWORD:<PASSWORD>END_PI" passwordReset : String -> String passwordReset token = "password/reset/{token}" |> String.replace "{token}" token passwordUpdate : String passwordUpdate = "PI:PASSWORD:<PASSWORD>END_PI" verificationNotice : String verificationNotice = "email/verify" verificationVerify : String -> String -> String verificationVerify id hash = "email/verify/{id}/{hash}" |> String.replace "{id}" id |> String.replace "{hash}" hash verificationResend : String verificationResend = "email/resend" home : String home = "home" todosStore : String todosStore = "todos" todosDestroy : String -> String todosDestroy id = "todos/{id}" |> String.replace "{id}" id todosUpdate : String -> String todosUpdate id = "todos/{id}" |> String.replace "{id}" id todosToggleAll : String todosToggleAll = "todos/toggle-all" todosDeleteComplete : String todosDeleteComplete = "todos/delete-complete"
elm
[ { "context": "ion Validate.email\n ( \"validemail@example.com\"\n , ValidationExpectat", "end": 1211, "score": 0.9995898008, "start": 1189, "tag": "EMAIL", "value": "validemail@example.com" } ]
tests/MetaTests.elm
teatimes/elm-form
131
module MetaTests exposing (all) import Expect exposing (Expectation) import Form.Error exposing (ErrorValue) import Form.Test.Helpers import Form.Test.ValidationExpectation as ValidationExpectation import Form.Validate as Validate exposing (Validation, string) import Test exposing (..) all : Test all = describe "meta tests" [ test "expect success but get error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "This is definitely not an email address" , ValidationExpectation.Valid ) expected = ValidationExpectation.Invalid Form.Error.InvalidEmail |> Expect.equal ValidationExpectation.Valid in actual |> Expect.equal expected , test "expect success get success" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "validemail@example.com" , ValidationExpectation.Valid ) in actual |> Expect.equal Expect.pass , test "expected error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "This is definitely not an email address" , ValidationExpectation.Invalid Form.Error.Empty ) expected = ValidationExpectation.Invalid Form.Error.InvalidEmail |> Expect.equal (ValidationExpectation.Invalid Form.Error.Empty) in actual |> Expect.equal expected , test "different error than expected" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "This is definitely not an email address" , ValidationExpectation.Invalid Form.Error.InvalidEmail ) in actual |> Expect.equal Expect.pass , test "custom error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation validateSuperpower ( "This is not a superpower" , ValidationExpectation.InvalidCustomError InvalidSuperpower ) in actual |> Expect.equal Expect.pass , test "expect custom error but get no error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation validateSuperpower ( "flying" , ValidationExpectation.InvalidCustomError InvalidSuperpower ) expected = Expect.equal (ValidationExpectation.InvalidCustomError InvalidSuperpower) (ValidationExpectation.ValidDecodesTo Flying) in actual |> Expect.equal expected ] type Superpower = Flying | Invisible type CustomError = InvalidSuperpower validateSuperpower : Validation CustomError Superpower validateSuperpower = Validate.customValidation string (\s -> case s of "flying" -> Ok Flying "invisible" -> Ok Invisible _ -> Err (Validate.customError InvalidSuperpower) )
60986
module MetaTests exposing (all) import Expect exposing (Expectation) import Form.Error exposing (ErrorValue) import Form.Test.Helpers import Form.Test.ValidationExpectation as ValidationExpectation import Form.Validate as Validate exposing (Validation, string) import Test exposing (..) all : Test all = describe "meta tests" [ test "expect success but get error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "This is definitely not an email address" , ValidationExpectation.Valid ) expected = ValidationExpectation.Invalid Form.Error.InvalidEmail |> Expect.equal ValidationExpectation.Valid in actual |> Expect.equal expected , test "expect success get success" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "<EMAIL>" , ValidationExpectation.Valid ) in actual |> Expect.equal Expect.pass , test "expected error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "This is definitely not an email address" , ValidationExpectation.Invalid Form.Error.Empty ) expected = ValidationExpectation.Invalid Form.Error.InvalidEmail |> Expect.equal (ValidationExpectation.Invalid Form.Error.Empty) in actual |> Expect.equal expected , test "different error than expected" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "This is definitely not an email address" , ValidationExpectation.Invalid Form.Error.InvalidEmail ) in actual |> Expect.equal Expect.pass , test "custom error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation validateSuperpower ( "This is not a superpower" , ValidationExpectation.InvalidCustomError InvalidSuperpower ) in actual |> Expect.equal Expect.pass , test "expect custom error but get no error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation validateSuperpower ( "flying" , ValidationExpectation.InvalidCustomError InvalidSuperpower ) expected = Expect.equal (ValidationExpectation.InvalidCustomError InvalidSuperpower) (ValidationExpectation.ValidDecodesTo Flying) in actual |> Expect.equal expected ] type Superpower = Flying | Invisible type CustomError = InvalidSuperpower validateSuperpower : Validation CustomError Superpower validateSuperpower = Validate.customValidation string (\s -> case s of "flying" -> Ok Flying "invisible" -> Ok Invisible _ -> Err (Validate.customError InvalidSuperpower) )
true
module MetaTests exposing (all) import Expect exposing (Expectation) import Form.Error exposing (ErrorValue) import Form.Test.Helpers import Form.Test.ValidationExpectation as ValidationExpectation import Form.Validate as Validate exposing (Validation, string) import Test exposing (..) all : Test all = describe "meta tests" [ test "expect success but get error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "This is definitely not an email address" , ValidationExpectation.Valid ) expected = ValidationExpectation.Invalid Form.Error.InvalidEmail |> Expect.equal ValidationExpectation.Valid in actual |> Expect.equal expected , test "expect success get success" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "PI:EMAIL:<EMAIL>END_PI" , ValidationExpectation.Valid ) in actual |> Expect.equal Expect.pass , test "expected error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "This is definitely not an email address" , ValidationExpectation.Invalid Form.Error.Empty ) expected = ValidationExpectation.Invalid Form.Error.InvalidEmail |> Expect.equal (ValidationExpectation.Invalid Form.Error.Empty) in actual |> Expect.equal expected , test "different error than expected" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation Validate.email ( "This is definitely not an email address" , ValidationExpectation.Invalid Form.Error.InvalidEmail ) in actual |> Expect.equal Expect.pass , test "custom error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation validateSuperpower ( "This is not a superpower" , ValidationExpectation.InvalidCustomError InvalidSuperpower ) in actual |> Expect.equal Expect.pass , test "expect custom error but get no error" <| \() -> let actual = Form.Test.Helpers.getValidationExpectation validateSuperpower ( "flying" , ValidationExpectation.InvalidCustomError InvalidSuperpower ) expected = Expect.equal (ValidationExpectation.InvalidCustomError InvalidSuperpower) (ValidationExpectation.ValidDecodesTo Flying) in actual |> Expect.equal expected ] type Superpower = Flying | Invisible type CustomError = InvalidSuperpower validateSuperpower : Validation CustomError Superpower validateSuperpower = Validate.customValidation string (\s -> case s of "flying" -> Ok Flying "invisible" -> Ok Invisible _ -> Err (Validate.customError InvalidSuperpower) )
elm
[ { "context": "mg_ \"static/elm.png\", nl, nl\n , note [ text \"Алексей Пирогов\" ]\n ]\n\n , section \"Введение\" \"что за Elm?\"\n", "end": 569, "score": 0.9998674393, "start": 554, "tag": "NAME", "value": "Алексей Пирогов" }, { "context": "e : String\n , age : Int }\n\nuser = { name = \\\"Moe\\\", age = 42 }\n\nuserAge = user.age\n\nnewUser = { us", "end": 2306, "score": 0.9988306761, "start": 2303, "tag": "NAME", "value": "Moe" }, { "context": "ений в runtime\"\n , a_ \"https://github.com/evancz/elm-architecture-tutorial/\"\n \"Elm arc", "end": 5918, "score": 0.9995166659, "start": 5912, "tag": "USERNAME", "value": "evancz" } ]
Slides.elm
astynax/about-elm
1
module Slides where import Maybe exposing (Maybe(..)) import String import Html exposing (Html, text, a, p, pre, code, div, span, img, br, ul, li, small, textarea) import Html.Attributes exposing (class, href, value, target) import SlideShow exposing (..) main : Signal Html main = start slides |> .html slides : List Slide slides = [ title <| slide "" [ text "Разработка", nl , text "интерактивных", nl , text "Web-приложений", nl , text "на языке Elm", nl, nl , img_ "static/elm.png", nl, nl , note [ text "Алексей Пирогов" ] ] , section "Введение" "что за Elm?" , slide "Elm?" [ text "Elm, это" , ul_ [ text "Функциональный язык" , text "Сильная статическая типизация" , text "Алгебраические Типы Данных" , text "Компиляция в JavaScript" , text "Нацеленность на построение UI" , text "Контроль над side-эффектами" , text "FRP, Time-travel Debugging, ..." ] ] , section "С чего начать?" "готовим окружение" , slide "Установка" [ source "shell" "$ npm install -g elm" ] , slide "Компоненты" [ ul_ <| List.map code_ [ "elm-make" , "elm-package" , "elm-reactor" , "elm-repl" ] ] , slide "Минимальный проект" [ source "shell" "$ tree . └── Main.elm 0 directories, 1 file $ cat Main.elm module Main where import Graphics.Element exposing (show) main = show \"Hello World!\"" ] , slide "Минимальный проект (запуск)" [ source "shell" "$ elm-make Main.elm Some new packages are needed. Here is the upgrade plan. Install: elm-lang/core 3.0.0 Do you approve of this plan? (y/n) y ... Successfully generated index.html" ] , section "Синтаксис" "кратенько" , slide "Синтаксис" <| snippet [ text "Алгебраические Типы Данных:" ] "type Color = Red | Green | Blue type Point = Point Int Int type Shape = Circle Point Int | Triangle Point Point Point | Rect Point Point" Nothing , slide "Синтаксис" <| snippet [ text "Записи (Records):" ] "type alias User = { name : String , age : Int } user = { name = \"Moe\", age = 42 } userAge = user.age newUser = { user | age = user.age + 1 }" Nothing , slide "Синтаксис" <| snippet [ text "Функции" ] "add : Int -> Int -> Int add x y = x + y add5 : Int -> Int add5 = add 5" Nothing , section "It's alive!" "Концепция, или галопом по FRP" , slide "Концепция" [ div [ class "center" ] [ text "\"Stream processing", nl , text "lets us model systems that have state", nl , text "without ever using", nl , text "assignment or mutable data.\"", nl , note [ text "SICP" ] ] ] , slide "Концепция" [ code_ "Signal", text " + ", code_ "Element", text " = основа всего!" , nl, nl , text "Самый главный тип в приложении:" , source "elm" "main : Signal Element main = show \"Hello world!\"" , nl , text "Другой пример:" , source "elm" "import Mouse Mouse.x : Signal Int Mouse.position : Signal (Int, Int) Mouse.isDown : Signal Bool" ] , slide "Концепция" <| snippet [ text "Работа с сигналами:" ] "clicks = Signal.foldp (+) 0 <| Signal.map (always 1) Mouse.clicks main = Signal.map show <| Signal.map2 (,) clicks Mouse.isDown" <| Just "import Graphics.Element exposing (centered) import Text import Signal import Mouse clicks = Signal.foldp (+) 0 <| Signal.map (always 1) Mouse.clicks main = Signal.map show <| Signal.map2 (,) clicks Mouse.isDown show = centered << Text.height 40 << Text.fromString << toString" , slide "Концепция" [ text "Ещё примеры:" , ul_ [ share "56d6dd25e4b070fd20daa274" "red circle" , share "56d7e93ce4b070fd20daa2e1" "blue circle" ] ] , section "Ближе к Web" "Дайте уже мне HTML и CSS!" , slide "Web" <| snippet [ text "(HTML + CSS) * Elm = " , package "evancz/elm-html/4.0.2" "elm-html" , text "(" , a_ "https://mbylstra.github.io/html-to-elm/" "*" , text "):" ] "page = div [ class \"content\" ] [ h1 [ style [ (\"color\", \"red\") ] ] [ text \"Hello, World!\" ] , ul [ id \"items\" ] [ item \"apple\" , item \"orange\" ]] item x = li [] [ text x ]" <| Just "import Html exposing (..) import Html.Attributes exposing (..) import Signal main = Signal.constant page page = div [ class \"content\" ] [ h1 [ style [ (\"color\", \"red\") ] ] [ text \"Hello, World!\" ] , ul [ id \"items\" ] [ item \"apple\" , item \"orange\" ]] item x = li [] [ text x ]" , slide "Web" <| snippet [ text "Model-View-Action-Update (" , package "evancz/start-app/2.0.2" "start-app" , text "):" ] "model : Model view : Model -> Html update : Action -> Model -> Model" <| Just "import StartApp.Simple as StartApp import Html exposing (..) import Html.Events exposing (onClick) type Action = Inc | Dec main = StartApp.start { model = model , view = view , update = update } model = 0 view address model = div [] [ h1 [] [ text <| toString model ] , button [ onClick address Dec ] [ text \"-\" ] , button [ onClick address Inc ] [ text \"+\" ] ] update action model = case action of Inc -> model + 1 Dec -> model - 1" , section "Напоследок" "Да-да, уже почти конец!" , slide "Напоследок" [ text "Плюсы:" , ul_ [ text "Отличный tooling!" , text "Null-safety" , text "Отсутствие исключений в runtime" , a_ "https://github.com/evancz/elm-architecture-tutorial/" "Elm architecture" , a_ "http://package.elm-lang.org/" "Elm Packages" ] ] , slide "Напоследок" [ text "Минусы:" , ul_ [ text "Язык ещё молод и всё ещё меняется" , text "Elm - не General Purpose Language" , text "Сообщество elmer'ов не слишком велико" , text "Иногда приходится писать на JavaScript" , text "Elm сияет, когда \"стоит у руля\"" ] ] , slide "Напоследок" [ text "Стоит упомянуть:" , ul_ [ a_ "http://elm-lang.org/guide/interop#ports" "JavaScript interop" , a_ "https://evancz.github.io/todomvc-perf-comparison/" "Benchmarks!" , a_ "http://debug.elm-lang.org/" "Time Traveling Debugger" , a_ "http://builtwithelm.co/" "\"Built with Elm\"" , a_ "http://www.elm-tutorial.org/" "Elm tutorial" ] ] , section "The End" "Вопросы?" ] -------------------------------------------------------------------------------- --| Helpers section : String -> String -> Slide section t n = title <| slide "" [ text t, nl, note [ text n ] ] note : List Html -> Html note = span [ class "note" ] snippet : List Html -> String -> Maybe String -> List Html snippet description content paste = List.append description <| List.append [ nl, nl , source "elm" content ] <| Maybe.withDefault [] <| Maybe.map (\x -> [ nl , note [ text "Скопируйте это " , textarea [ value x ] [] , text " и попробуйте " , a_ "http://elm-lang.org/try" "здесь" , text "." ] ] ) paste a_ : String -> String -> Html a_ url txt = a [ href url, target "blank" ] [ text txt ] share : String -> String -> Html share id = a_ (String.append "http://www.share-elm.com/sprout/" id) package : String -> String -> Html package path = a_ (String.append "http://package.elm-lang.org/packages/" path)
16451
module Slides where import Maybe exposing (Maybe(..)) import String import Html exposing (Html, text, a, p, pre, code, div, span, img, br, ul, li, small, textarea) import Html.Attributes exposing (class, href, value, target) import SlideShow exposing (..) main : Signal Html main = start slides |> .html slides : List Slide slides = [ title <| slide "" [ text "Разработка", nl , text "интерактивных", nl , text "Web-приложений", nl , text "на языке Elm", nl, nl , img_ "static/elm.png", nl, nl , note [ text "<NAME>" ] ] , section "Введение" "что за Elm?" , slide "Elm?" [ text "Elm, это" , ul_ [ text "Функциональный язык" , text "Сильная статическая типизация" , text "Алгебраические Типы Данных" , text "Компиляция в JavaScript" , text "Нацеленность на построение UI" , text "Контроль над side-эффектами" , text "FRP, Time-travel Debugging, ..." ] ] , section "С чего начать?" "готовим окружение" , slide "Установка" [ source "shell" "$ npm install -g elm" ] , slide "Компоненты" [ ul_ <| List.map code_ [ "elm-make" , "elm-package" , "elm-reactor" , "elm-repl" ] ] , slide "Минимальный проект" [ source "shell" "$ tree . └── Main.elm 0 directories, 1 file $ cat Main.elm module Main where import Graphics.Element exposing (show) main = show \"Hello World!\"" ] , slide "Минимальный проект (запуск)" [ source "shell" "$ elm-make Main.elm Some new packages are needed. Here is the upgrade plan. Install: elm-lang/core 3.0.0 Do you approve of this plan? (y/n) y ... Successfully generated index.html" ] , section "Синтаксис" "кратенько" , slide "Синтаксис" <| snippet [ text "Алгебраические Типы Данных:" ] "type Color = Red | Green | Blue type Point = Point Int Int type Shape = Circle Point Int | Triangle Point Point Point | Rect Point Point" Nothing , slide "Синтаксис" <| snippet [ text "Записи (Records):" ] "type alias User = { name : String , age : Int } user = { name = \"<NAME>\", age = 42 } userAge = user.age newUser = { user | age = user.age + 1 }" Nothing , slide "Синтаксис" <| snippet [ text "Функции" ] "add : Int -> Int -> Int add x y = x + y add5 : Int -> Int add5 = add 5" Nothing , section "It's alive!" "Концепция, или галопом по FRP" , slide "Концепция" [ div [ class "center" ] [ text "\"Stream processing", nl , text "lets us model systems that have state", nl , text "without ever using", nl , text "assignment or mutable data.\"", nl , note [ text "SICP" ] ] ] , slide "Концепция" [ code_ "Signal", text " + ", code_ "Element", text " = основа всего!" , nl, nl , text "Самый главный тип в приложении:" , source "elm" "main : Signal Element main = show \"Hello world!\"" , nl , text "Другой пример:" , source "elm" "import Mouse Mouse.x : Signal Int Mouse.position : Signal (Int, Int) Mouse.isDown : Signal Bool" ] , slide "Концепция" <| snippet [ text "Работа с сигналами:" ] "clicks = Signal.foldp (+) 0 <| Signal.map (always 1) Mouse.clicks main = Signal.map show <| Signal.map2 (,) clicks Mouse.isDown" <| Just "import Graphics.Element exposing (centered) import Text import Signal import Mouse clicks = Signal.foldp (+) 0 <| Signal.map (always 1) Mouse.clicks main = Signal.map show <| Signal.map2 (,) clicks Mouse.isDown show = centered << Text.height 40 << Text.fromString << toString" , slide "Концепция" [ text "Ещё примеры:" , ul_ [ share "56d6dd25e4b070fd20daa274" "red circle" , share "56d7e93ce4b070fd20daa2e1" "blue circle" ] ] , section "Ближе к Web" "Дайте уже мне HTML и CSS!" , slide "Web" <| snippet [ text "(HTML + CSS) * Elm = " , package "evancz/elm-html/4.0.2" "elm-html" , text "(" , a_ "https://mbylstra.github.io/html-to-elm/" "*" , text "):" ] "page = div [ class \"content\" ] [ h1 [ style [ (\"color\", \"red\") ] ] [ text \"Hello, World!\" ] , ul [ id \"items\" ] [ item \"apple\" , item \"orange\" ]] item x = li [] [ text x ]" <| Just "import Html exposing (..) import Html.Attributes exposing (..) import Signal main = Signal.constant page page = div [ class \"content\" ] [ h1 [ style [ (\"color\", \"red\") ] ] [ text \"Hello, World!\" ] , ul [ id \"items\" ] [ item \"apple\" , item \"orange\" ]] item x = li [] [ text x ]" , slide "Web" <| snippet [ text "Model-View-Action-Update (" , package "evancz/start-app/2.0.2" "start-app" , text "):" ] "model : Model view : Model -> Html update : Action -> Model -> Model" <| Just "import StartApp.Simple as StartApp import Html exposing (..) import Html.Events exposing (onClick) type Action = Inc | Dec main = StartApp.start { model = model , view = view , update = update } model = 0 view address model = div [] [ h1 [] [ text <| toString model ] , button [ onClick address Dec ] [ text \"-\" ] , button [ onClick address Inc ] [ text \"+\" ] ] update action model = case action of Inc -> model + 1 Dec -> model - 1" , section "Напоследок" "Да-да, уже почти конец!" , slide "Напоследок" [ text "Плюсы:" , ul_ [ text "Отличный tooling!" , text "Null-safety" , text "Отсутствие исключений в runtime" , a_ "https://github.com/evancz/elm-architecture-tutorial/" "Elm architecture" , a_ "http://package.elm-lang.org/" "Elm Packages" ] ] , slide "Напоследок" [ text "Минусы:" , ul_ [ text "Язык ещё молод и всё ещё меняется" , text "Elm - не General Purpose Language" , text "Сообщество elmer'ов не слишком велико" , text "Иногда приходится писать на JavaScript" , text "Elm сияет, когда \"стоит у руля\"" ] ] , slide "Напоследок" [ text "Стоит упомянуть:" , ul_ [ a_ "http://elm-lang.org/guide/interop#ports" "JavaScript interop" , a_ "https://evancz.github.io/todomvc-perf-comparison/" "Benchmarks!" , a_ "http://debug.elm-lang.org/" "Time Traveling Debugger" , a_ "http://builtwithelm.co/" "\"Built with Elm\"" , a_ "http://www.elm-tutorial.org/" "Elm tutorial" ] ] , section "The End" "Вопросы?" ] -------------------------------------------------------------------------------- --| Helpers section : String -> String -> Slide section t n = title <| slide "" [ text t, nl, note [ text n ] ] note : List Html -> Html note = span [ class "note" ] snippet : List Html -> String -> Maybe String -> List Html snippet description content paste = List.append description <| List.append [ nl, nl , source "elm" content ] <| Maybe.withDefault [] <| Maybe.map (\x -> [ nl , note [ text "Скопируйте это " , textarea [ value x ] [] , text " и попробуйте " , a_ "http://elm-lang.org/try" "здесь" , text "." ] ] ) paste a_ : String -> String -> Html a_ url txt = a [ href url, target "blank" ] [ text txt ] share : String -> String -> Html share id = a_ (String.append "http://www.share-elm.com/sprout/" id) package : String -> String -> Html package path = a_ (String.append "http://package.elm-lang.org/packages/" path)
true
module Slides where import Maybe exposing (Maybe(..)) import String import Html exposing (Html, text, a, p, pre, code, div, span, img, br, ul, li, small, textarea) import Html.Attributes exposing (class, href, value, target) import SlideShow exposing (..) main : Signal Html main = start slides |> .html slides : List Slide slides = [ title <| slide "" [ text "Разработка", nl , text "интерактивных", nl , text "Web-приложений", nl , text "на языке Elm", nl, nl , img_ "static/elm.png", nl, nl , note [ text "PI:NAME:<NAME>END_PI" ] ] , section "Введение" "что за Elm?" , slide "Elm?" [ text "Elm, это" , ul_ [ text "Функциональный язык" , text "Сильная статическая типизация" , text "Алгебраические Типы Данных" , text "Компиляция в JavaScript" , text "Нацеленность на построение UI" , text "Контроль над side-эффектами" , text "FRP, Time-travel Debugging, ..." ] ] , section "С чего начать?" "готовим окружение" , slide "Установка" [ source "shell" "$ npm install -g elm" ] , slide "Компоненты" [ ul_ <| List.map code_ [ "elm-make" , "elm-package" , "elm-reactor" , "elm-repl" ] ] , slide "Минимальный проект" [ source "shell" "$ tree . └── Main.elm 0 directories, 1 file $ cat Main.elm module Main where import Graphics.Element exposing (show) main = show \"Hello World!\"" ] , slide "Минимальный проект (запуск)" [ source "shell" "$ elm-make Main.elm Some new packages are needed. Here is the upgrade plan. Install: elm-lang/core 3.0.0 Do you approve of this plan? (y/n) y ... Successfully generated index.html" ] , section "Синтаксис" "кратенько" , slide "Синтаксис" <| snippet [ text "Алгебраические Типы Данных:" ] "type Color = Red | Green | Blue type Point = Point Int Int type Shape = Circle Point Int | Triangle Point Point Point | Rect Point Point" Nothing , slide "Синтаксис" <| snippet [ text "Записи (Records):" ] "type alias User = { name : String , age : Int } user = { name = \"PI:NAME:<NAME>END_PI\", age = 42 } userAge = user.age newUser = { user | age = user.age + 1 }" Nothing , slide "Синтаксис" <| snippet [ text "Функции" ] "add : Int -> Int -> Int add x y = x + y add5 : Int -> Int add5 = add 5" Nothing , section "It's alive!" "Концепция, или галопом по FRP" , slide "Концепция" [ div [ class "center" ] [ text "\"Stream processing", nl , text "lets us model systems that have state", nl , text "without ever using", nl , text "assignment or mutable data.\"", nl , note [ text "SICP" ] ] ] , slide "Концепция" [ code_ "Signal", text " + ", code_ "Element", text " = основа всего!" , nl, nl , text "Самый главный тип в приложении:" , source "elm" "main : Signal Element main = show \"Hello world!\"" , nl , text "Другой пример:" , source "elm" "import Mouse Mouse.x : Signal Int Mouse.position : Signal (Int, Int) Mouse.isDown : Signal Bool" ] , slide "Концепция" <| snippet [ text "Работа с сигналами:" ] "clicks = Signal.foldp (+) 0 <| Signal.map (always 1) Mouse.clicks main = Signal.map show <| Signal.map2 (,) clicks Mouse.isDown" <| Just "import Graphics.Element exposing (centered) import Text import Signal import Mouse clicks = Signal.foldp (+) 0 <| Signal.map (always 1) Mouse.clicks main = Signal.map show <| Signal.map2 (,) clicks Mouse.isDown show = centered << Text.height 40 << Text.fromString << toString" , slide "Концепция" [ text "Ещё примеры:" , ul_ [ share "56d6dd25e4b070fd20daa274" "red circle" , share "56d7e93ce4b070fd20daa2e1" "blue circle" ] ] , section "Ближе к Web" "Дайте уже мне HTML и CSS!" , slide "Web" <| snippet [ text "(HTML + CSS) * Elm = " , package "evancz/elm-html/4.0.2" "elm-html" , text "(" , a_ "https://mbylstra.github.io/html-to-elm/" "*" , text "):" ] "page = div [ class \"content\" ] [ h1 [ style [ (\"color\", \"red\") ] ] [ text \"Hello, World!\" ] , ul [ id \"items\" ] [ item \"apple\" , item \"orange\" ]] item x = li [] [ text x ]" <| Just "import Html exposing (..) import Html.Attributes exposing (..) import Signal main = Signal.constant page page = div [ class \"content\" ] [ h1 [ style [ (\"color\", \"red\") ] ] [ text \"Hello, World!\" ] , ul [ id \"items\" ] [ item \"apple\" , item \"orange\" ]] item x = li [] [ text x ]" , slide "Web" <| snippet [ text "Model-View-Action-Update (" , package "evancz/start-app/2.0.2" "start-app" , text "):" ] "model : Model view : Model -> Html update : Action -> Model -> Model" <| Just "import StartApp.Simple as StartApp import Html exposing (..) import Html.Events exposing (onClick) type Action = Inc | Dec main = StartApp.start { model = model , view = view , update = update } model = 0 view address model = div [] [ h1 [] [ text <| toString model ] , button [ onClick address Dec ] [ text \"-\" ] , button [ onClick address Inc ] [ text \"+\" ] ] update action model = case action of Inc -> model + 1 Dec -> model - 1" , section "Напоследок" "Да-да, уже почти конец!" , slide "Напоследок" [ text "Плюсы:" , ul_ [ text "Отличный tooling!" , text "Null-safety" , text "Отсутствие исключений в runtime" , a_ "https://github.com/evancz/elm-architecture-tutorial/" "Elm architecture" , a_ "http://package.elm-lang.org/" "Elm Packages" ] ] , slide "Напоследок" [ text "Минусы:" , ul_ [ text "Язык ещё молод и всё ещё меняется" , text "Elm - не General Purpose Language" , text "Сообщество elmer'ов не слишком велико" , text "Иногда приходится писать на JavaScript" , text "Elm сияет, когда \"стоит у руля\"" ] ] , slide "Напоследок" [ text "Стоит упомянуть:" , ul_ [ a_ "http://elm-lang.org/guide/interop#ports" "JavaScript interop" , a_ "https://evancz.github.io/todomvc-perf-comparison/" "Benchmarks!" , a_ "http://debug.elm-lang.org/" "Time Traveling Debugger" , a_ "http://builtwithelm.co/" "\"Built with Elm\"" , a_ "http://www.elm-tutorial.org/" "Elm tutorial" ] ] , section "The End" "Вопросы?" ] -------------------------------------------------------------------------------- --| Helpers section : String -> String -> Slide section t n = title <| slide "" [ text t, nl, note [ text n ] ] note : List Html -> Html note = span [ class "note" ] snippet : List Html -> String -> Maybe String -> List Html snippet description content paste = List.append description <| List.append [ nl, nl , source "elm" content ] <| Maybe.withDefault [] <| Maybe.map (\x -> [ nl , note [ text "Скопируйте это " , textarea [ value x ] [] , text " и попробуйте " , a_ "http://elm-lang.org/try" "здесь" , text "." ] ] ) paste a_ : String -> String -> Html a_ url txt = a [ href url, target "blank" ] [ text txt ] share : String -> String -> Html share id = a_ (String.append "http://www.share-elm.com/sprout/" id) package : String -> String -> Html package path = a_ (String.append "http://package.elm-lang.org/packages/" path)
elm
[ { "context": "{-\n Swaggy Jenkins\n Jenkins API clients generated from Swagger / O", "end": 20, "score": 0.9996216893, "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.999912858, "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.9996321201, "start": 240, "tag": "USERNAME", "value": "openapitools" } ]
clients/elm/generated/src/Data/PipelineStepImpl.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.PipelineStepImpl exposing (PipelineStepImpl, pipelineStepImplDecoder, pipelineStepImplEncoder) import Data.PipelineStepImpllinks exposing (PipelineStepImpllinks, pipelineStepImpllinksDecoder, pipelineStepImpllinksEncoder) import Data.InputStepImpl exposing (InputStepImpl, inputStepImplDecoder, inputStepImplEncoder) 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 PipelineStepImpl = { class : Maybe String , links : Maybe PipelineStepImpllinks , displayName : Maybe String , durationInMillis : Maybe Int , id : Maybe String , input : Maybe InputStepImpl , result : Maybe String , startTime : Maybe String , state : Maybe String } pipelineStepImplDecoder : Decoder PipelineStepImpl pipelineStepImplDecoder = decode PipelineStepImpl |> optional "_class" (Decode.nullable Decode.string) Nothing |> optional "_links" (Decode.nullable pipelineStepImpllinksDecoder) Nothing |> optional "displayName" (Decode.nullable Decode.string) Nothing |> optional "durationInMillis" (Decode.nullable Decode.int) Nothing |> optional "id" (Decode.nullable Decode.string) Nothing |> optional "input" (Decode.nullable inputStepImplDecoder) Nothing |> optional "result" (Decode.nullable Decode.string) Nothing |> optional "startTime" (Decode.nullable Decode.string) Nothing |> optional "state" (Decode.nullable Decode.string) Nothing pipelineStepImplEncoder : PipelineStepImpl -> Encode.Value pipelineStepImplEncoder model = Encode.object [ ( "_class", withDefault Encode.null (map Encode.string model.class) ) , ( "_links", withDefault Encode.null (map pipelineStepImpllinksEncoder model.links) ) , ( "displayName", withDefault Encode.null (map Encode.string model.displayName) ) , ( "durationInMillis", withDefault Encode.null (map Encode.int model.durationInMillis) ) , ( "id", withDefault Encode.null (map Encode.string model.id) ) , ( "input", withDefault Encode.null (map inputStepImplEncoder model.input) ) , ( "result", withDefault Encode.null (map Encode.string model.result) ) , ( "startTime", withDefault Encode.null (map Encode.string model.startTime) ) , ( "state", withDefault Encode.null (map Encode.string model.state) ) ]
5753
{- <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.PipelineStepImpl exposing (PipelineStepImpl, pipelineStepImplDecoder, pipelineStepImplEncoder) import Data.PipelineStepImpllinks exposing (PipelineStepImpllinks, pipelineStepImpllinksDecoder, pipelineStepImpllinksEncoder) import Data.InputStepImpl exposing (InputStepImpl, inputStepImplDecoder, inputStepImplEncoder) 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 PipelineStepImpl = { class : Maybe String , links : Maybe PipelineStepImpllinks , displayName : Maybe String , durationInMillis : Maybe Int , id : Maybe String , input : Maybe InputStepImpl , result : Maybe String , startTime : Maybe String , state : Maybe String } pipelineStepImplDecoder : Decoder PipelineStepImpl pipelineStepImplDecoder = decode PipelineStepImpl |> optional "_class" (Decode.nullable Decode.string) Nothing |> optional "_links" (Decode.nullable pipelineStepImpllinksDecoder) Nothing |> optional "displayName" (Decode.nullable Decode.string) Nothing |> optional "durationInMillis" (Decode.nullable Decode.int) Nothing |> optional "id" (Decode.nullable Decode.string) Nothing |> optional "input" (Decode.nullable inputStepImplDecoder) Nothing |> optional "result" (Decode.nullable Decode.string) Nothing |> optional "startTime" (Decode.nullable Decode.string) Nothing |> optional "state" (Decode.nullable Decode.string) Nothing pipelineStepImplEncoder : PipelineStepImpl -> Encode.Value pipelineStepImplEncoder model = Encode.object [ ( "_class", withDefault Encode.null (map Encode.string model.class) ) , ( "_links", withDefault Encode.null (map pipelineStepImpllinksEncoder model.links) ) , ( "displayName", withDefault Encode.null (map Encode.string model.displayName) ) , ( "durationInMillis", withDefault Encode.null (map Encode.int model.durationInMillis) ) , ( "id", withDefault Encode.null (map Encode.string model.id) ) , ( "input", withDefault Encode.null (map inputStepImplEncoder model.input) ) , ( "result", withDefault Encode.null (map Encode.string model.result) ) , ( "startTime", withDefault Encode.null (map Encode.string model.startTime) ) , ( "state", withDefault Encode.null (map Encode.string model.state) ) ]
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.PipelineStepImpl exposing (PipelineStepImpl, pipelineStepImplDecoder, pipelineStepImplEncoder) import Data.PipelineStepImpllinks exposing (PipelineStepImpllinks, pipelineStepImpllinksDecoder, pipelineStepImpllinksEncoder) import Data.InputStepImpl exposing (InputStepImpl, inputStepImplDecoder, inputStepImplEncoder) 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 PipelineStepImpl = { class : Maybe String , links : Maybe PipelineStepImpllinks , displayName : Maybe String , durationInMillis : Maybe Int , id : Maybe String , input : Maybe InputStepImpl , result : Maybe String , startTime : Maybe String , state : Maybe String } pipelineStepImplDecoder : Decoder PipelineStepImpl pipelineStepImplDecoder = decode PipelineStepImpl |> optional "_class" (Decode.nullable Decode.string) Nothing |> optional "_links" (Decode.nullable pipelineStepImpllinksDecoder) Nothing |> optional "displayName" (Decode.nullable Decode.string) Nothing |> optional "durationInMillis" (Decode.nullable Decode.int) Nothing |> optional "id" (Decode.nullable Decode.string) Nothing |> optional "input" (Decode.nullable inputStepImplDecoder) Nothing |> optional "result" (Decode.nullable Decode.string) Nothing |> optional "startTime" (Decode.nullable Decode.string) Nothing |> optional "state" (Decode.nullable Decode.string) Nothing pipelineStepImplEncoder : PipelineStepImpl -> Encode.Value pipelineStepImplEncoder model = Encode.object [ ( "_class", withDefault Encode.null (map Encode.string model.class) ) , ( "_links", withDefault Encode.null (map pipelineStepImpllinksEncoder model.links) ) , ( "displayName", withDefault Encode.null (map Encode.string model.displayName) ) , ( "durationInMillis", withDefault Encode.null (map Encode.int model.durationInMillis) ) , ( "id", withDefault Encode.null (map Encode.string model.id) ) , ( "input", withDefault Encode.null (map inputStepImplEncoder model.input) ) , ( "result", withDefault Encode.null (map Encode.string model.result) ) , ( "startTime", withDefault Encode.null (map Encode.string model.startTime) ) , ( "state", withDefault Encode.null (map Encode.string model.state) ) ]
elm
[ { "context": "\n Form.Validate.email\n [ ( \"valid@email.com\", Valid )\n , ( \"This is definitely not", "end": 716, "score": 0.9998978376, "start": 701, "tag": "EMAIL", "value": "valid@email.com" } ]
example/tests/ValidationTests.elm
bowst/elm-form
2
module ValidationTests exposing (..) import Form.Error import Form.Test import Form.Test.ValidationExpectation exposing (ValidationExpectation(..)) import Form.Validate import Model import Test exposing (..) suite : Test suite = describe "validations" [ Form.Test.describeValidation "superpower" Model.validateSuperpower [ ( "invisible", Valid ) , ( "unvisible", Invalid (Form.Error.CustomError Model.InvalidSuperpower) ) , ( "invisible", ValidDecodesTo Model.Invisible ) , ( "flying", ValidDecodesTo Model.Flying ) ] , Form.Test.describeValidation "email" Form.Validate.email [ ( "valid@email.com", Valid ) , ( "This is definitely not an email address", Invalid Form.Error.InvalidEmail ) , ( "stillvalid@withoutTLD", Valid ) ] , Form.Test.describeValidation "naturalInt" Model.naturalInt [ ( "123", ValidDecodesTo 123 ) , ( "-123", Invalid (Form.Error.CustomError Model.Nope) ) ] ]
46275
module ValidationTests exposing (..) import Form.Error import Form.Test import Form.Test.ValidationExpectation exposing (ValidationExpectation(..)) import Form.Validate import Model import Test exposing (..) suite : Test suite = describe "validations" [ Form.Test.describeValidation "superpower" Model.validateSuperpower [ ( "invisible", Valid ) , ( "unvisible", Invalid (Form.Error.CustomError Model.InvalidSuperpower) ) , ( "invisible", ValidDecodesTo Model.Invisible ) , ( "flying", ValidDecodesTo Model.Flying ) ] , Form.Test.describeValidation "email" Form.Validate.email [ ( "<EMAIL>", Valid ) , ( "This is definitely not an email address", Invalid Form.Error.InvalidEmail ) , ( "stillvalid@withoutTLD", Valid ) ] , Form.Test.describeValidation "naturalInt" Model.naturalInt [ ( "123", ValidDecodesTo 123 ) , ( "-123", Invalid (Form.Error.CustomError Model.Nope) ) ] ]
true
module ValidationTests exposing (..) import Form.Error import Form.Test import Form.Test.ValidationExpectation exposing (ValidationExpectation(..)) import Form.Validate import Model import Test exposing (..) suite : Test suite = describe "validations" [ Form.Test.describeValidation "superpower" Model.validateSuperpower [ ( "invisible", Valid ) , ( "unvisible", Invalid (Form.Error.CustomError Model.InvalidSuperpower) ) , ( "invisible", ValidDecodesTo Model.Invisible ) , ( "flying", ValidDecodesTo Model.Flying ) ] , Form.Test.describeValidation "email" Form.Validate.email [ ( "PI:EMAIL:<EMAIL>END_PI", Valid ) , ( "This is definitely not an email address", Invalid Form.Error.InvalidEmail ) , ( "stillvalid@withoutTLD", Valid ) ] , Form.Test.describeValidation "naturalInt" Model.naturalInt [ ( "123", ValidDecodesTo 123 ) , ( "-123", Invalid (Form.Error.CustomError Model.Nope) ) ] ]
elm
[ { "context": "icient probabilistic data structure, \nconceived by Burton Howard Bloom in 1970, that is used to test whether an\nelement ", "end": 981, "score": 0.9998506904, "start": 962, "tag": "NAME", "value": "Burton Howard Bloom" } ]
tests/Tests.elm
tasuki/elm-bloom
3
module Tests exposing (..) import Test exposing (..) import Expect import String import Bloom exposing (empty, add) import Regex exposing (Regex) import Array createTest : a -> ( b, b ) -> Test createTest i (expected, result) = test ("Test " ++ (Debug.toString i)) <| \() -> Expect.equal expected result createSuite : ( String, List ( a, a ) ) -> Test createSuite (suiteName, cases) = describe suiteName (List.indexedMap createTest cases) regex : String -> Regex regex str = Maybe.withDefault Regex.never <| Regex.fromString str trim : String -> String trim word = word |> Regex.replace (regex "^\\W+") (\_ -> "") |> Regex.replace (regex "\\W+$") (\_ -> "") tokenize : String -> List String tokenize = String.toLower >> String.words >> List.map trim >> List.filter ((/=) "") longText : List String longText = """ A Bloom filter is a space-efficient probabilistic data structure, conceived by Burton Howard Bloom in 1970, that is used to test whether an element is a member of a set. False positive matches are possible, but false negatives are not, thus a Bloom filter has a 100% recall rate. In other words, a query returns either "possibly in set" or "definitely not in set". Elements can be added to the set, but not removed (though this can be addressed with a "counting" filter). The more elements that are added to the set, the larger the probability of false positives. """ |> tokenize testCreate : ( String, List ( List number, List Int ) ) testCreate = Tuple.pair "Create Bloom Filter" [ ([], (empty 0 0 |> .set |> Array.toList)) , ([0,0,0,0,0,0,0,0,0,0], (empty 10 3 |> .set |> Array.toList)) ] testFilter : ( String, List ( Bool, Bool ) ) testFilter = let s = List.foldr add (empty 20 3) ["foo","bar","baz"] t = List.foldr add (empty 1000 4) longText checkT = List.map (\w -> Bloom.test w t) longText in Tuple.pair "Use Bloom Filter" [ (True, (Bloom.test "foo" s)) , (True, (Bloom.test "bar" s)) , (True, (Bloom.test "baz" s)) , (False, (Bloom.test "fuo" s)) , (False, (Bloom.test "bas" s)) , (False, (Bloom.test "bak" s)) , (True, (List.all identity checkT)) , (False, (Bloom.test "jorge" t)) , (False, (Bloom.test "luis" t)) , (False, (Bloom.test "borges" t)) ] all : Test all = describe "Bloom Filter" [createSuite testCreate, createSuite testFilter]
24229
module Tests exposing (..) import Test exposing (..) import Expect import String import Bloom exposing (empty, add) import Regex exposing (Regex) import Array createTest : a -> ( b, b ) -> Test createTest i (expected, result) = test ("Test " ++ (Debug.toString i)) <| \() -> Expect.equal expected result createSuite : ( String, List ( a, a ) ) -> Test createSuite (suiteName, cases) = describe suiteName (List.indexedMap createTest cases) regex : String -> Regex regex str = Maybe.withDefault Regex.never <| Regex.fromString str trim : String -> String trim word = word |> Regex.replace (regex "^\\W+") (\_ -> "") |> Regex.replace (regex "\\W+$") (\_ -> "") tokenize : String -> List String tokenize = String.toLower >> String.words >> List.map trim >> List.filter ((/=) "") longText : List String longText = """ A Bloom filter is a space-efficient probabilistic data structure, conceived by <NAME> in 1970, that is used to test whether an element is a member of a set. False positive matches are possible, but false negatives are not, thus a Bloom filter has a 100% recall rate. In other words, a query returns either "possibly in set" or "definitely not in set". Elements can be added to the set, but not removed (though this can be addressed with a "counting" filter). The more elements that are added to the set, the larger the probability of false positives. """ |> tokenize testCreate : ( String, List ( List number, List Int ) ) testCreate = Tuple.pair "Create Bloom Filter" [ ([], (empty 0 0 |> .set |> Array.toList)) , ([0,0,0,0,0,0,0,0,0,0], (empty 10 3 |> .set |> Array.toList)) ] testFilter : ( String, List ( Bool, Bool ) ) testFilter = let s = List.foldr add (empty 20 3) ["foo","bar","baz"] t = List.foldr add (empty 1000 4) longText checkT = List.map (\w -> Bloom.test w t) longText in Tuple.pair "Use Bloom Filter" [ (True, (Bloom.test "foo" s)) , (True, (Bloom.test "bar" s)) , (True, (Bloom.test "baz" s)) , (False, (Bloom.test "fuo" s)) , (False, (Bloom.test "bas" s)) , (False, (Bloom.test "bak" s)) , (True, (List.all identity checkT)) , (False, (Bloom.test "jorge" t)) , (False, (Bloom.test "luis" t)) , (False, (Bloom.test "borges" t)) ] all : Test all = describe "Bloom Filter" [createSuite testCreate, createSuite testFilter]
true
module Tests exposing (..) import Test exposing (..) import Expect import String import Bloom exposing (empty, add) import Regex exposing (Regex) import Array createTest : a -> ( b, b ) -> Test createTest i (expected, result) = test ("Test " ++ (Debug.toString i)) <| \() -> Expect.equal expected result createSuite : ( String, List ( a, a ) ) -> Test createSuite (suiteName, cases) = describe suiteName (List.indexedMap createTest cases) regex : String -> Regex regex str = Maybe.withDefault Regex.never <| Regex.fromString str trim : String -> String trim word = word |> Regex.replace (regex "^\\W+") (\_ -> "") |> Regex.replace (regex "\\W+$") (\_ -> "") tokenize : String -> List String tokenize = String.toLower >> String.words >> List.map trim >> List.filter ((/=) "") longText : List String longText = """ A Bloom filter is a space-efficient probabilistic data structure, conceived by PI:NAME:<NAME>END_PI in 1970, that is used to test whether an element is a member of a set. False positive matches are possible, but false negatives are not, thus a Bloom filter has a 100% recall rate. In other words, a query returns either "possibly in set" or "definitely not in set". Elements can be added to the set, but not removed (though this can be addressed with a "counting" filter). The more elements that are added to the set, the larger the probability of false positives. """ |> tokenize testCreate : ( String, List ( List number, List Int ) ) testCreate = Tuple.pair "Create Bloom Filter" [ ([], (empty 0 0 |> .set |> Array.toList)) , ([0,0,0,0,0,0,0,0,0,0], (empty 10 3 |> .set |> Array.toList)) ] testFilter : ( String, List ( Bool, Bool ) ) testFilter = let s = List.foldr add (empty 20 3) ["foo","bar","baz"] t = List.foldr add (empty 1000 4) longText checkT = List.map (\w -> Bloom.test w t) longText in Tuple.pair "Use Bloom Filter" [ (True, (Bloom.test "foo" s)) , (True, (Bloom.test "bar" s)) , (True, (Bloom.test "baz" s)) , (False, (Bloom.test "fuo" s)) , (False, (Bloom.test "bas" s)) , (False, (Bloom.test "bak" s)) , (True, (List.all identity checkT)) , (False, (Bloom.test "jorge" t)) , (False, (Bloom.test "luis" t)) , (False, (Bloom.test "borges" t)) ] all : Test all = describe "Bloom Filter" [createSuite testCreate, createSuite testFilter]
elm
[ { "context": "e version of the OpenAPI document: 1.0\n Contact: sainth@sainth.de\n\n NOTE: This file is auto generated by the open", "end": 191, "score": 0.9999150038, "start": 175, "tag": "EMAIL", "value": "sainth@sainth.de" }, { "context": "d by the openapi-generator.\n https://github.com/openapitools/openapi-generator.git\n Do not edit this file ma", "end": 290, "score": 0.9996453524, "start": 278, "tag": "USERNAME", "value": "openapitools" } ]
elm/src/Data/DataStorage.elm
sainthDE/pgtune_frontend
0
{- pgtune A service to generate some optimized configuration parameters for PostgreSQL based on best practices. The version of the OpenAPI document: 1.0 Contact: sainth@sainth.de 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.DataStorage exposing (DataStorage(..), decoder, encode) import Dict exposing (Dict) import Json.Decode as Decode exposing (Decoder) import Json.Decode.Pipeline exposing (optional, required) import Json.Encode as Encode type DataStorage = HDD | SSD | SAN decoder : Decoder DataStorage decoder = Decode.string |> Decode.andThen (\str -> case str of "HDD" -> Decode.succeed HDD "SSD" -> Decode.succeed SSD "SAN" -> Decode.succeed SAN other -> Decode.fail <| "Unknown type: " ++ other ) encode : DataStorage -> Encode.Value encode model = case model of HDD -> Encode.string "HDD" SSD -> Encode.string "SSD" SAN -> Encode.string "SAN"
21116
{- pgtune A service to generate some optimized configuration parameters for PostgreSQL based on best practices. The version of the OpenAPI document: 1.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.DataStorage exposing (DataStorage(..), decoder, encode) import Dict exposing (Dict) import Json.Decode as Decode exposing (Decoder) import Json.Decode.Pipeline exposing (optional, required) import Json.Encode as Encode type DataStorage = HDD | SSD | SAN decoder : Decoder DataStorage decoder = Decode.string |> Decode.andThen (\str -> case str of "HDD" -> Decode.succeed HDD "SSD" -> Decode.succeed SSD "SAN" -> Decode.succeed SAN other -> Decode.fail <| "Unknown type: " ++ other ) encode : DataStorage -> Encode.Value encode model = case model of HDD -> Encode.string "HDD" SSD -> Encode.string "SSD" SAN -> Encode.string "SAN"
true
{- pgtune A service to generate some optimized configuration parameters for PostgreSQL based on best practices. The version of the OpenAPI document: 1.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.DataStorage exposing (DataStorage(..), decoder, encode) import Dict exposing (Dict) import Json.Decode as Decode exposing (Decoder) import Json.Decode.Pipeline exposing (optional, required) import Json.Encode as Encode type DataStorage = HDD | SSD | SAN decoder : Decoder DataStorage decoder = Decode.string |> Decode.andThen (\str -> case str of "HDD" -> Decode.succeed HDD "SSD" -> Decode.succeed SSD "SAN" -> Decode.succeed SAN other -> Decode.fail <| "Unknown type: " ++ other ) encode : DataStorage -> Encode.Value encode model = case model of HDD -> Encode.string "HDD" SSD -> Encode.string "SSD" SAN -> Encode.string "SAN"
elm
[ { "context": "tate of the MinePlace board.\n-- Copyright (c) 2018 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n", "end": 193, "score": 0.9998731613, "start": 179, "tag": "NAME", "value": "Bill St. Clair" }, { "context": "lace board.\n-- Copyright (c) 2018 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n-- Distributed under th", "end": 216, "score": 0.9999260902, "start": 195, "tag": "EMAIL", "value": "billstclair@gmail.com" }, { "context": " walls\n in\n { id = id\n , name = name\n , description = description\n , owner = own", "end": 13525, "score": 0.9863114953, "start": 13521, "tag": "NAME", "value": "name" }, { "context": "{ userid = userid\n , passwordHash = passwordHash\n }\n )\n |> required \"", "end": 23257, "score": 0.9988632202, "start": 23245, "tag": "PASSWORD", "value": "passwordHash" } ]
src/MinePlace/EncodeDecode.elm
billstclair/mineplace
1
---------------------------------------------------------------------- -- -- EncodeDecode.elm -- Functions for maintaining the state of the MinePlace board. -- Copyright (c) 2018 Bill St. Clair <billstclair@gmail.com> -- Some rights reserved. -- Distributed under the MIT License -- See LICENSE.txt -- ---------------------------------------------------------------------- module MinePlace.EncodeDecode exposing ( boardEncoder , boardSpecEncoder , decodeBoard , decodeBoardSpec , decodeModel , decodePaintedWalls , decodePlayer , locationDecoder , locationEncoder , messageDecoder , messageEncoder , modelEncoder , paintedWallsDecoder , paintedWallsEncoder , playerEncoder , stringToValue , valueToString ) import Dict exposing (Dict) import Json.Decode as JD exposing (Decoder) import Json.Decode.Pipeline exposing (hardcoded, optional, required) import Json.Encode as JE exposing (Value) import MinePlace.Board exposing (boardToStrings, setId, stringsToBoard) import MinePlace.Types as Types exposing ( Appearance(..) , Board , BoardSpec , Colors , Direction(..) , ErrorKind(..) , FullPlayer , Game , GameDescription , GameName , GamePlayer , Image(..) , Layout(..) , Location , Message(..) , Model , OwnedPlace , OwnedPlacement , PaintedWall , PaintedWalls , Player , PlayerName , Point , SavedModel , SideImages , StaticImages , Url ) import WebSocketFramework exposing (decodePlist, unknownMessage) import WebSocketFramework.EncodeDecode exposing (genericMessageDecoder) import WebSocketFramework.ServerInterface as ServerInterface import WebSocketFramework.Types exposing ( DecoderPlist , GameId , MessageDecoder , MessageEncoder , Plist , PublicGame , ReqRsp(..) , ServerUrl ) valueToString : Value -> String valueToString value = JE.encode 0 value stringToValue : String -> Value stringToValue string = JD.decodeString JD.value string |> Result.withDefault JE.null layoutEncoder : Layout -> Value layoutEncoder layout = JE.string <| layoutToString layout layoutToString : Layout -> String layoutToString layout = case layout of TopViewLayout -> "TopViewLayout" EditingLayout -> "EditingLayout" _ -> "NormalLayout" stringToLayout : String -> Layout stringToLayout string = case string of "TopViewLayout" -> TopViewLayout "EditingLayout" -> EditingLayout _ -> NormalLayout layoutDecoder : Decoder Layout layoutDecoder = JD.map stringToLayout JD.string colorsEncoder : Colors -> Value colorsEncoder colors = JE.object [ ( "windowBackground", JE.string colors.windowBackground ) , ( "textColor", JE.string colors.textColor ) , ( "errorBackground", JE.string colors.errorBackground ) , ( "errorColor", JE.string colors.errorColor ) , ( "borderStroke", JE.string colors.borderStroke ) , ( "borderFill", JE.string colors.borderFill ) , ( "playerStroke", JE.string colors.playerStroke ) , ( "playerFill", JE.string colors.playerFill ) , ( "editorHighlightStroke", JE.string colors.editorHighlightStroke ) , ( "editorHighlightFill", JE.string colors.editorHighlightFill ) , ( "lineStroke", JE.string colors.lineStroke ) ] colorsDecoder : Decoder Colors colorsDecoder = JD.succeed Colors |> required "windowBackground" JD.string |> required "textColor" JD.string |> required "errorBackground" JD.string |> required "errorColor" JD.string |> required "borderStroke" JD.string |> required "borderFill" JD.string |> required "playerStroke" JD.string |> required "playerFill" JD.string |> required "editorHighlightStroke" JD.string |> required "editorHighlightFill" JD.string |> required "lineStroke" JD.string modelEncoder : Model -> Value modelEncoder model = JE.object [ ( "layout", layoutEncoder model.layout ) , ( "colors", colorsEncoder model.colors ) ] modelDecoder : Decoder SavedModel modelDecoder = JD.map2 SavedModel (JD.field "layout" layoutDecoder) (JD.oneOf [ JD.field "colors" colorsDecoder , JD.succeed Types.lightColors ] ) decodeValue : Decoder a -> Value -> Result String a decodeValue decoder value = case JD.decodeValue decoder value of Ok a -> Ok a Err err -> Err <| JD.errorToString err decodeModel : Value -> Result String SavedModel decodeModel value = decodeValue modelDecoder value boardEncoder : Board -> Value boardEncoder board = JE.object [ ( "id", JE.string board.id ) , ( "spec", boardSpecEncoder board ) ] boardSpecEncoder : Board -> Value boardSpecEncoder board = boardToStrings board |> JE.list JE.string boardSpecDecoder : Decoder Board boardSpecDecoder = JD.list JD.string |> JD.map (stringsToBoard "") boardDecoder : Decoder Board boardDecoder = JD.map2 setId (JD.field "id" JD.string) (JD.field "spec" boardSpecDecoder) decodeBoard : Value -> Result String Board decodeBoard value = decodeValue boardDecoder value decodeBoardSpec : Value -> Result String Board decodeBoardSpec value = decodeValue boardSpecDecoder value locationEncoder : Location -> Value locationEncoder ( x, y ) = JE.object [ ( "x", JE.int x ) , ( "y", JE.int y ) ] locationDecoder : Decoder Location locationDecoder = JD.map2 (\a b -> ( a, b )) (JD.field "x" JD.int) (JD.field "y" JD.int) directionEncoder : Direction -> Value directionEncoder direction = JE.string <| Types.directionToString direction directionDecoder : Decoder Direction directionDecoder = JD.string |> JD.andThen (\s -> case Types.stringToDirection s of Just dir -> JD.succeed dir _ -> JD.fail "Unknown Direction" ) playerEncoder : Player -> Value playerEncoder player = JE.object [ ( "id", JE.string player.id ) , ( "boardid", JE.string player.boardid ) , ( "name", JE.string player.name ) , ( "location", locationEncoder player.location ) , ( "direction", directionEncoder player.direction ) ] playerDecoder : Decoder Player playerDecoder = JD.map5 Player (JD.field "id" JD.string) (JD.field "boardid" JD.string) (JD.field "name" JD.string) (JD.field "location" locationDecoder) (JD.field "direction" directionDecoder) decodePlayer : Value -> Result String Player decodePlayer value = decodeValue playerDecoder value {---- Message coding ----} pointEncoder : Point -> Value pointEncoder ( x, y ) = JE.list JE.float [ x, y ] pointDecoder : Decoder Point pointDecoder = JD.list JD.float |> JD.andThen (\p -> case p of [ x, y ] -> JD.succeed ( x, y ) _ -> JD.fail "Malformed point" ) imageEncoder : Image -> Value imageEncoder image = case image of UrlImage url -> JE.object [ ( "UrlImage", JE.string url ) ] VectorImage pointLists -> JE.object [ ( "VectorImage" , JE.list identity <| List.map (JE.list pointEncoder) pointLists ) ] imageDecoder : Decoder Image imageDecoder = JD.oneOf [ JD.map UrlImage <| JD.field "UrlImage" JD.string , JD.map VectorImage <| JD.field "VectorImage" (JD.list (JD.list pointDecoder)) ] sideImagesEncoder : SideImages -> Value sideImagesEncoder images = JE.object [ ( "front", JE.list imageEncoder images.front ) , ( "back", JE.list imageEncoder images.back ) , ( "left", JE.list imageEncoder images.left ) , ( "right", JE.list imageEncoder images.right ) ] sideImagesDecoder : Decoder SideImages sideImagesDecoder = JD.succeed SideImages |> required "front" (JD.list imageDecoder) |> required "back" (JD.list imageDecoder) |> required "left" (JD.list imageDecoder) |> required "right" (JD.list imageDecoder) staticImagesEncoder : StaticImages -> Value staticImagesEncoder { front, back, left, right } = JE.object [ ( "front", imageEncoder front ) , ( "back", imageEncoder back ) , ( "left", imageEncoder left ) , ( "right", imageEncoder right ) ] staticImagesDecoder : Decoder StaticImages staticImagesDecoder = JD.succeed StaticImages |> required "front" imageDecoder |> required "back" imageDecoder |> required "left" imageDecoder |> required "right" imageDecoder appearanceEncoder : Appearance -> Value appearanceEncoder appearance = case appearance of InvisibleAppearance -> JE.object [ ( "InvisibleAppearance", JE.null ) ] DefaultAppearance -> JE.object [ ( "DefaultAppearance", JE.null ) ] StaticImageAppearance staticImages -> JE.object [ ( "StaticImageAppearance", staticImagesEncoder staticImages ) ] VaryingAppearance sideImages -> JE.object [ ( "VaryingAppearance", sideImagesEncoder sideImages ) ] appearanceDecoder : Decoder Appearance appearanceDecoder = JD.oneOf [ JD.map (\_ -> InvisibleAppearance) <| JD.field "InvisibleAppearance" JD.value , JD.map (\_ -> DefaultAppearance) <| JD.field "DefaultAppearance" JD.value , JD.map StaticImageAppearance <| JD.field "StaticImageAppearance" staticImagesDecoder , JD.map VaryingAppearance <| JD.field "VaryingAppearance" sideImagesDecoder ] fullPlayerEncoder : FullPlayer -> Value fullPlayerEncoder player = JE.object [ ( "id", JE.string player.id ) , ( "name", JE.string player.name ) , ( "appearance", appearanceEncoder player.appearance ) , ( "location", locationEncoder player.location ) , ( "direction", directionEncoder player.direction ) ] fullPlayerDecoder : Decoder FullPlayer fullPlayerDecoder = JD.succeed FullPlayer |> required "id" JD.string |> required "name" JD.string |> required "appearance" appearanceDecoder |> required "location" locationDecoder |> required "direction" directionDecoder paintedWallEncoder : PaintedWall -> Value paintedWallEncoder image = JE.object [ ( "owner", JE.string image.owner ) , ( "location", locationEncoder image.location ) , ( "direction", directionEncoder image.direction ) , ( "image", imageEncoder image.image ) ] paintedWallDecoder : Decoder PaintedWall paintedWallDecoder = JD.succeed PaintedWall |> required "owner" JD.string |> required "location" locationDecoder |> required "direction" directionDecoder |> required "image" imageDecoder {-| We'll need another encoder for the persistent store. It will store the dicts as separately-indexed items, to reduce bandwidth. -} gameEncoder : Game -> Value gameEncoder game = JE.object [ ( "id", JE.string game.id ) , ( "name", JE.string game.name ) , ( "description", JE.string game.description ) , ( "owner", JE.string game.owner ) , ( "board", boardEncoder game.board ) , ( "players" , JE.list fullPlayerEncoder <| Dict.values game.playerDict ) , ( "walls" , JE.list paintedWallEncoder <| List.concat (Dict.values game.wallsDict) ) ] makeGame : String -> String -> String -> String -> Board -> List FullPlayer -> List PaintedWall -> Game makeGame id name description owner board players walls = let playerNamesDict = List.foldr (\player dict -> Dict.insert player.location (case Dict.get player.location dict of Nothing -> [ player.name ] Just playrs -> player.name :: playrs ) dict ) Dict.empty players wallsDict = List.foldr (\wall dict -> Dict.insert wall.location (case Dict.get wall.location dict of Nothing -> [ wall ] Just ws -> wall :: ws ) dict ) Dict.empty walls in { id = id , name = name , description = description , owner = owner , board = board , playerDict = Dict.fromList <| List.map (\player -> ( player.name, player )) players , playerNamesDict = playerNamesDict , wallsDict = wallsDict } gameDecoder : Decoder Game gameDecoder = JD.succeed makeGame |> required "id" JD.string |> required "name" JD.string |> required "description" JD.string |> required "owner" JD.string |> required "board" boardDecoder |> required "players" (JD.list fullPlayerDecoder) |> required "walls" (JD.list paintedWallDecoder) gameDescriptionEncoder : GameDescription -> Value gameDescriptionEncoder description = JE.object [ ( "name", JE.string description.name ) , ( "description", JE.string description.description ) , ( "owner", JE.string description.owner ) ] gameDescriptionDecoder : Decoder GameDescription gameDescriptionDecoder = JD.succeed GameDescription |> required "name" JD.string |> required "description" JD.string |> required "owner" JD.string gamePlayerEncoder : GamePlayer -> Value gamePlayerEncoder player = JE.object [ ( "player", JE.string player.player ) , ( "gameid", JE.string player.gameid ) ] gamePlayerDecoder : Decoder GamePlayer gamePlayerDecoder = JD.succeed GamePlayer |> required "player" JD.string |> required "gameid" JD.string ownedPlaceEncoder : OwnedPlace -> Value ownedPlaceEncoder place = JE.object [ ( "player", gamePlayerEncoder place.player ) , ( "location", locationEncoder place.location ) ] ownedPlaceDecoder : Decoder OwnedPlace ownedPlaceDecoder = JD.succeed OwnedPlace |> required "player" gamePlayerDecoder |> required "location" locationDecoder ownedPlacementEncoder : OwnedPlacement -> Value ownedPlacementEncoder place = JE.object [ ( "player", gamePlayerEncoder place.player ) , ( "location", locationEncoder place.location ) , ( "direction", directionEncoder place.direction ) ] ownedPlacementDecoder : Decoder OwnedPlacement ownedPlacementDecoder = JD.succeed OwnedPlacement |> required "player" gamePlayerDecoder |> required "location" locationDecoder |> required "direction" directionDecoder errorKindEncoder : ErrorKind -> Value errorKindEncoder kind = case kind of ValidationFailedError -> JE.object [ ( "ValidationFailedError", JE.null ) ] UnknownPlayerIdError playerid -> JE.object [ ( "UnknownPlayerIdError", JE.string playerid ) ] UnknownPlayerError player -> JE.object [ ( "UnknownPlayerError", gamePlayerEncoder player ) ] IllegalMoveError place -> JE.object [ ( "IllegalMoveError", ownedPlaceEncoder place ) ] IllegalWallLocationError placement -> JE.object [ ( "IllegalWallLocationError" , ownedPlacementEncoder placement ) ] UnknownAppearanceError appearanceName -> JE.object [ ( "UnknownAppearanceError", JE.string appearanceName ) ] UnknownImageError imageName -> JE.object [ ( "UnknownImageError", JE.string imageName ) ] RandomError message -> JE.object [ ( "RandomError", JE.string message ) ] errorKindDecoder : Decoder ErrorKind errorKindDecoder = JD.oneOf [ JD.map (\_ -> ValidationFailedError) <| JD.field "ValidationFailedError" JD.value , JD.map UnknownPlayerIdError <| JD.field "UnknownPlayerIdError" JD.string , JD.map UnknownPlayerError <| JD.field "UnknownPlayerError" gamePlayerDecoder , JD.map IllegalMoveError <| JD.field "IllegalMoveError" ownedPlaceDecoder , JD.map IllegalWallLocationError <| JD.field "IllegalWallLocationError" ownedPlacementDecoder , JD.map UnknownAppearanceError <| JD.field "UnknownAppearanceError" JD.string , JD.map UnknownImageError <| JD.field "UnknownImageError" JD.string , JD.map RandomError <| JD.field "RandomError" JD.string ] {-| This is `Json.Encode.Extra.maybe` in elm-community/json-extra. I'm not including that whole package just for this one function. -} maybeNull : (a -> Value) -> Maybe a -> Value maybeNull encoder ma = Maybe.map encoder ma |> Maybe.withDefault JE.null messageEncoder : MessageEncoder Message messageEncoder msg = case msg of PingReq { message } -> ( Req "ping" , [ ( "message", JE.string message ) ] ) PongRsp { message } -> ( Rsp "pong" , [ ( "message", JE.string message ) ] ) ErrorRsp { error, message } -> ( Rsp "error" , [ ( "error", errorKindEncoder error ) , ( "message", JE.string message ) ] ) LoginWithPasswordReq { userid, passwordHash } -> ( Req "loginWithPassword" , [ ( "userid", JE.string userid ) , ( "passwordHash", JE.string passwordHash ) ] ) LoginRsp { playerid, currentGame, allGames } -> ( Rsp "login" , [ ( "playerid", JE.string playerid ) , ( "currentGame" , case currentGame of Nothing -> JE.null Just gameid -> JE.string gameid ) , ( "allGames" , JE.list gamePlayerEncoder allGames ) ] ) LogoutReq { playerid } -> ( Req "logout" , [ ( "playerid", JE.string playerid ) ] ) LogoutRsp { players } -> ( Rsp "logout" , [ ( "players" , JE.list gamePlayerEncoder players ) ] ) JoinGameReq { playerid, player } -> ( Req "joinGame" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) ] ) NewGameReq { playerid, game } -> ( Req "newGame" , [ ( "playerid", JE.string playerid ) , ( "game", gameEncoder game ) ] ) JoinGameRsp { player, game } -> ( Rsp "joinGame" , [ ( "player", gamePlayerEncoder player ) , ( "game", gameEncoder game ) ] ) JoinGameNotificationRsp { player, location, direction } -> ( Rsp "joinGameNotification" , [ ( "player", gamePlayerEncoder player ) , ( "location", locationEncoder location ) , ( "direction", directionEncoder direction ) ] ) LeaveReq { playerid, player } -> ( Req "leave" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) ] ) LeaveRsp { player } -> ( Rsp "leave" , [ ( "player", gamePlayerEncoder player ) ] ) ExitReq { playerid, player } -> ( Req "exit" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) ] ) ExitRsp { player } -> ( Rsp "exit" , [ ( "player", gamePlayerEncoder player ) ] ) MoveReq { playerid, player, location, direction } -> ( Req "move" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) , ( "location", maybeNull locationEncoder location ) , ( "direction", maybeNull directionEncoder direction ) ] ) MoveRsp { player, location, direction } -> ( Rsp "move" , [ ( "player", gamePlayerEncoder player ) , ( "location", locationEncoder location ) , ( "direction", directionEncoder direction ) ] ) _ -> ( Req "todo" , [] ) messageDecoder : MessageDecoder Message messageDecoder reqrspAndPlist = genericMessageDecoder reqPlist rspPlist reqrspAndPlist reqPlist : DecoderPlist Message reqPlist = [ ( "ping", pingReqDecoder ) , ( "loginWithPassword", loginWithPasswordReqDecoder ) , ( "logout", logoutReqDecoder ) , ( "joinGame", joinGameReqDecoder ) , ( "newGame", newGameReqDecoder ) , ( "leave", leaveReqDecoder ) , ( "exit", exitReqDecoder ) , ( "move", moveReqDecoder ) ] rspPlist : DecoderPlist Message rspPlist = [ ( "pong", pongRspDecoder ) , ( "error", errorRspDecoder ) , ( "login", loginRspDecoder ) , ( "logout", logoutRspDecoder ) , ( "joinGame", joinGameRspDecoder ) , ( "joinGameNotification", joinGameNotificationRspDecoder ) , ( "leave", leaveRspDecoder ) , ( "exit", exitRspDecoder ) , ( "move", moveRspDecoder ) ] {---- Req decoders ----} pingReqDecoder : Decoder Message pingReqDecoder = JD.map (\message -> PingReq { message = message }) (JD.field "message" JD.string) loginWithPasswordReqDecoder : Decoder Message loginWithPasswordReqDecoder = JD.succeed (\userid passwordHash -> LoginWithPasswordReq { userid = userid , passwordHash = passwordHash } ) |> required "userid" JD.string |> required "passwordHash" JD.string logoutReqDecoder : Decoder Message logoutReqDecoder = JD.succeed (\playerid -> LogoutReq { playerid = playerid } ) |> required "playerid" JD.string joinGameReqDecoder : Decoder Message joinGameReqDecoder = JD.succeed (\playerid player -> JoinGameReq { playerid = playerid , player = player } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder newGameReqDecoder : Decoder Message newGameReqDecoder = JD.succeed (\playerid game -> NewGameReq { playerid = playerid , game = game } ) |> required "playerid" JD.string |> required "game" gameDecoder leaveReqDecoder : Decoder Message leaveReqDecoder = JD.succeed (\playerid player -> LeaveReq { playerid = playerid , player = player } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder exitReqDecoder : Decoder Message exitReqDecoder = JD.succeed (\playerid player -> ExitReq { playerid = playerid , player = player } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder moveReqDecoder : Decoder Message moveReqDecoder = JD.succeed (\playerid player location direction -> MoveReq { playerid = playerid , player = player , location = location , direction = direction } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder |> required "location" (JD.nullable locationDecoder) |> required "direction" (JD.nullable directionDecoder) {---- Rsp decoders ----} pongRspDecoder : Decoder Message pongRspDecoder = JD.map (\message -> PongRsp { message = message }) (JD.field "message" JD.string) errorRspDecoder : Decoder Message errorRspDecoder = JD.succeed (\error message -> ErrorRsp { error = error , message = message } ) |> required "error" errorKindDecoder |> required "message" JD.string loginRspDecoder : Decoder Message loginRspDecoder = JD.succeed (\playerid currentGame allGames -> LoginRsp { playerid = playerid , currentGame = currentGame , allGames = allGames } ) |> required "playerid" JD.string |> required "currentGame" (JD.nullable JD.string) |> required "allGames" (JD.list gamePlayerDecoder) logoutRspDecoder : Decoder Message logoutRspDecoder = JD.succeed (\players -> LogoutRsp { players = players } ) |> required "players" (JD.list gamePlayerDecoder) joinGameRspDecoder : Decoder Message joinGameRspDecoder = JD.succeed (\player game -> JoinGameRsp { player = player , game = game } ) |> required "player" gamePlayerDecoder |> required "game" gameDecoder joinGameNotificationRspDecoder : Decoder Message joinGameNotificationRspDecoder = JD.succeed (\player location direction -> JoinGameNotificationRsp { player = player , location = location , direction = direction } ) |> required "player" gamePlayerDecoder |> required "location" locationDecoder |> required "direction" directionDecoder leaveRspDecoder : Decoder Message leaveRspDecoder = JD.succeed (\player -> LeaveRsp { player = player } ) |> required "player" gamePlayerDecoder exitRspDecoder : Decoder Message exitRspDecoder = JD.succeed (\player -> ExitRsp { player = player } ) |> required "player" gamePlayerDecoder moveRspDecoder : Decoder Message moveRspDecoder = JD.succeed (\player location direction -> MoveRsp { player = player , location = location , direction = direction } ) |> required "player" gamePlayerDecoder |> required "location" locationDecoder |> required "direction" directionDecoder paintedWallsEncoder : PaintedWalls -> Value paintedWallsEncoder walls = JE.list paintedWallEncoder walls paintedWallsDecoder : Decoder PaintedWalls paintedWallsDecoder = JD.list paintedWallDecoder decodePaintedWalls : Value -> Result String PaintedWalls decodePaintedWalls value = decodeValue paintedWallsDecoder value
50067
---------------------------------------------------------------------- -- -- EncodeDecode.elm -- Functions for maintaining the state of the MinePlace board. -- Copyright (c) 2018 <NAME> <<EMAIL>> -- Some rights reserved. -- Distributed under the MIT License -- See LICENSE.txt -- ---------------------------------------------------------------------- module MinePlace.EncodeDecode exposing ( boardEncoder , boardSpecEncoder , decodeBoard , decodeBoardSpec , decodeModel , decodePaintedWalls , decodePlayer , locationDecoder , locationEncoder , messageDecoder , messageEncoder , modelEncoder , paintedWallsDecoder , paintedWallsEncoder , playerEncoder , stringToValue , valueToString ) import Dict exposing (Dict) import Json.Decode as JD exposing (Decoder) import Json.Decode.Pipeline exposing (hardcoded, optional, required) import Json.Encode as JE exposing (Value) import MinePlace.Board exposing (boardToStrings, setId, stringsToBoard) import MinePlace.Types as Types exposing ( Appearance(..) , Board , BoardSpec , Colors , Direction(..) , ErrorKind(..) , FullPlayer , Game , GameDescription , GameName , GamePlayer , Image(..) , Layout(..) , Location , Message(..) , Model , OwnedPlace , OwnedPlacement , PaintedWall , PaintedWalls , Player , PlayerName , Point , SavedModel , SideImages , StaticImages , Url ) import WebSocketFramework exposing (decodePlist, unknownMessage) import WebSocketFramework.EncodeDecode exposing (genericMessageDecoder) import WebSocketFramework.ServerInterface as ServerInterface import WebSocketFramework.Types exposing ( DecoderPlist , GameId , MessageDecoder , MessageEncoder , Plist , PublicGame , ReqRsp(..) , ServerUrl ) valueToString : Value -> String valueToString value = JE.encode 0 value stringToValue : String -> Value stringToValue string = JD.decodeString JD.value string |> Result.withDefault JE.null layoutEncoder : Layout -> Value layoutEncoder layout = JE.string <| layoutToString layout layoutToString : Layout -> String layoutToString layout = case layout of TopViewLayout -> "TopViewLayout" EditingLayout -> "EditingLayout" _ -> "NormalLayout" stringToLayout : String -> Layout stringToLayout string = case string of "TopViewLayout" -> TopViewLayout "EditingLayout" -> EditingLayout _ -> NormalLayout layoutDecoder : Decoder Layout layoutDecoder = JD.map stringToLayout JD.string colorsEncoder : Colors -> Value colorsEncoder colors = JE.object [ ( "windowBackground", JE.string colors.windowBackground ) , ( "textColor", JE.string colors.textColor ) , ( "errorBackground", JE.string colors.errorBackground ) , ( "errorColor", JE.string colors.errorColor ) , ( "borderStroke", JE.string colors.borderStroke ) , ( "borderFill", JE.string colors.borderFill ) , ( "playerStroke", JE.string colors.playerStroke ) , ( "playerFill", JE.string colors.playerFill ) , ( "editorHighlightStroke", JE.string colors.editorHighlightStroke ) , ( "editorHighlightFill", JE.string colors.editorHighlightFill ) , ( "lineStroke", JE.string colors.lineStroke ) ] colorsDecoder : Decoder Colors colorsDecoder = JD.succeed Colors |> required "windowBackground" JD.string |> required "textColor" JD.string |> required "errorBackground" JD.string |> required "errorColor" JD.string |> required "borderStroke" JD.string |> required "borderFill" JD.string |> required "playerStroke" JD.string |> required "playerFill" JD.string |> required "editorHighlightStroke" JD.string |> required "editorHighlightFill" JD.string |> required "lineStroke" JD.string modelEncoder : Model -> Value modelEncoder model = JE.object [ ( "layout", layoutEncoder model.layout ) , ( "colors", colorsEncoder model.colors ) ] modelDecoder : Decoder SavedModel modelDecoder = JD.map2 SavedModel (JD.field "layout" layoutDecoder) (JD.oneOf [ JD.field "colors" colorsDecoder , JD.succeed Types.lightColors ] ) decodeValue : Decoder a -> Value -> Result String a decodeValue decoder value = case JD.decodeValue decoder value of Ok a -> Ok a Err err -> Err <| JD.errorToString err decodeModel : Value -> Result String SavedModel decodeModel value = decodeValue modelDecoder value boardEncoder : Board -> Value boardEncoder board = JE.object [ ( "id", JE.string board.id ) , ( "spec", boardSpecEncoder board ) ] boardSpecEncoder : Board -> Value boardSpecEncoder board = boardToStrings board |> JE.list JE.string boardSpecDecoder : Decoder Board boardSpecDecoder = JD.list JD.string |> JD.map (stringsToBoard "") boardDecoder : Decoder Board boardDecoder = JD.map2 setId (JD.field "id" JD.string) (JD.field "spec" boardSpecDecoder) decodeBoard : Value -> Result String Board decodeBoard value = decodeValue boardDecoder value decodeBoardSpec : Value -> Result String Board decodeBoardSpec value = decodeValue boardSpecDecoder value locationEncoder : Location -> Value locationEncoder ( x, y ) = JE.object [ ( "x", JE.int x ) , ( "y", JE.int y ) ] locationDecoder : Decoder Location locationDecoder = JD.map2 (\a b -> ( a, b )) (JD.field "x" JD.int) (JD.field "y" JD.int) directionEncoder : Direction -> Value directionEncoder direction = JE.string <| Types.directionToString direction directionDecoder : Decoder Direction directionDecoder = JD.string |> JD.andThen (\s -> case Types.stringToDirection s of Just dir -> JD.succeed dir _ -> JD.fail "Unknown Direction" ) playerEncoder : Player -> Value playerEncoder player = JE.object [ ( "id", JE.string player.id ) , ( "boardid", JE.string player.boardid ) , ( "name", JE.string player.name ) , ( "location", locationEncoder player.location ) , ( "direction", directionEncoder player.direction ) ] playerDecoder : Decoder Player playerDecoder = JD.map5 Player (JD.field "id" JD.string) (JD.field "boardid" JD.string) (JD.field "name" JD.string) (JD.field "location" locationDecoder) (JD.field "direction" directionDecoder) decodePlayer : Value -> Result String Player decodePlayer value = decodeValue playerDecoder value {---- Message coding ----} pointEncoder : Point -> Value pointEncoder ( x, y ) = JE.list JE.float [ x, y ] pointDecoder : Decoder Point pointDecoder = JD.list JD.float |> JD.andThen (\p -> case p of [ x, y ] -> JD.succeed ( x, y ) _ -> JD.fail "Malformed point" ) imageEncoder : Image -> Value imageEncoder image = case image of UrlImage url -> JE.object [ ( "UrlImage", JE.string url ) ] VectorImage pointLists -> JE.object [ ( "VectorImage" , JE.list identity <| List.map (JE.list pointEncoder) pointLists ) ] imageDecoder : Decoder Image imageDecoder = JD.oneOf [ JD.map UrlImage <| JD.field "UrlImage" JD.string , JD.map VectorImage <| JD.field "VectorImage" (JD.list (JD.list pointDecoder)) ] sideImagesEncoder : SideImages -> Value sideImagesEncoder images = JE.object [ ( "front", JE.list imageEncoder images.front ) , ( "back", JE.list imageEncoder images.back ) , ( "left", JE.list imageEncoder images.left ) , ( "right", JE.list imageEncoder images.right ) ] sideImagesDecoder : Decoder SideImages sideImagesDecoder = JD.succeed SideImages |> required "front" (JD.list imageDecoder) |> required "back" (JD.list imageDecoder) |> required "left" (JD.list imageDecoder) |> required "right" (JD.list imageDecoder) staticImagesEncoder : StaticImages -> Value staticImagesEncoder { front, back, left, right } = JE.object [ ( "front", imageEncoder front ) , ( "back", imageEncoder back ) , ( "left", imageEncoder left ) , ( "right", imageEncoder right ) ] staticImagesDecoder : Decoder StaticImages staticImagesDecoder = JD.succeed StaticImages |> required "front" imageDecoder |> required "back" imageDecoder |> required "left" imageDecoder |> required "right" imageDecoder appearanceEncoder : Appearance -> Value appearanceEncoder appearance = case appearance of InvisibleAppearance -> JE.object [ ( "InvisibleAppearance", JE.null ) ] DefaultAppearance -> JE.object [ ( "DefaultAppearance", JE.null ) ] StaticImageAppearance staticImages -> JE.object [ ( "StaticImageAppearance", staticImagesEncoder staticImages ) ] VaryingAppearance sideImages -> JE.object [ ( "VaryingAppearance", sideImagesEncoder sideImages ) ] appearanceDecoder : Decoder Appearance appearanceDecoder = JD.oneOf [ JD.map (\_ -> InvisibleAppearance) <| JD.field "InvisibleAppearance" JD.value , JD.map (\_ -> DefaultAppearance) <| JD.field "DefaultAppearance" JD.value , JD.map StaticImageAppearance <| JD.field "StaticImageAppearance" staticImagesDecoder , JD.map VaryingAppearance <| JD.field "VaryingAppearance" sideImagesDecoder ] fullPlayerEncoder : FullPlayer -> Value fullPlayerEncoder player = JE.object [ ( "id", JE.string player.id ) , ( "name", JE.string player.name ) , ( "appearance", appearanceEncoder player.appearance ) , ( "location", locationEncoder player.location ) , ( "direction", directionEncoder player.direction ) ] fullPlayerDecoder : Decoder FullPlayer fullPlayerDecoder = JD.succeed FullPlayer |> required "id" JD.string |> required "name" JD.string |> required "appearance" appearanceDecoder |> required "location" locationDecoder |> required "direction" directionDecoder paintedWallEncoder : PaintedWall -> Value paintedWallEncoder image = JE.object [ ( "owner", JE.string image.owner ) , ( "location", locationEncoder image.location ) , ( "direction", directionEncoder image.direction ) , ( "image", imageEncoder image.image ) ] paintedWallDecoder : Decoder PaintedWall paintedWallDecoder = JD.succeed PaintedWall |> required "owner" JD.string |> required "location" locationDecoder |> required "direction" directionDecoder |> required "image" imageDecoder {-| We'll need another encoder for the persistent store. It will store the dicts as separately-indexed items, to reduce bandwidth. -} gameEncoder : Game -> Value gameEncoder game = JE.object [ ( "id", JE.string game.id ) , ( "name", JE.string game.name ) , ( "description", JE.string game.description ) , ( "owner", JE.string game.owner ) , ( "board", boardEncoder game.board ) , ( "players" , JE.list fullPlayerEncoder <| Dict.values game.playerDict ) , ( "walls" , JE.list paintedWallEncoder <| List.concat (Dict.values game.wallsDict) ) ] makeGame : String -> String -> String -> String -> Board -> List FullPlayer -> List PaintedWall -> Game makeGame id name description owner board players walls = let playerNamesDict = List.foldr (\player dict -> Dict.insert player.location (case Dict.get player.location dict of Nothing -> [ player.name ] Just playrs -> player.name :: playrs ) dict ) Dict.empty players wallsDict = List.foldr (\wall dict -> Dict.insert wall.location (case Dict.get wall.location dict of Nothing -> [ wall ] Just ws -> wall :: ws ) dict ) Dict.empty walls in { id = id , name = <NAME> , description = description , owner = owner , board = board , playerDict = Dict.fromList <| List.map (\player -> ( player.name, player )) players , playerNamesDict = playerNamesDict , wallsDict = wallsDict } gameDecoder : Decoder Game gameDecoder = JD.succeed makeGame |> required "id" JD.string |> required "name" JD.string |> required "description" JD.string |> required "owner" JD.string |> required "board" boardDecoder |> required "players" (JD.list fullPlayerDecoder) |> required "walls" (JD.list paintedWallDecoder) gameDescriptionEncoder : GameDescription -> Value gameDescriptionEncoder description = JE.object [ ( "name", JE.string description.name ) , ( "description", JE.string description.description ) , ( "owner", JE.string description.owner ) ] gameDescriptionDecoder : Decoder GameDescription gameDescriptionDecoder = JD.succeed GameDescription |> required "name" JD.string |> required "description" JD.string |> required "owner" JD.string gamePlayerEncoder : GamePlayer -> Value gamePlayerEncoder player = JE.object [ ( "player", JE.string player.player ) , ( "gameid", JE.string player.gameid ) ] gamePlayerDecoder : Decoder GamePlayer gamePlayerDecoder = JD.succeed GamePlayer |> required "player" JD.string |> required "gameid" JD.string ownedPlaceEncoder : OwnedPlace -> Value ownedPlaceEncoder place = JE.object [ ( "player", gamePlayerEncoder place.player ) , ( "location", locationEncoder place.location ) ] ownedPlaceDecoder : Decoder OwnedPlace ownedPlaceDecoder = JD.succeed OwnedPlace |> required "player" gamePlayerDecoder |> required "location" locationDecoder ownedPlacementEncoder : OwnedPlacement -> Value ownedPlacementEncoder place = JE.object [ ( "player", gamePlayerEncoder place.player ) , ( "location", locationEncoder place.location ) , ( "direction", directionEncoder place.direction ) ] ownedPlacementDecoder : Decoder OwnedPlacement ownedPlacementDecoder = JD.succeed OwnedPlacement |> required "player" gamePlayerDecoder |> required "location" locationDecoder |> required "direction" directionDecoder errorKindEncoder : ErrorKind -> Value errorKindEncoder kind = case kind of ValidationFailedError -> JE.object [ ( "ValidationFailedError", JE.null ) ] UnknownPlayerIdError playerid -> JE.object [ ( "UnknownPlayerIdError", JE.string playerid ) ] UnknownPlayerError player -> JE.object [ ( "UnknownPlayerError", gamePlayerEncoder player ) ] IllegalMoveError place -> JE.object [ ( "IllegalMoveError", ownedPlaceEncoder place ) ] IllegalWallLocationError placement -> JE.object [ ( "IllegalWallLocationError" , ownedPlacementEncoder placement ) ] UnknownAppearanceError appearanceName -> JE.object [ ( "UnknownAppearanceError", JE.string appearanceName ) ] UnknownImageError imageName -> JE.object [ ( "UnknownImageError", JE.string imageName ) ] RandomError message -> JE.object [ ( "RandomError", JE.string message ) ] errorKindDecoder : Decoder ErrorKind errorKindDecoder = JD.oneOf [ JD.map (\_ -> ValidationFailedError) <| JD.field "ValidationFailedError" JD.value , JD.map UnknownPlayerIdError <| JD.field "UnknownPlayerIdError" JD.string , JD.map UnknownPlayerError <| JD.field "UnknownPlayerError" gamePlayerDecoder , JD.map IllegalMoveError <| JD.field "IllegalMoveError" ownedPlaceDecoder , JD.map IllegalWallLocationError <| JD.field "IllegalWallLocationError" ownedPlacementDecoder , JD.map UnknownAppearanceError <| JD.field "UnknownAppearanceError" JD.string , JD.map UnknownImageError <| JD.field "UnknownImageError" JD.string , JD.map RandomError <| JD.field "RandomError" JD.string ] {-| This is `Json.Encode.Extra.maybe` in elm-community/json-extra. I'm not including that whole package just for this one function. -} maybeNull : (a -> Value) -> Maybe a -> Value maybeNull encoder ma = Maybe.map encoder ma |> Maybe.withDefault JE.null messageEncoder : MessageEncoder Message messageEncoder msg = case msg of PingReq { message } -> ( Req "ping" , [ ( "message", JE.string message ) ] ) PongRsp { message } -> ( Rsp "pong" , [ ( "message", JE.string message ) ] ) ErrorRsp { error, message } -> ( Rsp "error" , [ ( "error", errorKindEncoder error ) , ( "message", JE.string message ) ] ) LoginWithPasswordReq { userid, passwordHash } -> ( Req "loginWithPassword" , [ ( "userid", JE.string userid ) , ( "passwordHash", JE.string passwordHash ) ] ) LoginRsp { playerid, currentGame, allGames } -> ( Rsp "login" , [ ( "playerid", JE.string playerid ) , ( "currentGame" , case currentGame of Nothing -> JE.null Just gameid -> JE.string gameid ) , ( "allGames" , JE.list gamePlayerEncoder allGames ) ] ) LogoutReq { playerid } -> ( Req "logout" , [ ( "playerid", JE.string playerid ) ] ) LogoutRsp { players } -> ( Rsp "logout" , [ ( "players" , JE.list gamePlayerEncoder players ) ] ) JoinGameReq { playerid, player } -> ( Req "joinGame" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) ] ) NewGameReq { playerid, game } -> ( Req "newGame" , [ ( "playerid", JE.string playerid ) , ( "game", gameEncoder game ) ] ) JoinGameRsp { player, game } -> ( Rsp "joinGame" , [ ( "player", gamePlayerEncoder player ) , ( "game", gameEncoder game ) ] ) JoinGameNotificationRsp { player, location, direction } -> ( Rsp "joinGameNotification" , [ ( "player", gamePlayerEncoder player ) , ( "location", locationEncoder location ) , ( "direction", directionEncoder direction ) ] ) LeaveReq { playerid, player } -> ( Req "leave" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) ] ) LeaveRsp { player } -> ( Rsp "leave" , [ ( "player", gamePlayerEncoder player ) ] ) ExitReq { playerid, player } -> ( Req "exit" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) ] ) ExitRsp { player } -> ( Rsp "exit" , [ ( "player", gamePlayerEncoder player ) ] ) MoveReq { playerid, player, location, direction } -> ( Req "move" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) , ( "location", maybeNull locationEncoder location ) , ( "direction", maybeNull directionEncoder direction ) ] ) MoveRsp { player, location, direction } -> ( Rsp "move" , [ ( "player", gamePlayerEncoder player ) , ( "location", locationEncoder location ) , ( "direction", directionEncoder direction ) ] ) _ -> ( Req "todo" , [] ) messageDecoder : MessageDecoder Message messageDecoder reqrspAndPlist = genericMessageDecoder reqPlist rspPlist reqrspAndPlist reqPlist : DecoderPlist Message reqPlist = [ ( "ping", pingReqDecoder ) , ( "loginWithPassword", loginWithPasswordReqDecoder ) , ( "logout", logoutReqDecoder ) , ( "joinGame", joinGameReqDecoder ) , ( "newGame", newGameReqDecoder ) , ( "leave", leaveReqDecoder ) , ( "exit", exitReqDecoder ) , ( "move", moveReqDecoder ) ] rspPlist : DecoderPlist Message rspPlist = [ ( "pong", pongRspDecoder ) , ( "error", errorRspDecoder ) , ( "login", loginRspDecoder ) , ( "logout", logoutRspDecoder ) , ( "joinGame", joinGameRspDecoder ) , ( "joinGameNotification", joinGameNotificationRspDecoder ) , ( "leave", leaveRspDecoder ) , ( "exit", exitRspDecoder ) , ( "move", moveRspDecoder ) ] {---- Req decoders ----} pingReqDecoder : Decoder Message pingReqDecoder = JD.map (\message -> PingReq { message = message }) (JD.field "message" JD.string) loginWithPasswordReqDecoder : Decoder Message loginWithPasswordReqDecoder = JD.succeed (\userid passwordHash -> LoginWithPasswordReq { userid = userid , passwordHash = <PASSWORD> } ) |> required "userid" JD.string |> required "passwordHash" JD.string logoutReqDecoder : Decoder Message logoutReqDecoder = JD.succeed (\playerid -> LogoutReq { playerid = playerid } ) |> required "playerid" JD.string joinGameReqDecoder : Decoder Message joinGameReqDecoder = JD.succeed (\playerid player -> JoinGameReq { playerid = playerid , player = player } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder newGameReqDecoder : Decoder Message newGameReqDecoder = JD.succeed (\playerid game -> NewGameReq { playerid = playerid , game = game } ) |> required "playerid" JD.string |> required "game" gameDecoder leaveReqDecoder : Decoder Message leaveReqDecoder = JD.succeed (\playerid player -> LeaveReq { playerid = playerid , player = player } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder exitReqDecoder : Decoder Message exitReqDecoder = JD.succeed (\playerid player -> ExitReq { playerid = playerid , player = player } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder moveReqDecoder : Decoder Message moveReqDecoder = JD.succeed (\playerid player location direction -> MoveReq { playerid = playerid , player = player , location = location , direction = direction } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder |> required "location" (JD.nullable locationDecoder) |> required "direction" (JD.nullable directionDecoder) {---- Rsp decoders ----} pongRspDecoder : Decoder Message pongRspDecoder = JD.map (\message -> PongRsp { message = message }) (JD.field "message" JD.string) errorRspDecoder : Decoder Message errorRspDecoder = JD.succeed (\error message -> ErrorRsp { error = error , message = message } ) |> required "error" errorKindDecoder |> required "message" JD.string loginRspDecoder : Decoder Message loginRspDecoder = JD.succeed (\playerid currentGame allGames -> LoginRsp { playerid = playerid , currentGame = currentGame , allGames = allGames } ) |> required "playerid" JD.string |> required "currentGame" (JD.nullable JD.string) |> required "allGames" (JD.list gamePlayerDecoder) logoutRspDecoder : Decoder Message logoutRspDecoder = JD.succeed (\players -> LogoutRsp { players = players } ) |> required "players" (JD.list gamePlayerDecoder) joinGameRspDecoder : Decoder Message joinGameRspDecoder = JD.succeed (\player game -> JoinGameRsp { player = player , game = game } ) |> required "player" gamePlayerDecoder |> required "game" gameDecoder joinGameNotificationRspDecoder : Decoder Message joinGameNotificationRspDecoder = JD.succeed (\player location direction -> JoinGameNotificationRsp { player = player , location = location , direction = direction } ) |> required "player" gamePlayerDecoder |> required "location" locationDecoder |> required "direction" directionDecoder leaveRspDecoder : Decoder Message leaveRspDecoder = JD.succeed (\player -> LeaveRsp { player = player } ) |> required "player" gamePlayerDecoder exitRspDecoder : Decoder Message exitRspDecoder = JD.succeed (\player -> ExitRsp { player = player } ) |> required "player" gamePlayerDecoder moveRspDecoder : Decoder Message moveRspDecoder = JD.succeed (\player location direction -> MoveRsp { player = player , location = location , direction = direction } ) |> required "player" gamePlayerDecoder |> required "location" locationDecoder |> required "direction" directionDecoder paintedWallsEncoder : PaintedWalls -> Value paintedWallsEncoder walls = JE.list paintedWallEncoder walls paintedWallsDecoder : Decoder PaintedWalls paintedWallsDecoder = JD.list paintedWallDecoder decodePaintedWalls : Value -> Result String PaintedWalls decodePaintedWalls value = decodeValue paintedWallsDecoder value
true
---------------------------------------------------------------------- -- -- EncodeDecode.elm -- Functions for maintaining the state of the MinePlace board. -- 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 MinePlace.EncodeDecode exposing ( boardEncoder , boardSpecEncoder , decodeBoard , decodeBoardSpec , decodeModel , decodePaintedWalls , decodePlayer , locationDecoder , locationEncoder , messageDecoder , messageEncoder , modelEncoder , paintedWallsDecoder , paintedWallsEncoder , playerEncoder , stringToValue , valueToString ) import Dict exposing (Dict) import Json.Decode as JD exposing (Decoder) import Json.Decode.Pipeline exposing (hardcoded, optional, required) import Json.Encode as JE exposing (Value) import MinePlace.Board exposing (boardToStrings, setId, stringsToBoard) import MinePlace.Types as Types exposing ( Appearance(..) , Board , BoardSpec , Colors , Direction(..) , ErrorKind(..) , FullPlayer , Game , GameDescription , GameName , GamePlayer , Image(..) , Layout(..) , Location , Message(..) , Model , OwnedPlace , OwnedPlacement , PaintedWall , PaintedWalls , Player , PlayerName , Point , SavedModel , SideImages , StaticImages , Url ) import WebSocketFramework exposing (decodePlist, unknownMessage) import WebSocketFramework.EncodeDecode exposing (genericMessageDecoder) import WebSocketFramework.ServerInterface as ServerInterface import WebSocketFramework.Types exposing ( DecoderPlist , GameId , MessageDecoder , MessageEncoder , Plist , PublicGame , ReqRsp(..) , ServerUrl ) valueToString : Value -> String valueToString value = JE.encode 0 value stringToValue : String -> Value stringToValue string = JD.decodeString JD.value string |> Result.withDefault JE.null layoutEncoder : Layout -> Value layoutEncoder layout = JE.string <| layoutToString layout layoutToString : Layout -> String layoutToString layout = case layout of TopViewLayout -> "TopViewLayout" EditingLayout -> "EditingLayout" _ -> "NormalLayout" stringToLayout : String -> Layout stringToLayout string = case string of "TopViewLayout" -> TopViewLayout "EditingLayout" -> EditingLayout _ -> NormalLayout layoutDecoder : Decoder Layout layoutDecoder = JD.map stringToLayout JD.string colorsEncoder : Colors -> Value colorsEncoder colors = JE.object [ ( "windowBackground", JE.string colors.windowBackground ) , ( "textColor", JE.string colors.textColor ) , ( "errorBackground", JE.string colors.errorBackground ) , ( "errorColor", JE.string colors.errorColor ) , ( "borderStroke", JE.string colors.borderStroke ) , ( "borderFill", JE.string colors.borderFill ) , ( "playerStroke", JE.string colors.playerStroke ) , ( "playerFill", JE.string colors.playerFill ) , ( "editorHighlightStroke", JE.string colors.editorHighlightStroke ) , ( "editorHighlightFill", JE.string colors.editorHighlightFill ) , ( "lineStroke", JE.string colors.lineStroke ) ] colorsDecoder : Decoder Colors colorsDecoder = JD.succeed Colors |> required "windowBackground" JD.string |> required "textColor" JD.string |> required "errorBackground" JD.string |> required "errorColor" JD.string |> required "borderStroke" JD.string |> required "borderFill" JD.string |> required "playerStroke" JD.string |> required "playerFill" JD.string |> required "editorHighlightStroke" JD.string |> required "editorHighlightFill" JD.string |> required "lineStroke" JD.string modelEncoder : Model -> Value modelEncoder model = JE.object [ ( "layout", layoutEncoder model.layout ) , ( "colors", colorsEncoder model.colors ) ] modelDecoder : Decoder SavedModel modelDecoder = JD.map2 SavedModel (JD.field "layout" layoutDecoder) (JD.oneOf [ JD.field "colors" colorsDecoder , JD.succeed Types.lightColors ] ) decodeValue : Decoder a -> Value -> Result String a decodeValue decoder value = case JD.decodeValue decoder value of Ok a -> Ok a Err err -> Err <| JD.errorToString err decodeModel : Value -> Result String SavedModel decodeModel value = decodeValue modelDecoder value boardEncoder : Board -> Value boardEncoder board = JE.object [ ( "id", JE.string board.id ) , ( "spec", boardSpecEncoder board ) ] boardSpecEncoder : Board -> Value boardSpecEncoder board = boardToStrings board |> JE.list JE.string boardSpecDecoder : Decoder Board boardSpecDecoder = JD.list JD.string |> JD.map (stringsToBoard "") boardDecoder : Decoder Board boardDecoder = JD.map2 setId (JD.field "id" JD.string) (JD.field "spec" boardSpecDecoder) decodeBoard : Value -> Result String Board decodeBoard value = decodeValue boardDecoder value decodeBoardSpec : Value -> Result String Board decodeBoardSpec value = decodeValue boardSpecDecoder value locationEncoder : Location -> Value locationEncoder ( x, y ) = JE.object [ ( "x", JE.int x ) , ( "y", JE.int y ) ] locationDecoder : Decoder Location locationDecoder = JD.map2 (\a b -> ( a, b )) (JD.field "x" JD.int) (JD.field "y" JD.int) directionEncoder : Direction -> Value directionEncoder direction = JE.string <| Types.directionToString direction directionDecoder : Decoder Direction directionDecoder = JD.string |> JD.andThen (\s -> case Types.stringToDirection s of Just dir -> JD.succeed dir _ -> JD.fail "Unknown Direction" ) playerEncoder : Player -> Value playerEncoder player = JE.object [ ( "id", JE.string player.id ) , ( "boardid", JE.string player.boardid ) , ( "name", JE.string player.name ) , ( "location", locationEncoder player.location ) , ( "direction", directionEncoder player.direction ) ] playerDecoder : Decoder Player playerDecoder = JD.map5 Player (JD.field "id" JD.string) (JD.field "boardid" JD.string) (JD.field "name" JD.string) (JD.field "location" locationDecoder) (JD.field "direction" directionDecoder) decodePlayer : Value -> Result String Player decodePlayer value = decodeValue playerDecoder value {---- Message coding ----} pointEncoder : Point -> Value pointEncoder ( x, y ) = JE.list JE.float [ x, y ] pointDecoder : Decoder Point pointDecoder = JD.list JD.float |> JD.andThen (\p -> case p of [ x, y ] -> JD.succeed ( x, y ) _ -> JD.fail "Malformed point" ) imageEncoder : Image -> Value imageEncoder image = case image of UrlImage url -> JE.object [ ( "UrlImage", JE.string url ) ] VectorImage pointLists -> JE.object [ ( "VectorImage" , JE.list identity <| List.map (JE.list pointEncoder) pointLists ) ] imageDecoder : Decoder Image imageDecoder = JD.oneOf [ JD.map UrlImage <| JD.field "UrlImage" JD.string , JD.map VectorImage <| JD.field "VectorImage" (JD.list (JD.list pointDecoder)) ] sideImagesEncoder : SideImages -> Value sideImagesEncoder images = JE.object [ ( "front", JE.list imageEncoder images.front ) , ( "back", JE.list imageEncoder images.back ) , ( "left", JE.list imageEncoder images.left ) , ( "right", JE.list imageEncoder images.right ) ] sideImagesDecoder : Decoder SideImages sideImagesDecoder = JD.succeed SideImages |> required "front" (JD.list imageDecoder) |> required "back" (JD.list imageDecoder) |> required "left" (JD.list imageDecoder) |> required "right" (JD.list imageDecoder) staticImagesEncoder : StaticImages -> Value staticImagesEncoder { front, back, left, right } = JE.object [ ( "front", imageEncoder front ) , ( "back", imageEncoder back ) , ( "left", imageEncoder left ) , ( "right", imageEncoder right ) ] staticImagesDecoder : Decoder StaticImages staticImagesDecoder = JD.succeed StaticImages |> required "front" imageDecoder |> required "back" imageDecoder |> required "left" imageDecoder |> required "right" imageDecoder appearanceEncoder : Appearance -> Value appearanceEncoder appearance = case appearance of InvisibleAppearance -> JE.object [ ( "InvisibleAppearance", JE.null ) ] DefaultAppearance -> JE.object [ ( "DefaultAppearance", JE.null ) ] StaticImageAppearance staticImages -> JE.object [ ( "StaticImageAppearance", staticImagesEncoder staticImages ) ] VaryingAppearance sideImages -> JE.object [ ( "VaryingAppearance", sideImagesEncoder sideImages ) ] appearanceDecoder : Decoder Appearance appearanceDecoder = JD.oneOf [ JD.map (\_ -> InvisibleAppearance) <| JD.field "InvisibleAppearance" JD.value , JD.map (\_ -> DefaultAppearance) <| JD.field "DefaultAppearance" JD.value , JD.map StaticImageAppearance <| JD.field "StaticImageAppearance" staticImagesDecoder , JD.map VaryingAppearance <| JD.field "VaryingAppearance" sideImagesDecoder ] fullPlayerEncoder : FullPlayer -> Value fullPlayerEncoder player = JE.object [ ( "id", JE.string player.id ) , ( "name", JE.string player.name ) , ( "appearance", appearanceEncoder player.appearance ) , ( "location", locationEncoder player.location ) , ( "direction", directionEncoder player.direction ) ] fullPlayerDecoder : Decoder FullPlayer fullPlayerDecoder = JD.succeed FullPlayer |> required "id" JD.string |> required "name" JD.string |> required "appearance" appearanceDecoder |> required "location" locationDecoder |> required "direction" directionDecoder paintedWallEncoder : PaintedWall -> Value paintedWallEncoder image = JE.object [ ( "owner", JE.string image.owner ) , ( "location", locationEncoder image.location ) , ( "direction", directionEncoder image.direction ) , ( "image", imageEncoder image.image ) ] paintedWallDecoder : Decoder PaintedWall paintedWallDecoder = JD.succeed PaintedWall |> required "owner" JD.string |> required "location" locationDecoder |> required "direction" directionDecoder |> required "image" imageDecoder {-| We'll need another encoder for the persistent store. It will store the dicts as separately-indexed items, to reduce bandwidth. -} gameEncoder : Game -> Value gameEncoder game = JE.object [ ( "id", JE.string game.id ) , ( "name", JE.string game.name ) , ( "description", JE.string game.description ) , ( "owner", JE.string game.owner ) , ( "board", boardEncoder game.board ) , ( "players" , JE.list fullPlayerEncoder <| Dict.values game.playerDict ) , ( "walls" , JE.list paintedWallEncoder <| List.concat (Dict.values game.wallsDict) ) ] makeGame : String -> String -> String -> String -> Board -> List FullPlayer -> List PaintedWall -> Game makeGame id name description owner board players walls = let playerNamesDict = List.foldr (\player dict -> Dict.insert player.location (case Dict.get player.location dict of Nothing -> [ player.name ] Just playrs -> player.name :: playrs ) dict ) Dict.empty players wallsDict = List.foldr (\wall dict -> Dict.insert wall.location (case Dict.get wall.location dict of Nothing -> [ wall ] Just ws -> wall :: ws ) dict ) Dict.empty walls in { id = id , name = PI:NAME:<NAME>END_PI , description = description , owner = owner , board = board , playerDict = Dict.fromList <| List.map (\player -> ( player.name, player )) players , playerNamesDict = playerNamesDict , wallsDict = wallsDict } gameDecoder : Decoder Game gameDecoder = JD.succeed makeGame |> required "id" JD.string |> required "name" JD.string |> required "description" JD.string |> required "owner" JD.string |> required "board" boardDecoder |> required "players" (JD.list fullPlayerDecoder) |> required "walls" (JD.list paintedWallDecoder) gameDescriptionEncoder : GameDescription -> Value gameDescriptionEncoder description = JE.object [ ( "name", JE.string description.name ) , ( "description", JE.string description.description ) , ( "owner", JE.string description.owner ) ] gameDescriptionDecoder : Decoder GameDescription gameDescriptionDecoder = JD.succeed GameDescription |> required "name" JD.string |> required "description" JD.string |> required "owner" JD.string gamePlayerEncoder : GamePlayer -> Value gamePlayerEncoder player = JE.object [ ( "player", JE.string player.player ) , ( "gameid", JE.string player.gameid ) ] gamePlayerDecoder : Decoder GamePlayer gamePlayerDecoder = JD.succeed GamePlayer |> required "player" JD.string |> required "gameid" JD.string ownedPlaceEncoder : OwnedPlace -> Value ownedPlaceEncoder place = JE.object [ ( "player", gamePlayerEncoder place.player ) , ( "location", locationEncoder place.location ) ] ownedPlaceDecoder : Decoder OwnedPlace ownedPlaceDecoder = JD.succeed OwnedPlace |> required "player" gamePlayerDecoder |> required "location" locationDecoder ownedPlacementEncoder : OwnedPlacement -> Value ownedPlacementEncoder place = JE.object [ ( "player", gamePlayerEncoder place.player ) , ( "location", locationEncoder place.location ) , ( "direction", directionEncoder place.direction ) ] ownedPlacementDecoder : Decoder OwnedPlacement ownedPlacementDecoder = JD.succeed OwnedPlacement |> required "player" gamePlayerDecoder |> required "location" locationDecoder |> required "direction" directionDecoder errorKindEncoder : ErrorKind -> Value errorKindEncoder kind = case kind of ValidationFailedError -> JE.object [ ( "ValidationFailedError", JE.null ) ] UnknownPlayerIdError playerid -> JE.object [ ( "UnknownPlayerIdError", JE.string playerid ) ] UnknownPlayerError player -> JE.object [ ( "UnknownPlayerError", gamePlayerEncoder player ) ] IllegalMoveError place -> JE.object [ ( "IllegalMoveError", ownedPlaceEncoder place ) ] IllegalWallLocationError placement -> JE.object [ ( "IllegalWallLocationError" , ownedPlacementEncoder placement ) ] UnknownAppearanceError appearanceName -> JE.object [ ( "UnknownAppearanceError", JE.string appearanceName ) ] UnknownImageError imageName -> JE.object [ ( "UnknownImageError", JE.string imageName ) ] RandomError message -> JE.object [ ( "RandomError", JE.string message ) ] errorKindDecoder : Decoder ErrorKind errorKindDecoder = JD.oneOf [ JD.map (\_ -> ValidationFailedError) <| JD.field "ValidationFailedError" JD.value , JD.map UnknownPlayerIdError <| JD.field "UnknownPlayerIdError" JD.string , JD.map UnknownPlayerError <| JD.field "UnknownPlayerError" gamePlayerDecoder , JD.map IllegalMoveError <| JD.field "IllegalMoveError" ownedPlaceDecoder , JD.map IllegalWallLocationError <| JD.field "IllegalWallLocationError" ownedPlacementDecoder , JD.map UnknownAppearanceError <| JD.field "UnknownAppearanceError" JD.string , JD.map UnknownImageError <| JD.field "UnknownImageError" JD.string , JD.map RandomError <| JD.field "RandomError" JD.string ] {-| This is `Json.Encode.Extra.maybe` in elm-community/json-extra. I'm not including that whole package just for this one function. -} maybeNull : (a -> Value) -> Maybe a -> Value maybeNull encoder ma = Maybe.map encoder ma |> Maybe.withDefault JE.null messageEncoder : MessageEncoder Message messageEncoder msg = case msg of PingReq { message } -> ( Req "ping" , [ ( "message", JE.string message ) ] ) PongRsp { message } -> ( Rsp "pong" , [ ( "message", JE.string message ) ] ) ErrorRsp { error, message } -> ( Rsp "error" , [ ( "error", errorKindEncoder error ) , ( "message", JE.string message ) ] ) LoginWithPasswordReq { userid, passwordHash } -> ( Req "loginWithPassword" , [ ( "userid", JE.string userid ) , ( "passwordHash", JE.string passwordHash ) ] ) LoginRsp { playerid, currentGame, allGames } -> ( Rsp "login" , [ ( "playerid", JE.string playerid ) , ( "currentGame" , case currentGame of Nothing -> JE.null Just gameid -> JE.string gameid ) , ( "allGames" , JE.list gamePlayerEncoder allGames ) ] ) LogoutReq { playerid } -> ( Req "logout" , [ ( "playerid", JE.string playerid ) ] ) LogoutRsp { players } -> ( Rsp "logout" , [ ( "players" , JE.list gamePlayerEncoder players ) ] ) JoinGameReq { playerid, player } -> ( Req "joinGame" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) ] ) NewGameReq { playerid, game } -> ( Req "newGame" , [ ( "playerid", JE.string playerid ) , ( "game", gameEncoder game ) ] ) JoinGameRsp { player, game } -> ( Rsp "joinGame" , [ ( "player", gamePlayerEncoder player ) , ( "game", gameEncoder game ) ] ) JoinGameNotificationRsp { player, location, direction } -> ( Rsp "joinGameNotification" , [ ( "player", gamePlayerEncoder player ) , ( "location", locationEncoder location ) , ( "direction", directionEncoder direction ) ] ) LeaveReq { playerid, player } -> ( Req "leave" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) ] ) LeaveRsp { player } -> ( Rsp "leave" , [ ( "player", gamePlayerEncoder player ) ] ) ExitReq { playerid, player } -> ( Req "exit" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) ] ) ExitRsp { player } -> ( Rsp "exit" , [ ( "player", gamePlayerEncoder player ) ] ) MoveReq { playerid, player, location, direction } -> ( Req "move" , [ ( "playerid", JE.string playerid ) , ( "player", gamePlayerEncoder player ) , ( "location", maybeNull locationEncoder location ) , ( "direction", maybeNull directionEncoder direction ) ] ) MoveRsp { player, location, direction } -> ( Rsp "move" , [ ( "player", gamePlayerEncoder player ) , ( "location", locationEncoder location ) , ( "direction", directionEncoder direction ) ] ) _ -> ( Req "todo" , [] ) messageDecoder : MessageDecoder Message messageDecoder reqrspAndPlist = genericMessageDecoder reqPlist rspPlist reqrspAndPlist reqPlist : DecoderPlist Message reqPlist = [ ( "ping", pingReqDecoder ) , ( "loginWithPassword", loginWithPasswordReqDecoder ) , ( "logout", logoutReqDecoder ) , ( "joinGame", joinGameReqDecoder ) , ( "newGame", newGameReqDecoder ) , ( "leave", leaveReqDecoder ) , ( "exit", exitReqDecoder ) , ( "move", moveReqDecoder ) ] rspPlist : DecoderPlist Message rspPlist = [ ( "pong", pongRspDecoder ) , ( "error", errorRspDecoder ) , ( "login", loginRspDecoder ) , ( "logout", logoutRspDecoder ) , ( "joinGame", joinGameRspDecoder ) , ( "joinGameNotification", joinGameNotificationRspDecoder ) , ( "leave", leaveRspDecoder ) , ( "exit", exitRspDecoder ) , ( "move", moveRspDecoder ) ] {---- Req decoders ----} pingReqDecoder : Decoder Message pingReqDecoder = JD.map (\message -> PingReq { message = message }) (JD.field "message" JD.string) loginWithPasswordReqDecoder : Decoder Message loginWithPasswordReqDecoder = JD.succeed (\userid passwordHash -> LoginWithPasswordReq { userid = userid , passwordHash = PI:PASSWORD:<PASSWORD>END_PI } ) |> required "userid" JD.string |> required "passwordHash" JD.string logoutReqDecoder : Decoder Message logoutReqDecoder = JD.succeed (\playerid -> LogoutReq { playerid = playerid } ) |> required "playerid" JD.string joinGameReqDecoder : Decoder Message joinGameReqDecoder = JD.succeed (\playerid player -> JoinGameReq { playerid = playerid , player = player } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder newGameReqDecoder : Decoder Message newGameReqDecoder = JD.succeed (\playerid game -> NewGameReq { playerid = playerid , game = game } ) |> required "playerid" JD.string |> required "game" gameDecoder leaveReqDecoder : Decoder Message leaveReqDecoder = JD.succeed (\playerid player -> LeaveReq { playerid = playerid , player = player } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder exitReqDecoder : Decoder Message exitReqDecoder = JD.succeed (\playerid player -> ExitReq { playerid = playerid , player = player } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder moveReqDecoder : Decoder Message moveReqDecoder = JD.succeed (\playerid player location direction -> MoveReq { playerid = playerid , player = player , location = location , direction = direction } ) |> required "playerid" JD.string |> required "player" gamePlayerDecoder |> required "location" (JD.nullable locationDecoder) |> required "direction" (JD.nullable directionDecoder) {---- Rsp decoders ----} pongRspDecoder : Decoder Message pongRspDecoder = JD.map (\message -> PongRsp { message = message }) (JD.field "message" JD.string) errorRspDecoder : Decoder Message errorRspDecoder = JD.succeed (\error message -> ErrorRsp { error = error , message = message } ) |> required "error" errorKindDecoder |> required "message" JD.string loginRspDecoder : Decoder Message loginRspDecoder = JD.succeed (\playerid currentGame allGames -> LoginRsp { playerid = playerid , currentGame = currentGame , allGames = allGames } ) |> required "playerid" JD.string |> required "currentGame" (JD.nullable JD.string) |> required "allGames" (JD.list gamePlayerDecoder) logoutRspDecoder : Decoder Message logoutRspDecoder = JD.succeed (\players -> LogoutRsp { players = players } ) |> required "players" (JD.list gamePlayerDecoder) joinGameRspDecoder : Decoder Message joinGameRspDecoder = JD.succeed (\player game -> JoinGameRsp { player = player , game = game } ) |> required "player" gamePlayerDecoder |> required "game" gameDecoder joinGameNotificationRspDecoder : Decoder Message joinGameNotificationRspDecoder = JD.succeed (\player location direction -> JoinGameNotificationRsp { player = player , location = location , direction = direction } ) |> required "player" gamePlayerDecoder |> required "location" locationDecoder |> required "direction" directionDecoder leaveRspDecoder : Decoder Message leaveRspDecoder = JD.succeed (\player -> LeaveRsp { player = player } ) |> required "player" gamePlayerDecoder exitRspDecoder : Decoder Message exitRspDecoder = JD.succeed (\player -> ExitRsp { player = player } ) |> required "player" gamePlayerDecoder moveRspDecoder : Decoder Message moveRspDecoder = JD.succeed (\player location direction -> MoveRsp { player = player , location = location , direction = direction } ) |> required "player" gamePlayerDecoder |> required "location" locationDecoder |> required "direction" directionDecoder paintedWallsEncoder : PaintedWalls -> Value paintedWallsEncoder walls = JE.list paintedWallEncoder walls paintedWallsDecoder : Decoder PaintedWalls paintedWallsDecoder = JD.list paintedWallDecoder decodePaintedWalls : Value -> Result String PaintedWalls decodePaintedWalls value = decodeValue paintedWallsDecoder value
elm
[ { "context": "0, CA.moveUp 25 ]\n [ Svg.text \"Detainer Warrants\" ]\n ]\n )\n )\n\n\nvi", "end": 20484, "score": 0.9996910095, "start": 20467, "tag": "NAME", "value": "Detainer Warrants" } ]
pages/src/Page/Index.elm
gregziegan/eviction-tracker
5
module Page.Index exposing (Data, Model, Msg, page) import Browser.Navigation import Chart as C import Chart.Attributes as CA import Chart.Events as CE import Chart.Item as CI import DataSource exposing (DataSource) import DataSource.Http import DataSource.Port import DateFormat import Dict import Element exposing (Element, fill, px, row) import Element.Font as Font import FormatNumber import FormatNumber.Locales exposing (usLocale) import Head import Head.Seo as Seo import Html.Attributes as Attrs import Json.Encode import List.Extra import Logo import OptimizedDecoder as Decode exposing (float, list, string) import OptimizedDecoder.Pipeline exposing (decode, required) import Page exposing (StaticPayload) import Pages.PageUrl exposing (PageUrl) import Pages.Secrets as Secrets import Path exposing (Path) import Rest.Static exposing (AmountAwardedMonth, DetainerWarrantsPerMonth, EvictionHistory, PlaintiffAttorneyWarrantCount, RollupMetadata, TopEvictor) import Runtime import Shared import Svg import Time import View exposing (View) type alias Model = { hovering : List EvictionHistory , hoveringAmounts : List (CI.Many AmountAwardedMonth CI.Any) , hoveringOnBar : List (CI.One Datum CI.Bar) } type alias RouteParams = {} page : Page.PageWithState RouteParams Data Model Msg page = Page.single { head = head , data = data } |> Page.buildWithLocalState { init = init , update = update , view = view , subscriptions = subscriptions } data : DataSource Data data = DataSource.Port.get "environmentVariable" (Json.Encode.string "ENV") Runtime.decodeEnvironment |> DataSource.andThen (\env -> let domain = Runtime.domain env in DataSource.map5 Data (topEvictorsData domain) (detainerWarrantsPerMonth domain) (plaintiffAttorneyWarrantCountPerMonth domain) (amountAwardedHistoryData domain) (apiMetadata domain) ) head : StaticPayload Data RouteParams -> List Head.Tag head static = Seo.summary { canonicalUrlOverride = Nothing , siteName = "Red Door Collective" , image = Logo.smallImage , description = "Organizing Nashville tenants for dignified housing." , locale = Nothing , title = title } |> Seo.website type alias Data = { topEvictors : List TopEvictor , warrantsPerMonth : List DetainerWarrantsPerMonth , plaintiffAttorneyWarrantCounts : List PlaintiffAttorneyWarrantCount , amountAwardedHistory : List Rest.Static.AmountAwardedMonth , rollupMeta : RollupMetadata } title = "Red Door Collective" view : Maybe PageUrl -> Shared.Model -> Model -> StaticPayload Data RouteParams -> View Msg view maybeUrl sharedModel model static = { title = title , body = [ Element.column [ Element.centerX , Element.width (fill |> Element.maximum 1000) , Font.size 14 , Element.paddingXY 5 10 ] [ Element.column [ Element.spacing 80 , Element.centerX , Element.width fill ] [ row [ Element.htmlAttribute (Attrs.class "responsive-desktop") ] [ topEvictorsChart { width = 1000, height = 600 } model static ] , row [ Element.htmlAttribute (Attrs.class "responsive-mobile") ] [ topEvictorsChart { width = 365, height = 400 } model static ] , row [ Element.htmlAttribute (Attrs.class "responsive-desktop") ] [ viewBarChart model { width = 1000, height = 600 } static.data.warrantsPerMonth ] , row [ Element.htmlAttribute (Attrs.class "responsive-mobile") ] [ viewBarChart model { width = 365, height = 365 } static.data.warrantsPerMonth ] , row [ Element.htmlAttribute <| Attrs.class "responsive-desktop" ] [ viewPlaintiffShareChart model { width = 1000, height = 800 } static.data.plaintiffAttorneyWarrantCounts ] , row [ Element.htmlAttribute <| Attrs.class "responsive-mobile" ] [ viewPlaintiffShareChart model { width = 365, height = 365 } static.data.plaintiffAttorneyWarrantCounts ] , row [ Element.htmlAttribute <| Attrs.class "responsive-desktop" ] [ viewAmountAwardedChart model { width = 1000, height = 800 } static.data.amountAwardedHistory ] , row [ Element.htmlAttribute <| Attrs.class "responsive-mobile" ] [ viewAmountAwardedChart model { width = 365, height = 365 } static.data.amountAwardedHistory ] , row [ Element.htmlAttribute <| Attrs.class "responsive-desktop", Element.centerX ] [ Element.text ("Detainer Warrants updated via Red Door Collective members as of: " ++ dateFormatLong static.data.rollupMeta.lastWarrantUpdatedAt) ] , row [ Element.width fill , Element.htmlAttribute <| Attrs.class "responsive-mobile" ] [ Element.paragraph [ Element.centerX , Element.width (fill |> Element.maximum 365) ] [ Element.text ("Detainer Warrants updated via Red Door Collective members as of: " ++ dateFormatLong static.data.rollupMeta.lastWarrantUpdatedAt) ] ] , row [ Element.height (Element.px 20) ] [] ] ] ] } topEvictorsData : String -> DataSource (List TopEvictor) topEvictorsData domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "plaintiffs")) (list (decode TopEvictor |> required "name" string |> required "history" (list (decode EvictionHistory |> required "date" float |> required "eviction_count" float ) ) ) ) detainerWarrantsPerMonth : String -> DataSource (List DetainerWarrantsPerMonth) detainerWarrantsPerMonth domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "detainer-warrants")) (list Rest.Static.detainerWarrantsPerMonthDecoder) plaintiffAttorneyWarrantCountPerMonth : String -> DataSource (List PlaintiffAttorneyWarrantCount) plaintiffAttorneyWarrantCountPerMonth domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "plaintiff-attorney")) (list Rest.Static.plaintiffAttorneyWarrantCountDecoder) amountAwardedHistoryData : String -> DataSource (List AmountAwardedMonth) amountAwardedHistoryData domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "amount-awarded/history")) (Decode.field "data" (list Rest.Static.amountAwardedMonthDecoder)) apiMetadata : String -> DataSource RollupMetadata apiMetadata domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "meta")) Rest.Static.rollupMetadataDecoder init : Maybe PageUrl -> Shared.Model -> StaticPayload Data RouteParams -> ( Model, Cmd Msg ) init pageUrl sharedModel payload = ( { hovering = [] , hoveringAmounts = [] , hoveringOnBar = [] } , Cmd.none ) type Msg = HoverOnBar (List (CI.One Datum CI.Bar)) | OnHoverAmounts (List (CI.Many AmountAwardedMonth CI.Any)) update : PageUrl -> Maybe Browser.Navigation.Key -> Shared.Model -> StaticPayload Data RouteParams -> Msg -> Model -> ( Model, Cmd Msg ) update pageUrl navKey sharedModel payload msg model = case msg of HoverOnBar hovering -> ( { model | hoveringOnBar = hovering }, Cmd.none ) OnHoverAmounts hovering -> ( { model | hoveringAmounts = hovering }, Cmd.none ) topEvictorsChart : Dimensions -> Model -> StaticPayload Data RouteParams -> Element Msg topEvictorsChart { width, height } model static = let series = static.data.topEvictors { titleSize, legendSize, spacing, tickNum } = if width < 600 then { titleSize = 12, legendSize = 8, spacing = 2, tickNum = 4 } else { titleSize = 20, legendSize = 12, spacing = 5, tickNum = 6 } in Element.el [ Element.width (px width), Element.height (px height) ] (Element.html (C.chart [ CA.height (toFloat height) , CA.width (toFloat width) , CA.margin { top = 20, bottom = 30, left = 60, right = 20 } , CA.padding { top = 40, bottom = 20, left = 0, right = 0 } ] ([ C.xLabels [ CA.format (\num -> dateFormat (Time.millisToPosix (round num))) , CA.amount tickNum ] , C.yLabels [ CA.withGrid ] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Top 10 Evictors in Davidson Co. TN by month" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Month" ] , C.labelAt .min CA.middle [ CA.moveLeft 45, CA.rotate 90 ] [ Svg.text "Evictions" ] ] ++ List.map (\evictor -> C.series .date [ C.interpolated .evictionCount [] [ CA.cross, CA.borderWidth 2, CA.border "white" ] |> C.named evictor.name ] evictor.history ) series ++ [ --C.each model.hovering <| -- \p item -> -- [ C.tooltip item.date [] [] [] ] C.legendsAt .max .max [ CA.column , CA.moveDown 20 , CA.alignRight , CA.spacing spacing ] [ CA.width 20 , CA.fontSize legendSize ] ] ) ) ) formatDollars number = "$" ++ FormatNumber.format usLocale number formatMillions number = "$" ++ String.fromFloat (number / 1000000) ++ "M" dateFormat : Time.Posix -> String dateFormat = DateFormat.format [ DateFormat.dayOfMonthFixed, DateFormat.text " ", DateFormat.monthNameAbbreviated ] Time.utc dateFormatLong : Time.Posix -> String dateFormatLong = DateFormat.format [ DateFormat.monthNameFull, DateFormat.text " ", DateFormat.dayOfMonthNumber, DateFormat.text ", ", DateFormat.yearNumber ] Time.utc -- BAR CHART type alias Datum = { time : Time.Posix, total : Float } barDateFormat : Time.Posix -> String barDateFormat = DateFormat.format [ DateFormat.monthNameAbbreviated, DateFormat.text " ", DateFormat.yearNumberLastTwo ] Time.utc type alias Dimensions = { width : Int, height : Int } viewBarChart : Model -> Dimensions -> List DetainerWarrantsPerMonth -> Element Msg viewBarChart model dimens allWarrants = let ( titleSize, warrants ) = if dimens.width < 600 then ( 12, List.drop 8 allWarrants ) else ( 20, allWarrants ) series = List.map (\s -> { time = s.time, total = toFloat s.totalWarrants }) warrants in Element.el [ Element.width (px dimens.width), Element.height (px dimens.height) ] (Element.html <| C.chart [ CA.height (toFloat dimens.height) , CA.width (toFloat dimens.width) , CE.onMouseMove HoverOnBar (CE.getNearest CI.bars) , CE.onMouseLeave (HoverOnBar []) , CA.margin { top = 20, bottom = 30, left = 80, right = 20 } , CA.padding { top = 40, bottom = 20, left = 0, right = 0 } ] [ C.yLabels [ CA.withGrid ] , C.bars [ CA.roundTop 0.2 , CA.margin 0.1 , CA.spacing 0.15 ] [ C.bar .total [ CA.borderWidth 1 ] |> C.named "Evictions" |> C.amongst model.hoveringOnBar (\_ -> [ CA.highlight 0.25 ]) ] series , C.barLabels [ CA.moveDown 20, CA.color "#FFFFFF" ] , C.binLabels (barDateFormat << .time) [ CA.moveDown 15 ] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Detainer warrants in Davidson Co. TN by month" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Month" ] , C.labelAt .min CA.middle [ CA.moveLeft 60, CA.rotate 90 ] [ Svg.text "# of Detainer warrants" ] , C.each model.hoveringOnBar <| \_ item -> [ C.tooltip item [] [] [] ] ] ) emptyStack = { name = "UNKNOWN", count = 0.0 } emptyStacks = { first = emptyStack , second = emptyStack , third = emptyStack , fourth = emptyStack , fifth = emptyStack , other = emptyStack , prs = emptyStack } viewPlaintiffShareChart : Model -> Dimensions -> List PlaintiffAttorneyWarrantCount -> Element Msg viewPlaintiffShareChart model dimens counts = let ( other, top5Plaintiffs ) = List.partition (\r -> List.member r.plaintiffAttorneyName [ "ALL OTHER", "Plaintiff Representing Self" ]) counts byCount = counts |> List.map (\r -> ( toFloat r.warrantCount , if r.plaintiffAttorneyName == "Plaintiff Representing Self" then "SELF REPRESENTING" else r.plaintiffAttorneyName ) ) |> Dict.fromList top5 = top5Plaintiffs |> List.Extra.indexedFoldl (\i r acc -> let datum = { name = r.plaintiffAttorneyName , count = toFloat r.warrantCount } in { acc | first = if i == 0 then datum else acc.first , second = if i == 1 then datum else acc.second , third = if i == 2 then datum else acc.third , fourth = if i == 3 then datum else acc.fourth , fifth = if i == 4 then datum else acc.fifth } ) emptyStacks series = [ top5 , { emptyStacks | other = { name = "ALL OTHER" , count = Maybe.withDefault 0.0 <| Maybe.map (toFloat << .warrantCount) <| List.head other } , prs = { name = "SELF REPRESENTING" , count = other |> List.filter ((==) "Plaintiff Representing Self" << .plaintiffAttorneyName) |> List.head |> Maybe.map (toFloat << .warrantCount) |> Maybe.withDefault 0.0 } } ] total = List.map (toFloat << .warrantCount) counts |> List.sum toPercent y = round (100 * y / total) extractName fn = Maybe.withDefault "Unknown" <| Maybe.map (.name << fn) <| List.head series { fontSize, firstShift, secondShift, titleSize } = if dimens.width < 600 then { fontSize = 8, firstShift = 10, secondShift = 20, titleSize = 12 } else { fontSize = 14, firstShift = 20, secondShift = 45, titleSize = 20 } in Element.el [ Element.width (px dimens.width), Element.height (px dimens.height) ] (Element.html (C.chart [ CA.height (toFloat dimens.height) , CA.width (toFloat dimens.width) , CA.margin { top = 20, bottom = 30, left = 80, right = 20 } , CA.padding { top = 20, bottom = 20, left = 0, right = 0 } ] [ C.yLabels [] , C.bars [ CA.margin 0.05 ] [ C.stacked [ C.bar (.count << .first) [] |> C.named (extractName .first) , C.bar (.count << .second) [] |> C.named (extractName .second) , C.bar (.count << .third) [] |> C.named (extractName .third) , C.bar (.count << .fourth) [] |> C.named (extractName .fourth) , C.bar (.count << .fifth) [] |> C.named (extractName .fifth) , C.bar (.count << .prs) [] |> C.named "SELF REPRESENTING" , C.bar (.count << .other) [] |> C.named "ALL OTHER" ] ] series , C.eachBar <| \p bar -> if CI.getY bar > 0 then [ C.label [ CA.fontSize fontSize, CA.moveDown firstShift, CA.color "white" ] [ Svg.text (Maybe.withDefault "" <| Dict.get (CI.getY bar) byCount) ] (CI.getTop p bar) , C.label [ CA.fontSize fontSize, CA.moveDown secondShift, CA.color "white" ] [ Svg.text (String.fromFloat (CI.getY bar) ++ " (" ++ (String.fromInt <| toPercent <| CI.getY bar) ++ "%)") ] (CI.getTop p bar) ] else [] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Plaintiff attorney listed on detainer warrants" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Plaintiff attorney" ] , C.labelAt .min CA.middle [ CA.moveLeft 60, CA.rotate 90, CA.moveUp 25 ] [ Svg.text "Detainer Warrants" ] ] ) ) viewAmountAwardedChart : Model -> Dimensions -> List AmountAwardedMonth -> Element Msg viewAmountAwardedChart model dimens awards = let titleSize = if dimens.width < 600 then 12 else 20 in Element.el [ Element.width (px dimens.width), Element.height (px dimens.height) ] (Element.html (C.chart [ CA.height <| toFloat dimens.height , CA.width <| toFloat dimens.width , CE.onMouseMove OnHoverAmounts (CE.getNearest CI.stacks) , CE.onMouseLeave (OnHoverAmounts []) , CA.margin { top = 20, bottom = 30, left = 100, right = 20 } , CA.padding { top = 20, bottom = 20, left = 0, right = 0 } ] [ C.xTicks [ CA.times Time.utc ] , C.xLabels [ CA.times Time.utc ] , C.yLabels [ CA.withGrid, CA.format formatMillions ] , C.series (toFloat << Time.posixToMillis << .time) [ C.interpolated (toFloat << .totalAmount) [ CA.opacity 0.6 , CA.gradient [] ] [ CA.circle, CA.color "white", CA.borderWidth 1 ] |> C.named "Amount Awarded" |> C.format formatDollars ] awards , C.each model.hoveringAmounts <| \_ item -> [ C.tooltip item [] [] [] ] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Plaintiffs awards in Davidson Co. TN by month" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Month" ] , C.labelAt .min CA.middle [ CA.moveLeft 80, CA.rotate 90, CA.moveUp 25 ] [ Svg.text "Amount awarded ($) in millions" ] ] ) ) subscriptions : Maybe PageUrl -> RouteParams -> Path -> Model -> Sub Msg subscriptions pageUrl params path model = Sub.none
37602
module Page.Index exposing (Data, Model, Msg, page) import Browser.Navigation import Chart as C import Chart.Attributes as CA import Chart.Events as CE import Chart.Item as CI import DataSource exposing (DataSource) import DataSource.Http import DataSource.Port import DateFormat import Dict import Element exposing (Element, fill, px, row) import Element.Font as Font import FormatNumber import FormatNumber.Locales exposing (usLocale) import Head import Head.Seo as Seo import Html.Attributes as Attrs import Json.Encode import List.Extra import Logo import OptimizedDecoder as Decode exposing (float, list, string) import OptimizedDecoder.Pipeline exposing (decode, required) import Page exposing (StaticPayload) import Pages.PageUrl exposing (PageUrl) import Pages.Secrets as Secrets import Path exposing (Path) import Rest.Static exposing (AmountAwardedMonth, DetainerWarrantsPerMonth, EvictionHistory, PlaintiffAttorneyWarrantCount, RollupMetadata, TopEvictor) import Runtime import Shared import Svg import Time import View exposing (View) type alias Model = { hovering : List EvictionHistory , hoveringAmounts : List (CI.Many AmountAwardedMonth CI.Any) , hoveringOnBar : List (CI.One Datum CI.Bar) } type alias RouteParams = {} page : Page.PageWithState RouteParams Data Model Msg page = Page.single { head = head , data = data } |> Page.buildWithLocalState { init = init , update = update , view = view , subscriptions = subscriptions } data : DataSource Data data = DataSource.Port.get "environmentVariable" (Json.Encode.string "ENV") Runtime.decodeEnvironment |> DataSource.andThen (\env -> let domain = Runtime.domain env in DataSource.map5 Data (topEvictorsData domain) (detainerWarrantsPerMonth domain) (plaintiffAttorneyWarrantCountPerMonth domain) (amountAwardedHistoryData domain) (apiMetadata domain) ) head : StaticPayload Data RouteParams -> List Head.Tag head static = Seo.summary { canonicalUrlOverride = Nothing , siteName = "Red Door Collective" , image = Logo.smallImage , description = "Organizing Nashville tenants for dignified housing." , locale = Nothing , title = title } |> Seo.website type alias Data = { topEvictors : List TopEvictor , warrantsPerMonth : List DetainerWarrantsPerMonth , plaintiffAttorneyWarrantCounts : List PlaintiffAttorneyWarrantCount , amountAwardedHistory : List Rest.Static.AmountAwardedMonth , rollupMeta : RollupMetadata } title = "Red Door Collective" view : Maybe PageUrl -> Shared.Model -> Model -> StaticPayload Data RouteParams -> View Msg view maybeUrl sharedModel model static = { title = title , body = [ Element.column [ Element.centerX , Element.width (fill |> Element.maximum 1000) , Font.size 14 , Element.paddingXY 5 10 ] [ Element.column [ Element.spacing 80 , Element.centerX , Element.width fill ] [ row [ Element.htmlAttribute (Attrs.class "responsive-desktop") ] [ topEvictorsChart { width = 1000, height = 600 } model static ] , row [ Element.htmlAttribute (Attrs.class "responsive-mobile") ] [ topEvictorsChart { width = 365, height = 400 } model static ] , row [ Element.htmlAttribute (Attrs.class "responsive-desktop") ] [ viewBarChart model { width = 1000, height = 600 } static.data.warrantsPerMonth ] , row [ Element.htmlAttribute (Attrs.class "responsive-mobile") ] [ viewBarChart model { width = 365, height = 365 } static.data.warrantsPerMonth ] , row [ Element.htmlAttribute <| Attrs.class "responsive-desktop" ] [ viewPlaintiffShareChart model { width = 1000, height = 800 } static.data.plaintiffAttorneyWarrantCounts ] , row [ Element.htmlAttribute <| Attrs.class "responsive-mobile" ] [ viewPlaintiffShareChart model { width = 365, height = 365 } static.data.plaintiffAttorneyWarrantCounts ] , row [ Element.htmlAttribute <| Attrs.class "responsive-desktop" ] [ viewAmountAwardedChart model { width = 1000, height = 800 } static.data.amountAwardedHistory ] , row [ Element.htmlAttribute <| Attrs.class "responsive-mobile" ] [ viewAmountAwardedChart model { width = 365, height = 365 } static.data.amountAwardedHistory ] , row [ Element.htmlAttribute <| Attrs.class "responsive-desktop", Element.centerX ] [ Element.text ("Detainer Warrants updated via Red Door Collective members as of: " ++ dateFormatLong static.data.rollupMeta.lastWarrantUpdatedAt) ] , row [ Element.width fill , Element.htmlAttribute <| Attrs.class "responsive-mobile" ] [ Element.paragraph [ Element.centerX , Element.width (fill |> Element.maximum 365) ] [ Element.text ("Detainer Warrants updated via Red Door Collective members as of: " ++ dateFormatLong static.data.rollupMeta.lastWarrantUpdatedAt) ] ] , row [ Element.height (Element.px 20) ] [] ] ] ] } topEvictorsData : String -> DataSource (List TopEvictor) topEvictorsData domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "plaintiffs")) (list (decode TopEvictor |> required "name" string |> required "history" (list (decode EvictionHistory |> required "date" float |> required "eviction_count" float ) ) ) ) detainerWarrantsPerMonth : String -> DataSource (List DetainerWarrantsPerMonth) detainerWarrantsPerMonth domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "detainer-warrants")) (list Rest.Static.detainerWarrantsPerMonthDecoder) plaintiffAttorneyWarrantCountPerMonth : String -> DataSource (List PlaintiffAttorneyWarrantCount) plaintiffAttorneyWarrantCountPerMonth domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "plaintiff-attorney")) (list Rest.Static.plaintiffAttorneyWarrantCountDecoder) amountAwardedHistoryData : String -> DataSource (List AmountAwardedMonth) amountAwardedHistoryData domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "amount-awarded/history")) (Decode.field "data" (list Rest.Static.amountAwardedMonthDecoder)) apiMetadata : String -> DataSource RollupMetadata apiMetadata domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "meta")) Rest.Static.rollupMetadataDecoder init : Maybe PageUrl -> Shared.Model -> StaticPayload Data RouteParams -> ( Model, Cmd Msg ) init pageUrl sharedModel payload = ( { hovering = [] , hoveringAmounts = [] , hoveringOnBar = [] } , Cmd.none ) type Msg = HoverOnBar (List (CI.One Datum CI.Bar)) | OnHoverAmounts (List (CI.Many AmountAwardedMonth CI.Any)) update : PageUrl -> Maybe Browser.Navigation.Key -> Shared.Model -> StaticPayload Data RouteParams -> Msg -> Model -> ( Model, Cmd Msg ) update pageUrl navKey sharedModel payload msg model = case msg of HoverOnBar hovering -> ( { model | hoveringOnBar = hovering }, Cmd.none ) OnHoverAmounts hovering -> ( { model | hoveringAmounts = hovering }, Cmd.none ) topEvictorsChart : Dimensions -> Model -> StaticPayload Data RouteParams -> Element Msg topEvictorsChart { width, height } model static = let series = static.data.topEvictors { titleSize, legendSize, spacing, tickNum } = if width < 600 then { titleSize = 12, legendSize = 8, spacing = 2, tickNum = 4 } else { titleSize = 20, legendSize = 12, spacing = 5, tickNum = 6 } in Element.el [ Element.width (px width), Element.height (px height) ] (Element.html (C.chart [ CA.height (toFloat height) , CA.width (toFloat width) , CA.margin { top = 20, bottom = 30, left = 60, right = 20 } , CA.padding { top = 40, bottom = 20, left = 0, right = 0 } ] ([ C.xLabels [ CA.format (\num -> dateFormat (Time.millisToPosix (round num))) , CA.amount tickNum ] , C.yLabels [ CA.withGrid ] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Top 10 Evictors in Davidson Co. TN by month" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Month" ] , C.labelAt .min CA.middle [ CA.moveLeft 45, CA.rotate 90 ] [ Svg.text "Evictions" ] ] ++ List.map (\evictor -> C.series .date [ C.interpolated .evictionCount [] [ CA.cross, CA.borderWidth 2, CA.border "white" ] |> C.named evictor.name ] evictor.history ) series ++ [ --C.each model.hovering <| -- \p item -> -- [ C.tooltip item.date [] [] [] ] C.legendsAt .max .max [ CA.column , CA.moveDown 20 , CA.alignRight , CA.spacing spacing ] [ CA.width 20 , CA.fontSize legendSize ] ] ) ) ) formatDollars number = "$" ++ FormatNumber.format usLocale number formatMillions number = "$" ++ String.fromFloat (number / 1000000) ++ "M" dateFormat : Time.Posix -> String dateFormat = DateFormat.format [ DateFormat.dayOfMonthFixed, DateFormat.text " ", DateFormat.monthNameAbbreviated ] Time.utc dateFormatLong : Time.Posix -> String dateFormatLong = DateFormat.format [ DateFormat.monthNameFull, DateFormat.text " ", DateFormat.dayOfMonthNumber, DateFormat.text ", ", DateFormat.yearNumber ] Time.utc -- BAR CHART type alias Datum = { time : Time.Posix, total : Float } barDateFormat : Time.Posix -> String barDateFormat = DateFormat.format [ DateFormat.monthNameAbbreviated, DateFormat.text " ", DateFormat.yearNumberLastTwo ] Time.utc type alias Dimensions = { width : Int, height : Int } viewBarChart : Model -> Dimensions -> List DetainerWarrantsPerMonth -> Element Msg viewBarChart model dimens allWarrants = let ( titleSize, warrants ) = if dimens.width < 600 then ( 12, List.drop 8 allWarrants ) else ( 20, allWarrants ) series = List.map (\s -> { time = s.time, total = toFloat s.totalWarrants }) warrants in Element.el [ Element.width (px dimens.width), Element.height (px dimens.height) ] (Element.html <| C.chart [ CA.height (toFloat dimens.height) , CA.width (toFloat dimens.width) , CE.onMouseMove HoverOnBar (CE.getNearest CI.bars) , CE.onMouseLeave (HoverOnBar []) , CA.margin { top = 20, bottom = 30, left = 80, right = 20 } , CA.padding { top = 40, bottom = 20, left = 0, right = 0 } ] [ C.yLabels [ CA.withGrid ] , C.bars [ CA.roundTop 0.2 , CA.margin 0.1 , CA.spacing 0.15 ] [ C.bar .total [ CA.borderWidth 1 ] |> C.named "Evictions" |> C.amongst model.hoveringOnBar (\_ -> [ CA.highlight 0.25 ]) ] series , C.barLabels [ CA.moveDown 20, CA.color "#FFFFFF" ] , C.binLabels (barDateFormat << .time) [ CA.moveDown 15 ] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Detainer warrants in Davidson Co. TN by month" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Month" ] , C.labelAt .min CA.middle [ CA.moveLeft 60, CA.rotate 90 ] [ Svg.text "# of Detainer warrants" ] , C.each model.hoveringOnBar <| \_ item -> [ C.tooltip item [] [] [] ] ] ) emptyStack = { name = "UNKNOWN", count = 0.0 } emptyStacks = { first = emptyStack , second = emptyStack , third = emptyStack , fourth = emptyStack , fifth = emptyStack , other = emptyStack , prs = emptyStack } viewPlaintiffShareChart : Model -> Dimensions -> List PlaintiffAttorneyWarrantCount -> Element Msg viewPlaintiffShareChart model dimens counts = let ( other, top5Plaintiffs ) = List.partition (\r -> List.member r.plaintiffAttorneyName [ "ALL OTHER", "Plaintiff Representing Self" ]) counts byCount = counts |> List.map (\r -> ( toFloat r.warrantCount , if r.plaintiffAttorneyName == "Plaintiff Representing Self" then "SELF REPRESENTING" else r.plaintiffAttorneyName ) ) |> Dict.fromList top5 = top5Plaintiffs |> List.Extra.indexedFoldl (\i r acc -> let datum = { name = r.plaintiffAttorneyName , count = toFloat r.warrantCount } in { acc | first = if i == 0 then datum else acc.first , second = if i == 1 then datum else acc.second , third = if i == 2 then datum else acc.third , fourth = if i == 3 then datum else acc.fourth , fifth = if i == 4 then datum else acc.fifth } ) emptyStacks series = [ top5 , { emptyStacks | other = { name = "ALL OTHER" , count = Maybe.withDefault 0.0 <| Maybe.map (toFloat << .warrantCount) <| List.head other } , prs = { name = "SELF REPRESENTING" , count = other |> List.filter ((==) "Plaintiff Representing Self" << .plaintiffAttorneyName) |> List.head |> Maybe.map (toFloat << .warrantCount) |> Maybe.withDefault 0.0 } } ] total = List.map (toFloat << .warrantCount) counts |> List.sum toPercent y = round (100 * y / total) extractName fn = Maybe.withDefault "Unknown" <| Maybe.map (.name << fn) <| List.head series { fontSize, firstShift, secondShift, titleSize } = if dimens.width < 600 then { fontSize = 8, firstShift = 10, secondShift = 20, titleSize = 12 } else { fontSize = 14, firstShift = 20, secondShift = 45, titleSize = 20 } in Element.el [ Element.width (px dimens.width), Element.height (px dimens.height) ] (Element.html (C.chart [ CA.height (toFloat dimens.height) , CA.width (toFloat dimens.width) , CA.margin { top = 20, bottom = 30, left = 80, right = 20 } , CA.padding { top = 20, bottom = 20, left = 0, right = 0 } ] [ C.yLabels [] , C.bars [ CA.margin 0.05 ] [ C.stacked [ C.bar (.count << .first) [] |> C.named (extractName .first) , C.bar (.count << .second) [] |> C.named (extractName .second) , C.bar (.count << .third) [] |> C.named (extractName .third) , C.bar (.count << .fourth) [] |> C.named (extractName .fourth) , C.bar (.count << .fifth) [] |> C.named (extractName .fifth) , C.bar (.count << .prs) [] |> C.named "SELF REPRESENTING" , C.bar (.count << .other) [] |> C.named "ALL OTHER" ] ] series , C.eachBar <| \p bar -> if CI.getY bar > 0 then [ C.label [ CA.fontSize fontSize, CA.moveDown firstShift, CA.color "white" ] [ Svg.text (Maybe.withDefault "" <| Dict.get (CI.getY bar) byCount) ] (CI.getTop p bar) , C.label [ CA.fontSize fontSize, CA.moveDown secondShift, CA.color "white" ] [ Svg.text (String.fromFloat (CI.getY bar) ++ " (" ++ (String.fromInt <| toPercent <| CI.getY bar) ++ "%)") ] (CI.getTop p bar) ] else [] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Plaintiff attorney listed on detainer warrants" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Plaintiff attorney" ] , C.labelAt .min CA.middle [ CA.moveLeft 60, CA.rotate 90, CA.moveUp 25 ] [ Svg.text "<NAME>" ] ] ) ) viewAmountAwardedChart : Model -> Dimensions -> List AmountAwardedMonth -> Element Msg viewAmountAwardedChart model dimens awards = let titleSize = if dimens.width < 600 then 12 else 20 in Element.el [ Element.width (px dimens.width), Element.height (px dimens.height) ] (Element.html (C.chart [ CA.height <| toFloat dimens.height , CA.width <| toFloat dimens.width , CE.onMouseMove OnHoverAmounts (CE.getNearest CI.stacks) , CE.onMouseLeave (OnHoverAmounts []) , CA.margin { top = 20, bottom = 30, left = 100, right = 20 } , CA.padding { top = 20, bottom = 20, left = 0, right = 0 } ] [ C.xTicks [ CA.times Time.utc ] , C.xLabels [ CA.times Time.utc ] , C.yLabels [ CA.withGrid, CA.format formatMillions ] , C.series (toFloat << Time.posixToMillis << .time) [ C.interpolated (toFloat << .totalAmount) [ CA.opacity 0.6 , CA.gradient [] ] [ CA.circle, CA.color "white", CA.borderWidth 1 ] |> C.named "Amount Awarded" |> C.format formatDollars ] awards , C.each model.hoveringAmounts <| \_ item -> [ C.tooltip item [] [] [] ] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Plaintiffs awards in Davidson Co. TN by month" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Month" ] , C.labelAt .min CA.middle [ CA.moveLeft 80, CA.rotate 90, CA.moveUp 25 ] [ Svg.text "Amount awarded ($) in millions" ] ] ) ) subscriptions : Maybe PageUrl -> RouteParams -> Path -> Model -> Sub Msg subscriptions pageUrl params path model = Sub.none
true
module Page.Index exposing (Data, Model, Msg, page) import Browser.Navigation import Chart as C import Chart.Attributes as CA import Chart.Events as CE import Chart.Item as CI import DataSource exposing (DataSource) import DataSource.Http import DataSource.Port import DateFormat import Dict import Element exposing (Element, fill, px, row) import Element.Font as Font import FormatNumber import FormatNumber.Locales exposing (usLocale) import Head import Head.Seo as Seo import Html.Attributes as Attrs import Json.Encode import List.Extra import Logo import OptimizedDecoder as Decode exposing (float, list, string) import OptimizedDecoder.Pipeline exposing (decode, required) import Page exposing (StaticPayload) import Pages.PageUrl exposing (PageUrl) import Pages.Secrets as Secrets import Path exposing (Path) import Rest.Static exposing (AmountAwardedMonth, DetainerWarrantsPerMonth, EvictionHistory, PlaintiffAttorneyWarrantCount, RollupMetadata, TopEvictor) import Runtime import Shared import Svg import Time import View exposing (View) type alias Model = { hovering : List EvictionHistory , hoveringAmounts : List (CI.Many AmountAwardedMonth CI.Any) , hoveringOnBar : List (CI.One Datum CI.Bar) } type alias RouteParams = {} page : Page.PageWithState RouteParams Data Model Msg page = Page.single { head = head , data = data } |> Page.buildWithLocalState { init = init , update = update , view = view , subscriptions = subscriptions } data : DataSource Data data = DataSource.Port.get "environmentVariable" (Json.Encode.string "ENV") Runtime.decodeEnvironment |> DataSource.andThen (\env -> let domain = Runtime.domain env in DataSource.map5 Data (topEvictorsData domain) (detainerWarrantsPerMonth domain) (plaintiffAttorneyWarrantCountPerMonth domain) (amountAwardedHistoryData domain) (apiMetadata domain) ) head : StaticPayload Data RouteParams -> List Head.Tag head static = Seo.summary { canonicalUrlOverride = Nothing , siteName = "Red Door Collective" , image = Logo.smallImage , description = "Organizing Nashville tenants for dignified housing." , locale = Nothing , title = title } |> Seo.website type alias Data = { topEvictors : List TopEvictor , warrantsPerMonth : List DetainerWarrantsPerMonth , plaintiffAttorneyWarrantCounts : List PlaintiffAttorneyWarrantCount , amountAwardedHistory : List Rest.Static.AmountAwardedMonth , rollupMeta : RollupMetadata } title = "Red Door Collective" view : Maybe PageUrl -> Shared.Model -> Model -> StaticPayload Data RouteParams -> View Msg view maybeUrl sharedModel model static = { title = title , body = [ Element.column [ Element.centerX , Element.width (fill |> Element.maximum 1000) , Font.size 14 , Element.paddingXY 5 10 ] [ Element.column [ Element.spacing 80 , Element.centerX , Element.width fill ] [ row [ Element.htmlAttribute (Attrs.class "responsive-desktop") ] [ topEvictorsChart { width = 1000, height = 600 } model static ] , row [ Element.htmlAttribute (Attrs.class "responsive-mobile") ] [ topEvictorsChart { width = 365, height = 400 } model static ] , row [ Element.htmlAttribute (Attrs.class "responsive-desktop") ] [ viewBarChart model { width = 1000, height = 600 } static.data.warrantsPerMonth ] , row [ Element.htmlAttribute (Attrs.class "responsive-mobile") ] [ viewBarChart model { width = 365, height = 365 } static.data.warrantsPerMonth ] , row [ Element.htmlAttribute <| Attrs.class "responsive-desktop" ] [ viewPlaintiffShareChart model { width = 1000, height = 800 } static.data.plaintiffAttorneyWarrantCounts ] , row [ Element.htmlAttribute <| Attrs.class "responsive-mobile" ] [ viewPlaintiffShareChart model { width = 365, height = 365 } static.data.plaintiffAttorneyWarrantCounts ] , row [ Element.htmlAttribute <| Attrs.class "responsive-desktop" ] [ viewAmountAwardedChart model { width = 1000, height = 800 } static.data.amountAwardedHistory ] , row [ Element.htmlAttribute <| Attrs.class "responsive-mobile" ] [ viewAmountAwardedChart model { width = 365, height = 365 } static.data.amountAwardedHistory ] , row [ Element.htmlAttribute <| Attrs.class "responsive-desktop", Element.centerX ] [ Element.text ("Detainer Warrants updated via Red Door Collective members as of: " ++ dateFormatLong static.data.rollupMeta.lastWarrantUpdatedAt) ] , row [ Element.width fill , Element.htmlAttribute <| Attrs.class "responsive-mobile" ] [ Element.paragraph [ Element.centerX , Element.width (fill |> Element.maximum 365) ] [ Element.text ("Detainer Warrants updated via Red Door Collective members as of: " ++ dateFormatLong static.data.rollupMeta.lastWarrantUpdatedAt) ] ] , row [ Element.height (Element.px 20) ] [] ] ] ] } topEvictorsData : String -> DataSource (List TopEvictor) topEvictorsData domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "plaintiffs")) (list (decode TopEvictor |> required "name" string |> required "history" (list (decode EvictionHistory |> required "date" float |> required "eviction_count" float ) ) ) ) detainerWarrantsPerMonth : String -> DataSource (List DetainerWarrantsPerMonth) detainerWarrantsPerMonth domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "detainer-warrants")) (list Rest.Static.detainerWarrantsPerMonthDecoder) plaintiffAttorneyWarrantCountPerMonth : String -> DataSource (List PlaintiffAttorneyWarrantCount) plaintiffAttorneyWarrantCountPerMonth domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "plaintiff-attorney")) (list Rest.Static.plaintiffAttorneyWarrantCountDecoder) amountAwardedHistoryData : String -> DataSource (List AmountAwardedMonth) amountAwardedHistoryData domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "amount-awarded/history")) (Decode.field "data" (list Rest.Static.amountAwardedMonthDecoder)) apiMetadata : String -> DataSource RollupMetadata apiMetadata domain = DataSource.Http.get (Secrets.succeed (Rest.Static.api domain "meta")) Rest.Static.rollupMetadataDecoder init : Maybe PageUrl -> Shared.Model -> StaticPayload Data RouteParams -> ( Model, Cmd Msg ) init pageUrl sharedModel payload = ( { hovering = [] , hoveringAmounts = [] , hoveringOnBar = [] } , Cmd.none ) type Msg = HoverOnBar (List (CI.One Datum CI.Bar)) | OnHoverAmounts (List (CI.Many AmountAwardedMonth CI.Any)) update : PageUrl -> Maybe Browser.Navigation.Key -> Shared.Model -> StaticPayload Data RouteParams -> Msg -> Model -> ( Model, Cmd Msg ) update pageUrl navKey sharedModel payload msg model = case msg of HoverOnBar hovering -> ( { model | hoveringOnBar = hovering }, Cmd.none ) OnHoverAmounts hovering -> ( { model | hoveringAmounts = hovering }, Cmd.none ) topEvictorsChart : Dimensions -> Model -> StaticPayload Data RouteParams -> Element Msg topEvictorsChart { width, height } model static = let series = static.data.topEvictors { titleSize, legendSize, spacing, tickNum } = if width < 600 then { titleSize = 12, legendSize = 8, spacing = 2, tickNum = 4 } else { titleSize = 20, legendSize = 12, spacing = 5, tickNum = 6 } in Element.el [ Element.width (px width), Element.height (px height) ] (Element.html (C.chart [ CA.height (toFloat height) , CA.width (toFloat width) , CA.margin { top = 20, bottom = 30, left = 60, right = 20 } , CA.padding { top = 40, bottom = 20, left = 0, right = 0 } ] ([ C.xLabels [ CA.format (\num -> dateFormat (Time.millisToPosix (round num))) , CA.amount tickNum ] , C.yLabels [ CA.withGrid ] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Top 10 Evictors in Davidson Co. TN by month" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Month" ] , C.labelAt .min CA.middle [ CA.moveLeft 45, CA.rotate 90 ] [ Svg.text "Evictions" ] ] ++ List.map (\evictor -> C.series .date [ C.interpolated .evictionCount [] [ CA.cross, CA.borderWidth 2, CA.border "white" ] |> C.named evictor.name ] evictor.history ) series ++ [ --C.each model.hovering <| -- \p item -> -- [ C.tooltip item.date [] [] [] ] C.legendsAt .max .max [ CA.column , CA.moveDown 20 , CA.alignRight , CA.spacing spacing ] [ CA.width 20 , CA.fontSize legendSize ] ] ) ) ) formatDollars number = "$" ++ FormatNumber.format usLocale number formatMillions number = "$" ++ String.fromFloat (number / 1000000) ++ "M" dateFormat : Time.Posix -> String dateFormat = DateFormat.format [ DateFormat.dayOfMonthFixed, DateFormat.text " ", DateFormat.monthNameAbbreviated ] Time.utc dateFormatLong : Time.Posix -> String dateFormatLong = DateFormat.format [ DateFormat.monthNameFull, DateFormat.text " ", DateFormat.dayOfMonthNumber, DateFormat.text ", ", DateFormat.yearNumber ] Time.utc -- BAR CHART type alias Datum = { time : Time.Posix, total : Float } barDateFormat : Time.Posix -> String barDateFormat = DateFormat.format [ DateFormat.monthNameAbbreviated, DateFormat.text " ", DateFormat.yearNumberLastTwo ] Time.utc type alias Dimensions = { width : Int, height : Int } viewBarChart : Model -> Dimensions -> List DetainerWarrantsPerMonth -> Element Msg viewBarChart model dimens allWarrants = let ( titleSize, warrants ) = if dimens.width < 600 then ( 12, List.drop 8 allWarrants ) else ( 20, allWarrants ) series = List.map (\s -> { time = s.time, total = toFloat s.totalWarrants }) warrants in Element.el [ Element.width (px dimens.width), Element.height (px dimens.height) ] (Element.html <| C.chart [ CA.height (toFloat dimens.height) , CA.width (toFloat dimens.width) , CE.onMouseMove HoverOnBar (CE.getNearest CI.bars) , CE.onMouseLeave (HoverOnBar []) , CA.margin { top = 20, bottom = 30, left = 80, right = 20 } , CA.padding { top = 40, bottom = 20, left = 0, right = 0 } ] [ C.yLabels [ CA.withGrid ] , C.bars [ CA.roundTop 0.2 , CA.margin 0.1 , CA.spacing 0.15 ] [ C.bar .total [ CA.borderWidth 1 ] |> C.named "Evictions" |> C.amongst model.hoveringOnBar (\_ -> [ CA.highlight 0.25 ]) ] series , C.barLabels [ CA.moveDown 20, CA.color "#FFFFFF" ] , C.binLabels (barDateFormat << .time) [ CA.moveDown 15 ] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Detainer warrants in Davidson Co. TN by month" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Month" ] , C.labelAt .min CA.middle [ CA.moveLeft 60, CA.rotate 90 ] [ Svg.text "# of Detainer warrants" ] , C.each model.hoveringOnBar <| \_ item -> [ C.tooltip item [] [] [] ] ] ) emptyStack = { name = "UNKNOWN", count = 0.0 } emptyStacks = { first = emptyStack , second = emptyStack , third = emptyStack , fourth = emptyStack , fifth = emptyStack , other = emptyStack , prs = emptyStack } viewPlaintiffShareChart : Model -> Dimensions -> List PlaintiffAttorneyWarrantCount -> Element Msg viewPlaintiffShareChart model dimens counts = let ( other, top5Plaintiffs ) = List.partition (\r -> List.member r.plaintiffAttorneyName [ "ALL OTHER", "Plaintiff Representing Self" ]) counts byCount = counts |> List.map (\r -> ( toFloat r.warrantCount , if r.plaintiffAttorneyName == "Plaintiff Representing Self" then "SELF REPRESENTING" else r.plaintiffAttorneyName ) ) |> Dict.fromList top5 = top5Plaintiffs |> List.Extra.indexedFoldl (\i r acc -> let datum = { name = r.plaintiffAttorneyName , count = toFloat r.warrantCount } in { acc | first = if i == 0 then datum else acc.first , second = if i == 1 then datum else acc.second , third = if i == 2 then datum else acc.third , fourth = if i == 3 then datum else acc.fourth , fifth = if i == 4 then datum else acc.fifth } ) emptyStacks series = [ top5 , { emptyStacks | other = { name = "ALL OTHER" , count = Maybe.withDefault 0.0 <| Maybe.map (toFloat << .warrantCount) <| List.head other } , prs = { name = "SELF REPRESENTING" , count = other |> List.filter ((==) "Plaintiff Representing Self" << .plaintiffAttorneyName) |> List.head |> Maybe.map (toFloat << .warrantCount) |> Maybe.withDefault 0.0 } } ] total = List.map (toFloat << .warrantCount) counts |> List.sum toPercent y = round (100 * y / total) extractName fn = Maybe.withDefault "Unknown" <| Maybe.map (.name << fn) <| List.head series { fontSize, firstShift, secondShift, titleSize } = if dimens.width < 600 then { fontSize = 8, firstShift = 10, secondShift = 20, titleSize = 12 } else { fontSize = 14, firstShift = 20, secondShift = 45, titleSize = 20 } in Element.el [ Element.width (px dimens.width), Element.height (px dimens.height) ] (Element.html (C.chart [ CA.height (toFloat dimens.height) , CA.width (toFloat dimens.width) , CA.margin { top = 20, bottom = 30, left = 80, right = 20 } , CA.padding { top = 20, bottom = 20, left = 0, right = 0 } ] [ C.yLabels [] , C.bars [ CA.margin 0.05 ] [ C.stacked [ C.bar (.count << .first) [] |> C.named (extractName .first) , C.bar (.count << .second) [] |> C.named (extractName .second) , C.bar (.count << .third) [] |> C.named (extractName .third) , C.bar (.count << .fourth) [] |> C.named (extractName .fourth) , C.bar (.count << .fifth) [] |> C.named (extractName .fifth) , C.bar (.count << .prs) [] |> C.named "SELF REPRESENTING" , C.bar (.count << .other) [] |> C.named "ALL OTHER" ] ] series , C.eachBar <| \p bar -> if CI.getY bar > 0 then [ C.label [ CA.fontSize fontSize, CA.moveDown firstShift, CA.color "white" ] [ Svg.text (Maybe.withDefault "" <| Dict.get (CI.getY bar) byCount) ] (CI.getTop p bar) , C.label [ CA.fontSize fontSize, CA.moveDown secondShift, CA.color "white" ] [ Svg.text (String.fromFloat (CI.getY bar) ++ " (" ++ (String.fromInt <| toPercent <| CI.getY bar) ++ "%)") ] (CI.getTop p bar) ] else [] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Plaintiff attorney listed on detainer warrants" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Plaintiff attorney" ] , C.labelAt .min CA.middle [ CA.moveLeft 60, CA.rotate 90, CA.moveUp 25 ] [ Svg.text "PI:NAME:<NAME>END_PI" ] ] ) ) viewAmountAwardedChart : Model -> Dimensions -> List AmountAwardedMonth -> Element Msg viewAmountAwardedChart model dimens awards = let titleSize = if dimens.width < 600 then 12 else 20 in Element.el [ Element.width (px dimens.width), Element.height (px dimens.height) ] (Element.html (C.chart [ CA.height <| toFloat dimens.height , CA.width <| toFloat dimens.width , CE.onMouseMove OnHoverAmounts (CE.getNearest CI.stacks) , CE.onMouseLeave (OnHoverAmounts []) , CA.margin { top = 20, bottom = 30, left = 100, right = 20 } , CA.padding { top = 20, bottom = 20, left = 0, right = 0 } ] [ C.xTicks [ CA.times Time.utc ] , C.xLabels [ CA.times Time.utc ] , C.yLabels [ CA.withGrid, CA.format formatMillions ] , C.series (toFloat << Time.posixToMillis << .time) [ C.interpolated (toFloat << .totalAmount) [ CA.opacity 0.6 , CA.gradient [] ] [ CA.circle, CA.color "white", CA.borderWidth 1 ] |> C.named "Amount Awarded" |> C.format formatDollars ] awards , C.each model.hoveringAmounts <| \_ item -> [ C.tooltip item [] [] [] ] , C.labelAt CA.middle .max [ CA.fontSize titleSize ] [ Svg.text "Plaintiffs awards in Davidson Co. TN by month" ] , C.labelAt CA.middle .min [ CA.moveDown 18 ] [ Svg.text "Month" ] , C.labelAt .min CA.middle [ CA.moveLeft 80, CA.rotate 90, CA.moveUp 25 ] [ Svg.text "Amount awarded ($) in millions" ] ] ) ) subscriptions : Maybe PageUrl -> RouteParams -> Path -> Model -> Sub Msg subscriptions pageUrl params path model = Sub.none
elm
[ { "context": "\" \"Email\"\n , viewInput model Password \"password\" \"Password\"\n , div []\n ", "end": 6595, "score": 0.8903234005, "start": 6587, "tag": "PASSWORD", "value": "password" }, { "context": " , viewInput model Password \"password\" \"Password\"\n , div []\n (List.map\n ", "end": 6606, "score": 0.9907363057, "start": 6598, "tag": "PASSWORD", "value": "Password" } ]
src/Example_15.elm
lucamug/elm-form-examples
19
module Main exposing (main) import Dict import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Http import Json.Decode as Decode import Json.Encode as Encode import Svg import Svg.Attributes import Utils import Validate exampleVersion : String exampleVersion = "15" type alias Model = { errors : List Error , email : String , password : String , fruits : Dict.Dict Fruit Bool , response : Maybe String , focus : Maybe FormField , showErrors : Bool , showPassword : Bool , formState : FormState } initialModel : Model initialModel = { errors = [] , email = "" , password = "" , fruits = Dict.fromList [ ( "Apple", False ) , ( "Banana", False ) , ( "Orange", False ) , ( "Mango", False ) , ( "Pear", False ) , ( "Strawberry", False ) ] , response = Nothing , focus = Nothing , showErrors = False , showPassword = False , formState = Editing } type alias Error = ( FormField, String ) type alias Fruit = String type FormState = Editing | Fetching type Msg = NoOp | SubmitForm | SetField FormField String | Response (Result Http.Error String) | OnFocus FormField | OnBlur FormField | ToggleShowPasssword | ToggleFruit Fruit type FormField = Email | Password -- UPDATE update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case Debug.log "msg" msg of NoOp -> ( model, Cmd.none ) SubmitForm -> case validate model of [] -> ( { model | errors = [], response = Nothing, formState = Fetching } , Http.send Response (postRequest model) ) errors -> ( { model | errors = errors, showErrors = True } , Cmd.none ) SetField field value -> ( model |> setField field value |> setErrors , Cmd.none ) Response (Ok response) -> ( { model | response = Just response, formState = Editing }, Cmd.none ) Response (Err error) -> ( { model | response = Just (toString error), formState = Editing }, Cmd.none ) OnFocus formField -> ( { model | focus = Just formField }, Cmd.none ) OnBlur formField -> ( { model | focus = Nothing }, Cmd.none ) ToggleShowPasssword -> ( { model | showPassword = not model.showPassword }, Cmd.none ) ToggleFruit fruit -> ( { model | fruits = toggle fruit model.fruits }, Cmd.none ) -- HELPERS toggle : comparable -> Dict.Dict comparable Bool -> Dict.Dict comparable Bool toggle key dict = Dict.update key (\oldValue -> case oldValue of Just value -> Just <| not value Nothing -> Nothing ) dict setErrors : Model -> Model setErrors model = case validate model of [] -> { model | errors = [] } errors -> { model | errors = errors } setField : FormField -> String -> Model -> Model setField field value model = case field of Email -> { model | email = value } Password -> { model | password = value } postRequest : Model -> Http.Request String postRequest model = let body = Encode.object [ ( "email", Encode.string model.email ) , ( "password", Encode.string model.password ) ] |> Http.jsonBody in Http.request { method = "POST" , headers = [] , url = Utils.urlMirrorService , body = body , expect = Http.expectString , timeout = Nothing , withCredentials = False } validate : Model -> List Error validate = Validate.all [ .email >> Validate.ifBlank ( Email, "Email can't be blank." ) , .password >> Validate.ifBlank ( Password, "Password can't be blank." ) ] onEnter : msg -> Attribute msg onEnter msg = keyCode |> Decode.andThen (\key -> if key == 13 then Decode.succeed msg else Decode.fail "Not enter" ) |> on "keyup" -- VIEWS view : Model -> Html Msg view model = Utils.view model exampleVersion viewForm viewInput : Model -> FormField -> String -> String -> Html Msg viewInput model formField inputType inputName = let hasFocus = case model.focus of Just focusedField -> focusedField == formField Nothing -> False content = case formField of Email -> model.email Password -> model.password in label [] [ div [ class "inputFieldContainer" ] [ input [ if formField == Password && model.showPassword then type_ "text" else type_ inputType , classList [ ( "focus", hasFocus ) ] , onInput <| SetField formField , onFocus <| OnFocus formField , onBlur <| OnBlur formField , value content ] [] , div [ classList [ ( "placeholder", True ) , ( "upperPosition", hasFocus || content /= "" ) ] ] [ text inputName ] , if formField == Password then div [ class "iconInsideField", onClick ToggleShowPasssword ] [ if model.showPassword then svgHide "orange" else svgShow "orange" ] else text "" ] , viewFormErrors model formField model.errors ] viewForm : Model -> Html Msg viewForm model = div [ class "form-container" ] [ div [ onEnter SubmitForm ] [ node "style" [] [ text "" ] , viewInput model Email "text" "Email" , viewInput model Password "password" "Password" , div [] (List.map (\fruit -> let value = Dict.get fruit model.fruits in label [ class "checkbox" ] [ input [ type_ "checkbox" , checked <| Maybe.withDefault False value , onClick <| ToggleFruit fruit ] [] , text <| " " ++ fruit ++ " is " , text <| toString <| value ] ) (Dict.keys model.fruits ) ) , button [ onClick SubmitForm , classList [ ( "disabled", not (List.isEmpty model.errors) && model.showErrors ) ] ] [ text "Submit" ] ] , if model.formState == Fetching then div [ class "form-cover" ] [] else text "" ] viewFormErrors : Model -> FormField -> List Error -> Html msg viewFormErrors model field errors = if model.showErrors then errors |> List.filter (\( fieldError, _ ) -> fieldError == field) |> List.map (\( _, error ) -> li [] [ text error ]) |> ul [ class "formErrors" ] else ul [ class "formErrors" ] [] -- SVG svgHide : String -> Html msg svgHide color = Svg.svg [ Svg.Attributes.viewBox "0 0 512 512", Svg.Attributes.height "32", Svg.Attributes.width "32" ] [ Svg.path [ Svg.Attributes.fill color , Svg.Attributes.d "M506 241l-89-89-14-13-258 258a227 227 0 0 0 272-37l89-89c8-8 8-22 0-30zM256 363a21 21 0 0 1 0-43c35 0 64-29 64-64a21 21 0 0 1 43 0c0 59-48 107-107 107zM95 152L6 241c-8 8-8 22 0 30l89 89 14 13 258-258c-86-49-198-37-272 37zm161 40c-35 0-64 29-64 64a21 21 0 0 1-43 0c0-59 48-107 107-107a21 21 0 0 1 0 43z" ] [] ] svgShow : String -> Html msg svgShow color = Svg.svg [ Svg.Attributes.viewBox "0 0 512 512", Svg.Attributes.height "32", Svg.Attributes.width "32" ] [ Svg.path [ Svg.Attributes.fill color , Svg.Attributes.d "M256 192a64 64 0 1 0 0 128 64 64 0 0 0 0-128zm250 49l-89-89c-89-89-233-89-322 0L6 241c-8 8-8 22 0 30l89 89a227 227 0 0 0 322 0l89-89c8-8 8-22 0-30zM256 363a107 107 0 1 1 0-214 107 107 0 0 1 0 214z" ] [] ] -- MAIN main : Program Never Model Msg main = program { init = ( initialModel, Cmd.none ) , view = view , update = update , subscriptions = \_ -> Sub.none }
4107
module Main exposing (main) import Dict import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Http import Json.Decode as Decode import Json.Encode as Encode import Svg import Svg.Attributes import Utils import Validate exampleVersion : String exampleVersion = "15" type alias Model = { errors : List Error , email : String , password : String , fruits : Dict.Dict Fruit Bool , response : Maybe String , focus : Maybe FormField , showErrors : Bool , showPassword : Bool , formState : FormState } initialModel : Model initialModel = { errors = [] , email = "" , password = "" , fruits = Dict.fromList [ ( "Apple", False ) , ( "Banana", False ) , ( "Orange", False ) , ( "Mango", False ) , ( "Pear", False ) , ( "Strawberry", False ) ] , response = Nothing , focus = Nothing , showErrors = False , showPassword = False , formState = Editing } type alias Error = ( FormField, String ) type alias Fruit = String type FormState = Editing | Fetching type Msg = NoOp | SubmitForm | SetField FormField String | Response (Result Http.Error String) | OnFocus FormField | OnBlur FormField | ToggleShowPasssword | ToggleFruit Fruit type FormField = Email | Password -- UPDATE update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case Debug.log "msg" msg of NoOp -> ( model, Cmd.none ) SubmitForm -> case validate model of [] -> ( { model | errors = [], response = Nothing, formState = Fetching } , Http.send Response (postRequest model) ) errors -> ( { model | errors = errors, showErrors = True } , Cmd.none ) SetField field value -> ( model |> setField field value |> setErrors , Cmd.none ) Response (Ok response) -> ( { model | response = Just response, formState = Editing }, Cmd.none ) Response (Err error) -> ( { model | response = Just (toString error), formState = Editing }, Cmd.none ) OnFocus formField -> ( { model | focus = Just formField }, Cmd.none ) OnBlur formField -> ( { model | focus = Nothing }, Cmd.none ) ToggleShowPasssword -> ( { model | showPassword = not model.showPassword }, Cmd.none ) ToggleFruit fruit -> ( { model | fruits = toggle fruit model.fruits }, Cmd.none ) -- HELPERS toggle : comparable -> Dict.Dict comparable Bool -> Dict.Dict comparable Bool toggle key dict = Dict.update key (\oldValue -> case oldValue of Just value -> Just <| not value Nothing -> Nothing ) dict setErrors : Model -> Model setErrors model = case validate model of [] -> { model | errors = [] } errors -> { model | errors = errors } setField : FormField -> String -> Model -> Model setField field value model = case field of Email -> { model | email = value } Password -> { model | password = value } postRequest : Model -> Http.Request String postRequest model = let body = Encode.object [ ( "email", Encode.string model.email ) , ( "password", Encode.string model.password ) ] |> Http.jsonBody in Http.request { method = "POST" , headers = [] , url = Utils.urlMirrorService , body = body , expect = Http.expectString , timeout = Nothing , withCredentials = False } validate : Model -> List Error validate = Validate.all [ .email >> Validate.ifBlank ( Email, "Email can't be blank." ) , .password >> Validate.ifBlank ( Password, "Password can't be blank." ) ] onEnter : msg -> Attribute msg onEnter msg = keyCode |> Decode.andThen (\key -> if key == 13 then Decode.succeed msg else Decode.fail "Not enter" ) |> on "keyup" -- VIEWS view : Model -> Html Msg view model = Utils.view model exampleVersion viewForm viewInput : Model -> FormField -> String -> String -> Html Msg viewInput model formField inputType inputName = let hasFocus = case model.focus of Just focusedField -> focusedField == formField Nothing -> False content = case formField of Email -> model.email Password -> model.password in label [] [ div [ class "inputFieldContainer" ] [ input [ if formField == Password && model.showPassword then type_ "text" else type_ inputType , classList [ ( "focus", hasFocus ) ] , onInput <| SetField formField , onFocus <| OnFocus formField , onBlur <| OnBlur formField , value content ] [] , div [ classList [ ( "placeholder", True ) , ( "upperPosition", hasFocus || content /= "" ) ] ] [ text inputName ] , if formField == Password then div [ class "iconInsideField", onClick ToggleShowPasssword ] [ if model.showPassword then svgHide "orange" else svgShow "orange" ] else text "" ] , viewFormErrors model formField model.errors ] viewForm : Model -> Html Msg viewForm model = div [ class "form-container" ] [ div [ onEnter SubmitForm ] [ node "style" [] [ text "" ] , viewInput model Email "text" "Email" , viewInput model Password "<PASSWORD>" "<PASSWORD>" , div [] (List.map (\fruit -> let value = Dict.get fruit model.fruits in label [ class "checkbox" ] [ input [ type_ "checkbox" , checked <| Maybe.withDefault False value , onClick <| ToggleFruit fruit ] [] , text <| " " ++ fruit ++ " is " , text <| toString <| value ] ) (Dict.keys model.fruits ) ) , button [ onClick SubmitForm , classList [ ( "disabled", not (List.isEmpty model.errors) && model.showErrors ) ] ] [ text "Submit" ] ] , if model.formState == Fetching then div [ class "form-cover" ] [] else text "" ] viewFormErrors : Model -> FormField -> List Error -> Html msg viewFormErrors model field errors = if model.showErrors then errors |> List.filter (\( fieldError, _ ) -> fieldError == field) |> List.map (\( _, error ) -> li [] [ text error ]) |> ul [ class "formErrors" ] else ul [ class "formErrors" ] [] -- SVG svgHide : String -> Html msg svgHide color = Svg.svg [ Svg.Attributes.viewBox "0 0 512 512", Svg.Attributes.height "32", Svg.Attributes.width "32" ] [ Svg.path [ Svg.Attributes.fill color , Svg.Attributes.d "M506 241l-89-89-14-13-258 258a227 227 0 0 0 272-37l89-89c8-8 8-22 0-30zM256 363a21 21 0 0 1 0-43c35 0 64-29 64-64a21 21 0 0 1 43 0c0 59-48 107-107 107zM95 152L6 241c-8 8-8 22 0 30l89 89 14 13 258-258c-86-49-198-37-272 37zm161 40c-35 0-64 29-64 64a21 21 0 0 1-43 0c0-59 48-107 107-107a21 21 0 0 1 0 43z" ] [] ] svgShow : String -> Html msg svgShow color = Svg.svg [ Svg.Attributes.viewBox "0 0 512 512", Svg.Attributes.height "32", Svg.Attributes.width "32" ] [ Svg.path [ Svg.Attributes.fill color , Svg.Attributes.d "M256 192a64 64 0 1 0 0 128 64 64 0 0 0 0-128zm250 49l-89-89c-89-89-233-89-322 0L6 241c-8 8-8 22 0 30l89 89a227 227 0 0 0 322 0l89-89c8-8 8-22 0-30zM256 363a107 107 0 1 1 0-214 107 107 0 0 1 0 214z" ] [] ] -- MAIN main : Program Never Model Msg main = program { init = ( initialModel, Cmd.none ) , view = view , update = update , subscriptions = \_ -> Sub.none }
true
module Main exposing (main) import Dict import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Http import Json.Decode as Decode import Json.Encode as Encode import Svg import Svg.Attributes import Utils import Validate exampleVersion : String exampleVersion = "15" type alias Model = { errors : List Error , email : String , password : String , fruits : Dict.Dict Fruit Bool , response : Maybe String , focus : Maybe FormField , showErrors : Bool , showPassword : Bool , formState : FormState } initialModel : Model initialModel = { errors = [] , email = "" , password = "" , fruits = Dict.fromList [ ( "Apple", False ) , ( "Banana", False ) , ( "Orange", False ) , ( "Mango", False ) , ( "Pear", False ) , ( "Strawberry", False ) ] , response = Nothing , focus = Nothing , showErrors = False , showPassword = False , formState = Editing } type alias Error = ( FormField, String ) type alias Fruit = String type FormState = Editing | Fetching type Msg = NoOp | SubmitForm | SetField FormField String | Response (Result Http.Error String) | OnFocus FormField | OnBlur FormField | ToggleShowPasssword | ToggleFruit Fruit type FormField = Email | Password -- UPDATE update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case Debug.log "msg" msg of NoOp -> ( model, Cmd.none ) SubmitForm -> case validate model of [] -> ( { model | errors = [], response = Nothing, formState = Fetching } , Http.send Response (postRequest model) ) errors -> ( { model | errors = errors, showErrors = True } , Cmd.none ) SetField field value -> ( model |> setField field value |> setErrors , Cmd.none ) Response (Ok response) -> ( { model | response = Just response, formState = Editing }, Cmd.none ) Response (Err error) -> ( { model | response = Just (toString error), formState = Editing }, Cmd.none ) OnFocus formField -> ( { model | focus = Just formField }, Cmd.none ) OnBlur formField -> ( { model | focus = Nothing }, Cmd.none ) ToggleShowPasssword -> ( { model | showPassword = not model.showPassword }, Cmd.none ) ToggleFruit fruit -> ( { model | fruits = toggle fruit model.fruits }, Cmd.none ) -- HELPERS toggle : comparable -> Dict.Dict comparable Bool -> Dict.Dict comparable Bool toggle key dict = Dict.update key (\oldValue -> case oldValue of Just value -> Just <| not value Nothing -> Nothing ) dict setErrors : Model -> Model setErrors model = case validate model of [] -> { model | errors = [] } errors -> { model | errors = errors } setField : FormField -> String -> Model -> Model setField field value model = case field of Email -> { model | email = value } Password -> { model | password = value } postRequest : Model -> Http.Request String postRequest model = let body = Encode.object [ ( "email", Encode.string model.email ) , ( "password", Encode.string model.password ) ] |> Http.jsonBody in Http.request { method = "POST" , headers = [] , url = Utils.urlMirrorService , body = body , expect = Http.expectString , timeout = Nothing , withCredentials = False } validate : Model -> List Error validate = Validate.all [ .email >> Validate.ifBlank ( Email, "Email can't be blank." ) , .password >> Validate.ifBlank ( Password, "Password can't be blank." ) ] onEnter : msg -> Attribute msg onEnter msg = keyCode |> Decode.andThen (\key -> if key == 13 then Decode.succeed msg else Decode.fail "Not enter" ) |> on "keyup" -- VIEWS view : Model -> Html Msg view model = Utils.view model exampleVersion viewForm viewInput : Model -> FormField -> String -> String -> Html Msg viewInput model formField inputType inputName = let hasFocus = case model.focus of Just focusedField -> focusedField == formField Nothing -> False content = case formField of Email -> model.email Password -> model.password in label [] [ div [ class "inputFieldContainer" ] [ input [ if formField == Password && model.showPassword then type_ "text" else type_ inputType , classList [ ( "focus", hasFocus ) ] , onInput <| SetField formField , onFocus <| OnFocus formField , onBlur <| OnBlur formField , value content ] [] , div [ classList [ ( "placeholder", True ) , ( "upperPosition", hasFocus || content /= "" ) ] ] [ text inputName ] , if formField == Password then div [ class "iconInsideField", onClick ToggleShowPasssword ] [ if model.showPassword then svgHide "orange" else svgShow "orange" ] else text "" ] , viewFormErrors model formField model.errors ] viewForm : Model -> Html Msg viewForm model = div [ class "form-container" ] [ div [ onEnter SubmitForm ] [ node "style" [] [ text "" ] , viewInput model Email "text" "Email" , viewInput model Password "PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI" , div [] (List.map (\fruit -> let value = Dict.get fruit model.fruits in label [ class "checkbox" ] [ input [ type_ "checkbox" , checked <| Maybe.withDefault False value , onClick <| ToggleFruit fruit ] [] , text <| " " ++ fruit ++ " is " , text <| toString <| value ] ) (Dict.keys model.fruits ) ) , button [ onClick SubmitForm , classList [ ( "disabled", not (List.isEmpty model.errors) && model.showErrors ) ] ] [ text "Submit" ] ] , if model.formState == Fetching then div [ class "form-cover" ] [] else text "" ] viewFormErrors : Model -> FormField -> List Error -> Html msg viewFormErrors model field errors = if model.showErrors then errors |> List.filter (\( fieldError, _ ) -> fieldError == field) |> List.map (\( _, error ) -> li [] [ text error ]) |> ul [ class "formErrors" ] else ul [ class "formErrors" ] [] -- SVG svgHide : String -> Html msg svgHide color = Svg.svg [ Svg.Attributes.viewBox "0 0 512 512", Svg.Attributes.height "32", Svg.Attributes.width "32" ] [ Svg.path [ Svg.Attributes.fill color , Svg.Attributes.d "M506 241l-89-89-14-13-258 258a227 227 0 0 0 272-37l89-89c8-8 8-22 0-30zM256 363a21 21 0 0 1 0-43c35 0 64-29 64-64a21 21 0 0 1 43 0c0 59-48 107-107 107zM95 152L6 241c-8 8-8 22 0 30l89 89 14 13 258-258c-86-49-198-37-272 37zm161 40c-35 0-64 29-64 64a21 21 0 0 1-43 0c0-59 48-107 107-107a21 21 0 0 1 0 43z" ] [] ] svgShow : String -> Html msg svgShow color = Svg.svg [ Svg.Attributes.viewBox "0 0 512 512", Svg.Attributes.height "32", Svg.Attributes.width "32" ] [ Svg.path [ Svg.Attributes.fill color , Svg.Attributes.d "M256 192a64 64 0 1 0 0 128 64 64 0 0 0 0-128zm250 49l-89-89c-89-89-233-89-322 0L6 241c-8 8-8 22 0 30l89 89a227 227 0 0 0 322 0l89-89c8-8 8-22 0-30zM256 363a107 107 0 1 1 0-214 107 107 0 0 1 0 214z" ] [] ] -- MAIN main : Program Never Model Msg main = program { init = ( initialModel, Cmd.none ) , view = view , update = update , subscriptions = \_ -> Sub.none }
elm
[ { "context": "\"attributes\": {\n \"firstname\": \"John\",\n \"lastname\": \"Doe\"\n ", "end": 1788, "score": 0.9998648763, "start": 1784, "tag": "NAME", "value": "John" }, { "context": "stname\": \"John\",\n \"lastname\": \"Doe\"\n },\n \"links\": {\n ", "end": 1827, "score": 0.9997496605, "start": 1824, "tag": "NAME", "value": "Doe" }, { "context": "Comment 2 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 2237, "score": 0.9999086261, "start": 2225, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "Comment 3 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 2647, "score": 0.999909699, "start": 2635, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "\"attributes\": {\n \"firstname\": \"John\",\n \"lastname\": \"Doe\"\n ", "end": 4388, "score": 0.9997619987, "start": 4384, "tag": "NAME", "value": "John" }, { "context": "stname\": \"John\",\n \"lastname\": \"Doe\"\n },\n \"links\": {\n ", "end": 4427, "score": 0.9996590614, "start": 4424, "tag": "NAME", "value": "Doe" }, { "context": "Comment 2 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 4837, "score": 0.9999052286, "start": 4825, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "Comment 3 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 5247, "score": 0.9999041557, "start": 5235, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "\"attributes\": {\n \"firstname\": \"John\",\n \"lastname\": \"Doe\"\n ", "end": 6896, "score": 0.999801755, "start": 6892, "tag": "NAME", "value": "John" }, { "context": "stname\": \"John\",\n \"lastname\": \"Doe\"\n },\n \"links\": {\n ", "end": 6935, "score": 0.9997252226, "start": 6932, "tag": "NAME", "value": "Doe" }, { "context": "Comment 2 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 7345, "score": 0.9999100566, "start": 7333, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "Comment 3 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 7755, "score": 0.9999113083, "start": 7743, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "\"attributes\": {\n \"firstname\": \"John\",\n \"lastname\": \"Doe\"\n ", "end": 9459, "score": 0.999787271, "start": 9455, "tag": "NAME", "value": "John" }, { "context": "stname\": \"John\",\n \"lastname\": \"Doe\"\n },\n \"links\": {\n ", "end": 9498, "score": 0.9980866909, "start": 9495, "tag": "NAME", "value": "Doe" }, { "context": "Comment 2 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 9908, "score": 0.9945902824, "start": 9896, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "Comment 3 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 10318, "score": 0.9999077916, "start": 10306, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "\"attributes\": {\n \"firstname\": \"John\",\n \"lastname\": \"Doe\"\n ", "end": 12021, "score": 0.9997534156, "start": 12017, "tag": "NAME", "value": "John" }, { "context": "stname\": \"John\",\n \"lastname\": \"Doe\"\n },\n \"links\": {\n ", "end": 12060, "score": 0.9996458292, "start": 12057, "tag": "NAME", "value": "Doe" }, { "context": "Comment 2 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 12470, "score": 0.9999104738, "start": 12458, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "Comment 3 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 12880, "score": 0.9999095798, "start": 12868, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "\"attributes\": {\n \"firstname\": \"John\",\n \"lastname\": \"Doe\"\n ", "end": 15022, "score": 0.9998260736, "start": 15018, "tag": "NAME", "value": "John" }, { "context": "stname\": \"John\",\n \"lastname\": \"Doe\"\n },\n \"links\": {\n ", "end": 15061, "score": 0.9995781183, "start": 15058, "tag": "NAME", "value": "Doe" }, { "context": "Comment 2 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 15471, "score": 0.9999162555, "start": 15459, "tag": "EMAIL", "value": "john@doe.com" }, { "context": "Comment 3 content\",\n \"email\": \"john@doe.com\"\n },\n \"links\": {\n ", "end": 15881, "score": 0.9999172091, "start": 15869, "tag": "EMAIL", "value": "john@doe.com" } ]
tests/JsonApi/Data/DocumentPayloads.elm
FabienHenon/jsonapi
9
module JsonApi.Data.DocumentPayloads exposing (invalidErrorPayload, validErrorPayload, validErrorPayloadWithData, validPayloadBadMeta, validPayloadJsonApiVersion, validPayloadMeta, validPayloadNoMeta, validPayloadOnlyMeta, validPayloadWithBadJsonApiVersion) validPayloadJsonApiVersion : String validPayloadJsonApiVersion = """ { "jsonapi": { "version": "2.0" }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "John", "lastname": "Doe" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadWithBadJsonApiVersion : String validPayloadWithBadJsonApiVersion = """ { "jsonapi": { "versions": "2.0" }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "John", "lastname": "Doe" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadNoMeta : String validPayloadNoMeta = """ { "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "John", "lastname": "Doe" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadBadMeta : String validPayloadBadMeta = """ { "meta": { "bad": true }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "John", "lastname": "Doe" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadMeta : String validPayloadMeta = """ { "meta": { "redirect": true }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "John", "lastname": "Doe" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadOnlyMeta : String validPayloadOnlyMeta = """ { "meta": { "redirect": true } } """ invalidErrorPayload : String invalidErrorPayload = """ { "errors": { "title": "My error" } } """ validErrorPayloadWithData : String validErrorPayloadWithData = """ { "errors": [ { "title": "My error" }, { "id": "error-id", "title": "My error 2" } ], "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "John", "lastname": "Doe" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "john@doe.com" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validErrorPayload : String validErrorPayload = """ { "errors": [ { "title": "My error" }, { "id": "error-id", "title": "My error 2" } ] } """
23674
module JsonApi.Data.DocumentPayloads exposing (invalidErrorPayload, validErrorPayload, validErrorPayloadWithData, validPayloadBadMeta, validPayloadJsonApiVersion, validPayloadMeta, validPayloadNoMeta, validPayloadOnlyMeta, validPayloadWithBadJsonApiVersion) validPayloadJsonApiVersion : String validPayloadJsonApiVersion = """ { "jsonapi": { "version": "2.0" }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "<NAME>", "lastname": "<NAME>" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadWithBadJsonApiVersion : String validPayloadWithBadJsonApiVersion = """ { "jsonapi": { "versions": "2.0" }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "<NAME>", "lastname": "<NAME>" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadNoMeta : String validPayloadNoMeta = """ { "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "<NAME>", "lastname": "<NAME>" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadBadMeta : String validPayloadBadMeta = """ { "meta": { "bad": true }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "<NAME>", "lastname": "<NAME>" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadMeta : String validPayloadMeta = """ { "meta": { "redirect": true }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "<NAME>", "lastname": "<NAME>" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadOnlyMeta : String validPayloadOnlyMeta = """ { "meta": { "redirect": true } } """ invalidErrorPayload : String invalidErrorPayload = """ { "errors": { "title": "My error" } } """ validErrorPayloadWithData : String validErrorPayloadWithData = """ { "errors": [ { "title": "My error" }, { "id": "error-id", "title": "My error 2" } ], "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "<NAME>", "lastname": "<NAME>" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "<EMAIL>" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validErrorPayload : String validErrorPayload = """ { "errors": [ { "title": "My error" }, { "id": "error-id", "title": "My error 2" } ] } """
true
module JsonApi.Data.DocumentPayloads exposing (invalidErrorPayload, validErrorPayload, validErrorPayloadWithData, validPayloadBadMeta, validPayloadJsonApiVersion, validPayloadMeta, validPayloadNoMeta, validPayloadOnlyMeta, validPayloadWithBadJsonApiVersion) validPayloadJsonApiVersion : String validPayloadJsonApiVersion = """ { "jsonapi": { "version": "2.0" }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "PI:NAME:<NAME>END_PI", "lastname": "PI:NAME:<NAME>END_PI" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadWithBadJsonApiVersion : String validPayloadWithBadJsonApiVersion = """ { "jsonapi": { "versions": "2.0" }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "PI:NAME:<NAME>END_PI", "lastname": "PI:NAME:<NAME>END_PI" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadNoMeta : String validPayloadNoMeta = """ { "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "PI:NAME:<NAME>END_PI", "lastname": "PI:NAME:<NAME>END_PI" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadBadMeta : String validPayloadBadMeta = """ { "meta": { "bad": true }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "PI:NAME:<NAME>END_PI", "lastname": "PI:NAME:<NAME>END_PI" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadMeta : String validPayloadMeta = """ { "meta": { "redirect": true }, "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "PI:NAME:<NAME>END_PI", "lastname": "PI:NAME:<NAME>END_PI" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validPayloadOnlyMeta : String validPayloadOnlyMeta = """ { "meta": { "redirect": true } } """ invalidErrorPayload : String invalidErrorPayload = """ { "errors": { "title": "My error" } } """ validErrorPayloadWithData : String validErrorPayloadWithData = """ { "errors": [ { "title": "My error" }, { "id": "error-id", "title": "My error 2" } ], "data": { "type": "posts", "id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad", "links": { "self": "http://link-to-post/1" }, "attributes": { "title": "First post", "content": "First post content" }, "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" } ] } } }, "included": [ { "type": "creators", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad", "attributes": { "firstname": "PI:NAME:<NAME>END_PI", "lastname": "PI:NAME:<NAME>END_PI" }, "links": { "self": "http://link-to-creator/1" }, "relationships": {} }, { "type": "comment", "id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab", "attributes": { "content": "Comment 2 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/2" }, "relationships": {} }, { "type": "comment", "id": "cb0759b0-03ab-4291-b067-84a9017fea6f", "attributes": { "content": "Comment 3 content", "email": "PI:EMAIL:<EMAIL>END_PI" }, "links": { "self": "http://link-to-comment/3" }, "relationships": {} } ] } """ validErrorPayload : String validErrorPayload = """ { "errors": [ { "title": "My error" }, { "id": "error-id", "title": "My error 2" } ] } """
elm
[ { "context": "te\n , view\n )\n\n{-\n\n Copyright 2018 Fabian Kirchner\n\n Licensed under the Apache License, Version 2.", "end": 192, "score": 0.9998623133, "start": 177, "tag": "NAME", "value": "Fabian Kirchner" } ]
examples/all-widgets/src/Listboxes/SingleSelect.elm
kirchner/listbox
2
module Listboxes.SingleSelect exposing ( Model , Msg , init , subscriptions , update , view ) {- Copyright 2018 Fabian Kirchner 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. -} import Html exposing (Html) import Html.Attributes as Attributes import Html.Events as Events import Json.Decode as Decode import List.Extra as List import Task import Widget.Listbox as Listbox exposing (Listbox) type alias Model = { importantFeaturesListbox : Listbox , importantFeatures : List String , selectedImportantFeature : Maybe String , unimportantFeaturesListbox : Listbox , unimportantFeatures : List String , selectedUnimportantFeature : Maybe String } init : Model init = { importantFeaturesListbox = Listbox.init , importantFeatures = [ "Proximity of public K-12 schools" , "Proximity of child-friendly parks" , "Proximity of grocery shopping" , "Proximity of fast food" , "Proximity of fine dining" , "Neighborhood walkability" , "Availability of public transit" , "Proximity of hospital and medical services" , "Level of traffic noise" , "Access to major highways" ] , selectedImportantFeature = Nothing , unimportantFeaturesListbox = Listbox.init , unimportantFeatures = [] , selectedUnimportantFeature = Nothing } ---- UPDATE type Msg = NoOp | ImportantFeaturesListboxMsg (Listbox.Msg String) | ImportantFeaturesUpPressed | ImportantFeaturesAltArrowUpPressed | ImportantFeaturesDownPressed | ImportantFeaturesAltArrowDownPressed | ImportantFeaturesNotImportantClicked | ImportantFeaturesDeletePressed | UnimportantFeaturesListboxMsg (Listbox.Msg String) | UnimportantFeaturesImportantClicked | UnimportantFeaturesEnterPressed update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of NoOp -> ( model, Cmd.none ) ImportantFeaturesListboxMsg listboxMsg -> let ( newListbox, listboxCmd, newSelection ) = Listbox.updateUnique listboxUpdateConfig (List.map Listbox.option model.importantFeatures) listboxMsg model.importantFeaturesListbox model.selectedImportantFeature in ( { model | importantFeaturesListbox = newListbox , selectedImportantFeature = newSelection } , Cmd.map ImportantFeaturesListboxMsg listboxCmd ) ImportantFeaturesUpPressed -> moveImportantFeatureUp model ImportantFeaturesAltArrowUpPressed -> moveImportantFeatureUp model ImportantFeaturesDownPressed -> moveImportantFeatureDown model ImportantFeaturesAltArrowDownPressed -> moveImportantFeatureDown model ImportantFeaturesNotImportantClicked -> case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> ( { model | selectedImportantFeature = Nothing , importantFeatures = List.filter (\f -> f /= feature) model.importantFeatures , unimportantFeatures = feature :: model.unimportantFeatures } , Cmd.none ) ImportantFeaturesDeletePressed -> case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let ( start, end ) = model.importantFeatures |> List.break (\f -> f == feature) ( newListbox, newSelection ) = case List.head (List.drop 1 end) |> or (List.head (List.reverse start)) of Nothing -> ( model.importantFeaturesListbox , model.selectedImportantFeature ) Just newFeature -> Listbox.withUnique model.selectedImportantFeature <| Listbox.focusEntry listboxUpdateConfig newFeature model.importantFeaturesListbox in ( { model | importantFeaturesListbox = newListbox , selectedImportantFeature = newSelection , importantFeatures = start ++ List.drop 1 end , unimportantFeatures = feature :: model.unimportantFeatures } , Cmd.none ) UnimportantFeaturesListboxMsg listboxMsg -> let ( newListbox, listboxCmd, newSelection ) = Listbox.updateUnique listboxUpdateConfig (List.map Listbox.option model.unimportantFeatures) listboxMsg model.unimportantFeaturesListbox model.selectedUnimportantFeature in ( { model | unimportantFeaturesListbox = newListbox , selectedUnimportantFeature = newSelection } , Cmd.map UnimportantFeaturesListboxMsg listboxCmd ) UnimportantFeaturesImportantClicked -> case model.selectedUnimportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> ( { model | selectedUnimportantFeature = Nothing , unimportantFeatures = List.filter (\f -> f /= feature) model.unimportantFeatures , importantFeatures = feature :: model.importantFeatures } , Cmd.none ) UnimportantFeaturesEnterPressed -> case model.selectedUnimportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let ( start, end ) = model.unimportantFeatures |> List.break (\f -> f == feature) ( newListbox, newSelection ) = case List.head (List.drop 1 end) |> or (List.head (List.reverse start)) of Nothing -> ( model.unimportantFeaturesListbox , model.selectedUnimportantFeature ) Just newFeature -> Listbox.withUnique model.selectedUnimportantFeature <| Listbox.focusEntry listboxUpdateConfig newFeature model.unimportantFeaturesListbox in ( { model | unimportantFeaturesListbox = newListbox , selectedUnimportantFeature = newSelection , unimportantFeatures = start ++ List.drop 1 end , importantFeatures = feature :: model.importantFeatures } , Cmd.none ) moveImportantFeatureUp : Model -> ( Model, Cmd Msg ) moveImportantFeatureUp model = case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let moveUp features = case features of current :: next :: rest -> if next == feature then next :: current :: moveUp rest else current :: moveUp (next :: rest) _ -> features in ( { model | importantFeatures = moveUp model.importantFeatures } , Cmd.map ImportantFeaturesListboxMsg <| Listbox.scrollToFocus "important-features-listbox" model.importantFeaturesListbox ) moveImportantFeatureDown : Model -> ( Model, Cmd Msg ) moveImportantFeatureDown model = case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let moveDown features = case features of current :: next :: rest -> if current == feature then next :: current :: moveDown rest else current :: moveDown (next :: rest) _ -> features in ( { model | importantFeatures = moveDown model.importantFeatures } , Cmd.map ImportantFeaturesListboxMsg <| Listbox.scrollToFocus "important-features-listbox" model.importantFeaturesListbox ) subscriptions : Model -> Sub Msg subscriptions model = Sub.batch [ Sub.map ImportantFeaturesListboxMsg (Listbox.subscriptions model.importantFeaturesListbox) , Sub.map UnimportantFeaturesListboxMsg (Listbox.subscriptions model.unimportantFeaturesListbox) ] ---- VIEW view : Model -> Html Msg view model = let firstSelected = List.head model.importantFeatures == model.selectedImportantFeature lastSelected = List.head (List.reverse model.importantFeatures) == model.selectedImportantFeature entries = List.map Listbox.option model.importantFeatures pathToListbox = [ "target" , "parentElement" , "parentElement" , "previousSibling" , "childNodes" , "1" , "firstChild" ] in Html.div [ Attributes.class "columns" ] [ Html.div [ Attributes.class "column" ] [ Html.div [ Attributes.class "field" ] [ Html.label [ Attributes.class "label" , Attributes.id "important-features-listbox-label" ] [ Html.text "Important features:" ] , Html.div [ Attributes.class "control" ] [ Listbox.customViewUnique listboxViewConfig { id = "important-features-listbox" , labelledBy = "important-features-listbox-label" , lift = ImportantFeaturesListboxMsg , onKeyDown = Decode.map2 Tuple.pair (Decode.field "key" Decode.string) (Decode.field "altKey" Decode.bool) |> Decode.andThen (\( rawCode, altDown ) -> case ( rawCode, altDown ) of ( "ArrowUp", True ) -> if firstSelected then Decode.fail "not handling that key here" else Decode.succeed ImportantFeaturesAltArrowUpPressed ( "ArrowDown", True ) -> if lastSelected then Decode.fail "not handling that key here" else Decode.succeed ImportantFeaturesAltArrowDownPressed ( "Delete", False ) -> Decode.succeed ImportantFeaturesDeletePressed _ -> Decode.fail "not handling that key here" ) , onMouseDown = Decode.fail "not handling this event here" , onMouseUp = Decode.fail "not handling this event here" , onBlur = Decode.fail "not handling this event here" } entries model.importantFeaturesListbox model.selectedImportantFeature ] ] , Html.div [ Attributes.class "field" , Attributes.class "is-grouped" , Attributes.attribute "role" "toolbar" , Attributes.attribute "aria-label" "Actions" ] [ Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedImportantFeature == Nothing || firstSelected) , Events.on "click" <| Decode.succeed ImportantFeaturesUpPressed , Attributes.attribute "aria-keyshortcuts" "Alt+ArrowUp" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedImportantFeature == Nothing || firstSelected) ] [ Html.text "Up" ] ] , Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedImportantFeature == Nothing || lastSelected) , Events.on "click" <| Decode.succeed ImportantFeaturesDownPressed , Attributes.attribute "aria-keyshortcuts" "Alt+ArrowDown" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedImportantFeature == Nothing || lastSelected) ] [ Html.text "Down" ] ] , Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedImportantFeature == Nothing) , Events.onClick ImportantFeaturesNotImportantClicked , Attributes.attribute "aria-keyshortcuts" "Delete" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedImportantFeature == Nothing) ] [ Html.span [] [ Html.text "Not Important " ] , Html.span [ Attributes.class "icon" , Attributes.style "font-size" "12px" , Attributes.class "is-small" ] [ Html.i [ Attributes.class "fas" , Attributes.class "fa-arrow-right" ] [] ] ] ] ] ] , Html.div [ Attributes.class "column" ] [ Html.div [ Attributes.class "field" ] [ Html.label [ Attributes.class "label" , Attributes.id "unimportant-features-listbox-label" ] [ Html.text "Unimportant features:" ] , Html.div [ Attributes.class "control" ] [ Listbox.customViewUnique listboxViewConfig { id = "unimportant-features-listbox" , labelledBy = "unimportant-features-listbox-label" , lift = UnimportantFeaturesListboxMsg , onKeyDown = Decode.field "key" Decode.string |> Decode.andThen (\rawCode -> case rawCode of "Enter" -> Decode.succeed UnimportantFeaturesEnterPressed _ -> Decode.fail "not handling that key here" ) , onMouseDown = Decode.fail "not handling this event here" , onMouseUp = Decode.fail "not handling this event here" , onBlur = Decode.fail "not handling this event here" } (List.map Listbox.option model.unimportantFeatures) model.unimportantFeaturesListbox model.selectedUnimportantFeature ] ] , Html.div [ Attributes.class "field" , Attributes.class "is-grouped" ] [ Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedUnimportantFeature == Nothing) , Events.onClick UnimportantFeaturesImportantClicked , Attributes.attribute "aria-keyshortcuts" "Enter" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedUnimportantFeature == Nothing) ] [ Html.span [ Attributes.class "icon" , Attributes.style "font-size" "12px" , Attributes.class "is-small" ] [ Html.i [ Attributes.class "fas" , Attributes.class "fa-arrow-left" ] [] ] , Html.span [] [ Html.text " Important" ] ] ] ] ] ] ---- CONFIGURATION listboxUpdateConfig : Listbox.UpdateConfig String listboxUpdateConfig = Listbox.updateConfig identity { jumpAtEnds = False , separateFocus = True , selectionFollowsFocus = True , handleHomeAndEnd = True , typeAhead = Listbox.noTypeAhead , minimalGap = 0 , initialGap = 0 } listboxViewConfig : Listbox.ViewConfig String Never listboxViewConfig = Listbox.viewConfig identity { ul = [ Attributes.class "list" ] , liOption = \{ keyboardFocused, mouseFocused, maybeQuery } name -> { attributes = [ Attributes.class "entry" , Attributes.classList [ ( "entry--keyboard-focused", keyboardFocused ) , ( "entry--mouse-focused", mouseFocused ) ] ] , children = [ Html.text name ] } , liDivider = Listbox.noDivider , empty = Html.div [] [ Html.text "this list is empty" ] , focusable = True } ---- HELPER or : Maybe a -> Maybe a -> Maybe a or fallback default = case default of Nothing -> fallback Just _ -> default boolToString : Bool -> String boolToString b = if b then "true" else "false"
12943
module Listboxes.SingleSelect exposing ( Model , Msg , init , subscriptions , update , view ) {- Copyright 2018 <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. -} import Html exposing (Html) import Html.Attributes as Attributes import Html.Events as Events import Json.Decode as Decode import List.Extra as List import Task import Widget.Listbox as Listbox exposing (Listbox) type alias Model = { importantFeaturesListbox : Listbox , importantFeatures : List String , selectedImportantFeature : Maybe String , unimportantFeaturesListbox : Listbox , unimportantFeatures : List String , selectedUnimportantFeature : Maybe String } init : Model init = { importantFeaturesListbox = Listbox.init , importantFeatures = [ "Proximity of public K-12 schools" , "Proximity of child-friendly parks" , "Proximity of grocery shopping" , "Proximity of fast food" , "Proximity of fine dining" , "Neighborhood walkability" , "Availability of public transit" , "Proximity of hospital and medical services" , "Level of traffic noise" , "Access to major highways" ] , selectedImportantFeature = Nothing , unimportantFeaturesListbox = Listbox.init , unimportantFeatures = [] , selectedUnimportantFeature = Nothing } ---- UPDATE type Msg = NoOp | ImportantFeaturesListboxMsg (Listbox.Msg String) | ImportantFeaturesUpPressed | ImportantFeaturesAltArrowUpPressed | ImportantFeaturesDownPressed | ImportantFeaturesAltArrowDownPressed | ImportantFeaturesNotImportantClicked | ImportantFeaturesDeletePressed | UnimportantFeaturesListboxMsg (Listbox.Msg String) | UnimportantFeaturesImportantClicked | UnimportantFeaturesEnterPressed update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of NoOp -> ( model, Cmd.none ) ImportantFeaturesListboxMsg listboxMsg -> let ( newListbox, listboxCmd, newSelection ) = Listbox.updateUnique listboxUpdateConfig (List.map Listbox.option model.importantFeatures) listboxMsg model.importantFeaturesListbox model.selectedImportantFeature in ( { model | importantFeaturesListbox = newListbox , selectedImportantFeature = newSelection } , Cmd.map ImportantFeaturesListboxMsg listboxCmd ) ImportantFeaturesUpPressed -> moveImportantFeatureUp model ImportantFeaturesAltArrowUpPressed -> moveImportantFeatureUp model ImportantFeaturesDownPressed -> moveImportantFeatureDown model ImportantFeaturesAltArrowDownPressed -> moveImportantFeatureDown model ImportantFeaturesNotImportantClicked -> case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> ( { model | selectedImportantFeature = Nothing , importantFeatures = List.filter (\f -> f /= feature) model.importantFeatures , unimportantFeatures = feature :: model.unimportantFeatures } , Cmd.none ) ImportantFeaturesDeletePressed -> case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let ( start, end ) = model.importantFeatures |> List.break (\f -> f == feature) ( newListbox, newSelection ) = case List.head (List.drop 1 end) |> or (List.head (List.reverse start)) of Nothing -> ( model.importantFeaturesListbox , model.selectedImportantFeature ) Just newFeature -> Listbox.withUnique model.selectedImportantFeature <| Listbox.focusEntry listboxUpdateConfig newFeature model.importantFeaturesListbox in ( { model | importantFeaturesListbox = newListbox , selectedImportantFeature = newSelection , importantFeatures = start ++ List.drop 1 end , unimportantFeatures = feature :: model.unimportantFeatures } , Cmd.none ) UnimportantFeaturesListboxMsg listboxMsg -> let ( newListbox, listboxCmd, newSelection ) = Listbox.updateUnique listboxUpdateConfig (List.map Listbox.option model.unimportantFeatures) listboxMsg model.unimportantFeaturesListbox model.selectedUnimportantFeature in ( { model | unimportantFeaturesListbox = newListbox , selectedUnimportantFeature = newSelection } , Cmd.map UnimportantFeaturesListboxMsg listboxCmd ) UnimportantFeaturesImportantClicked -> case model.selectedUnimportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> ( { model | selectedUnimportantFeature = Nothing , unimportantFeatures = List.filter (\f -> f /= feature) model.unimportantFeatures , importantFeatures = feature :: model.importantFeatures } , Cmd.none ) UnimportantFeaturesEnterPressed -> case model.selectedUnimportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let ( start, end ) = model.unimportantFeatures |> List.break (\f -> f == feature) ( newListbox, newSelection ) = case List.head (List.drop 1 end) |> or (List.head (List.reverse start)) of Nothing -> ( model.unimportantFeaturesListbox , model.selectedUnimportantFeature ) Just newFeature -> Listbox.withUnique model.selectedUnimportantFeature <| Listbox.focusEntry listboxUpdateConfig newFeature model.unimportantFeaturesListbox in ( { model | unimportantFeaturesListbox = newListbox , selectedUnimportantFeature = newSelection , unimportantFeatures = start ++ List.drop 1 end , importantFeatures = feature :: model.importantFeatures } , Cmd.none ) moveImportantFeatureUp : Model -> ( Model, Cmd Msg ) moveImportantFeatureUp model = case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let moveUp features = case features of current :: next :: rest -> if next == feature then next :: current :: moveUp rest else current :: moveUp (next :: rest) _ -> features in ( { model | importantFeatures = moveUp model.importantFeatures } , Cmd.map ImportantFeaturesListboxMsg <| Listbox.scrollToFocus "important-features-listbox" model.importantFeaturesListbox ) moveImportantFeatureDown : Model -> ( Model, Cmd Msg ) moveImportantFeatureDown model = case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let moveDown features = case features of current :: next :: rest -> if current == feature then next :: current :: moveDown rest else current :: moveDown (next :: rest) _ -> features in ( { model | importantFeatures = moveDown model.importantFeatures } , Cmd.map ImportantFeaturesListboxMsg <| Listbox.scrollToFocus "important-features-listbox" model.importantFeaturesListbox ) subscriptions : Model -> Sub Msg subscriptions model = Sub.batch [ Sub.map ImportantFeaturesListboxMsg (Listbox.subscriptions model.importantFeaturesListbox) , Sub.map UnimportantFeaturesListboxMsg (Listbox.subscriptions model.unimportantFeaturesListbox) ] ---- VIEW view : Model -> Html Msg view model = let firstSelected = List.head model.importantFeatures == model.selectedImportantFeature lastSelected = List.head (List.reverse model.importantFeatures) == model.selectedImportantFeature entries = List.map Listbox.option model.importantFeatures pathToListbox = [ "target" , "parentElement" , "parentElement" , "previousSibling" , "childNodes" , "1" , "firstChild" ] in Html.div [ Attributes.class "columns" ] [ Html.div [ Attributes.class "column" ] [ Html.div [ Attributes.class "field" ] [ Html.label [ Attributes.class "label" , Attributes.id "important-features-listbox-label" ] [ Html.text "Important features:" ] , Html.div [ Attributes.class "control" ] [ Listbox.customViewUnique listboxViewConfig { id = "important-features-listbox" , labelledBy = "important-features-listbox-label" , lift = ImportantFeaturesListboxMsg , onKeyDown = Decode.map2 Tuple.pair (Decode.field "key" Decode.string) (Decode.field "altKey" Decode.bool) |> Decode.andThen (\( rawCode, altDown ) -> case ( rawCode, altDown ) of ( "ArrowUp", True ) -> if firstSelected then Decode.fail "not handling that key here" else Decode.succeed ImportantFeaturesAltArrowUpPressed ( "ArrowDown", True ) -> if lastSelected then Decode.fail "not handling that key here" else Decode.succeed ImportantFeaturesAltArrowDownPressed ( "Delete", False ) -> Decode.succeed ImportantFeaturesDeletePressed _ -> Decode.fail "not handling that key here" ) , onMouseDown = Decode.fail "not handling this event here" , onMouseUp = Decode.fail "not handling this event here" , onBlur = Decode.fail "not handling this event here" } entries model.importantFeaturesListbox model.selectedImportantFeature ] ] , Html.div [ Attributes.class "field" , Attributes.class "is-grouped" , Attributes.attribute "role" "toolbar" , Attributes.attribute "aria-label" "Actions" ] [ Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedImportantFeature == Nothing || firstSelected) , Events.on "click" <| Decode.succeed ImportantFeaturesUpPressed , Attributes.attribute "aria-keyshortcuts" "Alt+ArrowUp" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedImportantFeature == Nothing || firstSelected) ] [ Html.text "Up" ] ] , Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedImportantFeature == Nothing || lastSelected) , Events.on "click" <| Decode.succeed ImportantFeaturesDownPressed , Attributes.attribute "aria-keyshortcuts" "Alt+ArrowDown" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedImportantFeature == Nothing || lastSelected) ] [ Html.text "Down" ] ] , Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedImportantFeature == Nothing) , Events.onClick ImportantFeaturesNotImportantClicked , Attributes.attribute "aria-keyshortcuts" "Delete" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedImportantFeature == Nothing) ] [ Html.span [] [ Html.text "Not Important " ] , Html.span [ Attributes.class "icon" , Attributes.style "font-size" "12px" , Attributes.class "is-small" ] [ Html.i [ Attributes.class "fas" , Attributes.class "fa-arrow-right" ] [] ] ] ] ] ] , Html.div [ Attributes.class "column" ] [ Html.div [ Attributes.class "field" ] [ Html.label [ Attributes.class "label" , Attributes.id "unimportant-features-listbox-label" ] [ Html.text "Unimportant features:" ] , Html.div [ Attributes.class "control" ] [ Listbox.customViewUnique listboxViewConfig { id = "unimportant-features-listbox" , labelledBy = "unimportant-features-listbox-label" , lift = UnimportantFeaturesListboxMsg , onKeyDown = Decode.field "key" Decode.string |> Decode.andThen (\rawCode -> case rawCode of "Enter" -> Decode.succeed UnimportantFeaturesEnterPressed _ -> Decode.fail "not handling that key here" ) , onMouseDown = Decode.fail "not handling this event here" , onMouseUp = Decode.fail "not handling this event here" , onBlur = Decode.fail "not handling this event here" } (List.map Listbox.option model.unimportantFeatures) model.unimportantFeaturesListbox model.selectedUnimportantFeature ] ] , Html.div [ Attributes.class "field" , Attributes.class "is-grouped" ] [ Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedUnimportantFeature == Nothing) , Events.onClick UnimportantFeaturesImportantClicked , Attributes.attribute "aria-keyshortcuts" "Enter" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedUnimportantFeature == Nothing) ] [ Html.span [ Attributes.class "icon" , Attributes.style "font-size" "12px" , Attributes.class "is-small" ] [ Html.i [ Attributes.class "fas" , Attributes.class "fa-arrow-left" ] [] ] , Html.span [] [ Html.text " Important" ] ] ] ] ] ] ---- CONFIGURATION listboxUpdateConfig : Listbox.UpdateConfig String listboxUpdateConfig = Listbox.updateConfig identity { jumpAtEnds = False , separateFocus = True , selectionFollowsFocus = True , handleHomeAndEnd = True , typeAhead = Listbox.noTypeAhead , minimalGap = 0 , initialGap = 0 } listboxViewConfig : Listbox.ViewConfig String Never listboxViewConfig = Listbox.viewConfig identity { ul = [ Attributes.class "list" ] , liOption = \{ keyboardFocused, mouseFocused, maybeQuery } name -> { attributes = [ Attributes.class "entry" , Attributes.classList [ ( "entry--keyboard-focused", keyboardFocused ) , ( "entry--mouse-focused", mouseFocused ) ] ] , children = [ Html.text name ] } , liDivider = Listbox.noDivider , empty = Html.div [] [ Html.text "this list is empty" ] , focusable = True } ---- HELPER or : Maybe a -> Maybe a -> Maybe a or fallback default = case default of Nothing -> fallback Just _ -> default boolToString : Bool -> String boolToString b = if b then "true" else "false"
true
module Listboxes.SingleSelect exposing ( Model , Msg , init , subscriptions , update , view ) {- Copyright 2018 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. -} import Html exposing (Html) import Html.Attributes as Attributes import Html.Events as Events import Json.Decode as Decode import List.Extra as List import Task import Widget.Listbox as Listbox exposing (Listbox) type alias Model = { importantFeaturesListbox : Listbox , importantFeatures : List String , selectedImportantFeature : Maybe String , unimportantFeaturesListbox : Listbox , unimportantFeatures : List String , selectedUnimportantFeature : Maybe String } init : Model init = { importantFeaturesListbox = Listbox.init , importantFeatures = [ "Proximity of public K-12 schools" , "Proximity of child-friendly parks" , "Proximity of grocery shopping" , "Proximity of fast food" , "Proximity of fine dining" , "Neighborhood walkability" , "Availability of public transit" , "Proximity of hospital and medical services" , "Level of traffic noise" , "Access to major highways" ] , selectedImportantFeature = Nothing , unimportantFeaturesListbox = Listbox.init , unimportantFeatures = [] , selectedUnimportantFeature = Nothing } ---- UPDATE type Msg = NoOp | ImportantFeaturesListboxMsg (Listbox.Msg String) | ImportantFeaturesUpPressed | ImportantFeaturesAltArrowUpPressed | ImportantFeaturesDownPressed | ImportantFeaturesAltArrowDownPressed | ImportantFeaturesNotImportantClicked | ImportantFeaturesDeletePressed | UnimportantFeaturesListboxMsg (Listbox.Msg String) | UnimportantFeaturesImportantClicked | UnimportantFeaturesEnterPressed update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of NoOp -> ( model, Cmd.none ) ImportantFeaturesListboxMsg listboxMsg -> let ( newListbox, listboxCmd, newSelection ) = Listbox.updateUnique listboxUpdateConfig (List.map Listbox.option model.importantFeatures) listboxMsg model.importantFeaturesListbox model.selectedImportantFeature in ( { model | importantFeaturesListbox = newListbox , selectedImportantFeature = newSelection } , Cmd.map ImportantFeaturesListboxMsg listboxCmd ) ImportantFeaturesUpPressed -> moveImportantFeatureUp model ImportantFeaturesAltArrowUpPressed -> moveImportantFeatureUp model ImportantFeaturesDownPressed -> moveImportantFeatureDown model ImportantFeaturesAltArrowDownPressed -> moveImportantFeatureDown model ImportantFeaturesNotImportantClicked -> case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> ( { model | selectedImportantFeature = Nothing , importantFeatures = List.filter (\f -> f /= feature) model.importantFeatures , unimportantFeatures = feature :: model.unimportantFeatures } , Cmd.none ) ImportantFeaturesDeletePressed -> case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let ( start, end ) = model.importantFeatures |> List.break (\f -> f == feature) ( newListbox, newSelection ) = case List.head (List.drop 1 end) |> or (List.head (List.reverse start)) of Nothing -> ( model.importantFeaturesListbox , model.selectedImportantFeature ) Just newFeature -> Listbox.withUnique model.selectedImportantFeature <| Listbox.focusEntry listboxUpdateConfig newFeature model.importantFeaturesListbox in ( { model | importantFeaturesListbox = newListbox , selectedImportantFeature = newSelection , importantFeatures = start ++ List.drop 1 end , unimportantFeatures = feature :: model.unimportantFeatures } , Cmd.none ) UnimportantFeaturesListboxMsg listboxMsg -> let ( newListbox, listboxCmd, newSelection ) = Listbox.updateUnique listboxUpdateConfig (List.map Listbox.option model.unimportantFeatures) listboxMsg model.unimportantFeaturesListbox model.selectedUnimportantFeature in ( { model | unimportantFeaturesListbox = newListbox , selectedUnimportantFeature = newSelection } , Cmd.map UnimportantFeaturesListboxMsg listboxCmd ) UnimportantFeaturesImportantClicked -> case model.selectedUnimportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> ( { model | selectedUnimportantFeature = Nothing , unimportantFeatures = List.filter (\f -> f /= feature) model.unimportantFeatures , importantFeatures = feature :: model.importantFeatures } , Cmd.none ) UnimportantFeaturesEnterPressed -> case model.selectedUnimportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let ( start, end ) = model.unimportantFeatures |> List.break (\f -> f == feature) ( newListbox, newSelection ) = case List.head (List.drop 1 end) |> or (List.head (List.reverse start)) of Nothing -> ( model.unimportantFeaturesListbox , model.selectedUnimportantFeature ) Just newFeature -> Listbox.withUnique model.selectedUnimportantFeature <| Listbox.focusEntry listboxUpdateConfig newFeature model.unimportantFeaturesListbox in ( { model | unimportantFeaturesListbox = newListbox , selectedUnimportantFeature = newSelection , unimportantFeatures = start ++ List.drop 1 end , importantFeatures = feature :: model.importantFeatures } , Cmd.none ) moveImportantFeatureUp : Model -> ( Model, Cmd Msg ) moveImportantFeatureUp model = case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let moveUp features = case features of current :: next :: rest -> if next == feature then next :: current :: moveUp rest else current :: moveUp (next :: rest) _ -> features in ( { model | importantFeatures = moveUp model.importantFeatures } , Cmd.map ImportantFeaturesListboxMsg <| Listbox.scrollToFocus "important-features-listbox" model.importantFeaturesListbox ) moveImportantFeatureDown : Model -> ( Model, Cmd Msg ) moveImportantFeatureDown model = case model.selectedImportantFeature of Nothing -> ( model, Cmd.none ) Just feature -> let moveDown features = case features of current :: next :: rest -> if current == feature then next :: current :: moveDown rest else current :: moveDown (next :: rest) _ -> features in ( { model | importantFeatures = moveDown model.importantFeatures } , Cmd.map ImportantFeaturesListboxMsg <| Listbox.scrollToFocus "important-features-listbox" model.importantFeaturesListbox ) subscriptions : Model -> Sub Msg subscriptions model = Sub.batch [ Sub.map ImportantFeaturesListboxMsg (Listbox.subscriptions model.importantFeaturesListbox) , Sub.map UnimportantFeaturesListboxMsg (Listbox.subscriptions model.unimportantFeaturesListbox) ] ---- VIEW view : Model -> Html Msg view model = let firstSelected = List.head model.importantFeatures == model.selectedImportantFeature lastSelected = List.head (List.reverse model.importantFeatures) == model.selectedImportantFeature entries = List.map Listbox.option model.importantFeatures pathToListbox = [ "target" , "parentElement" , "parentElement" , "previousSibling" , "childNodes" , "1" , "firstChild" ] in Html.div [ Attributes.class "columns" ] [ Html.div [ Attributes.class "column" ] [ Html.div [ Attributes.class "field" ] [ Html.label [ Attributes.class "label" , Attributes.id "important-features-listbox-label" ] [ Html.text "Important features:" ] , Html.div [ Attributes.class "control" ] [ Listbox.customViewUnique listboxViewConfig { id = "important-features-listbox" , labelledBy = "important-features-listbox-label" , lift = ImportantFeaturesListboxMsg , onKeyDown = Decode.map2 Tuple.pair (Decode.field "key" Decode.string) (Decode.field "altKey" Decode.bool) |> Decode.andThen (\( rawCode, altDown ) -> case ( rawCode, altDown ) of ( "ArrowUp", True ) -> if firstSelected then Decode.fail "not handling that key here" else Decode.succeed ImportantFeaturesAltArrowUpPressed ( "ArrowDown", True ) -> if lastSelected then Decode.fail "not handling that key here" else Decode.succeed ImportantFeaturesAltArrowDownPressed ( "Delete", False ) -> Decode.succeed ImportantFeaturesDeletePressed _ -> Decode.fail "not handling that key here" ) , onMouseDown = Decode.fail "not handling this event here" , onMouseUp = Decode.fail "not handling this event here" , onBlur = Decode.fail "not handling this event here" } entries model.importantFeaturesListbox model.selectedImportantFeature ] ] , Html.div [ Attributes.class "field" , Attributes.class "is-grouped" , Attributes.attribute "role" "toolbar" , Attributes.attribute "aria-label" "Actions" ] [ Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedImportantFeature == Nothing || firstSelected) , Events.on "click" <| Decode.succeed ImportantFeaturesUpPressed , Attributes.attribute "aria-keyshortcuts" "Alt+ArrowUp" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedImportantFeature == Nothing || firstSelected) ] [ Html.text "Up" ] ] , Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedImportantFeature == Nothing || lastSelected) , Events.on "click" <| Decode.succeed ImportantFeaturesDownPressed , Attributes.attribute "aria-keyshortcuts" "Alt+ArrowDown" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedImportantFeature == Nothing || lastSelected) ] [ Html.text "Down" ] ] , Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedImportantFeature == Nothing) , Events.onClick ImportantFeaturesNotImportantClicked , Attributes.attribute "aria-keyshortcuts" "Delete" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedImportantFeature == Nothing) ] [ Html.span [] [ Html.text "Not Important " ] , Html.span [ Attributes.class "icon" , Attributes.style "font-size" "12px" , Attributes.class "is-small" ] [ Html.i [ Attributes.class "fas" , Attributes.class "fa-arrow-right" ] [] ] ] ] ] ] , Html.div [ Attributes.class "column" ] [ Html.div [ Attributes.class "field" ] [ Html.label [ Attributes.class "label" , Attributes.id "unimportant-features-listbox-label" ] [ Html.text "Unimportant features:" ] , Html.div [ Attributes.class "control" ] [ Listbox.customViewUnique listboxViewConfig { id = "unimportant-features-listbox" , labelledBy = "unimportant-features-listbox-label" , lift = UnimportantFeaturesListboxMsg , onKeyDown = Decode.field "key" Decode.string |> Decode.andThen (\rawCode -> case rawCode of "Enter" -> Decode.succeed UnimportantFeaturesEnterPressed _ -> Decode.fail "not handling that key here" ) , onMouseDown = Decode.fail "not handling this event here" , onMouseUp = Decode.fail "not handling this event here" , onBlur = Decode.fail "not handling this event here" } (List.map Listbox.option model.unimportantFeatures) model.unimportantFeaturesListbox model.selectedUnimportantFeature ] ] , Html.div [ Attributes.class "field" , Attributes.class "is-grouped" ] [ Html.div [ Attributes.class "control" ] [ Html.button [ Attributes.class "button" , Attributes.disabled (model.selectedUnimportantFeature == Nothing) , Events.onClick UnimportantFeaturesImportantClicked , Attributes.attribute "aria-keyshortcuts" "Enter" , Attributes.attribute "aria-disabled" <| boolToString (model.selectedUnimportantFeature == Nothing) ] [ Html.span [ Attributes.class "icon" , Attributes.style "font-size" "12px" , Attributes.class "is-small" ] [ Html.i [ Attributes.class "fas" , Attributes.class "fa-arrow-left" ] [] ] , Html.span [] [ Html.text " Important" ] ] ] ] ] ] ---- CONFIGURATION listboxUpdateConfig : Listbox.UpdateConfig String listboxUpdateConfig = Listbox.updateConfig identity { jumpAtEnds = False , separateFocus = True , selectionFollowsFocus = True , handleHomeAndEnd = True , typeAhead = Listbox.noTypeAhead , minimalGap = 0 , initialGap = 0 } listboxViewConfig : Listbox.ViewConfig String Never listboxViewConfig = Listbox.viewConfig identity { ul = [ Attributes.class "list" ] , liOption = \{ keyboardFocused, mouseFocused, maybeQuery } name -> { attributes = [ Attributes.class "entry" , Attributes.classList [ ( "entry--keyboard-focused", keyboardFocused ) , ( "entry--mouse-focused", mouseFocused ) ] ] , children = [ Html.text name ] } , liDivider = Listbox.noDivider , empty = Html.div [] [ Html.text "this list is empty" ] , focusable = True } ---- HELPER or : Maybe a -> Maybe a -> Maybe a or fallback default = case default of Nothing -> fallback Just _ -> default boolToString : Bool -> String boolToString b = if b then "true" else "false"
elm
[ { "context": "lubin.net\"\n ]\n [ Html.text \"Justin Lubin\"\n ]\n\n , Html.br [] []\n ,", "end": 2639, "score": 0.9998050928, "start": 2627, "tag": "NAME", "value": "Justin Lubin" } ]
src/View.elm
justinlubin/lampora
1
module View exposing ( view ) import Html exposing (Html) import Html.Attributes as Attr import Html.Events as Events import Model exposing (Model) import Controller exposing (Msg(..)) import ECS import Vector import Tilemap exposing (Zone(..)) import World import Params title : Html Msg title = Html.h1 [ Attr.id "main-title" ] [ Html.text "The Shards of Mt. Lampora" ] score : Model -> Html Msg score model = let shard class = Html.div [ Attr.class <| "shard " ++ class ] [] in Html.div [ Attr.id "score" ] <| ( List.map (\_ -> shard "obtained") (List.range 1 model.game.world.score) ) ++ ( List.map (\_ -> shard "remaining") (List.range (model.game.world.score + 1) model.game.world.winningScore) ) screen : Model -> Html Msg screen model = let showWhen : World.State -> Html.Attribute Msg showWhen state = if state == model.game.world.state then Attr.style "opacity" "1" else Attr.style "opacity" "0" in Html.div [ Attr.id "screen" , Attr.style "width" <| String.fromInt Params.screenWidth ++ "px" , Attr.style "height" <| String.fromInt Params.screenHeight ++ "px" ] [ Html.canvas [ Attr.id "game" ] [] , Html.div [ Attr.id "won-overlay" , Attr.class "overlay" , showWhen World.Won ] [ Html.text "You win!" ] ] playButton : Model -> Html Msg playButton model = let loaded = Model.loaded model in Html.div ( [ Attr.id "play-button" ] ++ ( if model.playing then [ Attr.class "hidden" ] else if loaded then [ Events.onClick PlayClicked ] else [ Attr.class "disabled" ] ) ) ( if loaded then [ Html.text "Play!" ] else [ Html.text "Loading..." ] ) credits : Html Msg credits = Html.div [ Attr.id "credits" ] [ Html.h2 [ Attr.id "credits-title" ] [ Html.text "Controls & Credits" ] , Html.div [ Attr.id "credits-content" ] [ Html.i [] [ Html.text "Left/right arrow keys + Z to jump!" ] , Html.br [] [] , Html.text "Design, programming, music: " , Html.a [ Attr.href "http://jlubin.net" ] [ Html.text "Justin Lubin" ] , Html.br [] [] , Html.text "Programming language: " , Html.a [ Attr.href "https://elm-lang.org/" ] [ Html.text "Elm" ] , Html.br [] [] , Html.text "Level editor: " , Html.a [ Attr.href "https://www.mapeditor.org/" ] [ Html.text "Tiled" ] , Html.br [] [] , Html.text "Music software: " , Html.a [ Attr.href "https://musescore.org" ] [ Html.text "MuseScore" ] , Html.br [] [] , Html.text "Sound effect software: " , Html.a [ Attr.href "https://sfbgames.com/chiptone/" ] [ Html.text "ChipTone" ] ] ] view : Model -> Html Msg view model = Html.div [ Attr.id "arcade" ] [ title , score model , screen model , playButton model , credits ]
53462
module View exposing ( view ) import Html exposing (Html) import Html.Attributes as Attr import Html.Events as Events import Model exposing (Model) import Controller exposing (Msg(..)) import ECS import Vector import Tilemap exposing (Zone(..)) import World import Params title : Html Msg title = Html.h1 [ Attr.id "main-title" ] [ Html.text "The Shards of Mt. Lampora" ] score : Model -> Html Msg score model = let shard class = Html.div [ Attr.class <| "shard " ++ class ] [] in Html.div [ Attr.id "score" ] <| ( List.map (\_ -> shard "obtained") (List.range 1 model.game.world.score) ) ++ ( List.map (\_ -> shard "remaining") (List.range (model.game.world.score + 1) model.game.world.winningScore) ) screen : Model -> Html Msg screen model = let showWhen : World.State -> Html.Attribute Msg showWhen state = if state == model.game.world.state then Attr.style "opacity" "1" else Attr.style "opacity" "0" in Html.div [ Attr.id "screen" , Attr.style "width" <| String.fromInt Params.screenWidth ++ "px" , Attr.style "height" <| String.fromInt Params.screenHeight ++ "px" ] [ Html.canvas [ Attr.id "game" ] [] , Html.div [ Attr.id "won-overlay" , Attr.class "overlay" , showWhen World.Won ] [ Html.text "You win!" ] ] playButton : Model -> Html Msg playButton model = let loaded = Model.loaded model in Html.div ( [ Attr.id "play-button" ] ++ ( if model.playing then [ Attr.class "hidden" ] else if loaded then [ Events.onClick PlayClicked ] else [ Attr.class "disabled" ] ) ) ( if loaded then [ Html.text "Play!" ] else [ Html.text "Loading..." ] ) credits : Html Msg credits = Html.div [ Attr.id "credits" ] [ Html.h2 [ Attr.id "credits-title" ] [ Html.text "Controls & Credits" ] , Html.div [ Attr.id "credits-content" ] [ Html.i [] [ Html.text "Left/right arrow keys + Z to jump!" ] , Html.br [] [] , Html.text "Design, programming, music: " , Html.a [ Attr.href "http://jlubin.net" ] [ Html.text "<NAME>" ] , Html.br [] [] , Html.text "Programming language: " , Html.a [ Attr.href "https://elm-lang.org/" ] [ Html.text "Elm" ] , Html.br [] [] , Html.text "Level editor: " , Html.a [ Attr.href "https://www.mapeditor.org/" ] [ Html.text "Tiled" ] , Html.br [] [] , Html.text "Music software: " , Html.a [ Attr.href "https://musescore.org" ] [ Html.text "MuseScore" ] , Html.br [] [] , Html.text "Sound effect software: " , Html.a [ Attr.href "https://sfbgames.com/chiptone/" ] [ Html.text "ChipTone" ] ] ] view : Model -> Html Msg view model = Html.div [ Attr.id "arcade" ] [ title , score model , screen model , playButton model , credits ]
true
module View exposing ( view ) import Html exposing (Html) import Html.Attributes as Attr import Html.Events as Events import Model exposing (Model) import Controller exposing (Msg(..)) import ECS import Vector import Tilemap exposing (Zone(..)) import World import Params title : Html Msg title = Html.h1 [ Attr.id "main-title" ] [ Html.text "The Shards of Mt. Lampora" ] score : Model -> Html Msg score model = let shard class = Html.div [ Attr.class <| "shard " ++ class ] [] in Html.div [ Attr.id "score" ] <| ( List.map (\_ -> shard "obtained") (List.range 1 model.game.world.score) ) ++ ( List.map (\_ -> shard "remaining") (List.range (model.game.world.score + 1) model.game.world.winningScore) ) screen : Model -> Html Msg screen model = let showWhen : World.State -> Html.Attribute Msg showWhen state = if state == model.game.world.state then Attr.style "opacity" "1" else Attr.style "opacity" "0" in Html.div [ Attr.id "screen" , Attr.style "width" <| String.fromInt Params.screenWidth ++ "px" , Attr.style "height" <| String.fromInt Params.screenHeight ++ "px" ] [ Html.canvas [ Attr.id "game" ] [] , Html.div [ Attr.id "won-overlay" , Attr.class "overlay" , showWhen World.Won ] [ Html.text "You win!" ] ] playButton : Model -> Html Msg playButton model = let loaded = Model.loaded model in Html.div ( [ Attr.id "play-button" ] ++ ( if model.playing then [ Attr.class "hidden" ] else if loaded then [ Events.onClick PlayClicked ] else [ Attr.class "disabled" ] ) ) ( if loaded then [ Html.text "Play!" ] else [ Html.text "Loading..." ] ) credits : Html Msg credits = Html.div [ Attr.id "credits" ] [ Html.h2 [ Attr.id "credits-title" ] [ Html.text "Controls & Credits" ] , Html.div [ Attr.id "credits-content" ] [ Html.i [] [ Html.text "Left/right arrow keys + Z to jump!" ] , Html.br [] [] , Html.text "Design, programming, music: " , Html.a [ Attr.href "http://jlubin.net" ] [ Html.text "PI:NAME:<NAME>END_PI" ] , Html.br [] [] , Html.text "Programming language: " , Html.a [ Attr.href "https://elm-lang.org/" ] [ Html.text "Elm" ] , Html.br [] [] , Html.text "Level editor: " , Html.a [ Attr.href "https://www.mapeditor.org/" ] [ Html.text "Tiled" ] , Html.br [] [] , Html.text "Music software: " , Html.a [ Attr.href "https://musescore.org" ] [ Html.text "MuseScore" ] , Html.br [] [] , Html.text "Sound effect software: " , Html.a [ Attr.href "https://sfbgames.com/chiptone/" ] [ Html.text "ChipTone" ] ] ] view : Model -> Html Msg view model = Html.div [ Attr.id "arcade" ] [ title , score model , screen model , playButton model , credits ]
elm
[ { "context": " ListView.withItems\n [ { id = 0, name = \"Catarina\" }\n , { id = 1, name = \"Gabriel\" }\n ", "end": 9977, "score": 0.99964571, "start": 9969, "tag": "NAME", "value": "Catarina" }, { "context": ", name = \"Catarina\" }\n , { id = 1, name = \"Gabriel\" }\n ]\n someListView\n\n-}\nwithItems :", "end": 10016, "score": 0.9996991158, "start": 10009, "tag": "NAME", "value": "Gabriel" }, { "context": "ected }\n\n\n{-| Applies [`Element.width`](/packages/mdgriffith/elm-ui/latest/Element#width) to the component.\n\n ", "end": 11709, "score": 0.9814577103, "start": 11699, "tag": "USERNAME", "value": "mdgriffith" } ]
src/UI/ListView.elm
VladimirLogachev/paack-ui
0
module UI.ListView exposing ( ListView, selectList, simpleList , ToggleableConfig, ToggleableCover, toggleableList , withItems, withSelect, withSelected, withDomId , SearchConfig, withSearchField, withActionBar, withSelectAllButton , withFilter, withCustomExtraMenu, withHeader, withBadgedHeader , withWidth , SelectStyle, withSelectStyle , renderElement ) {-| `UI.ListView` is a styled searchable row list. The main variation (select-lists) has the capability of having one of its rows selected. The developer is responsible for coding the row's view. While this component then applies the borders and the click event. Also, it can optionally filter when having a search bar, and add an action bar. view : RenderConfig -> Model -> Element Msg view renderConfig model = ListView.selectList Msg.SelectElement elementToKey elementView |> ListView.withItems model.myListElements |> ListView.withSearchField { label = "Search for elements matching name.." , searchMsg = Msg.FilterSet , currentFilter = Maybe.map (\str -> ( str, elementHasString )) model.currentFilter } |> ListView.withActionBar { label = "Create new element" , icon = Icon.add , action = DialogMsg.OpenElementCreation |> Msg.ForDialog |> Action.DispatchMsg } |> ListView.withSelected (\{ id } -> Maybe.map (.id >> (==) id) model.selectedElement |> Maybe.withDefault False ) |> ListView.withWidth Element.fill |> ListView.renderElement renderConfig elementHasString : String -> Element -> Bool elementHasString str { name } = String.contains str name # Building @docs ListView, selectList, simpleList # Toggleable variation @docs ToggleableConfig, ToggleableCover, toggleableList # Options @docs withItems, withSelect, withSelected, withDomId ## Extra elements @docs SearchConfig, withSearchField, withActionBar, withSelectAllButton @docs withFilter, withCustomExtraMenu, withHeader, withBadgedHeader ## Width @docs withWidth ## Select Style @docs SelectStyle, withSelectStyle # Rendering @docs renderElement -} import Element exposing (Element, fill, shrink) import Element.Background as Background import Element.Border as Border import Element.Events as Events import Element.Font as Font import Element.Keyed as Keyed import UI.Badge as Badge exposing (Badge) import UI.Button as Button import UI.Checkbox as Checkbox import UI.Filter as Filter exposing (Filter) import UI.Icon as Icon import UI.Internal.Basics exposing (maybeAnd, prependMaybe) import UI.Internal.Clickable as Clickable import UI.Internal.Colors as Colors import UI.Internal.RenderConfig exposing (localeTerms) import UI.Internal.Size as Size import UI.Internal.ToggleableList as ToggleableList import UI.Internal.Utils.Element as Element import UI.Palette as Palette exposing (brightnessMiddle, tonePrimary) import UI.RenderConfig exposing (RenderConfig) import UI.Size as Size import UI.Text as Text import UI.TextField as TextField import UI.Utils.Action as Action import UI.Utils.Element exposing (zeroPadding) type alias Options object msg = { items : List object , searchField : Maybe (SearchConfig object msg) , actionBar : Maybe (Action.WithIcon msg) , select : Maybe (object -> msg) , isSelected : Maybe (object -> Bool) , width : Element.Length , selectStyle : SelectStyle , containerId : Maybe String , header : Maybe String , headerBadge : Maybe Badge , dropdown : Maybe (Dropdown msg) , selectAll : Maybe (SelectAll msg) , filter : Maybe (Filter msg) } type alias Properties object msg = { toKey : object -> String , renderItem : RenderConfig -> Bool -> object -> Element msg } {-| The `ListView object msg` type is used for describing the component for later rendering. -} type ListView object msg = SelectList (Properties object msg) (Options object msg) {-| `SearchConfig` assembles the required configuration for having a search field and filter. { title = "Elements" , label = "Search for elements matching name.." , searchMsg = Msg.FilterSet , currentFilter = Maybe.map (\str -> ( str, elementHasString )) model.currentFilter } -} type alias SearchConfig object msg = { label : String , searchMsg : String -> msg , currentFilter : Maybe ( String, String -> object -> Bool ) } {-| The selected item can be styled using [`ListView.withSelectStyle`](#withSelectStyle). - `backgroundColor`: The color in which the background assumes for selected items. When `Nothing` no color is applied. -} type alias SelectStyle = { backgroundColor : Maybe Palette.Color } -- Expose {-| Configuration required to render a toggleable-list. { detailsShowLabel = "Show details" -- For accessibility only , detailsCollapseLabel = "Hide details" -- For accessibility only , toCover = \{ name } -> -- ListView.ToggleableCover { title = name, caption = Nothing } , toDetails = \{ age } -> [ ( "Age", Element.text age ) ] , selectMsg = Msg.ElementSelect } -} type alias ToggleableConfig object msg = ToggleableList.Config object msg {-| What is displayed in a collapsed toggleable-list. { title = "Some item" , caption = Just "Created at 2020-06-10" } -} type alias ToggleableCover = ToggleableList.Cover type alias Dropdown msg = { toggleMsg : msg, isEnabled : Bool, body : DropdownBody msg } type DropdownBody msg = CustomDropdown (Element msg) -- Constructor {-| The main variation of `UI.ListView`. Click an element, and it will be selected. ListView.selectList Msg.SelectElement (\{ name } -> Element.el [ Element.padding 8 ] (Element.text name) ) -} selectList : (object -> msg) -> (object -> String) -> (Bool -> object -> Element msg) -> ListView object msg selectList selectMsg toKey renderItem = simpleList toKey renderItem |> withSelect selectMsg {-| A `UI.ListView` without built-in selection support. ListView.simpleList (\{ name } -> Element.el [ Element.padding 8 ] (Element.text name) ) -} simpleList : (object -> String) -> (Bool -> object -> Element msg) -> ListView object msg simpleList toKey renderItem = SelectList (Properties toKey (always renderItem)) defaultOptions {-| Toggleable-lists are a variation of select-lists where the selected element expands with details while all other's details keep collapsed. We recommend using `UI.Table` instead, as it uses toggleable-lists for its responsive mode. ListView.toggleableList { detailsShowLabel = "Show details" -- For accessibility only , detailsCollapseLabel = "Hide details" -- For accessibility only , toCover = \{ name } -> { title = name, caption = Nothing } , toDetails = \{ age } -> [ ( "Age", Element.text age ) ] , selectMsg = Msg.ElementSelect } |> ListView.withItems model.items |> ListView.withSelected isElementSelected |> ListView.renderElement renderConfig **NOTE**: Toggleable-list elements' view is not codable. -} toggleableList : ToggleableConfig object msg -> ListView object msg toggleableList config = let toggleableItemView parentCfg selected item = if selected then ToggleableList.selectedRow parentCfg config item else ToggleableList.defaultRow parentCfg config selected item in defaultOptions |> SelectList (Properties config.toKey toggleableItemView) |> withSelect config.selectMsg -- Options {-| Replaces the component's action-bar. An action-bar is an additional pre-styled stick row that, when clicked, triggers an action. ListView.withActionBar { label = "Create new element" , icon = Icon.add , onClick = Msg.UuidGen (Msg.ForDialog << DialogMsg.OpenElementCreation) } someListView -} withActionBar : Action.WithIcon msg -> ListView object msg -> ListView object msg withActionBar config (SelectList prop opt) = SelectList prop { opt | actionBar = Just config } {-| Adds button to toggle a custom menu element. ListView.withCustomExtraMenu toggleMsg isMenuVisible menuBody someListView -} withCustomExtraMenu : msg -> Bool -> Element msg -> ListView object msg -> ListView object msg withCustomExtraMenu toggleMsg isEnabled body (SelectList prop opt) = SelectList prop { opt | dropdown = Just <| Dropdown toggleMsg isEnabled (CustomDropdown body) } {-| Adds a button to select every entry. ListView.withSelectAllButton Msg.SelectAll isEverythingSelected someListView -} withSelectAllButton : (Bool -> msg) -> Bool -> ListView object msg -> ListView object msg withSelectAllButton message state (SelectList prop opt) = SelectList prop { opt | selectAll = Just <| SelectAll state message } {-| Adds a button to apply additional filters. ListView.withFilter additionalFilters someListView -} withFilter : Filter msg -> ListView object msg -> ListView object msg withFilter filter (SelectList prop opt) = SelectList prop { opt | filter = Just filter } {-| Replaces the component's list of elements. ListView.withItems [ { id = 0, name = "Catarina" } , { id = 1, name = "Gabriel" } ] someListView -} withItems : List object -> ListView object msg -> ListView object msg withItems items (SelectList prop opt) = SelectList prop { opt | items = items } {-| Replaces the component's search-field and allow filtering the elements. ListView.withSearchFied { detailsShowLabel = "Show details" -- For accessibility only , detailsCollapseLabel = "Hide details" -- For accessibility only , toCover = \{ name } -> -- ListView.ToggleableCover { title = name, caption = Nothing } , toDetails = \{ age } -> [ ( "Age", Element.text age ) ] , selectMsg = Msg.ElementSelect } someListView -} withSearchField : SearchConfig object msg -> ListView object msg -> ListView object msg withSearchField options (SelectList prop opt) = { opt | searchField = Just options } |> SelectList prop {-| Adds a message to be dispatched when an item is selected. ListView.withItems Msg.ElementSelect someListView -} withSelect : (object -> msg) -> ListView object msg -> ListView object msg withSelect options (SelectList prop opt) = { opt | select = Just options } |> SelectList prop {-| Marks every element as selected or not using a boolean-resulted lambda. ListView.withSelected (\{ id } -> id == model.selectedId) someListView -} withSelected : (object -> Bool) -> ListView object msg -> ListView object msg withSelected isSelected (SelectList prop opt) = SelectList prop { opt | isSelected = Just isSelected } {-| Applies [`Element.width`](/packages/mdgriffith/elm-ui/latest/Element#width) to the component. ListView.withWidth (Element.fill |> Element.minimum 220) someListView -} withWidth : Element.Length -> ListView object msg -> ListView object msg withWidth width (SelectList prop opt) = SelectList prop { opt | width = width } {-| Overwrite the appearance of the selected item. ListView.withSelectStyle { backgroundColor = Palette.color toneDanger brightnessMiddle } someListView -} withSelectStyle : SelectStyle -> ListView object msg -> ListView object msg withSelectStyle style (SelectList prop opt) = SelectList prop { opt | selectStyle = style } {-| Add id attribute to the HTML tags of the elements and the list itself. ListView.selectList Msg.SelectDrink softDrinkToString softDrinkView |> ListView.withDomId "softDrinks" Generates: < ... id="softDriks"> <... id="fanta">...</...> <... id="coke">...</...> <... id="drPepper">...</...> </...> **NOTE**: Only when `withDomId` is used children have `id`s. -} withDomId : String -> ListView object msg -> ListView object msg withDomId containerId (SelectList prop opt) = SelectList prop { opt | containerId = Just containerId } {-| Adds a header above the list. ListView.withHeader "ListView Header" someListView -} withHeader : String -> ListView object msg -> ListView object msg withHeader header (SelectList prop opt) = SelectList prop { opt | header = Just header } {-| Adds a header above the list, including a badge. ListView.withBadgedHeader "ListView Header" (Badge.primaryLight "NEW") someListView -} withBadgedHeader : String -> Badge -> ListView object msg -> ListView object msg withBadgedHeader header badge (SelectList prop opt) = SelectList prop { opt | header = Just header, headerBadge = Just badge } -- Render type alias SelectAll msg = { state : Bool , message : Bool -> msg } {-| End of the builder's life. The result of this function is a ready-to-insert Elm UI's Element. -} renderElement : RenderConfig -> ListView object msg -> Element msg renderElement cfg (SelectList prop opt) = let isSelected obj = case opt.isSelected of Just ask -> ask obj Nothing -> False in Element.column [ Element.width opt.width , Element.height fill , Element.scrollbarY ] [ searchFieldView cfg opt , toolbarView cfg opt , opt.items |> filterOptions opt.searchField |> List.map (\obj -> itemView cfg prop opt opt.selectStyle.backgroundColor (isSelected obj) obj ) |> Keyed.column ([ Border.widthEach { bottom = 0, left = 0, right = 0, top = 1 } , Border.color Colors.gray200 , Element.width fill , Element.height fill , Element.scrollbarY ] |> prependMaybe (Maybe.map Element.id opt.containerId) ) , actionBarView cfg opt.actionBar ] -- Internal actionBarView : RenderConfig -> Maybe (Action.WithIcon msg) -> Element msg actionBarView cfg actionBar = case actionBar of Just { label, icon, action } -> Element.row [ Element.width fill , Element.paddingEach { bottom = 12 , left = 20 , right = 12 , top = 12 } , Background.color Colors.navyBlue200 , Font.color Colors.navyBlue700 ] [ Text.body2 label |> Text.withColor (Palette.color tonePrimary brightnessMiddle) |> Text.renderElement cfg , icon label |> Icon.withSize Size.small |> Icon.renderElement cfg |> Element.el [ Element.alignRight ] ] |> Clickable.actionWrapElement cfg [ Element.width fill ] action Nothing -> Element.none searchFieldView : RenderConfig -> Options object msg -> Element msg searchFieldView cfg opt = case opt.searchField of Just { label, searchMsg, currentFilter } -> Element.column [ Element.width fill , Element.padding 12 ] [ headerView cfg opt , currentFilter |> Maybe.map Tuple.first |> Maybe.withDefault "" |> TextField.search searchMsg label |> TextField.withWidth TextField.widthFull |> TextField.withPlaceholder label |> TextField.withIcon (cfg |> localeTerms >> .listView >> .search |> Icon.search) |> TextField.renderElement cfg ] Nothing -> Element.none toolbarView : RenderConfig -> Options object msg -> Element msg toolbarView cfg opt = let entries = [] |> prependMaybe (Maybe.map (filterView cfg) opt.filter) |> prependMaybe (Maybe.map (selectAllButtonView cfg) opt.selectAll) in if List.isEmpty entries then Element.none else Element.row [ Element.width Element.fill , Element.paddingEach { bottom = 12 , left = 15 , right = 15 , top = 0 } ] entries selectAllButtonView : RenderConfig -> SelectAll msg -> Element msg selectAllButtonView cfg { state, message } = Checkbox.checkbox (cfg |> localeTerms >> .listView >> .selectAll) message state |> Checkbox.renderElement cfg |> Element.el [ Element.width fill, Element.alignTop ] filterView : RenderConfig -> Filter msg -> Element msg filterView cfg filter = filter |> Filter.withSize Filter.sizeExtraSmall |> Filter.withAlignRight |> Filter.renderElement cfg |> Element.el [ Element.width shrink, Element.alignRight, Element.alignTop ] headerView : RenderConfig -> Options object msg -> Element msg headerView cfg opt = case opt.header of Just header -> Element.row [ Element.width fill , Element.height fill , Element.paddingXY 0 12 , Element.spacing 8 ] [ Text.heading5 header |> Text.renderElement cfg , headerBadge cfg opt , dropdown cfg opt.dropdown ] Nothing -> Element.none dropdown : RenderConfig -> Maybe (Dropdown msg) -> Element msg dropdown cfg dropdownOptions = case dropdownOptions of Just opt -> let body = if opt.isEnabled then [ Element.below <| dropdownBody opt.body ] else [] in (cfg |> localeTerms >> .sidebar >> .moreActions) |> Icon.moreActions |> Icon.withColor Palette.primary |> Icon.withSize Size.Small |> Button.fromIcon |> Button.cmd opt.toggleMsg Button.clear |> Button.withSize Size.small |> Button.renderElement cfg |> Element.el (Element.alignRight :: Element.pointer :: Element.alignTop :: body ) Nothing -> Element.none headerBadge : RenderConfig -> Options object msg -> Element msg headerBadge cfg opt = case opt.headerBadge of Just badge -> badge |> Badge.renderElement cfg |> Element.el [ Element.centerY ] Nothing -> Element.none dropdownBody : DropdownBody msg -> Element msg dropdownBody body = case body of CustomDropdown html -> html itemView : RenderConfig -> Properties object msg -> Options object msg -> Maybe Palette.Color -> Bool -> object -> ( String, Element msg ) itemView cfg { renderItem, toKey } { select, containerId } background selected obj = let key = toKey obj attributes = [ Element.pointer , Element.width fill , Border.widthEach { zeroPadding | bottom = 1 } , Border.color Colors.gray200 ] |> prependMaybe (Maybe.map ((|>) obj >> Events.onClick) select) |> prependMaybe (background |> Maybe.map (Palette.toElementColor >> Background.color) |> maybeAnd selected ) |> prependMaybe (Maybe.map (always <| Element.id key) containerId) in ( key , Element.el attributes (renderItem cfg selected obj) ) defaultOptions : Options object msg defaultOptions = { items = [] , searchField = Nothing , actionBar = Nothing , select = Nothing , isSelected = Nothing , width = Element.fill , selectStyle = defaultSelectStyle , containerId = Nothing , header = Nothing , headerBadge = Nothing , dropdown = Nothing , selectAll = Nothing , filter = Nothing } defaultSelectStyle : SelectStyle defaultSelectStyle = { backgroundColor = Just (Palette.color tonePrimary brightnessMiddle) } -- Filter Internals filterOptions : Maybe (SearchConfig object msg) -> List object -> List object filterOptions searchOpt all = case Maybe.andThen .currentFilter searchOpt of Just ( value, filter ) -> List.filter (\obj -> filter value obj) all Nothing -> all
18839
module UI.ListView exposing ( ListView, selectList, simpleList , ToggleableConfig, ToggleableCover, toggleableList , withItems, withSelect, withSelected, withDomId , SearchConfig, withSearchField, withActionBar, withSelectAllButton , withFilter, withCustomExtraMenu, withHeader, withBadgedHeader , withWidth , SelectStyle, withSelectStyle , renderElement ) {-| `UI.ListView` is a styled searchable row list. The main variation (select-lists) has the capability of having one of its rows selected. The developer is responsible for coding the row's view. While this component then applies the borders and the click event. Also, it can optionally filter when having a search bar, and add an action bar. view : RenderConfig -> Model -> Element Msg view renderConfig model = ListView.selectList Msg.SelectElement elementToKey elementView |> ListView.withItems model.myListElements |> ListView.withSearchField { label = "Search for elements matching name.." , searchMsg = Msg.FilterSet , currentFilter = Maybe.map (\str -> ( str, elementHasString )) model.currentFilter } |> ListView.withActionBar { label = "Create new element" , icon = Icon.add , action = DialogMsg.OpenElementCreation |> Msg.ForDialog |> Action.DispatchMsg } |> ListView.withSelected (\{ id } -> Maybe.map (.id >> (==) id) model.selectedElement |> Maybe.withDefault False ) |> ListView.withWidth Element.fill |> ListView.renderElement renderConfig elementHasString : String -> Element -> Bool elementHasString str { name } = String.contains str name # Building @docs ListView, selectList, simpleList # Toggleable variation @docs ToggleableConfig, ToggleableCover, toggleableList # Options @docs withItems, withSelect, withSelected, withDomId ## Extra elements @docs SearchConfig, withSearchField, withActionBar, withSelectAllButton @docs withFilter, withCustomExtraMenu, withHeader, withBadgedHeader ## Width @docs withWidth ## Select Style @docs SelectStyle, withSelectStyle # Rendering @docs renderElement -} import Element exposing (Element, fill, shrink) import Element.Background as Background import Element.Border as Border import Element.Events as Events import Element.Font as Font import Element.Keyed as Keyed import UI.Badge as Badge exposing (Badge) import UI.Button as Button import UI.Checkbox as Checkbox import UI.Filter as Filter exposing (Filter) import UI.Icon as Icon import UI.Internal.Basics exposing (maybeAnd, prependMaybe) import UI.Internal.Clickable as Clickable import UI.Internal.Colors as Colors import UI.Internal.RenderConfig exposing (localeTerms) import UI.Internal.Size as Size import UI.Internal.ToggleableList as ToggleableList import UI.Internal.Utils.Element as Element import UI.Palette as Palette exposing (brightnessMiddle, tonePrimary) import UI.RenderConfig exposing (RenderConfig) import UI.Size as Size import UI.Text as Text import UI.TextField as TextField import UI.Utils.Action as Action import UI.Utils.Element exposing (zeroPadding) type alias Options object msg = { items : List object , searchField : Maybe (SearchConfig object msg) , actionBar : Maybe (Action.WithIcon msg) , select : Maybe (object -> msg) , isSelected : Maybe (object -> Bool) , width : Element.Length , selectStyle : SelectStyle , containerId : Maybe String , header : Maybe String , headerBadge : Maybe Badge , dropdown : Maybe (Dropdown msg) , selectAll : Maybe (SelectAll msg) , filter : Maybe (Filter msg) } type alias Properties object msg = { toKey : object -> String , renderItem : RenderConfig -> Bool -> object -> Element msg } {-| The `ListView object msg` type is used for describing the component for later rendering. -} type ListView object msg = SelectList (Properties object msg) (Options object msg) {-| `SearchConfig` assembles the required configuration for having a search field and filter. { title = "Elements" , label = "Search for elements matching name.." , searchMsg = Msg.FilterSet , currentFilter = Maybe.map (\str -> ( str, elementHasString )) model.currentFilter } -} type alias SearchConfig object msg = { label : String , searchMsg : String -> msg , currentFilter : Maybe ( String, String -> object -> Bool ) } {-| The selected item can be styled using [`ListView.withSelectStyle`](#withSelectStyle). - `backgroundColor`: The color in which the background assumes for selected items. When `Nothing` no color is applied. -} type alias SelectStyle = { backgroundColor : Maybe Palette.Color } -- Expose {-| Configuration required to render a toggleable-list. { detailsShowLabel = "Show details" -- For accessibility only , detailsCollapseLabel = "Hide details" -- For accessibility only , toCover = \{ name } -> -- ListView.ToggleableCover { title = name, caption = Nothing } , toDetails = \{ age } -> [ ( "Age", Element.text age ) ] , selectMsg = Msg.ElementSelect } -} type alias ToggleableConfig object msg = ToggleableList.Config object msg {-| What is displayed in a collapsed toggleable-list. { title = "Some item" , caption = Just "Created at 2020-06-10" } -} type alias ToggleableCover = ToggleableList.Cover type alias Dropdown msg = { toggleMsg : msg, isEnabled : Bool, body : DropdownBody msg } type DropdownBody msg = CustomDropdown (Element msg) -- Constructor {-| The main variation of `UI.ListView`. Click an element, and it will be selected. ListView.selectList Msg.SelectElement (\{ name } -> Element.el [ Element.padding 8 ] (Element.text name) ) -} selectList : (object -> msg) -> (object -> String) -> (Bool -> object -> Element msg) -> ListView object msg selectList selectMsg toKey renderItem = simpleList toKey renderItem |> withSelect selectMsg {-| A `UI.ListView` without built-in selection support. ListView.simpleList (\{ name } -> Element.el [ Element.padding 8 ] (Element.text name) ) -} simpleList : (object -> String) -> (Bool -> object -> Element msg) -> ListView object msg simpleList toKey renderItem = SelectList (Properties toKey (always renderItem)) defaultOptions {-| Toggleable-lists are a variation of select-lists where the selected element expands with details while all other's details keep collapsed. We recommend using `UI.Table` instead, as it uses toggleable-lists for its responsive mode. ListView.toggleableList { detailsShowLabel = "Show details" -- For accessibility only , detailsCollapseLabel = "Hide details" -- For accessibility only , toCover = \{ name } -> { title = name, caption = Nothing } , toDetails = \{ age } -> [ ( "Age", Element.text age ) ] , selectMsg = Msg.ElementSelect } |> ListView.withItems model.items |> ListView.withSelected isElementSelected |> ListView.renderElement renderConfig **NOTE**: Toggleable-list elements' view is not codable. -} toggleableList : ToggleableConfig object msg -> ListView object msg toggleableList config = let toggleableItemView parentCfg selected item = if selected then ToggleableList.selectedRow parentCfg config item else ToggleableList.defaultRow parentCfg config selected item in defaultOptions |> SelectList (Properties config.toKey toggleableItemView) |> withSelect config.selectMsg -- Options {-| Replaces the component's action-bar. An action-bar is an additional pre-styled stick row that, when clicked, triggers an action. ListView.withActionBar { label = "Create new element" , icon = Icon.add , onClick = Msg.UuidGen (Msg.ForDialog << DialogMsg.OpenElementCreation) } someListView -} withActionBar : Action.WithIcon msg -> ListView object msg -> ListView object msg withActionBar config (SelectList prop opt) = SelectList prop { opt | actionBar = Just config } {-| Adds button to toggle a custom menu element. ListView.withCustomExtraMenu toggleMsg isMenuVisible menuBody someListView -} withCustomExtraMenu : msg -> Bool -> Element msg -> ListView object msg -> ListView object msg withCustomExtraMenu toggleMsg isEnabled body (SelectList prop opt) = SelectList prop { opt | dropdown = Just <| Dropdown toggleMsg isEnabled (CustomDropdown body) } {-| Adds a button to select every entry. ListView.withSelectAllButton Msg.SelectAll isEverythingSelected someListView -} withSelectAllButton : (Bool -> msg) -> Bool -> ListView object msg -> ListView object msg withSelectAllButton message state (SelectList prop opt) = SelectList prop { opt | selectAll = Just <| SelectAll state message } {-| Adds a button to apply additional filters. ListView.withFilter additionalFilters someListView -} withFilter : Filter msg -> ListView object msg -> ListView object msg withFilter filter (SelectList prop opt) = SelectList prop { opt | filter = Just filter } {-| Replaces the component's list of elements. ListView.withItems [ { id = 0, name = "<NAME>" } , { id = 1, name = "<NAME>" } ] someListView -} withItems : List object -> ListView object msg -> ListView object msg withItems items (SelectList prop opt) = SelectList prop { opt | items = items } {-| Replaces the component's search-field and allow filtering the elements. ListView.withSearchFied { detailsShowLabel = "Show details" -- For accessibility only , detailsCollapseLabel = "Hide details" -- For accessibility only , toCover = \{ name } -> -- ListView.ToggleableCover { title = name, caption = Nothing } , toDetails = \{ age } -> [ ( "Age", Element.text age ) ] , selectMsg = Msg.ElementSelect } someListView -} withSearchField : SearchConfig object msg -> ListView object msg -> ListView object msg withSearchField options (SelectList prop opt) = { opt | searchField = Just options } |> SelectList prop {-| Adds a message to be dispatched when an item is selected. ListView.withItems Msg.ElementSelect someListView -} withSelect : (object -> msg) -> ListView object msg -> ListView object msg withSelect options (SelectList prop opt) = { opt | select = Just options } |> SelectList prop {-| Marks every element as selected or not using a boolean-resulted lambda. ListView.withSelected (\{ id } -> id == model.selectedId) someListView -} withSelected : (object -> Bool) -> ListView object msg -> ListView object msg withSelected isSelected (SelectList prop opt) = SelectList prop { opt | isSelected = Just isSelected } {-| Applies [`Element.width`](/packages/mdgriffith/elm-ui/latest/Element#width) to the component. ListView.withWidth (Element.fill |> Element.minimum 220) someListView -} withWidth : Element.Length -> ListView object msg -> ListView object msg withWidth width (SelectList prop opt) = SelectList prop { opt | width = width } {-| Overwrite the appearance of the selected item. ListView.withSelectStyle { backgroundColor = Palette.color toneDanger brightnessMiddle } someListView -} withSelectStyle : SelectStyle -> ListView object msg -> ListView object msg withSelectStyle style (SelectList prop opt) = SelectList prop { opt | selectStyle = style } {-| Add id attribute to the HTML tags of the elements and the list itself. ListView.selectList Msg.SelectDrink softDrinkToString softDrinkView |> ListView.withDomId "softDrinks" Generates: < ... id="softDriks"> <... id="fanta">...</...> <... id="coke">...</...> <... id="drPepper">...</...> </...> **NOTE**: Only when `withDomId` is used children have `id`s. -} withDomId : String -> ListView object msg -> ListView object msg withDomId containerId (SelectList prop opt) = SelectList prop { opt | containerId = Just containerId } {-| Adds a header above the list. ListView.withHeader "ListView Header" someListView -} withHeader : String -> ListView object msg -> ListView object msg withHeader header (SelectList prop opt) = SelectList prop { opt | header = Just header } {-| Adds a header above the list, including a badge. ListView.withBadgedHeader "ListView Header" (Badge.primaryLight "NEW") someListView -} withBadgedHeader : String -> Badge -> ListView object msg -> ListView object msg withBadgedHeader header badge (SelectList prop opt) = SelectList prop { opt | header = Just header, headerBadge = Just badge } -- Render type alias SelectAll msg = { state : Bool , message : Bool -> msg } {-| End of the builder's life. The result of this function is a ready-to-insert Elm UI's Element. -} renderElement : RenderConfig -> ListView object msg -> Element msg renderElement cfg (SelectList prop opt) = let isSelected obj = case opt.isSelected of Just ask -> ask obj Nothing -> False in Element.column [ Element.width opt.width , Element.height fill , Element.scrollbarY ] [ searchFieldView cfg opt , toolbarView cfg opt , opt.items |> filterOptions opt.searchField |> List.map (\obj -> itemView cfg prop opt opt.selectStyle.backgroundColor (isSelected obj) obj ) |> Keyed.column ([ Border.widthEach { bottom = 0, left = 0, right = 0, top = 1 } , Border.color Colors.gray200 , Element.width fill , Element.height fill , Element.scrollbarY ] |> prependMaybe (Maybe.map Element.id opt.containerId) ) , actionBarView cfg opt.actionBar ] -- Internal actionBarView : RenderConfig -> Maybe (Action.WithIcon msg) -> Element msg actionBarView cfg actionBar = case actionBar of Just { label, icon, action } -> Element.row [ Element.width fill , Element.paddingEach { bottom = 12 , left = 20 , right = 12 , top = 12 } , Background.color Colors.navyBlue200 , Font.color Colors.navyBlue700 ] [ Text.body2 label |> Text.withColor (Palette.color tonePrimary brightnessMiddle) |> Text.renderElement cfg , icon label |> Icon.withSize Size.small |> Icon.renderElement cfg |> Element.el [ Element.alignRight ] ] |> Clickable.actionWrapElement cfg [ Element.width fill ] action Nothing -> Element.none searchFieldView : RenderConfig -> Options object msg -> Element msg searchFieldView cfg opt = case opt.searchField of Just { label, searchMsg, currentFilter } -> Element.column [ Element.width fill , Element.padding 12 ] [ headerView cfg opt , currentFilter |> Maybe.map Tuple.first |> Maybe.withDefault "" |> TextField.search searchMsg label |> TextField.withWidth TextField.widthFull |> TextField.withPlaceholder label |> TextField.withIcon (cfg |> localeTerms >> .listView >> .search |> Icon.search) |> TextField.renderElement cfg ] Nothing -> Element.none toolbarView : RenderConfig -> Options object msg -> Element msg toolbarView cfg opt = let entries = [] |> prependMaybe (Maybe.map (filterView cfg) opt.filter) |> prependMaybe (Maybe.map (selectAllButtonView cfg) opt.selectAll) in if List.isEmpty entries then Element.none else Element.row [ Element.width Element.fill , Element.paddingEach { bottom = 12 , left = 15 , right = 15 , top = 0 } ] entries selectAllButtonView : RenderConfig -> SelectAll msg -> Element msg selectAllButtonView cfg { state, message } = Checkbox.checkbox (cfg |> localeTerms >> .listView >> .selectAll) message state |> Checkbox.renderElement cfg |> Element.el [ Element.width fill, Element.alignTop ] filterView : RenderConfig -> Filter msg -> Element msg filterView cfg filter = filter |> Filter.withSize Filter.sizeExtraSmall |> Filter.withAlignRight |> Filter.renderElement cfg |> Element.el [ Element.width shrink, Element.alignRight, Element.alignTop ] headerView : RenderConfig -> Options object msg -> Element msg headerView cfg opt = case opt.header of Just header -> Element.row [ Element.width fill , Element.height fill , Element.paddingXY 0 12 , Element.spacing 8 ] [ Text.heading5 header |> Text.renderElement cfg , headerBadge cfg opt , dropdown cfg opt.dropdown ] Nothing -> Element.none dropdown : RenderConfig -> Maybe (Dropdown msg) -> Element msg dropdown cfg dropdownOptions = case dropdownOptions of Just opt -> let body = if opt.isEnabled then [ Element.below <| dropdownBody opt.body ] else [] in (cfg |> localeTerms >> .sidebar >> .moreActions) |> Icon.moreActions |> Icon.withColor Palette.primary |> Icon.withSize Size.Small |> Button.fromIcon |> Button.cmd opt.toggleMsg Button.clear |> Button.withSize Size.small |> Button.renderElement cfg |> Element.el (Element.alignRight :: Element.pointer :: Element.alignTop :: body ) Nothing -> Element.none headerBadge : RenderConfig -> Options object msg -> Element msg headerBadge cfg opt = case opt.headerBadge of Just badge -> badge |> Badge.renderElement cfg |> Element.el [ Element.centerY ] Nothing -> Element.none dropdownBody : DropdownBody msg -> Element msg dropdownBody body = case body of CustomDropdown html -> html itemView : RenderConfig -> Properties object msg -> Options object msg -> Maybe Palette.Color -> Bool -> object -> ( String, Element msg ) itemView cfg { renderItem, toKey } { select, containerId } background selected obj = let key = toKey obj attributes = [ Element.pointer , Element.width fill , Border.widthEach { zeroPadding | bottom = 1 } , Border.color Colors.gray200 ] |> prependMaybe (Maybe.map ((|>) obj >> Events.onClick) select) |> prependMaybe (background |> Maybe.map (Palette.toElementColor >> Background.color) |> maybeAnd selected ) |> prependMaybe (Maybe.map (always <| Element.id key) containerId) in ( key , Element.el attributes (renderItem cfg selected obj) ) defaultOptions : Options object msg defaultOptions = { items = [] , searchField = Nothing , actionBar = Nothing , select = Nothing , isSelected = Nothing , width = Element.fill , selectStyle = defaultSelectStyle , containerId = Nothing , header = Nothing , headerBadge = Nothing , dropdown = Nothing , selectAll = Nothing , filter = Nothing } defaultSelectStyle : SelectStyle defaultSelectStyle = { backgroundColor = Just (Palette.color tonePrimary brightnessMiddle) } -- Filter Internals filterOptions : Maybe (SearchConfig object msg) -> List object -> List object filterOptions searchOpt all = case Maybe.andThen .currentFilter searchOpt of Just ( value, filter ) -> List.filter (\obj -> filter value obj) all Nothing -> all
true
module UI.ListView exposing ( ListView, selectList, simpleList , ToggleableConfig, ToggleableCover, toggleableList , withItems, withSelect, withSelected, withDomId , SearchConfig, withSearchField, withActionBar, withSelectAllButton , withFilter, withCustomExtraMenu, withHeader, withBadgedHeader , withWidth , SelectStyle, withSelectStyle , renderElement ) {-| `UI.ListView` is a styled searchable row list. The main variation (select-lists) has the capability of having one of its rows selected. The developer is responsible for coding the row's view. While this component then applies the borders and the click event. Also, it can optionally filter when having a search bar, and add an action bar. view : RenderConfig -> Model -> Element Msg view renderConfig model = ListView.selectList Msg.SelectElement elementToKey elementView |> ListView.withItems model.myListElements |> ListView.withSearchField { label = "Search for elements matching name.." , searchMsg = Msg.FilterSet , currentFilter = Maybe.map (\str -> ( str, elementHasString )) model.currentFilter } |> ListView.withActionBar { label = "Create new element" , icon = Icon.add , action = DialogMsg.OpenElementCreation |> Msg.ForDialog |> Action.DispatchMsg } |> ListView.withSelected (\{ id } -> Maybe.map (.id >> (==) id) model.selectedElement |> Maybe.withDefault False ) |> ListView.withWidth Element.fill |> ListView.renderElement renderConfig elementHasString : String -> Element -> Bool elementHasString str { name } = String.contains str name # Building @docs ListView, selectList, simpleList # Toggleable variation @docs ToggleableConfig, ToggleableCover, toggleableList # Options @docs withItems, withSelect, withSelected, withDomId ## Extra elements @docs SearchConfig, withSearchField, withActionBar, withSelectAllButton @docs withFilter, withCustomExtraMenu, withHeader, withBadgedHeader ## Width @docs withWidth ## Select Style @docs SelectStyle, withSelectStyle # Rendering @docs renderElement -} import Element exposing (Element, fill, shrink) import Element.Background as Background import Element.Border as Border import Element.Events as Events import Element.Font as Font import Element.Keyed as Keyed import UI.Badge as Badge exposing (Badge) import UI.Button as Button import UI.Checkbox as Checkbox import UI.Filter as Filter exposing (Filter) import UI.Icon as Icon import UI.Internal.Basics exposing (maybeAnd, prependMaybe) import UI.Internal.Clickable as Clickable import UI.Internal.Colors as Colors import UI.Internal.RenderConfig exposing (localeTerms) import UI.Internal.Size as Size import UI.Internal.ToggleableList as ToggleableList import UI.Internal.Utils.Element as Element import UI.Palette as Palette exposing (brightnessMiddle, tonePrimary) import UI.RenderConfig exposing (RenderConfig) import UI.Size as Size import UI.Text as Text import UI.TextField as TextField import UI.Utils.Action as Action import UI.Utils.Element exposing (zeroPadding) type alias Options object msg = { items : List object , searchField : Maybe (SearchConfig object msg) , actionBar : Maybe (Action.WithIcon msg) , select : Maybe (object -> msg) , isSelected : Maybe (object -> Bool) , width : Element.Length , selectStyle : SelectStyle , containerId : Maybe String , header : Maybe String , headerBadge : Maybe Badge , dropdown : Maybe (Dropdown msg) , selectAll : Maybe (SelectAll msg) , filter : Maybe (Filter msg) } type alias Properties object msg = { toKey : object -> String , renderItem : RenderConfig -> Bool -> object -> Element msg } {-| The `ListView object msg` type is used for describing the component for later rendering. -} type ListView object msg = SelectList (Properties object msg) (Options object msg) {-| `SearchConfig` assembles the required configuration for having a search field and filter. { title = "Elements" , label = "Search for elements matching name.." , searchMsg = Msg.FilterSet , currentFilter = Maybe.map (\str -> ( str, elementHasString )) model.currentFilter } -} type alias SearchConfig object msg = { label : String , searchMsg : String -> msg , currentFilter : Maybe ( String, String -> object -> Bool ) } {-| The selected item can be styled using [`ListView.withSelectStyle`](#withSelectStyle). - `backgroundColor`: The color in which the background assumes for selected items. When `Nothing` no color is applied. -} type alias SelectStyle = { backgroundColor : Maybe Palette.Color } -- Expose {-| Configuration required to render a toggleable-list. { detailsShowLabel = "Show details" -- For accessibility only , detailsCollapseLabel = "Hide details" -- For accessibility only , toCover = \{ name } -> -- ListView.ToggleableCover { title = name, caption = Nothing } , toDetails = \{ age } -> [ ( "Age", Element.text age ) ] , selectMsg = Msg.ElementSelect } -} type alias ToggleableConfig object msg = ToggleableList.Config object msg {-| What is displayed in a collapsed toggleable-list. { title = "Some item" , caption = Just "Created at 2020-06-10" } -} type alias ToggleableCover = ToggleableList.Cover type alias Dropdown msg = { toggleMsg : msg, isEnabled : Bool, body : DropdownBody msg } type DropdownBody msg = CustomDropdown (Element msg) -- Constructor {-| The main variation of `UI.ListView`. Click an element, and it will be selected. ListView.selectList Msg.SelectElement (\{ name } -> Element.el [ Element.padding 8 ] (Element.text name) ) -} selectList : (object -> msg) -> (object -> String) -> (Bool -> object -> Element msg) -> ListView object msg selectList selectMsg toKey renderItem = simpleList toKey renderItem |> withSelect selectMsg {-| A `UI.ListView` without built-in selection support. ListView.simpleList (\{ name } -> Element.el [ Element.padding 8 ] (Element.text name) ) -} simpleList : (object -> String) -> (Bool -> object -> Element msg) -> ListView object msg simpleList toKey renderItem = SelectList (Properties toKey (always renderItem)) defaultOptions {-| Toggleable-lists are a variation of select-lists where the selected element expands with details while all other's details keep collapsed. We recommend using `UI.Table` instead, as it uses toggleable-lists for its responsive mode. ListView.toggleableList { detailsShowLabel = "Show details" -- For accessibility only , detailsCollapseLabel = "Hide details" -- For accessibility only , toCover = \{ name } -> { title = name, caption = Nothing } , toDetails = \{ age } -> [ ( "Age", Element.text age ) ] , selectMsg = Msg.ElementSelect } |> ListView.withItems model.items |> ListView.withSelected isElementSelected |> ListView.renderElement renderConfig **NOTE**: Toggleable-list elements' view is not codable. -} toggleableList : ToggleableConfig object msg -> ListView object msg toggleableList config = let toggleableItemView parentCfg selected item = if selected then ToggleableList.selectedRow parentCfg config item else ToggleableList.defaultRow parentCfg config selected item in defaultOptions |> SelectList (Properties config.toKey toggleableItemView) |> withSelect config.selectMsg -- Options {-| Replaces the component's action-bar. An action-bar is an additional pre-styled stick row that, when clicked, triggers an action. ListView.withActionBar { label = "Create new element" , icon = Icon.add , onClick = Msg.UuidGen (Msg.ForDialog << DialogMsg.OpenElementCreation) } someListView -} withActionBar : Action.WithIcon msg -> ListView object msg -> ListView object msg withActionBar config (SelectList prop opt) = SelectList prop { opt | actionBar = Just config } {-| Adds button to toggle a custom menu element. ListView.withCustomExtraMenu toggleMsg isMenuVisible menuBody someListView -} withCustomExtraMenu : msg -> Bool -> Element msg -> ListView object msg -> ListView object msg withCustomExtraMenu toggleMsg isEnabled body (SelectList prop opt) = SelectList prop { opt | dropdown = Just <| Dropdown toggleMsg isEnabled (CustomDropdown body) } {-| Adds a button to select every entry. ListView.withSelectAllButton Msg.SelectAll isEverythingSelected someListView -} withSelectAllButton : (Bool -> msg) -> Bool -> ListView object msg -> ListView object msg withSelectAllButton message state (SelectList prop opt) = SelectList prop { opt | selectAll = Just <| SelectAll state message } {-| Adds a button to apply additional filters. ListView.withFilter additionalFilters someListView -} withFilter : Filter msg -> ListView object msg -> ListView object msg withFilter filter (SelectList prop opt) = SelectList prop { opt | filter = Just filter } {-| Replaces the component's list of elements. ListView.withItems [ { id = 0, name = "PI:NAME:<NAME>END_PI" } , { id = 1, name = "PI:NAME:<NAME>END_PI" } ] someListView -} withItems : List object -> ListView object msg -> ListView object msg withItems items (SelectList prop opt) = SelectList prop { opt | items = items } {-| Replaces the component's search-field and allow filtering the elements. ListView.withSearchFied { detailsShowLabel = "Show details" -- For accessibility only , detailsCollapseLabel = "Hide details" -- For accessibility only , toCover = \{ name } -> -- ListView.ToggleableCover { title = name, caption = Nothing } , toDetails = \{ age } -> [ ( "Age", Element.text age ) ] , selectMsg = Msg.ElementSelect } someListView -} withSearchField : SearchConfig object msg -> ListView object msg -> ListView object msg withSearchField options (SelectList prop opt) = { opt | searchField = Just options } |> SelectList prop {-| Adds a message to be dispatched when an item is selected. ListView.withItems Msg.ElementSelect someListView -} withSelect : (object -> msg) -> ListView object msg -> ListView object msg withSelect options (SelectList prop opt) = { opt | select = Just options } |> SelectList prop {-| Marks every element as selected or not using a boolean-resulted lambda. ListView.withSelected (\{ id } -> id == model.selectedId) someListView -} withSelected : (object -> Bool) -> ListView object msg -> ListView object msg withSelected isSelected (SelectList prop opt) = SelectList prop { opt | isSelected = Just isSelected } {-| Applies [`Element.width`](/packages/mdgriffith/elm-ui/latest/Element#width) to the component. ListView.withWidth (Element.fill |> Element.minimum 220) someListView -} withWidth : Element.Length -> ListView object msg -> ListView object msg withWidth width (SelectList prop opt) = SelectList prop { opt | width = width } {-| Overwrite the appearance of the selected item. ListView.withSelectStyle { backgroundColor = Palette.color toneDanger brightnessMiddle } someListView -} withSelectStyle : SelectStyle -> ListView object msg -> ListView object msg withSelectStyle style (SelectList prop opt) = SelectList prop { opt | selectStyle = style } {-| Add id attribute to the HTML tags of the elements and the list itself. ListView.selectList Msg.SelectDrink softDrinkToString softDrinkView |> ListView.withDomId "softDrinks" Generates: < ... id="softDriks"> <... id="fanta">...</...> <... id="coke">...</...> <... id="drPepper">...</...> </...> **NOTE**: Only when `withDomId` is used children have `id`s. -} withDomId : String -> ListView object msg -> ListView object msg withDomId containerId (SelectList prop opt) = SelectList prop { opt | containerId = Just containerId } {-| Adds a header above the list. ListView.withHeader "ListView Header" someListView -} withHeader : String -> ListView object msg -> ListView object msg withHeader header (SelectList prop opt) = SelectList prop { opt | header = Just header } {-| Adds a header above the list, including a badge. ListView.withBadgedHeader "ListView Header" (Badge.primaryLight "NEW") someListView -} withBadgedHeader : String -> Badge -> ListView object msg -> ListView object msg withBadgedHeader header badge (SelectList prop opt) = SelectList prop { opt | header = Just header, headerBadge = Just badge } -- Render type alias SelectAll msg = { state : Bool , message : Bool -> msg } {-| End of the builder's life. The result of this function is a ready-to-insert Elm UI's Element. -} renderElement : RenderConfig -> ListView object msg -> Element msg renderElement cfg (SelectList prop opt) = let isSelected obj = case opt.isSelected of Just ask -> ask obj Nothing -> False in Element.column [ Element.width opt.width , Element.height fill , Element.scrollbarY ] [ searchFieldView cfg opt , toolbarView cfg opt , opt.items |> filterOptions opt.searchField |> List.map (\obj -> itemView cfg prop opt opt.selectStyle.backgroundColor (isSelected obj) obj ) |> Keyed.column ([ Border.widthEach { bottom = 0, left = 0, right = 0, top = 1 } , Border.color Colors.gray200 , Element.width fill , Element.height fill , Element.scrollbarY ] |> prependMaybe (Maybe.map Element.id opt.containerId) ) , actionBarView cfg opt.actionBar ] -- Internal actionBarView : RenderConfig -> Maybe (Action.WithIcon msg) -> Element msg actionBarView cfg actionBar = case actionBar of Just { label, icon, action } -> Element.row [ Element.width fill , Element.paddingEach { bottom = 12 , left = 20 , right = 12 , top = 12 } , Background.color Colors.navyBlue200 , Font.color Colors.navyBlue700 ] [ Text.body2 label |> Text.withColor (Palette.color tonePrimary brightnessMiddle) |> Text.renderElement cfg , icon label |> Icon.withSize Size.small |> Icon.renderElement cfg |> Element.el [ Element.alignRight ] ] |> Clickable.actionWrapElement cfg [ Element.width fill ] action Nothing -> Element.none searchFieldView : RenderConfig -> Options object msg -> Element msg searchFieldView cfg opt = case opt.searchField of Just { label, searchMsg, currentFilter } -> Element.column [ Element.width fill , Element.padding 12 ] [ headerView cfg opt , currentFilter |> Maybe.map Tuple.first |> Maybe.withDefault "" |> TextField.search searchMsg label |> TextField.withWidth TextField.widthFull |> TextField.withPlaceholder label |> TextField.withIcon (cfg |> localeTerms >> .listView >> .search |> Icon.search) |> TextField.renderElement cfg ] Nothing -> Element.none toolbarView : RenderConfig -> Options object msg -> Element msg toolbarView cfg opt = let entries = [] |> prependMaybe (Maybe.map (filterView cfg) opt.filter) |> prependMaybe (Maybe.map (selectAllButtonView cfg) opt.selectAll) in if List.isEmpty entries then Element.none else Element.row [ Element.width Element.fill , Element.paddingEach { bottom = 12 , left = 15 , right = 15 , top = 0 } ] entries selectAllButtonView : RenderConfig -> SelectAll msg -> Element msg selectAllButtonView cfg { state, message } = Checkbox.checkbox (cfg |> localeTerms >> .listView >> .selectAll) message state |> Checkbox.renderElement cfg |> Element.el [ Element.width fill, Element.alignTop ] filterView : RenderConfig -> Filter msg -> Element msg filterView cfg filter = filter |> Filter.withSize Filter.sizeExtraSmall |> Filter.withAlignRight |> Filter.renderElement cfg |> Element.el [ Element.width shrink, Element.alignRight, Element.alignTop ] headerView : RenderConfig -> Options object msg -> Element msg headerView cfg opt = case opt.header of Just header -> Element.row [ Element.width fill , Element.height fill , Element.paddingXY 0 12 , Element.spacing 8 ] [ Text.heading5 header |> Text.renderElement cfg , headerBadge cfg opt , dropdown cfg opt.dropdown ] Nothing -> Element.none dropdown : RenderConfig -> Maybe (Dropdown msg) -> Element msg dropdown cfg dropdownOptions = case dropdownOptions of Just opt -> let body = if opt.isEnabled then [ Element.below <| dropdownBody opt.body ] else [] in (cfg |> localeTerms >> .sidebar >> .moreActions) |> Icon.moreActions |> Icon.withColor Palette.primary |> Icon.withSize Size.Small |> Button.fromIcon |> Button.cmd opt.toggleMsg Button.clear |> Button.withSize Size.small |> Button.renderElement cfg |> Element.el (Element.alignRight :: Element.pointer :: Element.alignTop :: body ) Nothing -> Element.none headerBadge : RenderConfig -> Options object msg -> Element msg headerBadge cfg opt = case opt.headerBadge of Just badge -> badge |> Badge.renderElement cfg |> Element.el [ Element.centerY ] Nothing -> Element.none dropdownBody : DropdownBody msg -> Element msg dropdownBody body = case body of CustomDropdown html -> html itemView : RenderConfig -> Properties object msg -> Options object msg -> Maybe Palette.Color -> Bool -> object -> ( String, Element msg ) itemView cfg { renderItem, toKey } { select, containerId } background selected obj = let key = toKey obj attributes = [ Element.pointer , Element.width fill , Border.widthEach { zeroPadding | bottom = 1 } , Border.color Colors.gray200 ] |> prependMaybe (Maybe.map ((|>) obj >> Events.onClick) select) |> prependMaybe (background |> Maybe.map (Palette.toElementColor >> Background.color) |> maybeAnd selected ) |> prependMaybe (Maybe.map (always <| Element.id key) containerId) in ( key , Element.el attributes (renderItem cfg selected obj) ) defaultOptions : Options object msg defaultOptions = { items = [] , searchField = Nothing , actionBar = Nothing , select = Nothing , isSelected = Nothing , width = Element.fill , selectStyle = defaultSelectStyle , containerId = Nothing , header = Nothing , headerBadge = Nothing , dropdown = Nothing , selectAll = Nothing , filter = Nothing } defaultSelectStyle : SelectStyle defaultSelectStyle = { backgroundColor = Just (Palette.color tonePrimary brightnessMiddle) } -- Filter Internals filterOptions : Maybe (SearchConfig object msg) -> List object -> List object filterOptions searchOpt all = case Maybe.andThen .currentFilter searchOpt of Just ( value, filter ) -> List.filter (\obj -> filter value obj) all Nothing -> all
elm
[ { "context": "erStyle ] ]\n [ text\n (\"© Chris Wells Wood, 2018. Version 1.1.0. \"\n ++ \"E", "end": 21783, "score": 0.9998961687, "start": 21767, "tag": "NAME", "value": "Chris Wells Wood" }, { "context": " )\n , a [ href \"https://github.com/ChrisWellsWood/martial-destiny\" ]\n [ text \"Source", "end": 21951, "score": 0.983787477, "start": 21937, "tag": "USERNAME", "value": "ChrisWellsWood" }, { "context": ".com/authors/dave-gandy\"\n , title \"Dave Gandy\"\n ]\n [ text \"Dave G", "end": 22386, "score": 0.9994804859, "start": 22376, "tag": "NAME", "value": "Dave Gandy" }, { "context": " Gandy\"\n ]\n [ text \"Dave Gandy\" ]\n , text \", \"\n , a\n ", "end": 22440, "score": 0.9993814826, "start": 22430, "tag": "NAME", "value": "Dave Gandy" }, { "context": "om/authors/eleonor-wang\"\n , title \"Eleonor Wang\"\n ]\n [ text \"Eleono", "end": 22592, "score": 0.9912111163, "start": 22580, "tag": "NAME", "value": "Eleonor Wang" }, { "context": "r Wang\"\n ]\n [ text \"Eleonor Wang\" ]\n , text \", \"\n , a\n ", "end": 22648, "score": 0.939586699, "start": 22636, "tag": "NAME", "value": "Eleonor Wang" }, { "context": " [ href\n \"https://github.com/ChrisWellsWood/martial-destiny/issues\"\n ]\n ", "end": 42866, "score": 0.8724951744, "start": 42852, "tag": "USERNAME", "value": "ChrisWellsWood" } ]
Main.elm
ChrisWellsWood/martial-destiny
1
port module Main exposing (..) import Css exposing (..) import Dict import Dom import Html import Html.Styled exposing (..) import Html.Styled.Attributes exposing (..) import Html.Styled.Events exposing (..) import Task main : Program (Maybe ExportedModel) Model Msg main = Html.programWithFlags { init = init , view = view >> toUnstyled , update = update , subscriptions = subscriptions } init : Maybe ExportedModel -> ( Model, Cmd Msg ) init savedSession = case savedSession of Just exportedModel -> (importModel exportedModel) ! [] Nothing -> emptyModel ! [] type alias Model = { combatants : Combatants , round : Int , popUp : PopUp } emptyModel : Model emptyModel = Model Dict.empty 1 Closed type alias ExportedModel = { combatants : List ( String, Combatant ) , round : Int } exportModel : Model -> ExportedModel exportModel model = ExportedModel (Dict.toList model.combatants) model.round importModel : ExportedModel -> Model importModel exportedModel = Model (Dict.fromList exportedModel.combatants) exportedModel.round Closed type alias Combatant = { name : String , initiative : Int , crash : Maybe Crash , onslaught : Int , turnFinished : Bool } type alias Crash = { crasher : String , turnsUntilReset : Int } type alias Combatants = Dict.Dict String Combatant type PopUp = NewCombatant String String | EditInitiative Combatant String | WitheringAttack Combatant (Maybe Combatant) (Maybe String) (Maybe Shift) | DecisiveAttack Combatant | EditOnslaught Combatant String | Confirm String Msg | Help | Closed type Shift = Shifted String | NoShift type AttackOutcome = Hit | Miss -- Update type Msg = OpenPopUp PopUp | FocusResult (Result Dom.Error ()) | ClosePopUp | SetCombatantName String | SetJoinCombat String | AddNewCombatant | Save | NewCombat | StartNewRound | ModifyInitiative Int | SetInitiative String | ApplyNewInitiative | SetWitheringTarget Combatant | SetWitheringDamage String | ResolveWitheringDamage | SetShiftJoinCombat String | ResolveInitiativeShift | ResolveDecisive AttackOutcome | ModifyOnslaught Int | SetOnslaught String | ApplyNewOnslaught | EndTurn Combatant | ResolveDelete Combatant update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of OpenPopUp popUp -> { model | popUp = popUp } ! [ Dom.focus "pop-up-focus" |> Task.attempt FocusResult ] FocusResult result -> case result of Err (Dom.NotFound id) -> let error = "ID \"" ++ id ++ "\"not found." in model ! [] Ok () -> model ! [] ClosePopUp -> { model | popUp = Closed } ! [] SetCombatantName name -> case model.popUp of NewCombatant _ joinCombat -> { model | popUp = NewCombatant name joinCombat } ! [] _ -> { model | popUp = Closed } ! [] SetJoinCombat joinCombat -> case model.popUp of NewCombatant name _ -> { model | popUp = NewCombatant name joinCombat } ! [] _ -> { model | popUp = Closed } ! [] AddNewCombatant -> case model.popUp of NewCombatant name joinCombatStr -> let joinCombat = String.toInt joinCombatStr |> Result.withDefault 0 |> (+) 3 newCombatant = Combatant name joinCombat Nothing 0 False updatedCombatants = Dict.insert name newCombatant model.combatants in update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] Save -> model ! [ exportModel model |> saveState ] NewCombat -> update Save emptyModel StartNewRound -> let updatedCombatants = Dict.values model.combatants |> List.map decrementCrash |> List.map (\c -> { c | turnFinished = False }) |> List.map (\c -> ( c.name, c )) |> Dict.fromList in update Save { model | combatants = updatedCombatants , round = model.round + 1 , popUp = Closed } ModifyInitiative modifyBy -> case model.popUp of EditInitiative combatant initiativeString -> { model | popUp = EditInitiative combatant (String.toInt initiativeString |> Result.withDefault 0 |> (+) modifyBy |> toString ) } ! [] _ -> { model | popUp = Closed } ! [] SetInitiative initiativeString -> case model.popUp of EditInitiative combatant _ -> { model | popUp = EditInitiative combatant initiativeString } ! [] _ -> { model | popUp = Closed } ! [] ApplyNewInitiative -> case model.popUp of EditInitiative combatant newInitiativeStr -> case String.toInt newInitiativeStr of Ok newInitiative -> update Save { model | popUp = Closed , combatants = Dict.insert combatant.name { combatant | initiative = newInitiative } model.combatants } Err _ -> { model | popUp = Closed } ! [] _ -> { model | popUp = Closed } ! [] SetWitheringTarget defender -> case model.popUp of WitheringAttack attacker _ _ _ -> { model | popUp = WitheringAttack attacker (Just defender) (Just "0") Nothing } ! [] _ -> { model | popUp = Closed } ! [] SetWitheringDamage damage -> case model.popUp of WitheringAttack attacker (Just defender) (Just _) _ -> { model | popUp = WitheringAttack attacker (Just defender) (Just damage) Nothing } ! [] _ -> { model | popUp = Closed } ! [] ResolveWitheringDamage -> case model.popUp of WitheringAttack attacker (Just defender) (Just damage) Nothing -> let ( uAttacker, uDefender, shift ) = resolveWithering attacker defender damage updatedCombatants = Dict.insert attacker.name uAttacker model.combatants |> Dict.insert defender.name uDefender in case shift of Shifted _ -> { model | popUp = WitheringAttack uAttacker (Just uDefender) (Just damage) (Just shift) } ! [] NoShift -> update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] SetShiftJoinCombat shiftJoinCombat -> case model.popUp of WitheringAttack a (Just d) (Just dam) (Just (Shifted _)) -> { model | popUp = WitheringAttack a (Just d) (Just dam) (Just (Shifted shiftJoinCombat)) } ! [] _ -> { model | popUp = Closed } ! [] ResolveInitiativeShift -> case model.popUp of WitheringAttack att (Just def) (Just dam) (Just (Shifted jc)) -> let joinCombat = String.toInt jc |> Result.withDefault 0 shiftInitiative = 3 + joinCombat attacker = { att | initiative = if shiftInitiative > att.initiative then shiftInitiative else att.initiative } updatedCombatants = Dict.insert attacker.name attacker model.combatants |> Dict.insert def.name def in update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] ResolveDecisive decisiveOutcome -> case model.popUp of DecisiveAttack combatant -> let attacker = resolveDecisive decisiveOutcome combatant updatedCombatants = Dict.insert attacker.name attacker model.combatants in update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] ModifyOnslaught modifyBy -> case model.popUp of EditOnslaught combatant onslaughtString -> { model | popUp = EditOnslaught combatant (String.toInt onslaughtString |> Result.withDefault 0 |> (+) modifyBy |> toString ) } ! [] _ -> { model | popUp = Closed } ! [] SetOnslaught onslaughtString -> case model.popUp of EditOnslaught combatant _ -> { model | popUp = EditOnslaught combatant onslaughtString } ! [] _ -> { model | popUp = Closed } ! [] ApplyNewOnslaught -> case model.popUp of EditOnslaught combatant newOnslaughtStr -> case String.toInt newOnslaughtStr of Ok newOnslaught -> update Save { model | popUp = Closed , combatants = Dict.insert combatant.name { combatant | onslaught = newOnslaught } model.combatants } Err _ -> { model | popUp = Closed } ! [] _ -> { model | popUp = Closed } ! [] EndTurn combatant -> let updatedCombatant = { combatant | turnFinished = True } updatedCombatants = Dict.insert updatedCombatant.name updatedCombatant model.combatants in update Save { model | combatants = updatedCombatants , popUp = Closed } ResolveDelete combatant -> let updatedCombatants = Dict.remove combatant.name model.combatants in update Save { model | combatants = updatedCombatants , popUp = Closed } sortByInitiative : Combatants -> Combatants sortByInitiative combatants = Dict.toList combatants |> List.sortBy (\( n, c ) -> c.initiative) |> List.reverse |> Dict.fromList decrementCrash : Combatant -> Combatant decrementCrash combatant = case combatant.crash of Just crash -> let updatedCrash = { crash | turnsUntilReset = crash.turnsUntilReset - 1 } in if updatedCrash.turnsUntilReset < 1 then { combatant | crash = Nothing , initiative = 3 } else { combatant | crash = Just updatedCrash } Nothing -> combatant resolveWithering : Combatant -> Combatant -> String -> ( Combatant, Combatant, Shift ) resolveWithering attacker defender damageStr = let damage = String.toInt damageStr |> Result.withDefault 0 defInitiative = defender.initiative - damage hasCrashed = if (defender.initiative > 0) && (defInitiative <= 0) then True else False updatedDefender = { defender | initiative = defInitiative , crash = if hasCrashed then Just (Crash attacker.name 3) else Nothing , onslaught = defender.onslaught + 1 } attInitiative = attacker.initiative + damage + 1 + (if hasCrashed then 5 else 0 ) shift = case attacker.crash of Just crash -> if hasCrashed && (crash.crasher == defender.name) then Shifted "0" else NoShift Nothing -> NoShift updatedAttacker = { attacker | initiative = attInitiative , onslaught = 0 , crash = if attInitiative > 0 then Nothing else attacker.crash , turnFinished = True } in ( updatedAttacker, updatedDefender, shift ) resolveDecisive : AttackOutcome -> Combatant -> Combatant resolveDecisive outcome combatant = case outcome of Hit -> { combatant | initiative = 3 } Miss -> { combatant | initiative = if combatant.initiative < 11 then combatant.initiative - 2 else combatant.initiative - 3 , onslaught = 0 , turnFinished = True } -- Ports port saveState : ExportedModel -> Cmd msg -- Subscriptions subscriptions : Model -> Sub msg subscriptions model = Sub.none -- Views view : Model -> Html Msg view model = div [ css [ defaultStyle ] ] [ header [ css [ headerStyle, rowFlexStyle ] ] [ div [] [ h1 [ css [ h1Style ] ] [ text "Threads of Martial Destiny" ] , b [] [ text "A combat tracker for Exalted 3rd Edition" ] ] , div [] [ img [ css [ iconStyle True ] , src "imgs/add.svg" , NewCombatant "" "0" |> OpenPopUp |> onClick , title "Add Combatant" ] [ text "Add Combatant" ] , img [ css [ iconStyle True ] , src "imgs/help.svg" , onClick <| OpenPopUp <| Help , title "Help" ] [ text "Help" ] , img [ css [ iconStyle True ] , src "imgs/new-combat.svg" , onClick <| OpenPopUp <| Confirm "New Combat" <| NewCombat , title "New Combat" ] [ text "New Combat" ] ] ] , div [ css [ bodyStyle ] ] ([ tracker model.round model.combatants ] ++ (case model.popUp of (NewCombatant _ _) as newCombatant -> [ newCombatantPopUp newCombatant ] (EditInitiative _ _) as editInitiative -> [ editInitiativePopUp editInitiative ] (WitheringAttack _ _ _ _) as witheringAttack -> [ witheringPopUp model.combatants witheringAttack ] (DecisiveAttack _) as decisiveAttack -> [ decisivePopUp decisiveAttack ] (EditOnslaught _ _) as editOnslaught -> [ editOnslaughtPopUp editOnslaught ] (Confirm _ _) as confirm -> [ confirmPopUp confirm ] Help -> [ helpPopUp ] Closed -> [] ) ) , footer [ css [ footerStyle ] ] [ text ("© Chris Wells Wood, 2018. Version 1.1.0. " ++ "Exalted is © White Wolf AB and Onyx Path. " ) , a [ href "https://github.com/ChrisWellsWood/martial-destiny" ] [ text "Source code." ] , br [] [] , text "Icons made by " , a [ href "https://www.flaticon.com/authors/appzgear" , title "Appzgear" ] [ text "Appzgear" ] , text ", " , a [ href "https://www.flaticon.com/authors/dave-gandy" , title "Dave Gandy" ] [ text "Dave Gandy" ] , text ", " , a [ href "https://www.flaticon.com/authors/eleonor-wang" , title "Eleonor Wang" ] [ text "Eleonor Wang" ] , text ", " , a [ href "http://www.freepik.com" , title "Freepik" ] [ text "Freepik" ] , text " and " , a [ href "https://www.flaticon.com/authors/pixel-perfect" , title "Pixel perfect" ] [ text "Pixel perfect" ] , text " from " , a [ href "https://www.flaticon.com/" , title "Flaticon" ] [ text "www.flaticon.com" ] , text " and are licensed by " , a [ href "http://creativecommons.org/licenses/by/3.0/" , title "Creative Commons BY 3.0" , Html.Styled.Attributes.target "_blank" ] [ text "CC 3.0 BY." ] ] ] tracker : Int -> Combatants -> Html Msg tracker round combatants = let readyCombatants = Dict.values combatants |> List.filter (not << .turnFinished) |> List.sortBy .initiative |> List.reverse turnFinishedCombatants = Dict.values combatants |> List.filter .turnFinished |> List.sortBy .initiative |> List.reverse in div [] (if Dict.size combatants > 0 then [ div [ css [ turnStyle, rowFlexStyle ] ] [ h2 [ css [ h2Style ] ] [ text <| "Round " ++ (toString round) ] , img [ css [ iconStyle True ] , onClick <| OpenPopUp <| Confirm "End Round" <| StartNewRound , src "imgs/end-round.svg" , title "Next Round" ] [ text "Next Round" ] ] , h2 [ css [ h2Style ] ] [ text "Ready" ] , div [ css [ trackerStyling ] ] (List.map (combatantCard <| Dict.size combatants) readyCombatants ) , styledHR [] [] , h2 [ css [ h2Style ] ] [ text "Turn Finished" ] , div [ css [ trackerStyling ] ] (List.map (combatantCard <| Dict.size combatants) turnFinishedCombatants ) ] else [] ) combatantCard : Int -> Combatant -> Html Msg combatantCard numCombatants combatant = let { name, initiative, onslaught, turnFinished } = combatant attacksActive = if numCombatants < 2 then False else True colour = if initiative < 1 then colourPallette.crash else if initiative < 11 then colourPallette.lowInitiative else colourPallette.highInitiative in div [ css [ combatantCardStyle colour ] ] [ b [] [ text name ] , styledHR [] [] , div [ css [ rowFlexStyle , initiativeStyle ] ] [ (toString initiative) ++ "i" |> text , img [ src "imgs/edit.svg" , css [ iconStyle True ] , onClick <| OpenPopUp <| EditInitiative combatant (toString initiative) , title "Edit Initiative" ] [] ] , styledHR [] [] , div [] ([ text ("Onslaught: " ++ (toString combatant.onslaught)) ] ++ case combatant.crash of Just crash -> [ br [] [] , text ("Crash: " ++ (toString crash.turnsUntilReset) ) ] Nothing -> [] ) , styledHR [] [] , div [ css [ rowFlexStyle ] ] [ img ([ css [ iconStyle attacksActive ] , src "imgs/withered-flower.svg" , title "Withering Attack" ] ++ if attacksActive then [ onClick <| OpenPopUp <| WitheringAttack combatant Nothing Nothing Nothing ] else [] ) [ text "Withering" ] , img [ css [ iconStyle attacksActive ] , onClick <| OpenPopUp <| DecisiveAttack combatant , src "imgs/sword.svg" , title "Decisive Attack" ] [ text "Decisive" ] , img [ src "imgs/reset.svg" , css [ iconStyle True ] , onClick <| OpenPopUp <| EditOnslaught combatant (toString onslaught) , title "Edit Onslaught" ] [] , img [ css [ iconStyle True ] , onClick <| OpenPopUp <| Confirm "End Turn" <| EndTurn combatant , src "imgs/end-turn.svg" , title "End Turn" ] [ text "End Turn" ] , img [ css [ iconStyle True ] , onClick <| OpenPopUp <| Confirm "Delete Combatant" <| ResolveDelete combatant , src "imgs/delete.svg" , title "Delete Combatant" ] [ text "Delete Combatant" ] ] ] newCombatantPopUp : PopUp -> Html Msg newCombatantPopUp newCombatant = div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case newCombatant of NewCombatant name joinCombatStr -> let addDisabled = case String.toInt joinCombatStr of Ok joinCombat -> case name of "" -> True _ -> False Err _ -> True in [ b [] [ text "Add New Combatant" ] , br [] [] , text "Name" , br [] [] , styledInput [ id "pop-up-focus", onInput SetCombatantName ] [] , br [] [] , text "Join Combat Successes" , br [] [] , styledInput [ onInput SetJoinCombat , size 3 , value joinCombatStr ] [] , styledHR [] [] , styledButton [ onClick AddNewCombatant , Html.Styled.Attributes.disabled addDisabled ] [ text "Add" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] editInitiativePopUp : PopUp -> Html Msg editInitiativePopUp editInitiative = let modifyInitiativeBtn modifyBy = styledButton [ onClick <| ModifyInitiative modifyBy ] [ text <| toString modifyBy ] in div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case editInitiative of EditInitiative combatant newInitiative -> let resolveDisabled = case String.toInt newInitiative of Ok _ -> False Err _ -> True in [ b [] [ text "Edit Initiative" ] , br [] [] , modifyInitiativeBtn -5 , modifyInitiativeBtn -1 , styledInput [ id "pop-up-focus" , onInput SetInitiative , value newInitiative , size 3 ] [] , modifyInitiativeBtn 1 , modifyInitiativeBtn 5 , styledHR [] [] , styledButton [ onClick <| ApplyNewInitiative , Html.Styled.Attributes.disabled resolveDisabled , title "Edit" ] [ text "Ok" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] disablingDiv : Html msg disablingDiv = div [ css [ disablingStyle ] ] [] witheringPopUp : Combatants -> PopUp -> Html Msg witheringPopUp combatants popUp = let selectTarget combatant = div [ css [ selectStyle ] , onClick <| SetWitheringTarget combatant ] [ text combatant.name ] in div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case popUp of WitheringAttack attacker Nothing Nothing _ -> [ b [] [ text "Select Target" ] ] ++ (Dict.toList combatants |> List.filter (\( n, c ) -> n /= attacker.name) |> List.map Tuple.second |> List.map selectTarget ) ++ [ styledHR [] [] ] WitheringAttack attacker (Just defender) (Just damageStr) Nothing -> let resolveDisabled = case String.toInt damageStr of Ok damage -> False Err _ -> True in [ b [] [ text "Set Post-Soak Damage" ] , br [] [] , attacker.name ++ " vs " ++ defender.name |> text , br [] [] , styledInput [ onInput SetWitheringDamage , value <| damageStr , size 3 ] [] , styledHR [] [] , styledButton [ onClick ResolveWitheringDamage , Html.Styled.Attributes.disabled resolveDisabled ] [ text "Resolve" ] ] WitheringAttack _ _ _ (Just (Shifted joinCombatStr)) -> let resolveDisabled = case String.toInt joinCombatStr of Ok joinCombat -> False Err _ -> True in [ b [] [ text "Initiative Shift!" ] , br [] [] , text "Join Combat Result" , br [] [] , styledInput [ onInput SetShiftJoinCombat ] [] , styledHR [] [] , styledButton [ onClick ResolveInitiativeShift , Html.Styled.Attributes.disabled resolveDisabled ] [ text "Resolve" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] decisivePopUp : PopUp -> Html Msg decisivePopUp popUp = div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case popUp of DecisiveAttack combatant -> [ b [] [ text "Decisive Attack" ] , br [] [] , styledButton [ onClick <| ResolveDecisive Hit ] [ text "Hit" ] , styledButton [ onClick <| ResolveDecisive Miss ] [ text "Miss" ] , styledHR [] [] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] editOnslaughtPopUp : PopUp -> Html Msg editOnslaughtPopUp editOnslaught = let modifyOnslaughtBtn modifyBy = styledButton [ onClick <| ModifyOnslaught modifyBy ] [ text <| toString modifyBy ] in div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case editOnslaught of EditOnslaught combatant newOnslaught -> let resolveDisabled = case String.toInt newOnslaught of Ok _ -> False Err _ -> True in [ b [] [ text "Edit Onslaught" ] , br [] [] , modifyOnslaughtBtn -5 , modifyOnslaughtBtn -1 , styledInput [ id "pop-up-focus" , onInput SetOnslaught , value newOnslaught , size 3 ] [] , modifyOnslaughtBtn 1 , modifyOnslaughtBtn 5 , styledHR [] [] , styledButton [ onClick <| ApplyNewOnslaught , Html.Styled.Attributes.disabled resolveDisabled , title "Edit" ] [ text "Ok" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] confirmPopUp : PopUp -> Html Msg confirmPopUp popUp = div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case popUp of Confirm description msg -> [ b [] [ text description ] , br [] [] , text "Are you sure?" , styledHR [] [] , styledButton [ onClick <| msg ] [ text "Ok" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] helpPopUp : Html Msg helpPopUp = div [] [ disablingDiv , div [ css [ popUpStyle , Css.maxHeight (pct 80) , Css.width (pct 80) , overflow auto ] ] [ text "Welcome to Threads of Martial Destiny, a combat tracker for " , a [ href "http://theonyxpath.com/category/worlds/exalted/" ] [ text "Exalted 3rd Edition" ] , ". The app saves its state regularly so don't worry if you " ++ "close or refresh the tab, you can pick up where you left " ++ "off. Here's a list of the buttons and what a description of " ++ "what they do:" |> text , Html.Styled.table [] [ iconDescription "imgs/add.svg" "Adds a new combatant to the combat." , iconDescription "imgs/new-combat.svg" "Starts a new combat deleting the current session." , iconDescription "imgs/end-round.svg" ("Ends the current round of combat, indicating that all " ++ "combatants have made taken actions." ) , iconDescription "imgs/edit.svg" "Edits the combatants initiative value." , iconDescription "imgs/withered-flower.svg" "Initiates a withering attack (the icon is a withered flower)." , iconDescription "imgs/sword.svg" "Initiates a decisive attack." , iconDescription "imgs/reset.svg" "Edits the combatants onslaught value." , iconDescription "imgs/end-turn.svg" ("Ends the combatants turn, indicating that they have taken " ++ "all their actions." ) , iconDescription "imgs/delete.svg" "Deletes the combatant." ] , "If you find any bugs or have any feature requests please add " ++ "an issue on " |> text , a [ href "https://github.com/ChrisWellsWood/martial-destiny/issues" ] [ text "GitHub" ] , text " or, even better, send me a pull request!" , styledHR [] [] , styledButton [ onClick ClosePopUp ] [ text "Close" ] ] ] iconDescription : String -> String -> Html msg iconDescription iconPath description = tr [] [ td [] [ img [ css [ iconStyle True ] , src iconPath ] [] ] , td [] [ text description ] ] -- Styles type alias Colour = Color type alias ColourPallette = { lowInitiative : Colour , highInitiative : Colour , crash : Colour , turnFinished : Colour , clicked : Colour , backgroundColor : Colour } -- https://coolors.co/91d696-b4d174-edc855-e49f64-d96969 colourPallette : ColourPallette colourPallette = { highInitiative = hex "91d696" , lowInitiative = hex "edc855" , crash = hex "d96969" , turnFinished = hex "999999" , clicked = hex "777777" , backgroundColor = hex "eeeeee" } defaultStyle : Style defaultStyle = Css.batch [ displayFlex , flexDirection column , fontFamilies [ "Tahoma", "Geneva", "sans-serif" ] , fontSize (px 18) , Css.height (pct 100) , justifyContent spaceBetween , Css.width (pct 100) , position absolute , top (px 0) , left (px 0) ] styledHR : List (Attribute msg) -> List (Html msg) -> Html msg styledHR = styled hr [ borderWidth (px 1) , borderStyle solid , borderColor <| hex "000000" , marginLeft (px 0) , marginRight (px 0) ] styledInput : List (Attribute msg) -> List (Html msg) -> Html msg styledInput = styled input [ borderWidth (px 2) , borderStyle solid , borderColor <| hex "000000" , fontSize (px 18) , margin (px 3) , padding (px 3) ] styledButton : List (Attribute msg) -> List (Html msg) -> Html msg styledButton = styled button [ backgroundColor colourPallette.turnFinished , Css.active [ backgroundColor colourPallette.clicked ] , Css.disabled [ backgroundColor colourPallette.backgroundColor ] , borderWidth (px 2) , borderStyle solid , borderColor <| hex "000000" , color <| hex "000000" , fontSize (px 18) , margin (px 3) , outline none , padding (px 3) ] headerStyle : Style headerStyle = Css.batch [ backgroundColor colourPallette.crash , padding (px 8) , Css.width auto , borderWidth4 (px 0) (px 0) (px 2) (px 0) , borderStyle solid , borderColor <| hex "000000" ] turnStyle : Style turnStyle = Css.batch [ backgroundColor colourPallette.highInitiative , padding (px 8) , Css.width auto , borderWidth4 (px 0) (px 0) (px 2) (px 0) , borderStyle solid , borderColor <| hex "000000" , margin4 (px 0) (px 0) (px 4) (px 0) ] rowFlexStyle : Style rowFlexStyle = Css.batch [ displayFlex , position relative , justifyContent spaceBetween , alignItems center ] h1Style : Style h1Style = Css.batch [ padding (px 0) , margin (px 0) ] h2Style : Style h2Style = Css.batch [ padding (px 0) , margin (px 0) , textAlign center ] bodyStyle : Style bodyStyle = Css.batch [ backgroundColor colourPallette.backgroundColor , Css.width (pct 100) , Css.height (pct 100) , overflow auto ] footerStyle : Style footerStyle = Css.batch [ borderWidth4 (px 2) (px 0) (px 0) (px 0) , borderStyle solid , borderColor <| hex "000000" , Css.width (pct 100) , fontSize (px 12) , color <| hex "aaaaaa" , padding (px 5) ] iconStyle : Bool -> Style iconStyle active = Css.batch ([ Css.height (px 24) , padding (px 3) , margin (px 3) , Css.width (px 24) , borderStyle solid , borderWidth (px 2) ] ++ if active then [ backgroundColor colourPallette.turnFinished , Css.active [ backgroundColor colourPallette.clicked ] ] else [ backgroundColor colourPallette.backgroundColor ] ) trackerStyling : Style trackerStyling = Css.batch [ displayFlex , flexWrap Css.wrap , justifyContent center ] combatantCardStyle : Colour -> Style combatantCardStyle bgColour = Css.batch [ backgroundColor bgColour , borderStyle solid , borderWidth (px 2) , Css.width (px 200) , overflow Css.hidden , overflowWrap normal , padding (px 8) , margin4 (px 2) (px 0) (px 2) (px 2) , displayFlex , flexDirection column , justifyContent spaceBetween ] initiativeStyle : Style initiativeStyle = Css.batch [ fontSize (px 36) , position relative ] disablingStyle : Style disablingStyle = Css.batch [ zIndex (int 1000) , position absolute , top (pct 0) , left (pct 0) , Css.width (pct 100) , Css.height (pct 100) , backgroundColor <| hex "dddddd" , opacity (num 0.5) ] selectStyle : Style selectStyle = Css.batch [ margin (px 3) , textAlign center , Css.hover [ backgroundColor colourPallette.turnFinished ] ] popUpStyle : Style popUpStyle = Css.batch [ backgroundColor colourPallette.lowInitiative , borderStyle solid , borderWidth (px 2) , left (pct 50) , padding (px 5) , position absolute , top (pct 50) , transform (translate2 (pct -50) (pct -50)) , Css.width (px 300) , zIndex (int 1001) ]
46375
port module Main exposing (..) import Css exposing (..) import Dict import Dom import Html import Html.Styled exposing (..) import Html.Styled.Attributes exposing (..) import Html.Styled.Events exposing (..) import Task main : Program (Maybe ExportedModel) Model Msg main = Html.programWithFlags { init = init , view = view >> toUnstyled , update = update , subscriptions = subscriptions } init : Maybe ExportedModel -> ( Model, Cmd Msg ) init savedSession = case savedSession of Just exportedModel -> (importModel exportedModel) ! [] Nothing -> emptyModel ! [] type alias Model = { combatants : Combatants , round : Int , popUp : PopUp } emptyModel : Model emptyModel = Model Dict.empty 1 Closed type alias ExportedModel = { combatants : List ( String, Combatant ) , round : Int } exportModel : Model -> ExportedModel exportModel model = ExportedModel (Dict.toList model.combatants) model.round importModel : ExportedModel -> Model importModel exportedModel = Model (Dict.fromList exportedModel.combatants) exportedModel.round Closed type alias Combatant = { name : String , initiative : Int , crash : Maybe Crash , onslaught : Int , turnFinished : Bool } type alias Crash = { crasher : String , turnsUntilReset : Int } type alias Combatants = Dict.Dict String Combatant type PopUp = NewCombatant String String | EditInitiative Combatant String | WitheringAttack Combatant (Maybe Combatant) (Maybe String) (Maybe Shift) | DecisiveAttack Combatant | EditOnslaught Combatant String | Confirm String Msg | Help | Closed type Shift = Shifted String | NoShift type AttackOutcome = Hit | Miss -- Update type Msg = OpenPopUp PopUp | FocusResult (Result Dom.Error ()) | ClosePopUp | SetCombatantName String | SetJoinCombat String | AddNewCombatant | Save | NewCombat | StartNewRound | ModifyInitiative Int | SetInitiative String | ApplyNewInitiative | SetWitheringTarget Combatant | SetWitheringDamage String | ResolveWitheringDamage | SetShiftJoinCombat String | ResolveInitiativeShift | ResolveDecisive AttackOutcome | ModifyOnslaught Int | SetOnslaught String | ApplyNewOnslaught | EndTurn Combatant | ResolveDelete Combatant update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of OpenPopUp popUp -> { model | popUp = popUp } ! [ Dom.focus "pop-up-focus" |> Task.attempt FocusResult ] FocusResult result -> case result of Err (Dom.NotFound id) -> let error = "ID \"" ++ id ++ "\"not found." in model ! [] Ok () -> model ! [] ClosePopUp -> { model | popUp = Closed } ! [] SetCombatantName name -> case model.popUp of NewCombatant _ joinCombat -> { model | popUp = NewCombatant name joinCombat } ! [] _ -> { model | popUp = Closed } ! [] SetJoinCombat joinCombat -> case model.popUp of NewCombatant name _ -> { model | popUp = NewCombatant name joinCombat } ! [] _ -> { model | popUp = Closed } ! [] AddNewCombatant -> case model.popUp of NewCombatant name joinCombatStr -> let joinCombat = String.toInt joinCombatStr |> Result.withDefault 0 |> (+) 3 newCombatant = Combatant name joinCombat Nothing 0 False updatedCombatants = Dict.insert name newCombatant model.combatants in update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] Save -> model ! [ exportModel model |> saveState ] NewCombat -> update Save emptyModel StartNewRound -> let updatedCombatants = Dict.values model.combatants |> List.map decrementCrash |> List.map (\c -> { c | turnFinished = False }) |> List.map (\c -> ( c.name, c )) |> Dict.fromList in update Save { model | combatants = updatedCombatants , round = model.round + 1 , popUp = Closed } ModifyInitiative modifyBy -> case model.popUp of EditInitiative combatant initiativeString -> { model | popUp = EditInitiative combatant (String.toInt initiativeString |> Result.withDefault 0 |> (+) modifyBy |> toString ) } ! [] _ -> { model | popUp = Closed } ! [] SetInitiative initiativeString -> case model.popUp of EditInitiative combatant _ -> { model | popUp = EditInitiative combatant initiativeString } ! [] _ -> { model | popUp = Closed } ! [] ApplyNewInitiative -> case model.popUp of EditInitiative combatant newInitiativeStr -> case String.toInt newInitiativeStr of Ok newInitiative -> update Save { model | popUp = Closed , combatants = Dict.insert combatant.name { combatant | initiative = newInitiative } model.combatants } Err _ -> { model | popUp = Closed } ! [] _ -> { model | popUp = Closed } ! [] SetWitheringTarget defender -> case model.popUp of WitheringAttack attacker _ _ _ -> { model | popUp = WitheringAttack attacker (Just defender) (Just "0") Nothing } ! [] _ -> { model | popUp = Closed } ! [] SetWitheringDamage damage -> case model.popUp of WitheringAttack attacker (Just defender) (Just _) _ -> { model | popUp = WitheringAttack attacker (Just defender) (Just damage) Nothing } ! [] _ -> { model | popUp = Closed } ! [] ResolveWitheringDamage -> case model.popUp of WitheringAttack attacker (Just defender) (Just damage) Nothing -> let ( uAttacker, uDefender, shift ) = resolveWithering attacker defender damage updatedCombatants = Dict.insert attacker.name uAttacker model.combatants |> Dict.insert defender.name uDefender in case shift of Shifted _ -> { model | popUp = WitheringAttack uAttacker (Just uDefender) (Just damage) (Just shift) } ! [] NoShift -> update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] SetShiftJoinCombat shiftJoinCombat -> case model.popUp of WitheringAttack a (Just d) (Just dam) (Just (Shifted _)) -> { model | popUp = WitheringAttack a (Just d) (Just dam) (Just (Shifted shiftJoinCombat)) } ! [] _ -> { model | popUp = Closed } ! [] ResolveInitiativeShift -> case model.popUp of WitheringAttack att (Just def) (Just dam) (Just (Shifted jc)) -> let joinCombat = String.toInt jc |> Result.withDefault 0 shiftInitiative = 3 + joinCombat attacker = { att | initiative = if shiftInitiative > att.initiative then shiftInitiative else att.initiative } updatedCombatants = Dict.insert attacker.name attacker model.combatants |> Dict.insert def.name def in update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] ResolveDecisive decisiveOutcome -> case model.popUp of DecisiveAttack combatant -> let attacker = resolveDecisive decisiveOutcome combatant updatedCombatants = Dict.insert attacker.name attacker model.combatants in update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] ModifyOnslaught modifyBy -> case model.popUp of EditOnslaught combatant onslaughtString -> { model | popUp = EditOnslaught combatant (String.toInt onslaughtString |> Result.withDefault 0 |> (+) modifyBy |> toString ) } ! [] _ -> { model | popUp = Closed } ! [] SetOnslaught onslaughtString -> case model.popUp of EditOnslaught combatant _ -> { model | popUp = EditOnslaught combatant onslaughtString } ! [] _ -> { model | popUp = Closed } ! [] ApplyNewOnslaught -> case model.popUp of EditOnslaught combatant newOnslaughtStr -> case String.toInt newOnslaughtStr of Ok newOnslaught -> update Save { model | popUp = Closed , combatants = Dict.insert combatant.name { combatant | onslaught = newOnslaught } model.combatants } Err _ -> { model | popUp = Closed } ! [] _ -> { model | popUp = Closed } ! [] EndTurn combatant -> let updatedCombatant = { combatant | turnFinished = True } updatedCombatants = Dict.insert updatedCombatant.name updatedCombatant model.combatants in update Save { model | combatants = updatedCombatants , popUp = Closed } ResolveDelete combatant -> let updatedCombatants = Dict.remove combatant.name model.combatants in update Save { model | combatants = updatedCombatants , popUp = Closed } sortByInitiative : Combatants -> Combatants sortByInitiative combatants = Dict.toList combatants |> List.sortBy (\( n, c ) -> c.initiative) |> List.reverse |> Dict.fromList decrementCrash : Combatant -> Combatant decrementCrash combatant = case combatant.crash of Just crash -> let updatedCrash = { crash | turnsUntilReset = crash.turnsUntilReset - 1 } in if updatedCrash.turnsUntilReset < 1 then { combatant | crash = Nothing , initiative = 3 } else { combatant | crash = Just updatedCrash } Nothing -> combatant resolveWithering : Combatant -> Combatant -> String -> ( Combatant, Combatant, Shift ) resolveWithering attacker defender damageStr = let damage = String.toInt damageStr |> Result.withDefault 0 defInitiative = defender.initiative - damage hasCrashed = if (defender.initiative > 0) && (defInitiative <= 0) then True else False updatedDefender = { defender | initiative = defInitiative , crash = if hasCrashed then Just (Crash attacker.name 3) else Nothing , onslaught = defender.onslaught + 1 } attInitiative = attacker.initiative + damage + 1 + (if hasCrashed then 5 else 0 ) shift = case attacker.crash of Just crash -> if hasCrashed && (crash.crasher == defender.name) then Shifted "0" else NoShift Nothing -> NoShift updatedAttacker = { attacker | initiative = attInitiative , onslaught = 0 , crash = if attInitiative > 0 then Nothing else attacker.crash , turnFinished = True } in ( updatedAttacker, updatedDefender, shift ) resolveDecisive : AttackOutcome -> Combatant -> Combatant resolveDecisive outcome combatant = case outcome of Hit -> { combatant | initiative = 3 } Miss -> { combatant | initiative = if combatant.initiative < 11 then combatant.initiative - 2 else combatant.initiative - 3 , onslaught = 0 , turnFinished = True } -- Ports port saveState : ExportedModel -> Cmd msg -- Subscriptions subscriptions : Model -> Sub msg subscriptions model = Sub.none -- Views view : Model -> Html Msg view model = div [ css [ defaultStyle ] ] [ header [ css [ headerStyle, rowFlexStyle ] ] [ div [] [ h1 [ css [ h1Style ] ] [ text "Threads of Martial Destiny" ] , b [] [ text "A combat tracker for Exalted 3rd Edition" ] ] , div [] [ img [ css [ iconStyle True ] , src "imgs/add.svg" , NewCombatant "" "0" |> OpenPopUp |> onClick , title "Add Combatant" ] [ text "Add Combatant" ] , img [ css [ iconStyle True ] , src "imgs/help.svg" , onClick <| OpenPopUp <| Help , title "Help" ] [ text "Help" ] , img [ css [ iconStyle True ] , src "imgs/new-combat.svg" , onClick <| OpenPopUp <| Confirm "New Combat" <| NewCombat , title "New Combat" ] [ text "New Combat" ] ] ] , div [ css [ bodyStyle ] ] ([ tracker model.round model.combatants ] ++ (case model.popUp of (NewCombatant _ _) as newCombatant -> [ newCombatantPopUp newCombatant ] (EditInitiative _ _) as editInitiative -> [ editInitiativePopUp editInitiative ] (WitheringAttack _ _ _ _) as witheringAttack -> [ witheringPopUp model.combatants witheringAttack ] (DecisiveAttack _) as decisiveAttack -> [ decisivePopUp decisiveAttack ] (EditOnslaught _ _) as editOnslaught -> [ editOnslaughtPopUp editOnslaught ] (Confirm _ _) as confirm -> [ confirmPopUp confirm ] Help -> [ helpPopUp ] Closed -> [] ) ) , footer [ css [ footerStyle ] ] [ text ("© <NAME>, 2018. Version 1.1.0. " ++ "Exalted is © White Wolf AB and Onyx Path. " ) , a [ href "https://github.com/ChrisWellsWood/martial-destiny" ] [ text "Source code." ] , br [] [] , text "Icons made by " , a [ href "https://www.flaticon.com/authors/appzgear" , title "Appzgear" ] [ text "Appzgear" ] , text ", " , a [ href "https://www.flaticon.com/authors/dave-gandy" , title "<NAME>" ] [ text "<NAME>" ] , text ", " , a [ href "https://www.flaticon.com/authors/eleonor-wang" , title "<NAME>" ] [ text "<NAME>" ] , text ", " , a [ href "http://www.freepik.com" , title "Freepik" ] [ text "Freepik" ] , text " and " , a [ href "https://www.flaticon.com/authors/pixel-perfect" , title "Pixel perfect" ] [ text "Pixel perfect" ] , text " from " , a [ href "https://www.flaticon.com/" , title "Flaticon" ] [ text "www.flaticon.com" ] , text " and are licensed by " , a [ href "http://creativecommons.org/licenses/by/3.0/" , title "Creative Commons BY 3.0" , Html.Styled.Attributes.target "_blank" ] [ text "CC 3.0 BY." ] ] ] tracker : Int -> Combatants -> Html Msg tracker round combatants = let readyCombatants = Dict.values combatants |> List.filter (not << .turnFinished) |> List.sortBy .initiative |> List.reverse turnFinishedCombatants = Dict.values combatants |> List.filter .turnFinished |> List.sortBy .initiative |> List.reverse in div [] (if Dict.size combatants > 0 then [ div [ css [ turnStyle, rowFlexStyle ] ] [ h2 [ css [ h2Style ] ] [ text <| "Round " ++ (toString round) ] , img [ css [ iconStyle True ] , onClick <| OpenPopUp <| Confirm "End Round" <| StartNewRound , src "imgs/end-round.svg" , title "Next Round" ] [ text "Next Round" ] ] , h2 [ css [ h2Style ] ] [ text "Ready" ] , div [ css [ trackerStyling ] ] (List.map (combatantCard <| Dict.size combatants) readyCombatants ) , styledHR [] [] , h2 [ css [ h2Style ] ] [ text "Turn Finished" ] , div [ css [ trackerStyling ] ] (List.map (combatantCard <| Dict.size combatants) turnFinishedCombatants ) ] else [] ) combatantCard : Int -> Combatant -> Html Msg combatantCard numCombatants combatant = let { name, initiative, onslaught, turnFinished } = combatant attacksActive = if numCombatants < 2 then False else True colour = if initiative < 1 then colourPallette.crash else if initiative < 11 then colourPallette.lowInitiative else colourPallette.highInitiative in div [ css [ combatantCardStyle colour ] ] [ b [] [ text name ] , styledHR [] [] , div [ css [ rowFlexStyle , initiativeStyle ] ] [ (toString initiative) ++ "i" |> text , img [ src "imgs/edit.svg" , css [ iconStyle True ] , onClick <| OpenPopUp <| EditInitiative combatant (toString initiative) , title "Edit Initiative" ] [] ] , styledHR [] [] , div [] ([ text ("Onslaught: " ++ (toString combatant.onslaught)) ] ++ case combatant.crash of Just crash -> [ br [] [] , text ("Crash: " ++ (toString crash.turnsUntilReset) ) ] Nothing -> [] ) , styledHR [] [] , div [ css [ rowFlexStyle ] ] [ img ([ css [ iconStyle attacksActive ] , src "imgs/withered-flower.svg" , title "Withering Attack" ] ++ if attacksActive then [ onClick <| OpenPopUp <| WitheringAttack combatant Nothing Nothing Nothing ] else [] ) [ text "Withering" ] , img [ css [ iconStyle attacksActive ] , onClick <| OpenPopUp <| DecisiveAttack combatant , src "imgs/sword.svg" , title "Decisive Attack" ] [ text "Decisive" ] , img [ src "imgs/reset.svg" , css [ iconStyle True ] , onClick <| OpenPopUp <| EditOnslaught combatant (toString onslaught) , title "Edit Onslaught" ] [] , img [ css [ iconStyle True ] , onClick <| OpenPopUp <| Confirm "End Turn" <| EndTurn combatant , src "imgs/end-turn.svg" , title "End Turn" ] [ text "End Turn" ] , img [ css [ iconStyle True ] , onClick <| OpenPopUp <| Confirm "Delete Combatant" <| ResolveDelete combatant , src "imgs/delete.svg" , title "Delete Combatant" ] [ text "Delete Combatant" ] ] ] newCombatantPopUp : PopUp -> Html Msg newCombatantPopUp newCombatant = div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case newCombatant of NewCombatant name joinCombatStr -> let addDisabled = case String.toInt joinCombatStr of Ok joinCombat -> case name of "" -> True _ -> False Err _ -> True in [ b [] [ text "Add New Combatant" ] , br [] [] , text "Name" , br [] [] , styledInput [ id "pop-up-focus", onInput SetCombatantName ] [] , br [] [] , text "Join Combat Successes" , br [] [] , styledInput [ onInput SetJoinCombat , size 3 , value joinCombatStr ] [] , styledHR [] [] , styledButton [ onClick AddNewCombatant , Html.Styled.Attributes.disabled addDisabled ] [ text "Add" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] editInitiativePopUp : PopUp -> Html Msg editInitiativePopUp editInitiative = let modifyInitiativeBtn modifyBy = styledButton [ onClick <| ModifyInitiative modifyBy ] [ text <| toString modifyBy ] in div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case editInitiative of EditInitiative combatant newInitiative -> let resolveDisabled = case String.toInt newInitiative of Ok _ -> False Err _ -> True in [ b [] [ text "Edit Initiative" ] , br [] [] , modifyInitiativeBtn -5 , modifyInitiativeBtn -1 , styledInput [ id "pop-up-focus" , onInput SetInitiative , value newInitiative , size 3 ] [] , modifyInitiativeBtn 1 , modifyInitiativeBtn 5 , styledHR [] [] , styledButton [ onClick <| ApplyNewInitiative , Html.Styled.Attributes.disabled resolveDisabled , title "Edit" ] [ text "Ok" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] disablingDiv : Html msg disablingDiv = div [ css [ disablingStyle ] ] [] witheringPopUp : Combatants -> PopUp -> Html Msg witheringPopUp combatants popUp = let selectTarget combatant = div [ css [ selectStyle ] , onClick <| SetWitheringTarget combatant ] [ text combatant.name ] in div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case popUp of WitheringAttack attacker Nothing Nothing _ -> [ b [] [ text "Select Target" ] ] ++ (Dict.toList combatants |> List.filter (\( n, c ) -> n /= attacker.name) |> List.map Tuple.second |> List.map selectTarget ) ++ [ styledHR [] [] ] WitheringAttack attacker (Just defender) (Just damageStr) Nothing -> let resolveDisabled = case String.toInt damageStr of Ok damage -> False Err _ -> True in [ b [] [ text "Set Post-Soak Damage" ] , br [] [] , attacker.name ++ " vs " ++ defender.name |> text , br [] [] , styledInput [ onInput SetWitheringDamage , value <| damageStr , size 3 ] [] , styledHR [] [] , styledButton [ onClick ResolveWitheringDamage , Html.Styled.Attributes.disabled resolveDisabled ] [ text "Resolve" ] ] WitheringAttack _ _ _ (Just (Shifted joinCombatStr)) -> let resolveDisabled = case String.toInt joinCombatStr of Ok joinCombat -> False Err _ -> True in [ b [] [ text "Initiative Shift!" ] , br [] [] , text "Join Combat Result" , br [] [] , styledInput [ onInput SetShiftJoinCombat ] [] , styledHR [] [] , styledButton [ onClick ResolveInitiativeShift , Html.Styled.Attributes.disabled resolveDisabled ] [ text "Resolve" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] decisivePopUp : PopUp -> Html Msg decisivePopUp popUp = div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case popUp of DecisiveAttack combatant -> [ b [] [ text "Decisive Attack" ] , br [] [] , styledButton [ onClick <| ResolveDecisive Hit ] [ text "Hit" ] , styledButton [ onClick <| ResolveDecisive Miss ] [ text "Miss" ] , styledHR [] [] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] editOnslaughtPopUp : PopUp -> Html Msg editOnslaughtPopUp editOnslaught = let modifyOnslaughtBtn modifyBy = styledButton [ onClick <| ModifyOnslaught modifyBy ] [ text <| toString modifyBy ] in div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case editOnslaught of EditOnslaught combatant newOnslaught -> let resolveDisabled = case String.toInt newOnslaught of Ok _ -> False Err _ -> True in [ b [] [ text "Edit Onslaught" ] , br [] [] , modifyOnslaughtBtn -5 , modifyOnslaughtBtn -1 , styledInput [ id "pop-up-focus" , onInput SetOnslaught , value newOnslaught , size 3 ] [] , modifyOnslaughtBtn 1 , modifyOnslaughtBtn 5 , styledHR [] [] , styledButton [ onClick <| ApplyNewOnslaught , Html.Styled.Attributes.disabled resolveDisabled , title "Edit" ] [ text "Ok" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] confirmPopUp : PopUp -> Html Msg confirmPopUp popUp = div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case popUp of Confirm description msg -> [ b [] [ text description ] , br [] [] , text "Are you sure?" , styledHR [] [] , styledButton [ onClick <| msg ] [ text "Ok" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] helpPopUp : Html Msg helpPopUp = div [] [ disablingDiv , div [ css [ popUpStyle , Css.maxHeight (pct 80) , Css.width (pct 80) , overflow auto ] ] [ text "Welcome to Threads of Martial Destiny, a combat tracker for " , a [ href "http://theonyxpath.com/category/worlds/exalted/" ] [ text "Exalted 3rd Edition" ] , ". The app saves its state regularly so don't worry if you " ++ "close or refresh the tab, you can pick up where you left " ++ "off. Here's a list of the buttons and what a description of " ++ "what they do:" |> text , Html.Styled.table [] [ iconDescription "imgs/add.svg" "Adds a new combatant to the combat." , iconDescription "imgs/new-combat.svg" "Starts a new combat deleting the current session." , iconDescription "imgs/end-round.svg" ("Ends the current round of combat, indicating that all " ++ "combatants have made taken actions." ) , iconDescription "imgs/edit.svg" "Edits the combatants initiative value." , iconDescription "imgs/withered-flower.svg" "Initiates a withering attack (the icon is a withered flower)." , iconDescription "imgs/sword.svg" "Initiates a decisive attack." , iconDescription "imgs/reset.svg" "Edits the combatants onslaught value." , iconDescription "imgs/end-turn.svg" ("Ends the combatants turn, indicating that they have taken " ++ "all their actions." ) , iconDescription "imgs/delete.svg" "Deletes the combatant." ] , "If you find any bugs or have any feature requests please add " ++ "an issue on " |> text , a [ href "https://github.com/ChrisWellsWood/martial-destiny/issues" ] [ text "GitHub" ] , text " or, even better, send me a pull request!" , styledHR [] [] , styledButton [ onClick ClosePopUp ] [ text "Close" ] ] ] iconDescription : String -> String -> Html msg iconDescription iconPath description = tr [] [ td [] [ img [ css [ iconStyle True ] , src iconPath ] [] ] , td [] [ text description ] ] -- Styles type alias Colour = Color type alias ColourPallette = { lowInitiative : Colour , highInitiative : Colour , crash : Colour , turnFinished : Colour , clicked : Colour , backgroundColor : Colour } -- https://coolors.co/91d696-b4d174-edc855-e49f64-d96969 colourPallette : ColourPallette colourPallette = { highInitiative = hex "91d696" , lowInitiative = hex "edc855" , crash = hex "d96969" , turnFinished = hex "999999" , clicked = hex "777777" , backgroundColor = hex "eeeeee" } defaultStyle : Style defaultStyle = Css.batch [ displayFlex , flexDirection column , fontFamilies [ "Tahoma", "Geneva", "sans-serif" ] , fontSize (px 18) , Css.height (pct 100) , justifyContent spaceBetween , Css.width (pct 100) , position absolute , top (px 0) , left (px 0) ] styledHR : List (Attribute msg) -> List (Html msg) -> Html msg styledHR = styled hr [ borderWidth (px 1) , borderStyle solid , borderColor <| hex "000000" , marginLeft (px 0) , marginRight (px 0) ] styledInput : List (Attribute msg) -> List (Html msg) -> Html msg styledInput = styled input [ borderWidth (px 2) , borderStyle solid , borderColor <| hex "000000" , fontSize (px 18) , margin (px 3) , padding (px 3) ] styledButton : List (Attribute msg) -> List (Html msg) -> Html msg styledButton = styled button [ backgroundColor colourPallette.turnFinished , Css.active [ backgroundColor colourPallette.clicked ] , Css.disabled [ backgroundColor colourPallette.backgroundColor ] , borderWidth (px 2) , borderStyle solid , borderColor <| hex "000000" , color <| hex "000000" , fontSize (px 18) , margin (px 3) , outline none , padding (px 3) ] headerStyle : Style headerStyle = Css.batch [ backgroundColor colourPallette.crash , padding (px 8) , Css.width auto , borderWidth4 (px 0) (px 0) (px 2) (px 0) , borderStyle solid , borderColor <| hex "000000" ] turnStyle : Style turnStyle = Css.batch [ backgroundColor colourPallette.highInitiative , padding (px 8) , Css.width auto , borderWidth4 (px 0) (px 0) (px 2) (px 0) , borderStyle solid , borderColor <| hex "000000" , margin4 (px 0) (px 0) (px 4) (px 0) ] rowFlexStyle : Style rowFlexStyle = Css.batch [ displayFlex , position relative , justifyContent spaceBetween , alignItems center ] h1Style : Style h1Style = Css.batch [ padding (px 0) , margin (px 0) ] h2Style : Style h2Style = Css.batch [ padding (px 0) , margin (px 0) , textAlign center ] bodyStyle : Style bodyStyle = Css.batch [ backgroundColor colourPallette.backgroundColor , Css.width (pct 100) , Css.height (pct 100) , overflow auto ] footerStyle : Style footerStyle = Css.batch [ borderWidth4 (px 2) (px 0) (px 0) (px 0) , borderStyle solid , borderColor <| hex "000000" , Css.width (pct 100) , fontSize (px 12) , color <| hex "aaaaaa" , padding (px 5) ] iconStyle : Bool -> Style iconStyle active = Css.batch ([ Css.height (px 24) , padding (px 3) , margin (px 3) , Css.width (px 24) , borderStyle solid , borderWidth (px 2) ] ++ if active then [ backgroundColor colourPallette.turnFinished , Css.active [ backgroundColor colourPallette.clicked ] ] else [ backgroundColor colourPallette.backgroundColor ] ) trackerStyling : Style trackerStyling = Css.batch [ displayFlex , flexWrap Css.wrap , justifyContent center ] combatantCardStyle : Colour -> Style combatantCardStyle bgColour = Css.batch [ backgroundColor bgColour , borderStyle solid , borderWidth (px 2) , Css.width (px 200) , overflow Css.hidden , overflowWrap normal , padding (px 8) , margin4 (px 2) (px 0) (px 2) (px 2) , displayFlex , flexDirection column , justifyContent spaceBetween ] initiativeStyle : Style initiativeStyle = Css.batch [ fontSize (px 36) , position relative ] disablingStyle : Style disablingStyle = Css.batch [ zIndex (int 1000) , position absolute , top (pct 0) , left (pct 0) , Css.width (pct 100) , Css.height (pct 100) , backgroundColor <| hex "dddddd" , opacity (num 0.5) ] selectStyle : Style selectStyle = Css.batch [ margin (px 3) , textAlign center , Css.hover [ backgroundColor colourPallette.turnFinished ] ] popUpStyle : Style popUpStyle = Css.batch [ backgroundColor colourPallette.lowInitiative , borderStyle solid , borderWidth (px 2) , left (pct 50) , padding (px 5) , position absolute , top (pct 50) , transform (translate2 (pct -50) (pct -50)) , Css.width (px 300) , zIndex (int 1001) ]
true
port module Main exposing (..) import Css exposing (..) import Dict import Dom import Html import Html.Styled exposing (..) import Html.Styled.Attributes exposing (..) import Html.Styled.Events exposing (..) import Task main : Program (Maybe ExportedModel) Model Msg main = Html.programWithFlags { init = init , view = view >> toUnstyled , update = update , subscriptions = subscriptions } init : Maybe ExportedModel -> ( Model, Cmd Msg ) init savedSession = case savedSession of Just exportedModel -> (importModel exportedModel) ! [] Nothing -> emptyModel ! [] type alias Model = { combatants : Combatants , round : Int , popUp : PopUp } emptyModel : Model emptyModel = Model Dict.empty 1 Closed type alias ExportedModel = { combatants : List ( String, Combatant ) , round : Int } exportModel : Model -> ExportedModel exportModel model = ExportedModel (Dict.toList model.combatants) model.round importModel : ExportedModel -> Model importModel exportedModel = Model (Dict.fromList exportedModel.combatants) exportedModel.round Closed type alias Combatant = { name : String , initiative : Int , crash : Maybe Crash , onslaught : Int , turnFinished : Bool } type alias Crash = { crasher : String , turnsUntilReset : Int } type alias Combatants = Dict.Dict String Combatant type PopUp = NewCombatant String String | EditInitiative Combatant String | WitheringAttack Combatant (Maybe Combatant) (Maybe String) (Maybe Shift) | DecisiveAttack Combatant | EditOnslaught Combatant String | Confirm String Msg | Help | Closed type Shift = Shifted String | NoShift type AttackOutcome = Hit | Miss -- Update type Msg = OpenPopUp PopUp | FocusResult (Result Dom.Error ()) | ClosePopUp | SetCombatantName String | SetJoinCombat String | AddNewCombatant | Save | NewCombat | StartNewRound | ModifyInitiative Int | SetInitiative String | ApplyNewInitiative | SetWitheringTarget Combatant | SetWitheringDamage String | ResolveWitheringDamage | SetShiftJoinCombat String | ResolveInitiativeShift | ResolveDecisive AttackOutcome | ModifyOnslaught Int | SetOnslaught String | ApplyNewOnslaught | EndTurn Combatant | ResolveDelete Combatant update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of OpenPopUp popUp -> { model | popUp = popUp } ! [ Dom.focus "pop-up-focus" |> Task.attempt FocusResult ] FocusResult result -> case result of Err (Dom.NotFound id) -> let error = "ID \"" ++ id ++ "\"not found." in model ! [] Ok () -> model ! [] ClosePopUp -> { model | popUp = Closed } ! [] SetCombatantName name -> case model.popUp of NewCombatant _ joinCombat -> { model | popUp = NewCombatant name joinCombat } ! [] _ -> { model | popUp = Closed } ! [] SetJoinCombat joinCombat -> case model.popUp of NewCombatant name _ -> { model | popUp = NewCombatant name joinCombat } ! [] _ -> { model | popUp = Closed } ! [] AddNewCombatant -> case model.popUp of NewCombatant name joinCombatStr -> let joinCombat = String.toInt joinCombatStr |> Result.withDefault 0 |> (+) 3 newCombatant = Combatant name joinCombat Nothing 0 False updatedCombatants = Dict.insert name newCombatant model.combatants in update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] Save -> model ! [ exportModel model |> saveState ] NewCombat -> update Save emptyModel StartNewRound -> let updatedCombatants = Dict.values model.combatants |> List.map decrementCrash |> List.map (\c -> { c | turnFinished = False }) |> List.map (\c -> ( c.name, c )) |> Dict.fromList in update Save { model | combatants = updatedCombatants , round = model.round + 1 , popUp = Closed } ModifyInitiative modifyBy -> case model.popUp of EditInitiative combatant initiativeString -> { model | popUp = EditInitiative combatant (String.toInt initiativeString |> Result.withDefault 0 |> (+) modifyBy |> toString ) } ! [] _ -> { model | popUp = Closed } ! [] SetInitiative initiativeString -> case model.popUp of EditInitiative combatant _ -> { model | popUp = EditInitiative combatant initiativeString } ! [] _ -> { model | popUp = Closed } ! [] ApplyNewInitiative -> case model.popUp of EditInitiative combatant newInitiativeStr -> case String.toInt newInitiativeStr of Ok newInitiative -> update Save { model | popUp = Closed , combatants = Dict.insert combatant.name { combatant | initiative = newInitiative } model.combatants } Err _ -> { model | popUp = Closed } ! [] _ -> { model | popUp = Closed } ! [] SetWitheringTarget defender -> case model.popUp of WitheringAttack attacker _ _ _ -> { model | popUp = WitheringAttack attacker (Just defender) (Just "0") Nothing } ! [] _ -> { model | popUp = Closed } ! [] SetWitheringDamage damage -> case model.popUp of WitheringAttack attacker (Just defender) (Just _) _ -> { model | popUp = WitheringAttack attacker (Just defender) (Just damage) Nothing } ! [] _ -> { model | popUp = Closed } ! [] ResolveWitheringDamage -> case model.popUp of WitheringAttack attacker (Just defender) (Just damage) Nothing -> let ( uAttacker, uDefender, shift ) = resolveWithering attacker defender damage updatedCombatants = Dict.insert attacker.name uAttacker model.combatants |> Dict.insert defender.name uDefender in case shift of Shifted _ -> { model | popUp = WitheringAttack uAttacker (Just uDefender) (Just damage) (Just shift) } ! [] NoShift -> update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] SetShiftJoinCombat shiftJoinCombat -> case model.popUp of WitheringAttack a (Just d) (Just dam) (Just (Shifted _)) -> { model | popUp = WitheringAttack a (Just d) (Just dam) (Just (Shifted shiftJoinCombat)) } ! [] _ -> { model | popUp = Closed } ! [] ResolveInitiativeShift -> case model.popUp of WitheringAttack att (Just def) (Just dam) (Just (Shifted jc)) -> let joinCombat = String.toInt jc |> Result.withDefault 0 shiftInitiative = 3 + joinCombat attacker = { att | initiative = if shiftInitiative > att.initiative then shiftInitiative else att.initiative } updatedCombatants = Dict.insert attacker.name attacker model.combatants |> Dict.insert def.name def in update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] ResolveDecisive decisiveOutcome -> case model.popUp of DecisiveAttack combatant -> let attacker = resolveDecisive decisiveOutcome combatant updatedCombatants = Dict.insert attacker.name attacker model.combatants in update Save { model | popUp = Closed , combatants = updatedCombatants } _ -> { model | popUp = Closed } ! [] ModifyOnslaught modifyBy -> case model.popUp of EditOnslaught combatant onslaughtString -> { model | popUp = EditOnslaught combatant (String.toInt onslaughtString |> Result.withDefault 0 |> (+) modifyBy |> toString ) } ! [] _ -> { model | popUp = Closed } ! [] SetOnslaught onslaughtString -> case model.popUp of EditOnslaught combatant _ -> { model | popUp = EditOnslaught combatant onslaughtString } ! [] _ -> { model | popUp = Closed } ! [] ApplyNewOnslaught -> case model.popUp of EditOnslaught combatant newOnslaughtStr -> case String.toInt newOnslaughtStr of Ok newOnslaught -> update Save { model | popUp = Closed , combatants = Dict.insert combatant.name { combatant | onslaught = newOnslaught } model.combatants } Err _ -> { model | popUp = Closed } ! [] _ -> { model | popUp = Closed } ! [] EndTurn combatant -> let updatedCombatant = { combatant | turnFinished = True } updatedCombatants = Dict.insert updatedCombatant.name updatedCombatant model.combatants in update Save { model | combatants = updatedCombatants , popUp = Closed } ResolveDelete combatant -> let updatedCombatants = Dict.remove combatant.name model.combatants in update Save { model | combatants = updatedCombatants , popUp = Closed } sortByInitiative : Combatants -> Combatants sortByInitiative combatants = Dict.toList combatants |> List.sortBy (\( n, c ) -> c.initiative) |> List.reverse |> Dict.fromList decrementCrash : Combatant -> Combatant decrementCrash combatant = case combatant.crash of Just crash -> let updatedCrash = { crash | turnsUntilReset = crash.turnsUntilReset - 1 } in if updatedCrash.turnsUntilReset < 1 then { combatant | crash = Nothing , initiative = 3 } else { combatant | crash = Just updatedCrash } Nothing -> combatant resolveWithering : Combatant -> Combatant -> String -> ( Combatant, Combatant, Shift ) resolveWithering attacker defender damageStr = let damage = String.toInt damageStr |> Result.withDefault 0 defInitiative = defender.initiative - damage hasCrashed = if (defender.initiative > 0) && (defInitiative <= 0) then True else False updatedDefender = { defender | initiative = defInitiative , crash = if hasCrashed then Just (Crash attacker.name 3) else Nothing , onslaught = defender.onslaught + 1 } attInitiative = attacker.initiative + damage + 1 + (if hasCrashed then 5 else 0 ) shift = case attacker.crash of Just crash -> if hasCrashed && (crash.crasher == defender.name) then Shifted "0" else NoShift Nothing -> NoShift updatedAttacker = { attacker | initiative = attInitiative , onslaught = 0 , crash = if attInitiative > 0 then Nothing else attacker.crash , turnFinished = True } in ( updatedAttacker, updatedDefender, shift ) resolveDecisive : AttackOutcome -> Combatant -> Combatant resolveDecisive outcome combatant = case outcome of Hit -> { combatant | initiative = 3 } Miss -> { combatant | initiative = if combatant.initiative < 11 then combatant.initiative - 2 else combatant.initiative - 3 , onslaught = 0 , turnFinished = True } -- Ports port saveState : ExportedModel -> Cmd msg -- Subscriptions subscriptions : Model -> Sub msg subscriptions model = Sub.none -- Views view : Model -> Html Msg view model = div [ css [ defaultStyle ] ] [ header [ css [ headerStyle, rowFlexStyle ] ] [ div [] [ h1 [ css [ h1Style ] ] [ text "Threads of Martial Destiny" ] , b [] [ text "A combat tracker for Exalted 3rd Edition" ] ] , div [] [ img [ css [ iconStyle True ] , src "imgs/add.svg" , NewCombatant "" "0" |> OpenPopUp |> onClick , title "Add Combatant" ] [ text "Add Combatant" ] , img [ css [ iconStyle True ] , src "imgs/help.svg" , onClick <| OpenPopUp <| Help , title "Help" ] [ text "Help" ] , img [ css [ iconStyle True ] , src "imgs/new-combat.svg" , onClick <| OpenPopUp <| Confirm "New Combat" <| NewCombat , title "New Combat" ] [ text "New Combat" ] ] ] , div [ css [ bodyStyle ] ] ([ tracker model.round model.combatants ] ++ (case model.popUp of (NewCombatant _ _) as newCombatant -> [ newCombatantPopUp newCombatant ] (EditInitiative _ _) as editInitiative -> [ editInitiativePopUp editInitiative ] (WitheringAttack _ _ _ _) as witheringAttack -> [ witheringPopUp model.combatants witheringAttack ] (DecisiveAttack _) as decisiveAttack -> [ decisivePopUp decisiveAttack ] (EditOnslaught _ _) as editOnslaught -> [ editOnslaughtPopUp editOnslaught ] (Confirm _ _) as confirm -> [ confirmPopUp confirm ] Help -> [ helpPopUp ] Closed -> [] ) ) , footer [ css [ footerStyle ] ] [ text ("© PI:NAME:<NAME>END_PI, 2018. Version 1.1.0. " ++ "Exalted is © White Wolf AB and Onyx Path. " ) , a [ href "https://github.com/ChrisWellsWood/martial-destiny" ] [ text "Source code." ] , br [] [] , text "Icons made by " , a [ href "https://www.flaticon.com/authors/appzgear" , title "Appzgear" ] [ text "Appzgear" ] , text ", " , a [ href "https://www.flaticon.com/authors/dave-gandy" , title "PI:NAME:<NAME>END_PI" ] [ text "PI:NAME:<NAME>END_PI" ] , text ", " , a [ href "https://www.flaticon.com/authors/eleonor-wang" , title "PI:NAME:<NAME>END_PI" ] [ text "PI:NAME:<NAME>END_PI" ] , text ", " , a [ href "http://www.freepik.com" , title "Freepik" ] [ text "Freepik" ] , text " and " , a [ href "https://www.flaticon.com/authors/pixel-perfect" , title "Pixel perfect" ] [ text "Pixel perfect" ] , text " from " , a [ href "https://www.flaticon.com/" , title "Flaticon" ] [ text "www.flaticon.com" ] , text " and are licensed by " , a [ href "http://creativecommons.org/licenses/by/3.0/" , title "Creative Commons BY 3.0" , Html.Styled.Attributes.target "_blank" ] [ text "CC 3.0 BY." ] ] ] tracker : Int -> Combatants -> Html Msg tracker round combatants = let readyCombatants = Dict.values combatants |> List.filter (not << .turnFinished) |> List.sortBy .initiative |> List.reverse turnFinishedCombatants = Dict.values combatants |> List.filter .turnFinished |> List.sortBy .initiative |> List.reverse in div [] (if Dict.size combatants > 0 then [ div [ css [ turnStyle, rowFlexStyle ] ] [ h2 [ css [ h2Style ] ] [ text <| "Round " ++ (toString round) ] , img [ css [ iconStyle True ] , onClick <| OpenPopUp <| Confirm "End Round" <| StartNewRound , src "imgs/end-round.svg" , title "Next Round" ] [ text "Next Round" ] ] , h2 [ css [ h2Style ] ] [ text "Ready" ] , div [ css [ trackerStyling ] ] (List.map (combatantCard <| Dict.size combatants) readyCombatants ) , styledHR [] [] , h2 [ css [ h2Style ] ] [ text "Turn Finished" ] , div [ css [ trackerStyling ] ] (List.map (combatantCard <| Dict.size combatants) turnFinishedCombatants ) ] else [] ) combatantCard : Int -> Combatant -> Html Msg combatantCard numCombatants combatant = let { name, initiative, onslaught, turnFinished } = combatant attacksActive = if numCombatants < 2 then False else True colour = if initiative < 1 then colourPallette.crash else if initiative < 11 then colourPallette.lowInitiative else colourPallette.highInitiative in div [ css [ combatantCardStyle colour ] ] [ b [] [ text name ] , styledHR [] [] , div [ css [ rowFlexStyle , initiativeStyle ] ] [ (toString initiative) ++ "i" |> text , img [ src "imgs/edit.svg" , css [ iconStyle True ] , onClick <| OpenPopUp <| EditInitiative combatant (toString initiative) , title "Edit Initiative" ] [] ] , styledHR [] [] , div [] ([ text ("Onslaught: " ++ (toString combatant.onslaught)) ] ++ case combatant.crash of Just crash -> [ br [] [] , text ("Crash: " ++ (toString crash.turnsUntilReset) ) ] Nothing -> [] ) , styledHR [] [] , div [ css [ rowFlexStyle ] ] [ img ([ css [ iconStyle attacksActive ] , src "imgs/withered-flower.svg" , title "Withering Attack" ] ++ if attacksActive then [ onClick <| OpenPopUp <| WitheringAttack combatant Nothing Nothing Nothing ] else [] ) [ text "Withering" ] , img [ css [ iconStyle attacksActive ] , onClick <| OpenPopUp <| DecisiveAttack combatant , src "imgs/sword.svg" , title "Decisive Attack" ] [ text "Decisive" ] , img [ src "imgs/reset.svg" , css [ iconStyle True ] , onClick <| OpenPopUp <| EditOnslaught combatant (toString onslaught) , title "Edit Onslaught" ] [] , img [ css [ iconStyle True ] , onClick <| OpenPopUp <| Confirm "End Turn" <| EndTurn combatant , src "imgs/end-turn.svg" , title "End Turn" ] [ text "End Turn" ] , img [ css [ iconStyle True ] , onClick <| OpenPopUp <| Confirm "Delete Combatant" <| ResolveDelete combatant , src "imgs/delete.svg" , title "Delete Combatant" ] [ text "Delete Combatant" ] ] ] newCombatantPopUp : PopUp -> Html Msg newCombatantPopUp newCombatant = div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case newCombatant of NewCombatant name joinCombatStr -> let addDisabled = case String.toInt joinCombatStr of Ok joinCombat -> case name of "" -> True _ -> False Err _ -> True in [ b [] [ text "Add New Combatant" ] , br [] [] , text "Name" , br [] [] , styledInput [ id "pop-up-focus", onInput SetCombatantName ] [] , br [] [] , text "Join Combat Successes" , br [] [] , styledInput [ onInput SetJoinCombat , size 3 , value joinCombatStr ] [] , styledHR [] [] , styledButton [ onClick AddNewCombatant , Html.Styled.Attributes.disabled addDisabled ] [ text "Add" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] editInitiativePopUp : PopUp -> Html Msg editInitiativePopUp editInitiative = let modifyInitiativeBtn modifyBy = styledButton [ onClick <| ModifyInitiative modifyBy ] [ text <| toString modifyBy ] in div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case editInitiative of EditInitiative combatant newInitiative -> let resolveDisabled = case String.toInt newInitiative of Ok _ -> False Err _ -> True in [ b [] [ text "Edit Initiative" ] , br [] [] , modifyInitiativeBtn -5 , modifyInitiativeBtn -1 , styledInput [ id "pop-up-focus" , onInput SetInitiative , value newInitiative , size 3 ] [] , modifyInitiativeBtn 1 , modifyInitiativeBtn 5 , styledHR [] [] , styledButton [ onClick <| ApplyNewInitiative , Html.Styled.Attributes.disabled resolveDisabled , title "Edit" ] [ text "Ok" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] disablingDiv : Html msg disablingDiv = div [ css [ disablingStyle ] ] [] witheringPopUp : Combatants -> PopUp -> Html Msg witheringPopUp combatants popUp = let selectTarget combatant = div [ css [ selectStyle ] , onClick <| SetWitheringTarget combatant ] [ text combatant.name ] in div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case popUp of WitheringAttack attacker Nothing Nothing _ -> [ b [] [ text "Select Target" ] ] ++ (Dict.toList combatants |> List.filter (\( n, c ) -> n /= attacker.name) |> List.map Tuple.second |> List.map selectTarget ) ++ [ styledHR [] [] ] WitheringAttack attacker (Just defender) (Just damageStr) Nothing -> let resolveDisabled = case String.toInt damageStr of Ok damage -> False Err _ -> True in [ b [] [ text "Set Post-Soak Damage" ] , br [] [] , attacker.name ++ " vs " ++ defender.name |> text , br [] [] , styledInput [ onInput SetWitheringDamage , value <| damageStr , size 3 ] [] , styledHR [] [] , styledButton [ onClick ResolveWitheringDamage , Html.Styled.Attributes.disabled resolveDisabled ] [ text "Resolve" ] ] WitheringAttack _ _ _ (Just (Shifted joinCombatStr)) -> let resolveDisabled = case String.toInt joinCombatStr of Ok joinCombat -> False Err _ -> True in [ b [] [ text "Initiative Shift!" ] , br [] [] , text "Join Combat Result" , br [] [] , styledInput [ onInput SetShiftJoinCombat ] [] , styledHR [] [] , styledButton [ onClick ResolveInitiativeShift , Html.Styled.Attributes.disabled resolveDisabled ] [ text "Resolve" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] decisivePopUp : PopUp -> Html Msg decisivePopUp popUp = div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case popUp of DecisiveAttack combatant -> [ b [] [ text "Decisive Attack" ] , br [] [] , styledButton [ onClick <| ResolveDecisive Hit ] [ text "Hit" ] , styledButton [ onClick <| ResolveDecisive Miss ] [ text "Miss" ] , styledHR [] [] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] editOnslaughtPopUp : PopUp -> Html Msg editOnslaughtPopUp editOnslaught = let modifyOnslaughtBtn modifyBy = styledButton [ onClick <| ModifyOnslaught modifyBy ] [ text <| toString modifyBy ] in div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case editOnslaught of EditOnslaught combatant newOnslaught -> let resolveDisabled = case String.toInt newOnslaught of Ok _ -> False Err _ -> True in [ b [] [ text "Edit Onslaught" ] , br [] [] , modifyOnslaughtBtn -5 , modifyOnslaughtBtn -1 , styledInput [ id "pop-up-focus" , onInput SetOnslaught , value newOnslaught , size 3 ] [] , modifyOnslaughtBtn 1 , modifyOnslaughtBtn 5 , styledHR [] [] , styledButton [ onClick <| ApplyNewOnslaught , Html.Styled.Attributes.disabled resolveDisabled , title "Edit" ] [ text "Ok" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] confirmPopUp : PopUp -> Html Msg confirmPopUp popUp = div [] [ disablingDiv , div [ css [ popUpStyle ] ] ((case popUp of Confirm description msg -> [ b [] [ text description ] , br [] [] , text "Are you sure?" , styledHR [] [] , styledButton [ onClick <| msg ] [ text "Ok" ] ] _ -> [] ) ++ [ styledButton [ onClick ClosePopUp ] [ text "Cancel" ] ] ) ] helpPopUp : Html Msg helpPopUp = div [] [ disablingDiv , div [ css [ popUpStyle , Css.maxHeight (pct 80) , Css.width (pct 80) , overflow auto ] ] [ text "Welcome to Threads of Martial Destiny, a combat tracker for " , a [ href "http://theonyxpath.com/category/worlds/exalted/" ] [ text "Exalted 3rd Edition" ] , ". The app saves its state regularly so don't worry if you " ++ "close or refresh the tab, you can pick up where you left " ++ "off. Here's a list of the buttons and what a description of " ++ "what they do:" |> text , Html.Styled.table [] [ iconDescription "imgs/add.svg" "Adds a new combatant to the combat." , iconDescription "imgs/new-combat.svg" "Starts a new combat deleting the current session." , iconDescription "imgs/end-round.svg" ("Ends the current round of combat, indicating that all " ++ "combatants have made taken actions." ) , iconDescription "imgs/edit.svg" "Edits the combatants initiative value." , iconDescription "imgs/withered-flower.svg" "Initiates a withering attack (the icon is a withered flower)." , iconDescription "imgs/sword.svg" "Initiates a decisive attack." , iconDescription "imgs/reset.svg" "Edits the combatants onslaught value." , iconDescription "imgs/end-turn.svg" ("Ends the combatants turn, indicating that they have taken " ++ "all their actions." ) , iconDescription "imgs/delete.svg" "Deletes the combatant." ] , "If you find any bugs or have any feature requests please add " ++ "an issue on " |> text , a [ href "https://github.com/ChrisWellsWood/martial-destiny/issues" ] [ text "GitHub" ] , text " or, even better, send me a pull request!" , styledHR [] [] , styledButton [ onClick ClosePopUp ] [ text "Close" ] ] ] iconDescription : String -> String -> Html msg iconDescription iconPath description = tr [] [ td [] [ img [ css [ iconStyle True ] , src iconPath ] [] ] , td [] [ text description ] ] -- Styles type alias Colour = Color type alias ColourPallette = { lowInitiative : Colour , highInitiative : Colour , crash : Colour , turnFinished : Colour , clicked : Colour , backgroundColor : Colour } -- https://coolors.co/91d696-b4d174-edc855-e49f64-d96969 colourPallette : ColourPallette colourPallette = { highInitiative = hex "91d696" , lowInitiative = hex "edc855" , crash = hex "d96969" , turnFinished = hex "999999" , clicked = hex "777777" , backgroundColor = hex "eeeeee" } defaultStyle : Style defaultStyle = Css.batch [ displayFlex , flexDirection column , fontFamilies [ "Tahoma", "Geneva", "sans-serif" ] , fontSize (px 18) , Css.height (pct 100) , justifyContent spaceBetween , Css.width (pct 100) , position absolute , top (px 0) , left (px 0) ] styledHR : List (Attribute msg) -> List (Html msg) -> Html msg styledHR = styled hr [ borderWidth (px 1) , borderStyle solid , borderColor <| hex "000000" , marginLeft (px 0) , marginRight (px 0) ] styledInput : List (Attribute msg) -> List (Html msg) -> Html msg styledInput = styled input [ borderWidth (px 2) , borderStyle solid , borderColor <| hex "000000" , fontSize (px 18) , margin (px 3) , padding (px 3) ] styledButton : List (Attribute msg) -> List (Html msg) -> Html msg styledButton = styled button [ backgroundColor colourPallette.turnFinished , Css.active [ backgroundColor colourPallette.clicked ] , Css.disabled [ backgroundColor colourPallette.backgroundColor ] , borderWidth (px 2) , borderStyle solid , borderColor <| hex "000000" , color <| hex "000000" , fontSize (px 18) , margin (px 3) , outline none , padding (px 3) ] headerStyle : Style headerStyle = Css.batch [ backgroundColor colourPallette.crash , padding (px 8) , Css.width auto , borderWidth4 (px 0) (px 0) (px 2) (px 0) , borderStyle solid , borderColor <| hex "000000" ] turnStyle : Style turnStyle = Css.batch [ backgroundColor colourPallette.highInitiative , padding (px 8) , Css.width auto , borderWidth4 (px 0) (px 0) (px 2) (px 0) , borderStyle solid , borderColor <| hex "000000" , margin4 (px 0) (px 0) (px 4) (px 0) ] rowFlexStyle : Style rowFlexStyle = Css.batch [ displayFlex , position relative , justifyContent spaceBetween , alignItems center ] h1Style : Style h1Style = Css.batch [ padding (px 0) , margin (px 0) ] h2Style : Style h2Style = Css.batch [ padding (px 0) , margin (px 0) , textAlign center ] bodyStyle : Style bodyStyle = Css.batch [ backgroundColor colourPallette.backgroundColor , Css.width (pct 100) , Css.height (pct 100) , overflow auto ] footerStyle : Style footerStyle = Css.batch [ borderWidth4 (px 2) (px 0) (px 0) (px 0) , borderStyle solid , borderColor <| hex "000000" , Css.width (pct 100) , fontSize (px 12) , color <| hex "aaaaaa" , padding (px 5) ] iconStyle : Bool -> Style iconStyle active = Css.batch ([ Css.height (px 24) , padding (px 3) , margin (px 3) , Css.width (px 24) , borderStyle solid , borderWidth (px 2) ] ++ if active then [ backgroundColor colourPallette.turnFinished , Css.active [ backgroundColor colourPallette.clicked ] ] else [ backgroundColor colourPallette.backgroundColor ] ) trackerStyling : Style trackerStyling = Css.batch [ displayFlex , flexWrap Css.wrap , justifyContent center ] combatantCardStyle : Colour -> Style combatantCardStyle bgColour = Css.batch [ backgroundColor bgColour , borderStyle solid , borderWidth (px 2) , Css.width (px 200) , overflow Css.hidden , overflowWrap normal , padding (px 8) , margin4 (px 2) (px 0) (px 2) (px 2) , displayFlex , flexDirection column , justifyContent spaceBetween ] initiativeStyle : Style initiativeStyle = Css.batch [ fontSize (px 36) , position relative ] disablingStyle : Style disablingStyle = Css.batch [ zIndex (int 1000) , position absolute , top (pct 0) , left (pct 0) , Css.width (pct 100) , Css.height (pct 100) , backgroundColor <| hex "dddddd" , opacity (num 0.5) ] selectStyle : Style selectStyle = Css.batch [ margin (px 3) , textAlign center , Css.hover [ backgroundColor colourPallette.turnFinished ] ] popUpStyle : Style popUpStyle = Css.batch [ backgroundColor colourPallette.lowInitiative , borderStyle solid , borderWidth (px 2) , left (pct 50) , padding (px 5) , position absolute , top (pct 50) , transform (translate2 (pct -50) (pct -50)) , Css.width (px 300) , zIndex (int 1001) ]
elm
[ { "context": "DateMonth, birthDateYear, none, phone, email, fax, firstName, gender, lastName, mobilePhone, edit, editAccount", "end": 146, "score": 0.9970712662, "start": 137, "tag": "NAME", "value": "firstName" }, { "context": "birthDateYear, none, phone, email, fax, firstName, gender, lastName, mobilePhone, edit, editAccountLink, ti", "end": 154, "score": 0.9527924657, "start": 148, "tag": "NAME", "value": "gender" }, { "context": "eYear, none, phone, email, fax, firstName, gender, lastName, mobilePhone, edit, editAccountLink, title, chang", "end": 164, "score": 0.9969263673, "start": 156, "tag": "NAME", "value": "lastName" }, { "context": "DateMonth, birthDateYear, none, phone, email, fax, firstName, gender, lastName, mobilePhone, edit, editAccount", "end": 400, "score": 0.9970619082, "start": 391, "tag": "NAME", "value": "firstName" }, { "context": "eYear, none, phone, email, fax, firstName, gender, lastName, mobilePhone, edit, editAccountLink, title, chang", "end": 418, "score": 0.8556818366, "start": 410, "tag": "NAME", "value": "lastName" }, { "context": "lAttribute msg =\n { avatar : Maybe String\n , firstName : Maybe String\n , lastName : Maybe String\n ", "end": 1230, "score": 0.6773833036, "start": 1221, "tag": "NAME", "value": "firstName" }, { "context": " msg\nemptyAttribute =\n { avatar = Nothing\n , firstName = Nothing\n , lastName = Nothing\n , title = ", "end": 1964, "score": 0.8820756674, "start": 1955, "tag": "NAME", "value": "firstName" } ]
src/Engage/Form/Profile.elm
EngageSoftware/elm-engage-common
0
module Engage.Form.Profile exposing ( view , address, avatar, birthDate, birthDateMonth, birthDateYear, none, phone, email, fax, firstName, gender, lastName, mobilePhone, edit, editAccountLink, title, changePassword , Attribute ) {-| Form.Profile # View @docs view # Attributes @docs address, avatar, birthDate, birthDateMonth, birthDateYear, none, phone, email, fax, firstName, gender, lastName, mobilePhone, edit, editAccountLink, title, changePassword #Types @docs Attribute -} import Date exposing (Date) import Engage.CssHelpers import Engage.Entity.Address exposing (Address, Countries, RegionsCountry) import Engage.Entity.Gender as Gender exposing (Gender) import Engage.Form.Address import Engage.Form.FormAction as FormAction import Engage.ListItem exposing (ListItem) import Engage.Localization as Localization exposing (Localization) import Engage.Namespace as Namespace exposing (Namespace) import Engage.UI.Attribute as Attribute import Engage.UI.Button as Button import Engage.UI.Info as Info import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onClick) import String type alias InternalAttribute msg = { avatar : Maybe String , firstName : Maybe String , lastName : Maybe String , title : Maybe String , email : Maybe ( String, String ) , phone : Maybe ( String, String ) , mobilePhone : Maybe ( String, String ) , fax : Maybe ( String, String ) , edit : Maybe ( String, msg ) , address : Maybe ( String, Address ) , gender : Maybe ( String, Gender ) , birthDate : Maybe ( String, Maybe Date ) , isDayFirst : Maybe Bool , birthDateYear : Maybe ( String, Maybe ListItem ) , birthDateMonth : Maybe ( String, Maybe ListItem ) , editAccountLink : Maybe ( String, String ) , changePassword : Maybe ( String, msg ) } emptyAttribute : InternalAttribute msg emptyAttribute = { avatar = Nothing , firstName = Nothing , lastName = Nothing , title = Nothing , email = Nothing , phone = Nothing , mobilePhone = Nothing , fax = Nothing , edit = Nothing , address = Nothing , gender = Nothing , birthDate = Nothing , isDayFirst = Nothing , birthDateYear = Nothing , birthDateMonth = Nothing , editAccountLink = Nothing , changePassword = Nothing } {-| The Attribute type -} type alias Attribute msg = InternalAttribute msg -> InternalAttribute msg {-| Get the none Attribute -} none : Attribute msg none = \attribute -> attribute {-| Get the first name Attribute -} firstName : String -> Attribute msg firstName text = \attribute -> { attribute | firstName = Just text } {-| Get the title Attribute -} title : String -> Attribute msg title text = \attribute -> { attribute | title = Just text } {-| Get the address Attribute -} address : String -> Address -> Attribute msg address label addressData = \attribute -> { attribute | address = Just ( label, addressData ) } {-| Get the last name Attribute -} lastName : String -> Attribute msg lastName text = \attribute -> { attribute | lastName = Just text } {-| Get the avatar Attribute -} avatar : String -> Attribute msg avatar text = \attribute -> { attribute | avatar = Just text } {-| Get the email Attribute -} email : String -> String -> Attribute msg email label text = \attribute -> { attribute | email = Just ( label, text ) } {-| Get the phone Attribute -} phone : String -> String -> Attribute msg phone label text = \attribute -> { attribute | phone = Just ( label, text ) } {-| Get the mobile phone Attribute -} mobilePhone : String -> String -> Attribute msg mobilePhone label text = \attribute -> { attribute | mobilePhone = Just ( label, text ) } {-| Get the fax Attribute -} fax : String -> String -> Attribute msg fax label text = \attribute -> { attribute | fax = Just ( label, text ) } {-| Get the gender Attribute -} gender : String -> Gender -> Attribute msg gender label value = \attribute -> { attribute | gender = Just ( label, value ) } {-| Get the birth date Attribute -} birthDate : String -> Maybe Date -> Bool -> Attribute msg birthDate label date isDayFirst = \attribute -> { attribute | birthDate = Just ( label, date ), isDayFirst = Just isDayFirst } {-| Get the birth date year Attribute -} birthDateYear : String -> Maybe ListItem -> Attribute msg birthDateYear label item = \attribute -> { attribute | birthDateYear = Just ( label, item ) } {-| Get the birth date month Attribute -} birthDateMonth : String -> Maybe ListItem -> Attribute msg birthDateMonth label item = \attribute -> { attribute | birthDateMonth = Just ( label, item ) } {-| Get the edit Attribute -} edit : String -> msg -> Attribute msg edit text msg = \attribute -> { attribute | edit = Just ( text, msg ) } {-| Get the change password Attribute -} changePassword : String -> msg -> Attribute msg changePassword text msg = \attribute -> { attribute | changePassword = Just ( text, msg ) } {-| Get the edit account link Attribute -} editAccountLink : String -> String -> Attribute msg editAccountLink text value = \attribute -> { attribute | editAccountLink = Just ( text, value ) } {-| Get the view -} view : { args | namespace : Namespace, localization : Localization, countries : Countries, regions : RegionsCountry } -> List (Attribute msg) -> List (Html msg) -> Html msg view ({ namespace, localization } as args) attributes additionalContents = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace attribute = Attribute.process emptyAttribute attributes in div [ class [ "Profile" ] ] [ avatarView namespace attribute , div [ class [ "ProfileInfo" ] ] [ div [ class [ "ProfileHeader" ] ] [ nameView namespace attribute , titleView namespace attribute , emailView namespace attribute , phoneView namespace attribute , mobilePhoneView namespace attribute , faxView namespace attribute ] , div [ class [ "ProfileBody" ] ] ([ genderView namespace attribute , birthDateView namespace localization attribute , birthDateMonthView namespace attribute , birthDateYearView namespace attribute , addressView args attribute ] ++ additionalContents ) , actionView namespace attribute ] ] genderView : Namespace -> InternalAttribute msg -> Html msg genderView namespace attribute = let do label genderValue = if String.isEmpty genderValue then text "" else Info.multiple namespace (Info.getLabel label) [ text genderValue ] in attribute.gender |> Maybe.map (\( label, genderValue ) -> do label (Gender.toString genderValue)) |> Maybe.withDefault (text "") birthDateView : Namespace -> Localization -> InternalAttribute msg -> Html msg birthDateView namespace localization attribute = let defaultDateFormat = Localization.localizeStringWithDefault "MMMM d, yyyy" "BirthDateFormat" { localization = localization } dateFormat = case attribute.isDayFirst of Just isDayFirst -> if isDayFirst then "dd/MM/yyyy" else defaultDateFormat _ -> defaultDateFormat do label maybeDate = case maybeDate of Nothing -> text "" Just date -> Info.multiple namespace (Info.getLabel label) [ text (Date.format dateFormat date) ] in attribute.birthDate |> Maybe.map (\( label, date ) -> do label date) |> Maybe.withDefault (text "") birthDateYearView : Namespace -> InternalAttribute msg -> Html msg birthDateYearView namespace attribute = let do label maybeItem = case maybeItem of Nothing -> text "" Just item -> Info.multiple namespace (Info.getLabel label) [ text (String.fromInt (Tuple.first item)) ] in attribute.birthDateYear |> Maybe.map (\( label, item ) -> do label item) |> Maybe.withDefault (text "") birthDateMonthView : Namespace -> InternalAttribute msg -> Html msg birthDateMonthView namespace attribute = let do label maybeItem = case maybeItem of Nothing -> text "" Just item -> Info.multiple namespace (Info.getLabel label) [ text (String.fromInt (Tuple.first item)) ] in attribute.birthDateMonth |> Maybe.map (\( label, item ) -> do label item) |> Maybe.withDefault (text "") nameView : Namespace -> InternalAttribute msg -> Html msg nameView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace firstNameValue = attribute.firstName |> Maybe.withDefault "" lastNameValue = attribute.lastName |> Maybe.withDefault "" name = firstNameValue ++ " " ++ lastNameValue in if name |> String.trim |> String.isEmpty then text "" else h3 [ class [ "ProfileName" ] ] [ text name ] titleView : Namespace -> InternalAttribute msg -> Html msg titleView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.title |> Maybe.map (\newTitle -> div [ class [ "ProfileTitle" ] ] [ text newTitle ]) |> Maybe.withDefault (text "") addressView : { args | namespace : Namespace, localization : Localization, countries : Countries, regions : RegionsCountry } -> InternalAttribute msg -> Html msg addressView ({ namespace } as args) attribute = let isEmpty = Engage.Form.Address.isEmpty do label addressValue = if isEmpty addressValue then text "" else Info.multiple namespace (Info.getLabel label) [ Engage.Form.Address.view args addressValue ] in attribute.address |> Maybe.map (\( label, addressValue ) -> do label addressValue) |> Maybe.withDefault (text "") avatarView : Namespace -> InternalAttribute msg -> Html msg avatarView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.avatar |> Maybe.map (\avatarValue -> div [ class (if String.isEmpty avatarValue then [ "ProfileNoAvatar", "ProfileAvatar" ] else [ "ProfileAvatar" ] ) ] [ img [ src (if String.isEmpty avatarValue then "/DesktopModules/EngageCore.Participant/images/noprofile.png" else avatarValue ) ] [] ] ) |> Maybe.withDefault (text "") emailView : Namespace -> InternalAttribute msg -> Html msg emailView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.email |> Maybe.map (\( label, emailValue ) -> div [ class [ "ProfileEmail" ] ] [ Info.email namespace (Info.getLabel label) emailValue ]) |> Maybe.withDefault (text "") phoneView : Namespace -> InternalAttribute msg -> Html msg phoneView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.phone |> Maybe.map (\( label, phoneValue ) -> div [ class [ "ProfilePhone" ] ] [ Info.phone namespace (Info.getLabel label) phoneValue ]) |> Maybe.withDefault (text "") mobilePhoneView : Namespace -> InternalAttribute msg -> Html msg mobilePhoneView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.mobilePhone |> Maybe.map (\( label, mobilePhoneValue ) -> div [ class [ "ProfileCellphone" ] ] [ Info.mobilePhone namespace (Info.getLabel label) mobilePhoneValue ]) |> Maybe.withDefault (text "") faxView : Namespace -> InternalAttribute msg -> Html msg faxView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.fax |> Maybe.map (\( label, faxValue ) -> div [ class [ "ProfileFax" ] ] [ Info.fax namespace (Info.getLabel label) faxValue ]) |> Maybe.withDefault (text "") actionView : Namespace -> InternalAttribute msg -> Html msg actionView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in FormAction.formAction namespace [ attribute.edit |> Maybe.map (\( text, msg ) -> div [ class [ "ProfileEditButton" ] ] [ Button.primarySmall { namespace = namespace , attributes = [ onClick msg ] , text = text } ] ) |> Maybe.withDefault (text "") , attribute.changePassword |> Maybe.map (\( text, msg ) -> div [ class [ "ProfileChangePasswordButton" ] ] [ Button.primarySmall { namespace = namespace , attributes = [ onClick msg ] , text = text } ] ) |> Maybe.withDefault (text "") , attribute.editAccountLink |> Maybe.map (\( text, url ) -> div [ class [ "ProfileEditAccountLink" ] ] [ a [ href url, Html.Attributes.attribute "class" "dialog-link" ] [ Html.text text ] ] ) |> Maybe.withDefault (text "") ] []
61300
module Engage.Form.Profile exposing ( view , address, avatar, birthDate, birthDateMonth, birthDateYear, none, phone, email, fax, <NAME>, <NAME>, <NAME>, mobilePhone, edit, editAccountLink, title, changePassword , Attribute ) {-| Form.Profile # View @docs view # Attributes @docs address, avatar, birthDate, birthDateMonth, birthDateYear, none, phone, email, fax, <NAME>, gender, <NAME>, mobilePhone, edit, editAccountLink, title, changePassword #Types @docs Attribute -} import Date exposing (Date) import Engage.CssHelpers import Engage.Entity.Address exposing (Address, Countries, RegionsCountry) import Engage.Entity.Gender as Gender exposing (Gender) import Engage.Form.Address import Engage.Form.FormAction as FormAction import Engage.ListItem exposing (ListItem) import Engage.Localization as Localization exposing (Localization) import Engage.Namespace as Namespace exposing (Namespace) import Engage.UI.Attribute as Attribute import Engage.UI.Button as Button import Engage.UI.Info as Info import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onClick) import String type alias InternalAttribute msg = { avatar : Maybe String , <NAME> : Maybe String , lastName : Maybe String , title : Maybe String , email : Maybe ( String, String ) , phone : Maybe ( String, String ) , mobilePhone : Maybe ( String, String ) , fax : Maybe ( String, String ) , edit : Maybe ( String, msg ) , address : Maybe ( String, Address ) , gender : Maybe ( String, Gender ) , birthDate : Maybe ( String, Maybe Date ) , isDayFirst : Maybe Bool , birthDateYear : Maybe ( String, Maybe ListItem ) , birthDateMonth : Maybe ( String, Maybe ListItem ) , editAccountLink : Maybe ( String, String ) , changePassword : Maybe ( String, msg ) } emptyAttribute : InternalAttribute msg emptyAttribute = { avatar = Nothing , <NAME> = Nothing , lastName = Nothing , title = Nothing , email = Nothing , phone = Nothing , mobilePhone = Nothing , fax = Nothing , edit = Nothing , address = Nothing , gender = Nothing , birthDate = Nothing , isDayFirst = Nothing , birthDateYear = Nothing , birthDateMonth = Nothing , editAccountLink = Nothing , changePassword = Nothing } {-| The Attribute type -} type alias Attribute msg = InternalAttribute msg -> InternalAttribute msg {-| Get the none Attribute -} none : Attribute msg none = \attribute -> attribute {-| Get the first name Attribute -} firstName : String -> Attribute msg firstName text = \attribute -> { attribute | firstName = Just text } {-| Get the title Attribute -} title : String -> Attribute msg title text = \attribute -> { attribute | title = Just text } {-| Get the address Attribute -} address : String -> Address -> Attribute msg address label addressData = \attribute -> { attribute | address = Just ( label, addressData ) } {-| Get the last name Attribute -} lastName : String -> Attribute msg lastName text = \attribute -> { attribute | lastName = Just text } {-| Get the avatar Attribute -} avatar : String -> Attribute msg avatar text = \attribute -> { attribute | avatar = Just text } {-| Get the email Attribute -} email : String -> String -> Attribute msg email label text = \attribute -> { attribute | email = Just ( label, text ) } {-| Get the phone Attribute -} phone : String -> String -> Attribute msg phone label text = \attribute -> { attribute | phone = Just ( label, text ) } {-| Get the mobile phone Attribute -} mobilePhone : String -> String -> Attribute msg mobilePhone label text = \attribute -> { attribute | mobilePhone = Just ( label, text ) } {-| Get the fax Attribute -} fax : String -> String -> Attribute msg fax label text = \attribute -> { attribute | fax = Just ( label, text ) } {-| Get the gender Attribute -} gender : String -> Gender -> Attribute msg gender label value = \attribute -> { attribute | gender = Just ( label, value ) } {-| Get the birth date Attribute -} birthDate : String -> Maybe Date -> Bool -> Attribute msg birthDate label date isDayFirst = \attribute -> { attribute | birthDate = Just ( label, date ), isDayFirst = Just isDayFirst } {-| Get the birth date year Attribute -} birthDateYear : String -> Maybe ListItem -> Attribute msg birthDateYear label item = \attribute -> { attribute | birthDateYear = Just ( label, item ) } {-| Get the birth date month Attribute -} birthDateMonth : String -> Maybe ListItem -> Attribute msg birthDateMonth label item = \attribute -> { attribute | birthDateMonth = Just ( label, item ) } {-| Get the edit Attribute -} edit : String -> msg -> Attribute msg edit text msg = \attribute -> { attribute | edit = Just ( text, msg ) } {-| Get the change password Attribute -} changePassword : String -> msg -> Attribute msg changePassword text msg = \attribute -> { attribute | changePassword = Just ( text, msg ) } {-| Get the edit account link Attribute -} editAccountLink : String -> String -> Attribute msg editAccountLink text value = \attribute -> { attribute | editAccountLink = Just ( text, value ) } {-| Get the view -} view : { args | namespace : Namespace, localization : Localization, countries : Countries, regions : RegionsCountry } -> List (Attribute msg) -> List (Html msg) -> Html msg view ({ namespace, localization } as args) attributes additionalContents = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace attribute = Attribute.process emptyAttribute attributes in div [ class [ "Profile" ] ] [ avatarView namespace attribute , div [ class [ "ProfileInfo" ] ] [ div [ class [ "ProfileHeader" ] ] [ nameView namespace attribute , titleView namespace attribute , emailView namespace attribute , phoneView namespace attribute , mobilePhoneView namespace attribute , faxView namespace attribute ] , div [ class [ "ProfileBody" ] ] ([ genderView namespace attribute , birthDateView namespace localization attribute , birthDateMonthView namespace attribute , birthDateYearView namespace attribute , addressView args attribute ] ++ additionalContents ) , actionView namespace attribute ] ] genderView : Namespace -> InternalAttribute msg -> Html msg genderView namespace attribute = let do label genderValue = if String.isEmpty genderValue then text "" else Info.multiple namespace (Info.getLabel label) [ text genderValue ] in attribute.gender |> Maybe.map (\( label, genderValue ) -> do label (Gender.toString genderValue)) |> Maybe.withDefault (text "") birthDateView : Namespace -> Localization -> InternalAttribute msg -> Html msg birthDateView namespace localization attribute = let defaultDateFormat = Localization.localizeStringWithDefault "MMMM d, yyyy" "BirthDateFormat" { localization = localization } dateFormat = case attribute.isDayFirst of Just isDayFirst -> if isDayFirst then "dd/MM/yyyy" else defaultDateFormat _ -> defaultDateFormat do label maybeDate = case maybeDate of Nothing -> text "" Just date -> Info.multiple namespace (Info.getLabel label) [ text (Date.format dateFormat date) ] in attribute.birthDate |> Maybe.map (\( label, date ) -> do label date) |> Maybe.withDefault (text "") birthDateYearView : Namespace -> InternalAttribute msg -> Html msg birthDateYearView namespace attribute = let do label maybeItem = case maybeItem of Nothing -> text "" Just item -> Info.multiple namespace (Info.getLabel label) [ text (String.fromInt (Tuple.first item)) ] in attribute.birthDateYear |> Maybe.map (\( label, item ) -> do label item) |> Maybe.withDefault (text "") birthDateMonthView : Namespace -> InternalAttribute msg -> Html msg birthDateMonthView namespace attribute = let do label maybeItem = case maybeItem of Nothing -> text "" Just item -> Info.multiple namespace (Info.getLabel label) [ text (String.fromInt (Tuple.first item)) ] in attribute.birthDateMonth |> Maybe.map (\( label, item ) -> do label item) |> Maybe.withDefault (text "") nameView : Namespace -> InternalAttribute msg -> Html msg nameView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace firstNameValue = attribute.firstName |> Maybe.withDefault "" lastNameValue = attribute.lastName |> Maybe.withDefault "" name = firstNameValue ++ " " ++ lastNameValue in if name |> String.trim |> String.isEmpty then text "" else h3 [ class [ "ProfileName" ] ] [ text name ] titleView : Namespace -> InternalAttribute msg -> Html msg titleView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.title |> Maybe.map (\newTitle -> div [ class [ "ProfileTitle" ] ] [ text newTitle ]) |> Maybe.withDefault (text "") addressView : { args | namespace : Namespace, localization : Localization, countries : Countries, regions : RegionsCountry } -> InternalAttribute msg -> Html msg addressView ({ namespace } as args) attribute = let isEmpty = Engage.Form.Address.isEmpty do label addressValue = if isEmpty addressValue then text "" else Info.multiple namespace (Info.getLabel label) [ Engage.Form.Address.view args addressValue ] in attribute.address |> Maybe.map (\( label, addressValue ) -> do label addressValue) |> Maybe.withDefault (text "") avatarView : Namespace -> InternalAttribute msg -> Html msg avatarView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.avatar |> Maybe.map (\avatarValue -> div [ class (if String.isEmpty avatarValue then [ "ProfileNoAvatar", "ProfileAvatar" ] else [ "ProfileAvatar" ] ) ] [ img [ src (if String.isEmpty avatarValue then "/DesktopModules/EngageCore.Participant/images/noprofile.png" else avatarValue ) ] [] ] ) |> Maybe.withDefault (text "") emailView : Namespace -> InternalAttribute msg -> Html msg emailView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.email |> Maybe.map (\( label, emailValue ) -> div [ class [ "ProfileEmail" ] ] [ Info.email namespace (Info.getLabel label) emailValue ]) |> Maybe.withDefault (text "") phoneView : Namespace -> InternalAttribute msg -> Html msg phoneView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.phone |> Maybe.map (\( label, phoneValue ) -> div [ class [ "ProfilePhone" ] ] [ Info.phone namespace (Info.getLabel label) phoneValue ]) |> Maybe.withDefault (text "") mobilePhoneView : Namespace -> InternalAttribute msg -> Html msg mobilePhoneView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.mobilePhone |> Maybe.map (\( label, mobilePhoneValue ) -> div [ class [ "ProfileCellphone" ] ] [ Info.mobilePhone namespace (Info.getLabel label) mobilePhoneValue ]) |> Maybe.withDefault (text "") faxView : Namespace -> InternalAttribute msg -> Html msg faxView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.fax |> Maybe.map (\( label, faxValue ) -> div [ class [ "ProfileFax" ] ] [ Info.fax namespace (Info.getLabel label) faxValue ]) |> Maybe.withDefault (text "") actionView : Namespace -> InternalAttribute msg -> Html msg actionView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in FormAction.formAction namespace [ attribute.edit |> Maybe.map (\( text, msg ) -> div [ class [ "ProfileEditButton" ] ] [ Button.primarySmall { namespace = namespace , attributes = [ onClick msg ] , text = text } ] ) |> Maybe.withDefault (text "") , attribute.changePassword |> Maybe.map (\( text, msg ) -> div [ class [ "ProfileChangePasswordButton" ] ] [ Button.primarySmall { namespace = namespace , attributes = [ onClick msg ] , text = text } ] ) |> Maybe.withDefault (text "") , attribute.editAccountLink |> Maybe.map (\( text, url ) -> div [ class [ "ProfileEditAccountLink" ] ] [ a [ href url, Html.Attributes.attribute "class" "dialog-link" ] [ Html.text text ] ] ) |> Maybe.withDefault (text "") ] []
true
module Engage.Form.Profile exposing ( view , address, avatar, birthDate, birthDateMonth, birthDateYear, none, phone, email, fax, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, mobilePhone, edit, editAccountLink, title, changePassword , Attribute ) {-| Form.Profile # View @docs view # Attributes @docs address, avatar, birthDate, birthDateMonth, birthDateYear, none, phone, email, fax, PI:NAME:<NAME>END_PI, gender, PI:NAME:<NAME>END_PI, mobilePhone, edit, editAccountLink, title, changePassword #Types @docs Attribute -} import Date exposing (Date) import Engage.CssHelpers import Engage.Entity.Address exposing (Address, Countries, RegionsCountry) import Engage.Entity.Gender as Gender exposing (Gender) import Engage.Form.Address import Engage.Form.FormAction as FormAction import Engage.ListItem exposing (ListItem) import Engage.Localization as Localization exposing (Localization) import Engage.Namespace as Namespace exposing (Namespace) import Engage.UI.Attribute as Attribute import Engage.UI.Button as Button import Engage.UI.Info as Info import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onClick) import String type alias InternalAttribute msg = { avatar : Maybe String , PI:NAME:<NAME>END_PI : Maybe String , lastName : Maybe String , title : Maybe String , email : Maybe ( String, String ) , phone : Maybe ( String, String ) , mobilePhone : Maybe ( String, String ) , fax : Maybe ( String, String ) , edit : Maybe ( String, msg ) , address : Maybe ( String, Address ) , gender : Maybe ( String, Gender ) , birthDate : Maybe ( String, Maybe Date ) , isDayFirst : Maybe Bool , birthDateYear : Maybe ( String, Maybe ListItem ) , birthDateMonth : Maybe ( String, Maybe ListItem ) , editAccountLink : Maybe ( String, String ) , changePassword : Maybe ( String, msg ) } emptyAttribute : InternalAttribute msg emptyAttribute = { avatar = Nothing , PI:NAME:<NAME>END_PI = Nothing , lastName = Nothing , title = Nothing , email = Nothing , phone = Nothing , mobilePhone = Nothing , fax = Nothing , edit = Nothing , address = Nothing , gender = Nothing , birthDate = Nothing , isDayFirst = Nothing , birthDateYear = Nothing , birthDateMonth = Nothing , editAccountLink = Nothing , changePassword = Nothing } {-| The Attribute type -} type alias Attribute msg = InternalAttribute msg -> InternalAttribute msg {-| Get the none Attribute -} none : Attribute msg none = \attribute -> attribute {-| Get the first name Attribute -} firstName : String -> Attribute msg firstName text = \attribute -> { attribute | firstName = Just text } {-| Get the title Attribute -} title : String -> Attribute msg title text = \attribute -> { attribute | title = Just text } {-| Get the address Attribute -} address : String -> Address -> Attribute msg address label addressData = \attribute -> { attribute | address = Just ( label, addressData ) } {-| Get the last name Attribute -} lastName : String -> Attribute msg lastName text = \attribute -> { attribute | lastName = Just text } {-| Get the avatar Attribute -} avatar : String -> Attribute msg avatar text = \attribute -> { attribute | avatar = Just text } {-| Get the email Attribute -} email : String -> String -> Attribute msg email label text = \attribute -> { attribute | email = Just ( label, text ) } {-| Get the phone Attribute -} phone : String -> String -> Attribute msg phone label text = \attribute -> { attribute | phone = Just ( label, text ) } {-| Get the mobile phone Attribute -} mobilePhone : String -> String -> Attribute msg mobilePhone label text = \attribute -> { attribute | mobilePhone = Just ( label, text ) } {-| Get the fax Attribute -} fax : String -> String -> Attribute msg fax label text = \attribute -> { attribute | fax = Just ( label, text ) } {-| Get the gender Attribute -} gender : String -> Gender -> Attribute msg gender label value = \attribute -> { attribute | gender = Just ( label, value ) } {-| Get the birth date Attribute -} birthDate : String -> Maybe Date -> Bool -> Attribute msg birthDate label date isDayFirst = \attribute -> { attribute | birthDate = Just ( label, date ), isDayFirst = Just isDayFirst } {-| Get the birth date year Attribute -} birthDateYear : String -> Maybe ListItem -> Attribute msg birthDateYear label item = \attribute -> { attribute | birthDateYear = Just ( label, item ) } {-| Get the birth date month Attribute -} birthDateMonth : String -> Maybe ListItem -> Attribute msg birthDateMonth label item = \attribute -> { attribute | birthDateMonth = Just ( label, item ) } {-| Get the edit Attribute -} edit : String -> msg -> Attribute msg edit text msg = \attribute -> { attribute | edit = Just ( text, msg ) } {-| Get the change password Attribute -} changePassword : String -> msg -> Attribute msg changePassword text msg = \attribute -> { attribute | changePassword = Just ( text, msg ) } {-| Get the edit account link Attribute -} editAccountLink : String -> String -> Attribute msg editAccountLink text value = \attribute -> { attribute | editAccountLink = Just ( text, value ) } {-| Get the view -} view : { args | namespace : Namespace, localization : Localization, countries : Countries, regions : RegionsCountry } -> List (Attribute msg) -> List (Html msg) -> Html msg view ({ namespace, localization } as args) attributes additionalContents = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace attribute = Attribute.process emptyAttribute attributes in div [ class [ "Profile" ] ] [ avatarView namespace attribute , div [ class [ "ProfileInfo" ] ] [ div [ class [ "ProfileHeader" ] ] [ nameView namespace attribute , titleView namespace attribute , emailView namespace attribute , phoneView namespace attribute , mobilePhoneView namespace attribute , faxView namespace attribute ] , div [ class [ "ProfileBody" ] ] ([ genderView namespace attribute , birthDateView namespace localization attribute , birthDateMonthView namespace attribute , birthDateYearView namespace attribute , addressView args attribute ] ++ additionalContents ) , actionView namespace attribute ] ] genderView : Namespace -> InternalAttribute msg -> Html msg genderView namespace attribute = let do label genderValue = if String.isEmpty genderValue then text "" else Info.multiple namespace (Info.getLabel label) [ text genderValue ] in attribute.gender |> Maybe.map (\( label, genderValue ) -> do label (Gender.toString genderValue)) |> Maybe.withDefault (text "") birthDateView : Namespace -> Localization -> InternalAttribute msg -> Html msg birthDateView namespace localization attribute = let defaultDateFormat = Localization.localizeStringWithDefault "MMMM d, yyyy" "BirthDateFormat" { localization = localization } dateFormat = case attribute.isDayFirst of Just isDayFirst -> if isDayFirst then "dd/MM/yyyy" else defaultDateFormat _ -> defaultDateFormat do label maybeDate = case maybeDate of Nothing -> text "" Just date -> Info.multiple namespace (Info.getLabel label) [ text (Date.format dateFormat date) ] in attribute.birthDate |> Maybe.map (\( label, date ) -> do label date) |> Maybe.withDefault (text "") birthDateYearView : Namespace -> InternalAttribute msg -> Html msg birthDateYearView namespace attribute = let do label maybeItem = case maybeItem of Nothing -> text "" Just item -> Info.multiple namespace (Info.getLabel label) [ text (String.fromInt (Tuple.first item)) ] in attribute.birthDateYear |> Maybe.map (\( label, item ) -> do label item) |> Maybe.withDefault (text "") birthDateMonthView : Namespace -> InternalAttribute msg -> Html msg birthDateMonthView namespace attribute = let do label maybeItem = case maybeItem of Nothing -> text "" Just item -> Info.multiple namespace (Info.getLabel label) [ text (String.fromInt (Tuple.first item)) ] in attribute.birthDateMonth |> Maybe.map (\( label, item ) -> do label item) |> Maybe.withDefault (text "") nameView : Namespace -> InternalAttribute msg -> Html msg nameView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace firstNameValue = attribute.firstName |> Maybe.withDefault "" lastNameValue = attribute.lastName |> Maybe.withDefault "" name = firstNameValue ++ " " ++ lastNameValue in if name |> String.trim |> String.isEmpty then text "" else h3 [ class [ "ProfileName" ] ] [ text name ] titleView : Namespace -> InternalAttribute msg -> Html msg titleView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.title |> Maybe.map (\newTitle -> div [ class [ "ProfileTitle" ] ] [ text newTitle ]) |> Maybe.withDefault (text "") addressView : { args | namespace : Namespace, localization : Localization, countries : Countries, regions : RegionsCountry } -> InternalAttribute msg -> Html msg addressView ({ namespace } as args) attribute = let isEmpty = Engage.Form.Address.isEmpty do label addressValue = if isEmpty addressValue then text "" else Info.multiple namespace (Info.getLabel label) [ Engage.Form.Address.view args addressValue ] in attribute.address |> Maybe.map (\( label, addressValue ) -> do label addressValue) |> Maybe.withDefault (text "") avatarView : Namespace -> InternalAttribute msg -> Html msg avatarView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.avatar |> Maybe.map (\avatarValue -> div [ class (if String.isEmpty avatarValue then [ "ProfileNoAvatar", "ProfileAvatar" ] else [ "ProfileAvatar" ] ) ] [ img [ src (if String.isEmpty avatarValue then "/DesktopModules/EngageCore.Participant/images/noprofile.png" else avatarValue ) ] [] ] ) |> Maybe.withDefault (text "") emailView : Namespace -> InternalAttribute msg -> Html msg emailView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.email |> Maybe.map (\( label, emailValue ) -> div [ class [ "ProfileEmail" ] ] [ Info.email namespace (Info.getLabel label) emailValue ]) |> Maybe.withDefault (text "") phoneView : Namespace -> InternalAttribute msg -> Html msg phoneView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.phone |> Maybe.map (\( label, phoneValue ) -> div [ class [ "ProfilePhone" ] ] [ Info.phone namespace (Info.getLabel label) phoneValue ]) |> Maybe.withDefault (text "") mobilePhoneView : Namespace -> InternalAttribute msg -> Html msg mobilePhoneView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.mobilePhone |> Maybe.map (\( label, mobilePhoneValue ) -> div [ class [ "ProfileCellphone" ] ] [ Info.mobilePhone namespace (Info.getLabel label) mobilePhoneValue ]) |> Maybe.withDefault (text "") faxView : Namespace -> InternalAttribute msg -> Html msg faxView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in attribute.fax |> Maybe.map (\( label, faxValue ) -> div [ class [ "ProfileFax" ] ] [ Info.fax namespace (Info.getLabel label) faxValue ]) |> Maybe.withDefault (text "") actionView : Namespace -> InternalAttribute msg -> Html msg actionView namespace attribute = let class = namespace |> Namespace.toString |> Engage.CssHelpers.withNamespace in FormAction.formAction namespace [ attribute.edit |> Maybe.map (\( text, msg ) -> div [ class [ "ProfileEditButton" ] ] [ Button.primarySmall { namespace = namespace , attributes = [ onClick msg ] , text = text } ] ) |> Maybe.withDefault (text "") , attribute.changePassword |> Maybe.map (\( text, msg ) -> div [ class [ "ProfileChangePasswordButton" ] ] [ Button.primarySmall { namespace = namespace , attributes = [ onClick msg ] , text = text } ] ) |> Maybe.withDefault (text "") , attribute.editAccountLink |> Maybe.map (\( text, url ) -> div [ class [ "ProfileEditAccountLink" ] ] [ a [ href url, Html.Attributes.attribute "class" "dialog-link" ] [ Html.text text ] ] ) |> Maybe.withDefault (text "") ] []
elm
[ { "context": "n by \"\n , a [ href \"https://github.com/evancz\" ] [ text \"Evan Czaplicki\" ]\n ]\n ", "end": 8095, "score": 0.9996242523, "start": 8089, "tag": "USERNAME", "value": "evancz" }, { "context": " , a [ href \"https://github.com/evancz\" ] [ text \"Evan Czaplicki\" ]\n ]\n , p []\n [ tex", "end": 8121, "score": 0.999869287, "start": 8107, "tag": "NAME", "value": "Evan Czaplicki" } ]
examples/elm/Todo.elm
EnverOsmanov/todomvc
3
port module Todo exposing (..) {-| TodoMVC implemented in Elm, using plain HTML and CSS for rendering. This application is broken up into four distinct parts: 1. Model - a full description of the application as data 2. Update - a way to update the model based on user actions 3. View - a way to visualize our model with HTML This program is not particularly large, so definitely see the following document for notes on structuring more complex GUIs with Elm: http://guide.elm-lang.org/architecture/ -} import Dom import Task import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Html.Lazy exposing (lazy, lazy2) import Html.App import Navigation exposing (Parser) import String import String.Extra import Todo.Task -- MODEL -- The full application state of our todo app. type alias Model = { tasks : List Todo.Task.Model , field : String , uid : Int , visibility : String } type alias Flags = Maybe Model emptyModel : Model emptyModel = { tasks = [] , visibility = "All" , field = "" , uid = 0 } -- UPDATE -- A description of the kinds of actions that can be performed on the model of -- our application. See the following post for more info on this pattern and -- some alternatives: http://guide.elm-lang.org/architecture/ type Msg = NoOp | UpdateField String | Add | UpdateTask ( Int, Todo.Task.Msg ) | DeleteComplete | CheckAll Bool | ChangeVisibility String -- How we update our Model on any given Message update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case Debug.log "MESSAGE: " msg of NoOp -> ( model, Cmd.none ) UpdateField str -> let newModel = { model | field = str } in ( newModel, save model ) Add -> let description = String.trim model.field newModel = if String.isEmpty description then model else { model | uid = model.uid + 1 , field = "" , tasks = model.tasks ++ [ Todo.Task.init description model.uid ] } in ( newModel, save newModel ) UpdateTask ( id, taskMsg ) -> let updateTask t = if t.id == id then Todo.Task.update taskMsg t else Just t newModel = { model | tasks = List.filterMap updateTask model.tasks } in case taskMsg of Todo.Task.Focus elementId -> newModel ! [ save newModel, focusTask elementId ] _ -> ( newModel, save newModel ) DeleteComplete -> let newModel = { model | tasks = List.filter (not << .completed) model.tasks } in ( newModel, save newModel ) CheckAll bool -> let updateTask t = { t | completed = bool } newModel = { model | tasks = List.map updateTask model.tasks } in ( newModel, save newModel ) ChangeVisibility visibility -> let newModel = { model | visibility = visibility } in ( newModel, save model ) focusTask : String -> Cmd Msg focusTask elementId = Task.perform (\_ -> NoOp) (\_ -> NoOp) (Dom.focus elementId) -- VIEW view : Model -> Html Msg view model = div [ class "todomvc-wrapper" , style [ ( "visibility", "hidden" ) ] ] [ section [ class "todoapp" ] [ lazy taskEntry model.field , lazy2 taskList model.visibility model.tasks , lazy2 controls model.visibility model.tasks ] , infoFooter ] taskEntry : String -> Html Msg taskEntry task = header [ class "header" ] [ h1 [] [ text "todos" ] , input [ class "new-todo" , placeholder "What needs to be done?" , autofocus True , value task , name "newTodo" , onInput UpdateField , Todo.Task.onFinish Add NoOp ] [] ] taskList : String -> List Todo.Task.Model -> Html Msg taskList visibility tasks = let isVisible todo = case visibility of "Completed" -> todo.completed "Active" -> not todo.completed -- "All" _ -> True allCompleted = List.all .completed tasks cssVisibility = if List.isEmpty tasks then "hidden" else "visible" in section [ class "main" , style [ ( "visibility", cssVisibility ) ] ] [ input [ class "toggle-all" , id "toggle-all" , type' "checkbox" , name "toggle" , checked allCompleted , onClick (CheckAll (not allCompleted)) ] [] , label [ for "toggle-all" ] [ text "Mark all as complete" ] , ul [ class "todo-list" ] (List.map (\task -> let id = task.id taskView = Todo.Task.view task in Html.App.map (\msg -> UpdateTask ( id, msg )) taskView ) (List.filter isVisible tasks) ) ] controls : String -> List Todo.Task.Model -> Html Msg controls visibility tasks = let tasksCompleted = List.length (List.filter .completed tasks) tasksLeft = List.length tasks - tasksCompleted item_ = if tasksLeft == 1 then " item" else " items" in footer [ class "footer" , hidden (List.isEmpty tasks) ] [ span [ class "todo-count" ] [ strong [] [ text (toString tasksLeft) ] , text (item_ ++ " left") ] , ul [ class "filters" ] [ visibilitySwap "#/" "All" visibility , text " " , visibilitySwap "#/active" "Active" visibility , text " " , visibilitySwap "#/completed" "Completed" visibility ] , button [ class "clear-completed" , hidden (tasksCompleted == 0) , onClick DeleteComplete ] [ text ("Clear completed (" ++ toString tasksCompleted ++ ")") ] ] visibilitySwap : String -> String -> String -> Html Msg visibilitySwap uri visibility actualVisibility = let className = if visibility == actualVisibility then "selected" else "" in li [ onClick (ChangeVisibility visibility) ] [ a [ class className, href uri ] [ text visibility ] ] infoFooter : Html msg infoFooter = footer [ class "info" ] [ p [] [ text "Double-click to edit a todo" ] , p [] [ text "Written by " , a [ href "https://github.com/evancz" ] [ text "Evan Czaplicki" ] ] , p [] [ text "Part of " , a [ href "http://todomvc.com" ] [ text "TodoMVC" ] ] ] -- wire the entire application together main : Program Flags main = Navigation.programWithFlags urlParser { urlUpdate = urlUpdate , view = view , init = init , update = update , subscriptions = subscriptions } -- URL PARSERS - check out evancz/url-parser for fancier URL parsing toUrl : String -> String toUrl visibility = "#/" ++ String.toLower visibility fromUrl : String -> Maybe String fromUrl hash = let cleanHash = String.dropLeft 2 hash in if (List.member cleanHash [ "all", "active", "completed" ]) == True then Just cleanHash else Nothing urlParser : Parser (Maybe String) urlParser = Navigation.makeParser (fromUrl << .hash) {-| The URL is turned into a Maybe value. If the URL is valid, we just update our model with the new visibility settings. If it is not a valid URL, we set the visibility filter to show all tasks. -} urlUpdate : Maybe String -> Model -> ( Model, Cmd Msg ) urlUpdate result model = case result of Just visibility -> update (ChangeVisibility (String.Extra.toSentenceCase visibility)) model Nothing -> update (ChangeVisibility "All") model init : Flags -> Maybe String -> ( Model, Cmd Msg ) init flags url = urlUpdate url (Maybe.withDefault emptyModel flags) -- interactions with localStorage port save : Model -> Cmd msg subscriptions : Model -> Sub Msg subscriptions model = Sub.none
1277
port module Todo exposing (..) {-| TodoMVC implemented in Elm, using plain HTML and CSS for rendering. This application is broken up into four distinct parts: 1. Model - a full description of the application as data 2. Update - a way to update the model based on user actions 3. View - a way to visualize our model with HTML This program is not particularly large, so definitely see the following document for notes on structuring more complex GUIs with Elm: http://guide.elm-lang.org/architecture/ -} import Dom import Task import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Html.Lazy exposing (lazy, lazy2) import Html.App import Navigation exposing (Parser) import String import String.Extra import Todo.Task -- MODEL -- The full application state of our todo app. type alias Model = { tasks : List Todo.Task.Model , field : String , uid : Int , visibility : String } type alias Flags = Maybe Model emptyModel : Model emptyModel = { tasks = [] , visibility = "All" , field = "" , uid = 0 } -- UPDATE -- A description of the kinds of actions that can be performed on the model of -- our application. See the following post for more info on this pattern and -- some alternatives: http://guide.elm-lang.org/architecture/ type Msg = NoOp | UpdateField String | Add | UpdateTask ( Int, Todo.Task.Msg ) | DeleteComplete | CheckAll Bool | ChangeVisibility String -- How we update our Model on any given Message update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case Debug.log "MESSAGE: " msg of NoOp -> ( model, Cmd.none ) UpdateField str -> let newModel = { model | field = str } in ( newModel, save model ) Add -> let description = String.trim model.field newModel = if String.isEmpty description then model else { model | uid = model.uid + 1 , field = "" , tasks = model.tasks ++ [ Todo.Task.init description model.uid ] } in ( newModel, save newModel ) UpdateTask ( id, taskMsg ) -> let updateTask t = if t.id == id then Todo.Task.update taskMsg t else Just t newModel = { model | tasks = List.filterMap updateTask model.tasks } in case taskMsg of Todo.Task.Focus elementId -> newModel ! [ save newModel, focusTask elementId ] _ -> ( newModel, save newModel ) DeleteComplete -> let newModel = { model | tasks = List.filter (not << .completed) model.tasks } in ( newModel, save newModel ) CheckAll bool -> let updateTask t = { t | completed = bool } newModel = { model | tasks = List.map updateTask model.tasks } in ( newModel, save newModel ) ChangeVisibility visibility -> let newModel = { model | visibility = visibility } in ( newModel, save model ) focusTask : String -> Cmd Msg focusTask elementId = Task.perform (\_ -> NoOp) (\_ -> NoOp) (Dom.focus elementId) -- VIEW view : Model -> Html Msg view model = div [ class "todomvc-wrapper" , style [ ( "visibility", "hidden" ) ] ] [ section [ class "todoapp" ] [ lazy taskEntry model.field , lazy2 taskList model.visibility model.tasks , lazy2 controls model.visibility model.tasks ] , infoFooter ] taskEntry : String -> Html Msg taskEntry task = header [ class "header" ] [ h1 [] [ text "todos" ] , input [ class "new-todo" , placeholder "What needs to be done?" , autofocus True , value task , name "newTodo" , onInput UpdateField , Todo.Task.onFinish Add NoOp ] [] ] taskList : String -> List Todo.Task.Model -> Html Msg taskList visibility tasks = let isVisible todo = case visibility of "Completed" -> todo.completed "Active" -> not todo.completed -- "All" _ -> True allCompleted = List.all .completed tasks cssVisibility = if List.isEmpty tasks then "hidden" else "visible" in section [ class "main" , style [ ( "visibility", cssVisibility ) ] ] [ input [ class "toggle-all" , id "toggle-all" , type' "checkbox" , name "toggle" , checked allCompleted , onClick (CheckAll (not allCompleted)) ] [] , label [ for "toggle-all" ] [ text "Mark all as complete" ] , ul [ class "todo-list" ] (List.map (\task -> let id = task.id taskView = Todo.Task.view task in Html.App.map (\msg -> UpdateTask ( id, msg )) taskView ) (List.filter isVisible tasks) ) ] controls : String -> List Todo.Task.Model -> Html Msg controls visibility tasks = let tasksCompleted = List.length (List.filter .completed tasks) tasksLeft = List.length tasks - tasksCompleted item_ = if tasksLeft == 1 then " item" else " items" in footer [ class "footer" , hidden (List.isEmpty tasks) ] [ span [ class "todo-count" ] [ strong [] [ text (toString tasksLeft) ] , text (item_ ++ " left") ] , ul [ class "filters" ] [ visibilitySwap "#/" "All" visibility , text " " , visibilitySwap "#/active" "Active" visibility , text " " , visibilitySwap "#/completed" "Completed" visibility ] , button [ class "clear-completed" , hidden (tasksCompleted == 0) , onClick DeleteComplete ] [ text ("Clear completed (" ++ toString tasksCompleted ++ ")") ] ] visibilitySwap : String -> String -> String -> Html Msg visibilitySwap uri visibility actualVisibility = let className = if visibility == actualVisibility then "selected" else "" in li [ onClick (ChangeVisibility visibility) ] [ a [ class className, href uri ] [ text visibility ] ] infoFooter : Html msg infoFooter = footer [ class "info" ] [ p [] [ text "Double-click to edit a todo" ] , p [] [ text "Written by " , a [ href "https://github.com/evancz" ] [ text "<NAME>" ] ] , p [] [ text "Part of " , a [ href "http://todomvc.com" ] [ text "TodoMVC" ] ] ] -- wire the entire application together main : Program Flags main = Navigation.programWithFlags urlParser { urlUpdate = urlUpdate , view = view , init = init , update = update , subscriptions = subscriptions } -- URL PARSERS - check out evancz/url-parser for fancier URL parsing toUrl : String -> String toUrl visibility = "#/" ++ String.toLower visibility fromUrl : String -> Maybe String fromUrl hash = let cleanHash = String.dropLeft 2 hash in if (List.member cleanHash [ "all", "active", "completed" ]) == True then Just cleanHash else Nothing urlParser : Parser (Maybe String) urlParser = Navigation.makeParser (fromUrl << .hash) {-| The URL is turned into a Maybe value. If the URL is valid, we just update our model with the new visibility settings. If it is not a valid URL, we set the visibility filter to show all tasks. -} urlUpdate : Maybe String -> Model -> ( Model, Cmd Msg ) urlUpdate result model = case result of Just visibility -> update (ChangeVisibility (String.Extra.toSentenceCase visibility)) model Nothing -> update (ChangeVisibility "All") model init : Flags -> Maybe String -> ( Model, Cmd Msg ) init flags url = urlUpdate url (Maybe.withDefault emptyModel flags) -- interactions with localStorage port save : Model -> Cmd msg subscriptions : Model -> Sub Msg subscriptions model = Sub.none
true
port module Todo exposing (..) {-| TodoMVC implemented in Elm, using plain HTML and CSS for rendering. This application is broken up into four distinct parts: 1. Model - a full description of the application as data 2. Update - a way to update the model based on user actions 3. View - a way to visualize our model with HTML This program is not particularly large, so definitely see the following document for notes on structuring more complex GUIs with Elm: http://guide.elm-lang.org/architecture/ -} import Dom import Task import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Html.Lazy exposing (lazy, lazy2) import Html.App import Navigation exposing (Parser) import String import String.Extra import Todo.Task -- MODEL -- The full application state of our todo app. type alias Model = { tasks : List Todo.Task.Model , field : String , uid : Int , visibility : String } type alias Flags = Maybe Model emptyModel : Model emptyModel = { tasks = [] , visibility = "All" , field = "" , uid = 0 } -- UPDATE -- A description of the kinds of actions that can be performed on the model of -- our application. See the following post for more info on this pattern and -- some alternatives: http://guide.elm-lang.org/architecture/ type Msg = NoOp | UpdateField String | Add | UpdateTask ( Int, Todo.Task.Msg ) | DeleteComplete | CheckAll Bool | ChangeVisibility String -- How we update our Model on any given Message update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case Debug.log "MESSAGE: " msg of NoOp -> ( model, Cmd.none ) UpdateField str -> let newModel = { model | field = str } in ( newModel, save model ) Add -> let description = String.trim model.field newModel = if String.isEmpty description then model else { model | uid = model.uid + 1 , field = "" , tasks = model.tasks ++ [ Todo.Task.init description model.uid ] } in ( newModel, save newModel ) UpdateTask ( id, taskMsg ) -> let updateTask t = if t.id == id then Todo.Task.update taskMsg t else Just t newModel = { model | tasks = List.filterMap updateTask model.tasks } in case taskMsg of Todo.Task.Focus elementId -> newModel ! [ save newModel, focusTask elementId ] _ -> ( newModel, save newModel ) DeleteComplete -> let newModel = { model | tasks = List.filter (not << .completed) model.tasks } in ( newModel, save newModel ) CheckAll bool -> let updateTask t = { t | completed = bool } newModel = { model | tasks = List.map updateTask model.tasks } in ( newModel, save newModel ) ChangeVisibility visibility -> let newModel = { model | visibility = visibility } in ( newModel, save model ) focusTask : String -> Cmd Msg focusTask elementId = Task.perform (\_ -> NoOp) (\_ -> NoOp) (Dom.focus elementId) -- VIEW view : Model -> Html Msg view model = div [ class "todomvc-wrapper" , style [ ( "visibility", "hidden" ) ] ] [ section [ class "todoapp" ] [ lazy taskEntry model.field , lazy2 taskList model.visibility model.tasks , lazy2 controls model.visibility model.tasks ] , infoFooter ] taskEntry : String -> Html Msg taskEntry task = header [ class "header" ] [ h1 [] [ text "todos" ] , input [ class "new-todo" , placeholder "What needs to be done?" , autofocus True , value task , name "newTodo" , onInput UpdateField , Todo.Task.onFinish Add NoOp ] [] ] taskList : String -> List Todo.Task.Model -> Html Msg taskList visibility tasks = let isVisible todo = case visibility of "Completed" -> todo.completed "Active" -> not todo.completed -- "All" _ -> True allCompleted = List.all .completed tasks cssVisibility = if List.isEmpty tasks then "hidden" else "visible" in section [ class "main" , style [ ( "visibility", cssVisibility ) ] ] [ input [ class "toggle-all" , id "toggle-all" , type' "checkbox" , name "toggle" , checked allCompleted , onClick (CheckAll (not allCompleted)) ] [] , label [ for "toggle-all" ] [ text "Mark all as complete" ] , ul [ class "todo-list" ] (List.map (\task -> let id = task.id taskView = Todo.Task.view task in Html.App.map (\msg -> UpdateTask ( id, msg )) taskView ) (List.filter isVisible tasks) ) ] controls : String -> List Todo.Task.Model -> Html Msg controls visibility tasks = let tasksCompleted = List.length (List.filter .completed tasks) tasksLeft = List.length tasks - tasksCompleted item_ = if tasksLeft == 1 then " item" else " items" in footer [ class "footer" , hidden (List.isEmpty tasks) ] [ span [ class "todo-count" ] [ strong [] [ text (toString tasksLeft) ] , text (item_ ++ " left") ] , ul [ class "filters" ] [ visibilitySwap "#/" "All" visibility , text " " , visibilitySwap "#/active" "Active" visibility , text " " , visibilitySwap "#/completed" "Completed" visibility ] , button [ class "clear-completed" , hidden (tasksCompleted == 0) , onClick DeleteComplete ] [ text ("Clear completed (" ++ toString tasksCompleted ++ ")") ] ] visibilitySwap : String -> String -> String -> Html Msg visibilitySwap uri visibility actualVisibility = let className = if visibility == actualVisibility then "selected" else "" in li [ onClick (ChangeVisibility visibility) ] [ a [ class className, href uri ] [ text visibility ] ] infoFooter : Html msg infoFooter = footer [ class "info" ] [ p [] [ text "Double-click to edit a todo" ] , p [] [ text "Written by " , a [ href "https://github.com/evancz" ] [ text "PI:NAME:<NAME>END_PI" ] ] , p [] [ text "Part of " , a [ href "http://todomvc.com" ] [ text "TodoMVC" ] ] ] -- wire the entire application together main : Program Flags main = Navigation.programWithFlags urlParser { urlUpdate = urlUpdate , view = view , init = init , update = update , subscriptions = subscriptions } -- URL PARSERS - check out evancz/url-parser for fancier URL parsing toUrl : String -> String toUrl visibility = "#/" ++ String.toLower visibility fromUrl : String -> Maybe String fromUrl hash = let cleanHash = String.dropLeft 2 hash in if (List.member cleanHash [ "all", "active", "completed" ]) == True then Just cleanHash else Nothing urlParser : Parser (Maybe String) urlParser = Navigation.makeParser (fromUrl << .hash) {-| The URL is turned into a Maybe value. If the URL is valid, we just update our model with the new visibility settings. If it is not a valid URL, we set the visibility filter to show all tasks. -} urlUpdate : Maybe String -> Model -> ( Model, Cmd Msg ) urlUpdate result model = case result of Just visibility -> update (ChangeVisibility (String.Extra.toSentenceCase visibility)) model Nothing -> update (ChangeVisibility "All") model init : Flags -> Maybe String -> ( Model, Cmd Msg ) init flags url = urlUpdate url (Maybe.withDefault emptyModel flags) -- interactions with localStorage port save : Model -> Cmd msg subscriptions : Model -> Sub Msg subscriptions model = Sub.none
elm
[ { "context": "community/list-extra\", 21.28475703 )\n , ( \"mdgriffith/elm-ui\", 21.01525279 )\n , ( \"elm/svg\", 20.", "end": 819, "score": 0.9627959132, "start": 809, "tag": "USERNAME", "value": "mdgriffith" }, { "context": "-json-decode-pipeline\", 18.8763277 )\n , ( \"rtfeldman/elm-css\", 12.36916545 )\n , ( \"avh4/elm-col", "end": 964, "score": 0.9962856174, "start": 955, "tag": "USERNAME", "value": "rtfeldman" }, { "context": "community/maybe-extra\", 8.38839645 )\n , ( \"krisajenkins/remotedata\", 7.80414698 )\n , ( \"elm/file\",", "end": 1189, "score": 0.9965308905, "start": 1177, "tag": "USERNAME", "value": "krisajenkins" }, { "context": "\"rundis/elm-bootstrap\", 5.97488205 )\n , ( \"justinmimbs/date\", 5.15831017 )\n , ( \"elm-community/js", "end": 1497, "score": 0.7458752394, "start": 1486, "tag": "USERNAME", "value": "justinmimbs" }, { "context": "ommunity/string-extra\", 4.23226837 )\n , ( \"mpizenberg/elm-pointer-events\", 3.77488665 )\n , ( \"el", "end": 1648, "score": 0.9754574895, "start": 1638, "tag": "USERNAME", "value": "mpizenberg" }, { "context": "\"dillonkearns/elm-rss\", 2.79940758 )\n , ( \"rtfeldman/elm-hex\", 2.71486235 )\n , ( \"ryannhg/date-", "end": 2151, "score": 0.8015785813, "start": 2142, "tag": "USERNAME", "value": "rtfeldman" }, { "context": " ( \"rtfeldman/elm-hex\", 2.71486235 )\n , ( \"ryannhg/date-format\", 2.69281928 )\n , ( \"elm-explo", "end": 2195, "score": 0.7229782939, "start": 2188, "tag": "USERNAME", "value": "ryannhg" }, { "context": "lm-explorations/webgl\", 2.67113902 )\n , ( \"dillonkearns/elm-markdown\", 2.61302108 )\n , ( \"elm-comm", "end": 2299, "score": 0.8770155907, "start": 2287, "tag": "USERNAME", "value": "dillonkearns" }, { "context": "community/dict-extra\", 2.6126905 )\n , ( \"noahzgordon/elm-color-extra\", 2.50191896 )\n , ( \"dillo", "end": 2404, "score": 0.7848734856, "start": 2395, "tag": "USERNAME", "value": "ahzgordon" }, { "context": "rdon/elm-color-extra\", 2.50191896 )\n , ( \"dillonkearns/elm-graphql\", 2.43280404 )\n , ( \"lukewestb", "end": 2461, "score": 0.8261548281, "start": 2450, "tag": "USERNAME", "value": "illonkearns" }, { "context": "onkearns/elm-graphql\", 2.43280404 )\n , ( \"lukewestby/elm-string-interpolate\", 2.21887162 )\n , (", "end": 2512, "score": 0.8622047901, "start": 2503, "tag": "USERNAME", "value": "ukewestby" }, { "context": "-string-interpolate\", 2.21887162 )\n , ( \"joakin/elm-canvas\", 2.06071881 )\n , ( \"justinmimb", "end": 2570, "score": 0.7686495781, "start": 2566, "tag": "USERNAME", "value": "akin" }, { "context": " ( \"joakin/elm-canvas\", 2.06071881 )\n , ( \"justinmimbs/time-extra\", 2.02711878 )\n , ( \"ianmackenz", "end": 2621, "score": 0.97664994, "start": 2610, "tag": "USERNAME", "value": "justinmimbs" }, { "context": "ustinmimbs/time-extra\", 2.02711878 )\n , ( \"ianmackenzie/elm-geometry\", 1.93496966 )\n , ( \"elm-comm", "end": 2673, "score": 0.9855232239, "start": 2661, "tag": "USERNAME", "value": "ianmackenzie" }, { "context": " , ( \"ohanhi/keyboard\", 1.82651929 )\n , ( \"mdgriffith/elm-markup\", 1.79477894 )\n , ( \"ianmackenz", "end": 2822, "score": 0.8947123885, "start": 2812, "tag": "USERNAME", "value": "mdgriffith" }, { "context": "mdgriffith/elm-markup\", 1.79477894 )\n , ( \"ianmackenzie/elm-units\", 1.77692833 )\n , ( \"truqu/elm-b", "end": 2874, "score": 0.9665638208, "start": 2862, "tag": "USERNAME", "value": "ianmackenzie" }, { "context": ", ( \"truqu/elm-base64\", 1.65642656 )\n , ( \"gampleman/elm-visualization\", 1.59352132 )\n , ( \"jfm", "end": 2967, "score": 0.9001118541, "start": 2958, "tag": "USERNAME", "value": "gampleman" }, { "context": "man/elm-visualization\", 1.59352132 )\n , ( \"jfmengels/elm-review\", 1.58147495 )\n , ( \"hecrj/html", "end": 3023, "score": 0.9805289507, "start": 3014, "tag": "USERNAME", "value": "jfmengels" }, { "context": "engels/elm-review\", 1.58147495 )\n , ( \"hecrj/html-parser\", 1.54538153 )\n , ( \"mdgriffit", "end": 3068, "score": 0.6069657803, "start": 3067, "tag": "USERNAME", "value": "j" }, { "context": " ( \"hecrj/html-parser\", 1.54538153 )\n , ( \"mdgriffith/elm-animator\", 1.54119939 )\n , ( \"stil4m/e", "end": 3119, "score": 0.7909352183, "start": 3109, "tag": "USERNAME", "value": "mdgriffith" }, { "context": "ommunity/array-extra\", 1.5177429 )\n , ( \"evancz/elm-playground\", 1.49471032 )\n , ( \"elm-ex", "end": 3265, "score": 0.7920117974, "start": 3261, "tag": "USERNAME", "value": "ancz" }, { "context": "plorations/benchmark\", 1.43905721 )\n , ( \"danyx23/elm-uuid\", 1.40987928 )\n , ( \"ianmackenzie", "end": 3371, "score": 0.8495991826, "start": 3365, "tag": "USERNAME", "value": "anyx23" }, { "context": ", ( \"danyx23/elm-uuid\", 1.40987928 )\n , ( \"ianmackenzie/elm-3d-scene\", 1.39304298 )\n , ( \"lukewest", "end": 3421, "score": 0.9510992169, "start": 3409, "tag": "USERNAME", "value": "ianmackenzie" }, { "context": "ckenzie/elm-3d-scene\", 1.39304298 )\n , ( \"lukewestby/elm-http-builder\", 1.38467299 )\n , ( \"rtfe", "end": 3473, "score": 0.6851930618, "start": 3464, "tag": "USERNAME", "value": "ukewestby" }, { "context": "stby/elm-http-builder\", 1.38467299 )\n , ( \"rtfeldman/elm-validate\", 1.37146825 )\n , ( \"elm/proj", "end": 3528, "score": 0.9862012267, "start": 3519, "tag": "USERNAME", "value": "rtfeldman" }, { "context": "t-metadata-utils\", 1.35373173 )\n , ( \"terezka/line-charts\", 1.3095579 )\n , ( \"cuducos/el", "end": 3632, "score": 0.6646875143, "start": 3630, "tag": "USERNAME", "value": "ka" }, { "context": " \"terezka/line-charts\", 1.3095579 )\n , ( \"cuducos/elm-format-number\", 1.21964339 )\n , ( \"mdg", "end": 3679, "score": 0.6895278692, "start": 3673, "tag": "USERNAME", "value": "uducos" }, { "context": "cos/elm-format-number\", 1.21964339 )\n , ( \"mdgriffith/elm-style-animation\", 1.21027623 )\n , ( \"J", "end": 3736, "score": 0.9651492238, "start": 3726, "tag": "USERNAME", "value": "mdgriffith" }, { "context": "h/elm-style-animation\", 1.21027623 )\n , ( \"Janiczek/cmd-extra\", 1.16277179 )\n , ( \"pablohirafu", "end": 3793, "score": 0.6812635064, "start": 3785, "tag": "USERNAME", "value": "Janiczek" }, { "context": "( \"Janiczek/cmd-extra\", 1.16277179 )\n , ( \"pablohirafuji/elm-markdown\", 1.16211273 )\n , ( \"featheri", "end": 3845, "score": 0.9609645009, "start": 3832, "tag": "USERNAME", "value": "pablohirafuji" }, { "context": "ASOutreach/graphicsvg\", 1.118421 )\n , ( \"mgold/elm-nonempty-list\", 1.06806795 )\n , ( \"tim", "end": 4106, "score": 0.5844523907, "start": 4103, "tag": "USERNAME", "value": "old" }, { "context": "/elm-nonempty-list\", 1.06806795 )\n , ( \"timjs/elm-collage\", 1.06749701 )\n , ( \"folkertde", "end": 4158, "score": 0.8388621807, "start": 4156, "tag": "USERNAME", "value": "js" }, { "context": " ( \"timjs/elm-collage\", 1.06749701 )\n , ( \"folkertdev/one-true-path-experiment\", 1.03353175 )\n ,", "end": 4209, "score": 0.7729840279, "start": 4199, "tag": "USERNAME", "value": "folkertdev" }, { "context": "4/elm-program-test\", 1.01810543 )\n , ( \"surprisetalk/elm-bulma\", 0.96419058 )\n , ( \"elm-communi", "end": 4325, "score": 0.6594498754, "start": 4316, "tag": "USERNAME", "value": "prisetalk" }, { "context": " \"elm-community/graph\", 0.93775505 )\n , ( \"ryannhg/elm-spa\", 0.91699362 )\n , ( \"pzp1997/assoc", "end": 4419, "score": 0.9780041575, "start": 4412, "tag": "USERNAME", "value": "ryannhg" }, { "context": "\"elm-community/intdict\", 0.8476579 )\n , ( \"bartavelle/json-helpers\", 0.83941682 )\n , ( \"danfishg", "end": 4620, "score": 0.9093931913, "start": 4610, "tag": "USERNAME", "value": "bartavelle" }, { "context": "rtavelle/json-helpers\", 0.83941682 )\n , ( \"danfishgold/base64-bytes\", 0.83681365 )\n , ( \"sparksp/", "end": 4673, "score": 0.8462662697, "start": 4662, "tag": "USERNAME", "value": "danfishgold" }, { "context": " , ( \"truqu/elm-md5\", 0.70189214 )\n , ( \"andrewMacmurray/elm-delay\", 0.68450709 )\n , ( \"aforemny/ma", "end": 5032, "score": 0.9519604445, "start": 5017, "tag": "USERNAME", "value": "andrewMacmurray" }, { "context": "ewMacmurray/elm-delay\", 0.68450709 )\n , ( \"aforemny/material-components-web-elm\", 0.67701128 )\n ", "end": 5079, "score": 0.9261339307, "start": 5071, "tag": "USERNAME", "value": "aforemny" }, { "context": "al-components-web-elm\", 0.67701128 )\n , ( \"justinmimbs/timezone-data\", 0.67701033 )\n , ( \"cmditch", "end": 5147, "score": 0.9963697195, "start": 5136, "tag": "USERNAME", "value": "justinmimbs" }, { "context": "inmimbs/timezone-data\", 0.67701033 )\n , ( \"cmditch/elm-bigint\", 0.66515013 )\n , ( \"wernerdegr", "end": 5197, "score": 0.9168796539, "start": 5190, "tag": "USERNAME", "value": "cmditch" }, { "context": "( \"cmditch/elm-bigint\", 0.66515013 )\n , ( \"wernerdegroot/listzipper\", 0.65981506 )\n , ( \"jinjor/elm", "end": 5250, "score": 0.9882836938, "start": 5237, "tag": "USERNAME", "value": "wernerdegroot" }, { "context": "nerdegroot/listzipper\", 0.65981506 )\n , ( \"jinjor/elm-debounce\", 0.65157382 )\n , ( \"Panagiot", "end": 5296, "score": 0.9937423468, "start": 5290, "tag": "USERNAME", "value": "jinjor" }, { "context": " \"jinjor/elm-debounce\", 0.65157382 )\n , ( \"PanagiotisGeorgiadis/elm-datetime\", 0.64939135 )\n , ( \"", "end": 5350, "score": 0.7915192842, "start": 5338, "tag": "USERNAME", "value": "PanagiotisGe" }, { "context": "bounce\", 0.65157382 )\n , ( \"PanagiotisGeorgiadis/elm-datetime\", 0.64939135 )\n , ( \"ianmacke", "end": 5358, "score": 0.5912075639, "start": 5353, "tag": "USERNAME", "value": "iadis" }, { "context": "orgiadis/elm-datetime\", 0.64939135 )\n , ( \"ianmackenzie/elm-geometry-svg\", 0.63453537 )\n , ( \"Chad", "end": 5412, "score": 0.9926958084, "start": 5400, "tag": "USERNAME", "value": "ianmackenzie" }, { "context": "tech/elm-bool-extra\", 0.62067315 )\n , ( \"lynn/elm-arithmetic\", 0.60440016 )\n , ( \"pabloh", "end": 5514, "score": 0.5843527317, "start": 5512, "tag": "USERNAME", "value": "nn" }, { "context": " \"lynn/elm-arithmetic\", 0.60440016 )\n , ( \"pablohirafuji/elm-syntax-highlight\", 0.60259155 )\n , ( \"", "end": 5571, "score": 0.9722053409, "start": 5558, "tag": "USERNAME", "value": "pablohirafuji" }, { "context": "/elm-syntax-highlight\", 0.60259155 )\n , ( \"arturopala/elm-monocle\", 0.59790553 )\n , ( \"frandibar", "end": 5631, "score": 0.9044587016, "start": 5621, "tag": "USERNAME", "value": "arturopala" }, { "context": "rturopala/elm-monocle\", 0.59790553 )\n , ( \"frandibar/elm-font-awesome-5\", 0.58007091 )\n , ( \"ju", "end": 5681, "score": 0.8640347719, "start": 5672, "tag": "USERNAME", "value": "frandibar" }, { "context": "ar/elm-font-awesome-5\", 0.58007091 )\n , ( \"justgook/elm-image\", 0.56065333 )\n , ( \"miniBill/el", "end": 5737, "score": 0.9322950244, "start": 5729, "tag": "USERNAME", "value": "justgook" }, { "context": "justgook/elm-image\", 0.56065333 )\n , ( \"miniBill/elm-codec\", 0.55814043 )\n , ( \"zaboco/elm-", "end": 5784, "score": 0.7574851513, "start": 5779, "tag": "USERNAME", "value": "iBill" }, { "context": "( \"miniBill/elm-codec\", 0.55814043 )\n , ( \"zaboco/elm-draggable\", 0.55544337 )\n , ( \"billstc", "end": 5829, "score": 0.973724544, "start": 5823, "tag": "USERNAME", "value": "zaboco" }, { "context": "\"zaboco/elm-draggable\", 0.55544337 )\n , ( \"billstclair/elm-port-funnel\", 0.54505022 )\n , ( \"norpa", "end": 5883, "score": 0.9553872347, "start": 5872, "tag": "USERNAME", "value": "billstclair" }, { "context": "clair/elm-port-funnel\", 0.54505022 )\n , ( \"norpan/elm-html5-drag-drop\", 0.54306867 )\n , ( \"T", "end": 5934, "score": 0.910400033, "start": 5928, "tag": "USERNAME", "value": "norpan" }, { "context": " ( \"TSFoster/elm-uuid\", 0.53512402 )\n , ( \"ianmackenzie/elm-3d-camera\", 0.52840696 )\n , ( \"jfmenge", "end": 6041, "score": 0.9874431491, "start": 6029, "tag": "USERNAME", "value": "ianmackenzie" }, { "context": "ckenzie/elm-3d-camera\", 0.52840696 )\n , ( \"jfmengels/elm-review-unused\", 0.51706478 )\n , ( \"oha", "end": 6093, "score": 0.9726811051, "start": 6084, "tag": "USERNAME", "value": "jfmengels" }, { "context": "els/elm-review-unused\", 0.51706478 )\n , ( \"ohanhi/remotedata-http\", 0.49473739 )\n , ( \"icida", "end": 6146, "score": 0.8015214801, "start": 6140, "tag": "USERNAME", "value": "ohanhi" }, { "context": "nhi/remotedata-http\", 0.49473739 )\n , ( \"icidasset/elm-binary\", 0.46635256 )\n , ( \"CurrySoftw", "end": 6200, "score": 0.6870871782, "start": 6193, "tag": "USERNAME", "value": "idasset" }, { "context": "asset/elm-binary\", 0.46635256 )\n , ( \"CurrySoftware/elm-datepicker\", 0.46026974 )\n , ( \"abadi1", "end": 6253, "score": 0.5993532538, "start": 6245, "tag": "USERNAME", "value": "Software" }, { "context": "ftware/elm-datepicker\", 0.46026974 )\n , ( \"abadi199/elm-input-extra\", 0.45043369 )\n , ( \"tesk9", "end": 6305, "score": 0.951985836, "start": 6297, "tag": "USERNAME", "value": "abadi199" }, { "context": "99/elm-input-extra\", 0.45043369 )\n , ( \"tesk9/palette\", 0.44476755 )\n , ( \"zwilias/elm-r", "end": 6355, "score": 0.7703970671, "start": 6353, "tag": "USERNAME", "value": "k9" }, { "context": " , ( \"tesk9/palette\", 0.44476755 )\n , ( \"zwilias/elm-rosetree\", 0.44070751 )\n , ( \"annaghi/", "end": 6399, "score": 0.8258482218, "start": 6394, "tag": "USERNAME", "value": "ilias" }, { "context": "ake/proper-keyboard\", 0.43812191 )\n , ( \"lovasoa/elm-csv\", 0.43385591 )\n , ( \"billstclair/e", "end": 6552, "score": 0.7844907045, "start": 6547, "tag": "USERNAME", "value": "vasoa" }, { "context": " , ( \"lovasoa/elm-csv\", 0.43385591 )\n , ( \"billstclair/elm-websocket-client\", 0.4211239 )\n , ( \"c", "end": 6600, "score": 0.9420175552, "start": 6589, "tag": "USERNAME", "value": "billstclair" }, { "context": "m-websocket-client\", 0.4211239 )\n , ( \"ccapndave/elm-update-extra\", 0.41977621 )\n , ( \"robi", "end": 6658, "score": 0.7191313505, "start": 6653, "tag": "USERNAME", "value": "ndave" }, { "context": "dave/elm-update-extra\", 0.41977621 )\n , ( \"robinheghan/murmur3\", 0.41709346 )\n , ( \"icidasset/elm", "end": 6715, "score": 0.7984116673, "start": 6704, "tag": "USERNAME", "value": "robinheghan" }, { "context": "rasund/elm-ui-widgets\", 0.40258153 )\n , ( \"truqu/elm-review-noleftpizza\", 0.39533714 )\n , (", "end": 6865, "score": 0.9529220462, "start": 6860, "tag": "USERNAME", "value": "truqu" }, { "context": "/non-empty-list-alias\", 0.39042555 )\n , ( \"simonh1000/elm-jwt\", 0.38886083 )\n , ( \"pablohirafuji", "end": 7033, "score": 0.9933406711, "start": 7023, "tag": "USERNAME", "value": "simonh1000" }, { "context": "( \"simonh1000/elm-jwt\", 0.38886083 )\n , ( \"pablohirafuji/elm-qrcode\", 0.38671063 )\n , ( \"j-panasiuk", "end": 7083, "score": 0.8565263152, "start": 7070, "tag": "USERNAME", "value": "pablohirafuji" }, { "context": "ohirafuji/elm-qrcode\", 0.38671063 )\n , ( \"j-panasiuk/elm-ionicons\", 0.38431649 )\n , ( \"lattywar", "end": 7133, "score": 0.8803252578, "start": 7125, "tag": "USERNAME", "value": "panasiuk" }, { "context": "asiuk/elm-ionicons\", 0.38431649 )\n , ( \"lattyware/elm-json-diff\", 0.37994196 )\n , ( \"zwilias", "end": 7184, "score": 0.6100469828, "start": 7178, "tag": "USERNAME", "value": "tyware" }, { "context": "are/elm-json-diff\", 0.37994196 )\n , ( \"zwilias/elm-html-string\", 0.37515704 )\n , ( \"arowM", "end": 7234, "score": 0.5150556564, "start": 7231, "tag": "USERNAME", "value": "ias" }, { "context": "s/elm-html-string\", 0.37515704 )\n , ( \"arowM/elm-form-decoder\", 0.37362769 )\n , ( \"mgol", "end": 7284, "score": 0.5461223125, "start": 7283, "tag": "USERNAME", "value": "M" }, { "context": "wM/elm-form-decoder\", 0.37362769 )\n , ( \"mgold/elm-animation\", 0.37188307 )\n , ( \"ianmack", "end": 7335, "score": 0.657589972, "start": 7332, "tag": "USERNAME", "value": "old" }, { "context": " \"mgold/elm-animation\", 0.37188307 )\n , ( \"ianmackenzie/elm-triangular-mesh\", 0.37009167 )\n , ( \"T", "end": 7390, "score": 0.9693232775, "start": 7378, "tag": "USERNAME", "value": "ianmackenzie" }, { "context": "oster/elm-tuple-extra\", 0.36731534 )\n , ( \"tripokey/elm-fuzzy\", 0.36692263 )\n , ( \"Punie/elm-p", "end": 7500, "score": 0.9373905659, "start": 7492, "tag": "USERNAME", "value": "tripokey" }, { "context": "uset/elm-json-decode\", 0.32811851 )\n , ( \"ktonon/elm-crypto\", 0.32801593 )\n , ( \"elm-commun", "end": 7989, "score": 0.7505899668, "start": 7984, "tag": "USERNAME", "value": "tonon" }, { "context": "\"jzxhuang/http-extras\", 0.32137401 )\n , ( \"folkertdev/elm-deque\", 0.32109268 )\n , ( \"ianmackenzi", "end": 8190, "score": 0.9014683962, "start": 8180, "tag": "USERNAME", "value": "folkertdev" }, { "context": "lkertdev/elm-deque\", 0.32109268 )\n , ( \"ianmackenzie/elm-1d-parameter\", 0.32006002 )\n , ( \"ccap", "end": 8241, "score": 0.7750678658, "start": 8232, "tag": "USERNAME", "value": "mackenzie" }, { "context": "( \"1602/elm-feather\", 0.31660394 )\n , ( \"mdgriffith/style-elements\", 0.31212673 )\n , ( \"NoRedI", "end": 8494, "score": 0.7276363373, "start": 8486, "tag": "USERNAME", "value": "griffith" }, { "context": "\"NoRedInk/elm-uuid\", 0.31183615 )\n , ( \"perzanko/elm-loading\", 0.30855664 )\n , ( \"linuss/sm", "end": 8592, "score": 0.8028076291, "start": 8587, "tag": "USERNAME", "value": "zanko" }, { "context": "rzanko/elm-loading\", 0.30855664 )\n , ( \"linuss/smooth-scroll\", 0.3077922 )\n , ( \"etaque/e", "end": 8639, "score": 0.736415863, "start": 8636, "tag": "USERNAME", "value": "uss" }, { "context": " \"etaque/elm-form\", 0.30348605 )\n , ( \"gingko/time-distance\", 0.30336385 )\n , ( \"GlobalW", "end": 8731, "score": 0.6784592867, "start": 8729, "tag": "USERNAME", "value": "ko" }, { "context": "lm-string-conversions\", 0.29331575 )\n , ( \"AdrianRibao/elm-derberos-date\", 0.28990482 )\n , ( \"kal", "end": 8896, "score": 0.9285176992, "start": 8885, "tag": "USERNAME", "value": "AdrianRibao" }, { "context": "/elm-derberos-date\", 0.28990482 )\n , ( \"kalutheo/elm-ui-explorer\", 0.28612503 )\n , ( \"justg", "end": 8951, "score": 0.5736138821, "start": 8946, "tag": "USERNAME", "value": "utheo" }, { "context": "o/elm-ui-explorer\", 0.28612503 )\n , ( \"justgage/tachyons-elm\", 0.28523698 )\n , ( \"Gizra/el", "end": 9004, "score": 0.7598153949, "start": 9000, "tag": "USERNAME", "value": "gage" }, { "context": "tgage/tachyons-elm\", 0.28523698 )\n , ( \"Gizra/elm-debouncer\", 0.28504558 )\n , ( \"turboMa", "end": 9051, "score": 0.5691813827, "start": 9049, "tag": "USERNAME", "value": "ra" }, { "context": "( \"the-sett/elm-color\", 0.28403224 )\n , ( \"billstclair/elm-sortable-table\", 0.28271317 )\n , ( \"ca", "end": 9198, "score": 0.8312026262, "start": 9187, "tag": "USERNAME", "value": "billstclair" }, { "context": "sortable-table\", 0.28271317 )\n , ( \"capitalist/elm-octicons\", 0.28195837 )\n , ( \"simonh10", "end": 9256, "score": 0.5150219798, "start": 9253, "tag": "USERNAME", "value": "ist" }, { "context": "pitalist/elm-octicons\", 0.28195837 )\n , ( \"simonh1000/elm-colorpicker\", 0.27117854 )\n , ( \"pilat", "end": 9308, "score": 0.9789228439, "start": 9298, "tag": "USERNAME", "value": "simonh1000" }, { "context": "h1000/elm-colorpicker\", 0.27117854 )\n , ( \"pilatch/flip\", 0.26704357 )\n , ( \"folkertdev/elm-s", "end": 9360, "score": 0.8899728656, "start": 9353, "tag": "USERNAME", "value": "pilatch" }, { "context": " , ( \"pilatch/flip\", 0.26704357 )\n , ( \"folkertdev/elm-state\", 0.26525221 )\n , ( \"jfmengels/e", "end": 9404, "score": 0.9523499608, "start": 9394, "tag": "USERNAME", "value": "folkertdev" }, { "context": "\"folkertdev/elm-state\", 0.26525221 )\n , ( \"jfmengels/elm-review-debug\", 0.26221985 )\n , ( \"TSFo", "end": 9452, "score": 0.9195436835, "start": 9443, "tag": "USERNAME", "value": "jfmengels" }, { "context": "TSFoster/elm-sha1\", 0.26165276 )\n , ( \"klazuka/elm-json-tree-view\", 0.26067484 )\n , ( \"Ja", "end": 9551, "score": 0.5691676736, "start": 9548, "tag": "USERNAME", "value": "uka" }, { "context": "elm-json-tree-view\", 0.26067484 )\n , ( \"Janiczek/elm-bidict\", 0.25968504 )\n , ( \"danmarcab/", "end": 9607, "score": 0.6201778054, "start": 9602, "tag": "USERNAME", "value": "iczek" }, { "context": "aniczek/elm-bidict\", 0.25968504 )\n , ( \"danmarcab/material-icons\", 0.25622646 )\n , ( \"basti1", "end": 9656, "score": 0.7644907236, "start": 9650, "tag": "USERNAME", "value": "marcab" }, { "context": "arcab/material-icons\", 0.25622646 )\n , ( \"basti1302/elm-human-readable-filesize\", 0.24826223 )\n ", "end": 9706, "score": 0.5859341025, "start": 9701, "tag": "USERNAME", "value": "asti1" }, { "context": "-readable-filesize\", 0.24826223 )\n , ( \"panthershark/email-parser\", 0.24690589 )\n , ( \"fredcy/e", "end": 9778, "score": 0.7958289981, "start": 9769, "tag": "USERNAME", "value": "thershark" }, { "context": " \"fredcy/elm-parseint\", 0.24670168 )\n , ( \"jorgengranseth/elm-string-format\", 0.24568559 )\n , ( \"hec", "end": 9882, "score": 0.9361031055, "start": 9868, "tag": "USERNAME", "value": "jorgengranseth" }, { "context": "zie/elm-geometry-test\", 0.24302217 )\n , ( \"billstclair/elm-sha256\", 0.24141562 )\n , ( \"ianmackenz", "end": 10049, "score": 0.6835469007, "start": 10038, "tag": "USERNAME", "value": "billstclair" }, { "context": "\"Chadtech/unique-list\", 0.22899954 )\n , ( \"jamesmacaulay/elm-graphql\", 0.22776995 )\n , ( \"ymtszw/el", "end": 10442, "score": 0.9730141759, "start": 10429, "tag": "USERNAME", "value": "jamesmacaulay" }, { "context": "ymtszw/elm-xml-decode\", 0.22661962 )\n , ( \"billstclair/elm-localstorage\", 0.22374157 )\n , ( ", "end": 10539, "score": 0.8066951632, "start": 10533, "tag": "USERNAME", "value": "billst" }, { "context": "lair/elm-localstorage\", 0.22374157 )\n , ( \"mthadley/elm-hash-routing\", 0.22155574 )\n , ( \"capp", "end": 10598, "score": 0.9720377922, "start": 10590, "tag": "USERNAME", "value": "mthadley" }, { "context": "ley/elm-hash-routing\", 0.22155574 )\n , ( \"cappyzawa/elm-ui-colors\", 0.22082952 )\n , ( \"the-set", "end": 10653, "score": 0.8950241208, "start": 10645, "tag": "USERNAME", "value": "appyzawa" }, { "context": "e-sett/elm-syntax-dsl\", 0.22020009 )\n , ( \"damienklinnert/elm-spinner\", 0.21776168 )\n , ( \"matthewsj", "end": 10762, "score": 0.9881151319, "start": 10748, "tag": "USERNAME", "value": "damienklinnert" }, { "context": "nklinnert/elm-spinner\", 0.21776168 )\n , ( \"matthewsj/elm-ordering\", 0.21745709 )\n , ( \"folkertd", "end": 10812, "score": 0.957800746, "start": 10803, "tag": "USERNAME", "value": "matthewsj" }, { "context": "atthewsj/elm-ordering\", 0.21745709 )\n , ( \"folkertdev/elm-flate\", 0.2170955 )\n , ( \"carwow/elm-s", "end": 10864, "score": 0.9009945989, "start": 10854, "tag": "USERNAME", "value": "folkertdev" }, { "context": " \"folkertdev/elm-flate\", 0.2170955 )\n , ( \"carwow/elm-slider\", 0.21197636 )\n , ( \"jinjor/elm", "end": 10908, "score": 0.7004979849, "start": 10902, "tag": "USERNAME", "value": "carwow" }, { "context": " ( \"carwow/elm-slider\", 0.21197636 )\n , ( \"jinjor/elm-diff\", 0.21185364 )\n , ( \"ursi/elm-css", "end": 10954, "score": 0.9928919077, "start": 10948, "tag": "USERNAME", "value": "jinjor" }, { "context": "lm-embed-youtube\", 0.20671199 )\n , ( \"PaackEng/elm-ui-dialog\", 0.2006389 )\n , ( \"CoderDen", "end": 11153, "score": 0.6434354186, "start": 11150, "tag": "USERNAME", "value": "Eng" }, { "context": "ennis/elm-time-format\", 0.19815286 )\n , ( \"gicentre/elm-vegalite\", 0.19740117 )\n , ( \"yotamDvi", "end": 11259, "score": 0.7551552057, "start": 11251, "tag": "USERNAME", "value": "gicentre" }, { "context": "gicentre/elm-vegalite\", 0.19740117 )\n , ( \"yotamDvir/elm-pivot\", 0.19665382 )\n , ( \"NoRedInk/el", "end": 11310, "score": 0.8887504339, "start": 11301, "tag": "USERNAME", "value": "yotamDvir" }, { "context": " , ( \"ggb/numeral-elm\", 0.19337426 )\n , ( \"zwilias/json-decode-exploration\", 0.1918353 )\n , (", "end": 11454, "score": 0.8501349092, "start": 11447, "tag": "USERNAME", "value": "zwilias" }, { "context": "els/elm-review-common\", 0.18847052 )\n , ( \"BrianHicks/elm-css-reset\", 0.18822892 )\n , ( \"Jan", "end": 11568, "score": 0.9133788943, "start": 11562, "tag": "USERNAME", "value": "BrianH" }, { "context": "anHicks/elm-css-reset\", 0.18822892 )\n , ( \"Janiczek/elm-graph\", 0.18803528 )\n , ( \"ericgj/elm-", "end": 11623, "score": 0.9054815769, "start": 11615, "tag": "USERNAME", "value": "Janiczek" }, { "context": "( \"Janiczek/elm-graph\", 0.18803528 )\n , ( \"ericgj/elm-csv-decode\", 0.1876914 )\n , ( \"periodi", "end": 11668, "score": 0.9220811129, "start": 11662, "tag": "USERNAME", "value": "ericgj" }, { "context": "asoa/elm-rolling-list\", 0.18097298 )\n , ( \"krisajenkins/elm-astar\", 0.18017187 )\n , ( \"BrianHicks/", "end": 11919, "score": 0.9811643958, "start": 11907, "tag": "USERNAME", "value": "krisajenkins" }, { "context": "risajenkins/elm-astar\", 0.18017187 )\n , ( \"BrianHicks/elm-particle\", 0.17786303 )\n , ( \"folkertd", "end": 11968, "score": 0.9777625799, "start": 11958, "tag": "USERNAME", "value": "BrianHicks" }, { "context": "ianHicks/elm-particle\", 0.17786303 )\n , ( \"folkertdev/elm-sha2\", 0.17785039 )\n , ( \"Garados007/e", "end": 12020, "score": 0.8189895153, "start": 12010, "tag": "USERNAME", "value": "folkertdev" }, { "context": " \"folkertdev/elm-sha2\", 0.17785039 )\n , ( \"Garados007/elm-svg-parser\", 0.17754484 )\n , ( \"gample", "end": 12068, "score": 0.6958302259, "start": 12058, "tag": "USERNAME", "value": "Garados007" }, { "context": "dos007/elm-svg-parser\", 0.17754484 )\n , ( \"gampleman/elm-mapbox\", 0.17754114 )\n , ( \"NoRedInk/e", "end": 12121, "score": 0.9641671181, "start": 12112, "tag": "USERNAME", "value": "gampleman" }, { "context": "RedInk/elm-compare\", 0.17712889 )\n , ( \"joneshf/elm-tagged\", 0.17681944 )\n , ( \"the-sett/l", "end": 12217, "score": 0.6947331429, "start": 12213, "tag": "USERNAME", "value": "eshf" }, { "context": "zy-tree-with-zipper\", 0.17263832 )\n , ( \"jfmengels/elm-review-documentation\", 0.17208178 )\n ,", "end": 12373, "score": 0.5717895031, "start": 12366, "tag": "USERNAME", "value": "mengels" }, { "context": "sund/elm-ui-framework\", 0.16892692 )\n , ( \"ianmackenzie/elm-units-prefixed\", 0.16798459 )\n ", "end": 12534, "score": 0.5880436897, "start": 12530, "tag": "USERNAME", "value": "ianm" }, { "context": "m-ui-framework\", 0.16892692 )\n , ( \"ianmackenzie/elm-units-prefixed\", 0.16798459 )\n , ( \"jx", "end": 12542, "score": 0.5842533112, "start": 12537, "tag": "USERNAME", "value": "enzie" }, { "context": "ie/elm-units-prefixed\", 0.16798459 )\n , ( \"jxxcarlson/elm-typed-time\", 0.16708656 )\n , ( \"ianmac", "end": 12600, "score": 0.9723851085, "start": 12590, "tag": "USERNAME", "value": "jxxcarlson" }, { "context": "arlson/elm-typed-time\", 0.16708656 )\n , ( \"ianmackenzie/elm-float-extra\", 0.16430595 )\n , ( \"matke", "end": 12656, "score": 0.9840361476, "start": 12644, "tag": "USERNAME", "value": "ianmackenzie" }, { "context": "enzie/elm-float-extra\", 0.16430595 )\n , ( \"matken11235/html-styled-extra\", 0.16388741 )\n , ( \"sup", "end": 12712, "score": 0.9393196702, "start": 12701, "tag": "USERNAME", "value": "matken11235" }, { "context": "tml-styled-extra\", 0.16388741 )\n , ( \"supermacro/elm-antd\", 0.16388741 )\n , ( \"jasonliang-d", "end": 12769, "score": 0.6919225454, "start": 12764, "tag": "USERNAME", "value": "macro" }, { "context": " \"supermacro/elm-antd\", 0.16388741 )\n , ( \"jasonliang-dev/elm-heroicons\", 0.16388741 )\n , ( \"robinhe", "end": 12821, "score": 0.9924713969, "start": 12807, "tag": "USERNAME", "value": "jasonliang-dev" }, { "context": "ang-dev/elm-heroicons\", 0.16388741 )\n , ( \"robinheghan/keyboard-events\", 0.16388741 )\n , ( \"Maybe", "end": 12875, "score": 0.8211997747, "start": 12864, "tag": "USERNAME", "value": "robinheghan" }, { "context": "/keyboard-events\", 0.16388741 )\n , ( \"MaybeJustJames/yaml\", 0.16388741 )\n , ( \"coinop-logan/elm", "end": 12934, "score": 0.5498677492, "start": 12925, "tag": "USERNAME", "value": "JustJames" }, { "context": "iew-noredundantcons\", 0.16278661 )\n , ( \"ahstro/elm-bulma-classes\", 0.16268257 )\n , ( \"rlu", "end": 13157, "score": 0.5072598457, "start": 13153, "tag": "USERNAME", "value": "stro" }, { "context": "tro/elm-bulma-classes\", 0.16268257 )\n , ( \"rluiten/elm-text-search\", 0.16195907 )\n , ( \"norpa", "end": 13211, "score": 0.7301599383, "start": 13204, "tag": "USERNAME", "value": "rluiten" }, { "context": "en/elm-text-search\", 0.16195907 )\n , ( \"norpan/elm-json-patch\", 0.1618311 )\n , ( \"avh4/el", "end": 13262, "score": 0.5461666584, "start": 13259, "tag": "USERNAME", "value": "pan" }, { "context": " , ( \"avh4/elm-fifo\", 0.16165577 )\n , ( \"eriktim/elm-protocol-buffers\", 0.1569727 )\n , ( \"z", "end": 13354, "score": 0.9859787226, "start": 13347, "tag": "USERNAME", "value": "eriktim" }, { "context": "elm-protocol-buffers\", 0.1569727 )\n , ( \"zwilias/elm-utf-tools\", 0.15675438 )\n , ( \"fabhof/", "end": 13410, "score": 0.6748394966, "start": 13405, "tag": "USERNAME", "value": "ilias" }, { "context": "lias/elm-utf-tools\", 0.15675438 )\n , ( \"fabhof/elm-ui-datepicker\", 0.15601158 )\n , ( \"Kra", "end": 13459, "score": 0.8567444682, "start": 13456, "tag": "USERNAME", "value": "hof" }, { "context": "m-ui-datepicker\", 0.15601158 )\n , ( \"Kraxorax/elm-matrix-a\", 0.1550815 )\n , ( \"Zinggi/el", "end": 13514, "score": 0.5767429471, "start": 13512, "tag": "USERNAME", "value": "ax" }, { "context": "pd-andy/elm-web-audio\", 0.14559802 )\n , ( \"ianmackenzie/elm-units-interval\", 0.14409245 )\n , ( \"al", "end": 13713, "score": 0.8588817716, "start": 13701, "tag": "USERNAME", "value": "ianmackenzie" }, { "context": "ie/elm-units-interval\", 0.14409245 )\n , ( \"alex-tan/elm-dialog\", 0.14326271 )\n , ( \"joakin/elm", "end": 13769, "score": 0.8390108943, "start": 13761, "tag": "USERNAME", "value": "alex-tan" }, { "context": "alex-tan/elm-dialog\", 0.14326271 )\n , ( \"joakin/elm-grid\", 0.14239279 )\n , ( \"marcosh/elm-", "end": 13815, "score": 0.7861874104, "start": 13811, "tag": "USERNAME", "value": "akin" }, { "context": " , ( \"joakin/elm-grid\", 0.14239279 )\n , ( \"marcosh/elm-html-to-unicode\", 0.14136611 )\n , ( \"K", "end": 13860, "score": 0.8727936745, "start": 13853, "tag": "USERNAME", "value": "marcosh" }, { "context": " , ( \"K-Adam/elm-dom\", 0.14100964 )\n , ( \"stoeffel/elm-verify\", 0.14049657 )\n , ( \"thaterikpe", "end": 13960, "score": 0.7536096573, "start": 13952, "tag": "USERNAME", "value": "stoeffel" }, { "context": " \"stoeffel/elm-verify\", 0.14049657 )\n , ( \"thaterikperson/elm-strftime\", 0.14048949 )\n , ( \"joshfori", "end": 14014, "score": 0.8966832161, "start": 14000, "tag": "USERNAME", "value": "thaterikperson" }, { "context": "ikperson/elm-strftime\", 0.14048949 )\n , ( \"joshforisha/elm-html-entities\", 0.14014579 )\n , ( \"Chr", "end": 14067, "score": 0.9463661909, "start": 14056, "tag": "USERNAME", "value": "joshforisha" }, { "context": "html-entities\", 0.14014579 )\n , ( \"ChristophP/elm-i18next\", 0.14009583 )\n , ( \"WhileTruu", "end": 14124, "score": 0.5944315791, "start": 14122, "tag": "USERNAME", "value": "hP" }, { "context": "ng/elm-ui-dropdown\", 0.13349351 )\n , ( \"jinjor/elm-xml-parser\", 0.13308261 )\n , ( \"Spaxe/", "end": 14332, "score": 0.8302533627, "start": 14329, "tag": "USERNAME", "value": "jor" }, { "context": "lm-game-resources\", 0.13123514 )\n , ( \"justgook/webgl-shape\", 0.13025186 )\n , ( \"miyamoen/", "end": 14482, "score": 0.8820900321, "start": 14478, "tag": "USERNAME", "value": "gook" }, { "context": "yamoen/select-list\", 0.12993603 )\n , ( \"cmditch/elm-ethereum\", 0.12836444 )\n , ( \"visotype", "end": 14579, "score": 0.7175645232, "start": 14575, "tag": "USERNAME", "value": "itch" }, { "context": "/svg-path-lowlevel\", 0.12684362 )\n , ( \"rtfeldman/elm-sorter-experiment\", 0.12623643 )\n , ( ", "end": 14732, "score": 0.5791777372, "start": 14726, "tag": "USERNAME", "value": "eldman" }, { "context": "/structured-writer\", 0.12619772 )\n , ( \"lucamug/style-framework\", 0.12605465 )\n , ( \"stoef", "end": 14843, "score": 0.6106371284, "start": 14839, "tag": "USERNAME", "value": "amug" }, { "context": " , ( \"STTR13/ziplist\", 0.12570977 )\n , ( \"FabienHenon/elm-infinite-list-view\", 0.12559581 )\n ", "end": 14981, "score": 0.4555526674, "start": 14978, "tag": "NAME", "value": "Fab" }, { "context": " ( \"STTR13/ziplist\", 0.12570977 )\n , ( \"FabienHenon/elm-infinite-list-view\", 0.12559581 )\n ", "end": 14985, "score": 0.6276377439, "start": 14981, "tag": "USERNAME", "value": "ienH" }, { "context": "STTR13/ziplist\", 0.12570977 )\n , ( \"FabienHenon/elm-infinite-list-view\", 0.12559581 )\n ,", "end": 14987, "score": 0.5093511939, "start": 14985, "tag": "NAME", "value": "en" }, { "context": "TR13/ziplist\", 0.12570977 )\n , ( \"FabienHenon/elm-infinite-list-view\", 0.12559581 )\n , (", "end": 14989, "score": 0.5675421953, "start": 14987, "tag": "USERNAME", "value": "on" }, { "context": "lm-infinite-list-view\", 0.12559581 )\n , ( \"FabienHenon/elm-infinite-scroll\", 0.12528226 )\n ,", "end": 15047, "score": 0.6543539166, "start": 15041, "tag": "NAME", "value": "Fabien" }, { "context": "inite-list-view\", 0.12559581 )\n , ( \"FabienHenon/elm-infinite-scroll\", 0.12528226 )\n , ", "end": 15048, "score": 0.7051869035, "start": 15047, "tag": "USERNAME", "value": "H" }, { "context": "nite-list-view\", 0.12559581 )\n , ( \"FabienHenon/elm-infinite-scroll\", 0.12528226 )\n , ( ", "end": 15050, "score": 0.6524553895, "start": 15048, "tag": "NAME", "value": "en" }, { "context": "te-list-view\", 0.12559581 )\n , ( \"FabienHenon/elm-infinite-scroll\", 0.12528226 )\n , ( \"s", "end": 15052, "score": 0.5361069441, "start": 15050, "tag": "USERNAME", "value": "on" }, { "context": "( \"coinop-logan/phace\", 0.12151759 )\n , ( \"BrianHicks/elm-trend\", 0.12024157 )\n , ( \"MartinSStew", "end": 15634, "score": 0.7964273691, "start": 15624, "tag": "USERNAME", "value": "BrianHicks" }, { "context": "\"BrianHicks/elm-trend\", 0.12024157 )\n , ( \"MartinSStewart/elm-audio\", 0.11849084 )\n , ( \"rl-king/elm", "end": 15687, "score": 0.9174270034, "start": 15673, "tag": "USERNAME", "value": "MartinSStewart" }, { "context": "-king/elm-scroll-to\", 0.11522835 )\n , ( \"erlandsona/assoc-set\", 0.11493819 )\n , ( \"justgoo", "end": 15782, "score": 0.5150087476, "start": 15778, "tag": "USERNAME", "value": "land" }, { "context": "\"erlandsona/assoc-set\", 0.11493819 )\n , ( \"justgook/webgl-playground\", 0.11294313 )\n , ( \"tesk", "end": 15833, "score": 0.7932493091, "start": 15825, "tag": "USERNAME", "value": "justgook" }, { "context": ", ( \"w0rm/elm-physics\", 0.11193187 )\n , ( \"jgrenat/elm-html-test-runner\", 0.1106782 )\n , ( \"k", "end": 15990, "score": 0.9340324998, "start": 15983, "tag": "USERNAME", "value": "jgrenat" }, { "context": "t/elm-html-test-runner\", 0.1106782 )\n , ( \"krisajenkins/elm-exts\", 0.11045032 )\n , ( \"ianmackenzie", "end": 16051, "score": 0.9801239967, "start": 16039, "tag": "USERNAME", "value": "krisajenkins" }, { "context": "krisajenkins/elm-exts\", 0.11045032 )\n , ( \"ianmackenzie/elm-interval\", 0.11014532 )\n , ( \"mhoare/e", "end": 16101, "score": 0.991096139, "start": 16089, "tag": "USERNAME", "value": "ianmackenzie" }, { "context": ", ( \"Punie/elm-matrix\", 0.10890224 )\n , ( \"bburdette/websocket\", 0.1081962 )\n , ( \"danyx23/elm-", "end": 16241, "score": 0.7822358608, "start": 16232, "tag": "USERNAME", "value": "bburdette" }, { "context": " \"bburdette/websocket\", 0.1081962 )\n , ( \"danyx23/elm-mimetype\", 0.10773962 )\n , ( \"arowM/el", "end": 16286, "score": 0.6858439445, "start": 16280, "tag": "USERNAME", "value": "anyx23" }, { "context": " \"arowM/elm-reference\", 0.10549205 )\n , ( \"mdgriffith/stylish-elephants\", 0.1052336 )\n , ( \"yota", "end": 16598, "score": 0.777541697, "start": 16588, "tag": "USERNAME", "value": "mdgriffith" }, { "context": "owM/elm-neat-layout\", 0.09346707 )\n , ( \"bgrosse-midokura/composable-form\", 0.09309911 )\n , ( \"jxxca", "end": 17465, "score": 0.7403042316, "start": 17451, "tag": "USERNAME", "value": "rosse-midokura" }, { "context": "kura/composable-form\", 0.09309911 )\n , ( \"jxxcarlson/elm-cell-grid\", 0.0918109 )\n , ( \"indicatr", "end": 17520, "score": 0.897880435, "start": 17511, "tag": "USERNAME", "value": "xxcarlson" }, { "context": "-chartjs-webcomponent\", 0.09174394 )\n , ( \"andre-dietrich/parser-combinators\", 0.09165459 )\n , ( \"ac", "end": 17640, "score": 0.8259045482, "start": 17626, "tag": "USERNAME", "value": "andre-dietrich" }, { "context": "parser-combinators\", 0.09165459 )\n , ( \"achutkiran/material-components-elm\", 0.09163468 )\n , ", "end": 17698, "score": 0.6976680756, "start": 17691, "tag": "USERNAME", "value": "utkiran" }, { "context": "ial-components-elm\", 0.09163468 )\n , ( \"inkuzmin/elm-multiselect\", 0.09139183 )\n , ( \"stoef", "end": 17759, "score": 0.5417859554, "start": 17754, "tag": "USERNAME", "value": "uzmin" }, { "context": "in/elm-multiselect\", 0.09139183 )\n , ( \"stoeffel/editable\", 0.09126776 )\n , ( \"Chadtech/id\"", "end": 17812, "score": 0.557525754, "start": 17807, "tag": "USERNAME", "value": "effel" }, { "context": "oabroad/commatosed\", 0.09054461 )\n , ( \"kirchner/elm-selectize\", 0.0905111 )\n , ( \"phollyer", "end": 17948, "score": 0.6867667437, "start": 17943, "tag": "USERNAME", "value": "chner" }, { "context": "kirchner/elm-selectize\", 0.0905111 )\n , ( \"phollyer/elm-phoenix-websocket\", 0.09013808 )\n , ( ", "end": 17998, "score": 0.9212203026, "start": 17990, "tag": "USERNAME", "value": "phollyer" }, { "context": "-css-modern-normalize\", 0.09013808 )\n , ( \"gampleman/elm-examples-helper\", 0.09013808 )\n , ( \"m", "end": 18116, "score": 0.8491230011, "start": 18107, "tag": "USERNAME", "value": "gampleman" }, { "context": "( \"malaire/elm-uint64\", 0.09013808 )\n , ( \"JohnBugner/elm-matrix\", 0.09013808 )\n , ( \"TheSacredL", "end": 18222, "score": 0.9925668836, "start": 18212, "tag": "USERNAME", "value": "JohnBugner" }, { "context": "nBugner/elm-matrix\", 0.09013808 )\n , ( \"TheSacredLipton/elm-ui-hexcolor\", 0.09013808 )\n , ( \"jfmen", "end": 18277, "score": 0.8090634346, "start": 18265, "tag": "USERNAME", "value": "SacredLipton" }, { "context": "ipton/elm-ui-hexcolor\", 0.09013808 )\n , ( \"jfmengels/elm-review-the-elm-architecture\", 0.09013808 )\n ", "end": 18331, "score": 0.9116075635, "start": 18322, "tag": "USERNAME", "value": "jfmengels" }, { "context": "-the-elm-architecture\", 0.09013808 )\n , ( \"jschomay/elm-paginate\", 0.08956332 )\n , ( \"alex-tan", "end": 18400, "score": 0.9036977291, "start": 18392, "tag": "USERNAME", "value": "jschomay" }, { "context": "jschomay/elm-paginate\", 0.08956332 )\n , ( \"alex-tan/elm-tree-diagram\", 0.08945404 )\n , ( \"xarv", "end": 18450, "score": 0.8188988566, "start": 18442, "tag": "USERNAME", "value": "alex-tan" }, { "context": "elm-game-essentials\", 0.08916985 )\n , ( \"mgold/elm-geojson\", 0.08897403 )\n , ( \"marshallf", "end": 18651, "score": 0.5766893029, "start": 18648, "tag": "USERNAME", "value": "old" }, { "context": " ( \"mgold/elm-geojson\", 0.08897403 )\n , ( \"marshallformula/elm-swiper\", 0.0886618 )\n , ( \"jxxcarlson/", "end": 18707, "score": 0.9965613484, "start": 18692, "tag": "USERNAME", "value": "marshallformula" }, { "context": "hallformula/elm-swiper\", 0.0886618 )\n , ( \"jxxcarlson/elm-markdown\", 0.08820943 )\n , ( \"Microsof", "end": 18756, "score": 0.995362103, "start": 18746, "tag": "USERNAME", "value": "jxxcarlson" }, { "context": "ewmana/chroma-elm\", 0.08810571 )\n , ( \"justgook/alt-linear-algebra\", 0.08789221 )\n , ( \"la", "end": 18910, "score": 0.8130294085, "start": 18906, "tag": "USERNAME", "value": "gook" }, { "context": "\"z5h/component-result\", 0.08501743 )\n , ( \"BrianHicks/elm-string-graphemes\", 0.08438992 )\n , ( \"", "end": 19222, "score": 0.6978133917, "start": 19212, "tag": "USERNAME", "value": "BrianHicks" }, { "context": "( \"tremlab/bugsnag-elm\", 0.0819437 )\n , ( \"fredcy/elm-debouncer\", 0.0819437 )\n , ( \"dzuk-mut", "end": 19426, "score": 0.7698094845, "start": 19420, "tag": "USERNAME", "value": "fredcy" }, { "context": "helovek0v/bbase64\", 0.0819437 )\n , ( \"andre-dietrich/elm-conditional\", 0.0819437 )\n , ( \"r", "end": 19673, "score": 0.7074611187, "start": 19670, "tag": "USERNAME", "value": "die" }, { "context": "k0v/bbase64\", 0.0819437 )\n , ( \"andre-dietrich/elm-conditional\", 0.0819437 )\n , ( \"robinh", "end": 19678, "score": 0.6140128374, "start": 19675, "tag": "USERNAME", "value": "ich" }, { "context": "etrich/elm-conditional\", 0.0819437 )\n , ( \"robinheghan/elm-deque\", 0.0819437 )\n , ( \"MartinSStewa", "end": 19733, "score": 0.8193167448, "start": 19722, "tag": "USERNAME", "value": "robinheghan" }, { "context": "\"robinheghan/elm-deque\", 0.0819437 )\n , ( \"MartinSStewart/elm-serialize\", 0.0819437 )\n , ( \"jxxcarls", "end": 19785, "score": 0.8845069408, "start": 19771, "tag": "USERNAME", "value": "MartinSStewart" }, { "context": "SStewart/elm-serialize\", 0.0819437 )\n , ( \"jxxcarlson/hex\", 0.08025377 )\n , ( \"prikhi/decimal\", ", "end": 19837, "score": 0.7678249478, "start": 19827, "tag": "USERNAME", "value": "jxxcarlson" }, { "context": "( \"league/unique-id\", 0.07962549 )\n , ( \"jschomay/elm-narrative-engine\", 0.07850368 )\n , ( \"", "end": 19966, "score": 0.8216540813, "start": 19960, "tag": "USERNAME", "value": "chomay" }, { "context": "lm-narrative-engine\", 0.07850368 )\n , ( \"blissfully/elm-chartjs-webcomponent\", 0.07789183 )\n ,", "end": 20026, "score": 0.717607379, "start": 20018, "tag": "USERNAME", "value": "issfully" }, { "context": "-chartjs-webcomponent\", 0.07789183 )\n , ( \"jxxcarlson/elm-graph\", 0.07777827 )\n , ( \"samhstn/tim", "end": 20090, "score": 0.9886578321, "start": 20080, "tag": "USERNAME", "value": "jxxcarlson" }, { "context": "xcarlson/elm-graph\", 0.07777827 )\n , ( \"samhstn/time-format\", 0.07741896 )\n , ( \"jxxcarlso", "end": 20136, "score": 0.7093957067, "start": 20132, "tag": "USERNAME", "value": "hstn" }, { "context": " \"samhstn/time-format\", 0.07741896 )\n , ( \"jxxcarlson/elm-pseudorandom\", 0.0772143 )\n , ( \"the-s", "end": 20187, "score": 0.8111073375, "start": 20177, "tag": "USERNAME", "value": "jxxcarlson" }, { "context": "ermario/elm-countries\", 0.07415019 )\n , ( \"gribouille/elm-treeview\", 0.07393474 )\n , ( \"etaque/e", "end": 20767, "score": 0.8001072407, "start": 20757, "tag": "USERNAME", "value": "gribouille" }, { "context": "047aka/elm-hsl-color\", 0.0731552 )\n , ( \"ryry0/elm-numeric\", 0.07297005 )\n , ( \"rogerioch", "end": 21169, "score": 0.7360260487, "start": 21166, "tag": "USERNAME", "value": "ry0" }, { "context": " ( \"ryry0/elm-numeric\", 0.07297005 )\n , ( \"rogeriochaves/elm-test-bdd-style\", 0.07295471 )\n , ( \"wa", "end": 21223, "score": 0.9372425079, "start": 21210, "tag": "USERNAME", "value": "rogeriochaves" }, { "context": "es/elm-test-bdd-style\", 0.07295471 )\n , ( \"waratuman/elm-coder\", 0.07280749 )\n , ( \"hrldcpr/elm", "end": 21280, "score": 0.7593520284, "start": 21271, "tag": "USERNAME", "value": "waratuman" }, { "context": "waratuman/elm-coder\", 0.07280749 )\n , ( \"hrldcpr/elm-cons\", 0.0725321 )\n , ( \"prozacchiwawa", "end": 21326, "score": 0.6770576239, "start": 21321, "tag": "USERNAME", "value": "ldcpr" }, { "context": "( \"hrldcpr/elm-cons\", 0.0725321 )\n , ( \"prozacchiwawa/elm-keccak\", 0.07208187 )\n , ( \"jims/html-", "end": 21376, "score": 0.6033142805, "start": 21366, "tag": "USERNAME", "value": "zacchiwawa" }, { "context": "html-parser\", 0.07206386 )\n , ( \"PanagiotisGeorgiadis/elm-datepicker\", 0.07190215 )\n , (", "end": 21473, "score": 0.5679867268, "start": 21471, "tag": "USERNAME", "value": "Ge" }, { "context": "ser\", 0.07206386 )\n , ( \"PanagiotisGeorgiadis/elm-datepicker\", 0.07190215 )\n , ( \"Lesley", "end": 21481, "score": 0.5064473152, "start": 21479, "tag": "USERNAME", "value": "is" }, { "context": "iss/elm-rte-toolkit\", 0.0716879 )\n , ( \"isaacseymour/deprecated-time\", 0.07141021 )\n , ( \"sport", "end": 21634, "score": 0.7173631191, "start": 21625, "tag": "USERNAME", "value": "acseymour" }, { "context": "\"Chadtech/elm-money\", 0.07039523 )\n , ( \"kuzminadya/mogeefont\", 0.07026973 )\n , ( \"fifth-postu", "end": 21774, "score": 0.6403005719, "start": 21766, "tag": "USERNAME", "value": "zminadya" }, { "context": "dmy/elm-imf-date-time\", 0.06669301 )\n , ( \"SiriusStarr/elm-password-strength\", 0.06574762 )\n , ( ", "end": 22185, "score": 0.7802122831, "start": 22174, "tag": "USERNAME", "value": "SiriusStarr" }, { "context": "mentLIVE/elm-dropdown\", 0.06568054 )\n , ( \"peterszerzo/line-charts\", 0.06567449 )\n , ( \"ktonon/el", "end": 22304, "score": 0.9324216843, "start": 22293, "tag": "USERNAME", "value": "peterszerzo" }, { "context": "terszerzo/line-charts\", 0.06567449 )\n , ( \"ktonon/elm-word\", 0.0656437 )\n , ( \"the-sett/elm-", "end": 22351, "score": 0.9183014035, "start": 22345, "tag": "USERNAME", "value": "ktonon" }, { "context": "the-sett/elm-aws-core\", 0.06546173 )\n , ( \"mercurymedia/elm-datetime-picker\", 0.06484787 )\n , ( \"M", "end": 22450, "score": 0.8748033047, "start": 22438, "tag": "USERNAME", "value": "mercurymedia" }, { "context": "a/elm-datetime-picker\", 0.06484787 )\n , ( \"MartinSStewart/elm-box-packing\", 0.06441992 )\n , ( \"Globa", "end": 22513, "score": 0.9000294209, "start": 22499, "tag": "USERNAME", "value": "MartinSStewart" }, { "context": "lazamar/dict-parser\", 0.0631332 )\n , ( \"savardd/elm-time-travel\", 0.06297284 )\n , ( \"cappy", "end": 22672, "score": 0.5689909458, "start": 22668, "tag": "USERNAME", "value": "ardd" }, { "context": " ( \"prikhi/http-tasks\", 0.06107279 )\n , ( \"cedric-h/elm-google-sign-in\", 0.05997924 )\n , ( \"pe", "end": 23078, "score": 0.7093716264, "start": 23070, "tag": "USERNAME", "value": "cedric-h" }, { "context": "\"pehota/elm-zondicons\", 0.05897221 )\n , ( \"JonRowe/elm-jwt\", 0.05871744 )\n , ( \"etaque/elm-tr", "end": 23182, "score": 0.9983859062, "start": 23175, "tag": "USERNAME", "value": "JonRowe" }, { "context": "/elm-daterange-picker\", 0.05695909 )\n , ( \"stephenreddek/elm-emoji\", 0.05690545 )\n , ( \"driebit/elm", "end": 23752, "score": 0.9577095509, "start": 23739, "tag": "USERNAME", "value": "stephenreddek" }, { "context": " , ( \"terezka/yaml\", 0.05491881 )\n , ( \"kyasu1/elm-ulid\", 0.05461156 )\n , ( \"Kinto/elm-ki", "end": 24026, "score": 0.8623921275, "start": 24022, "tag": "USERNAME", "value": "asu1" }, { "context": " , ( \"Kinto/elm-kinto\", 0.05458142 )\n , ( \"ghivert/elm-graphql\", 0.05449382 )\n , ( \"ursi/elm-", "end": 24115, "score": 0.7964329123, "start": 24108, "tag": "USERNAME", "value": "ghivert" }, { "context": " , ( \"ursi/elm-scroll\", 0.0543715 )\n , ( \"tiziano88/elm-protobuf\", 0.05431539 )\n , ( \"Punie/el", "end": 24208, "score": 0.8910877109, "start": 24199, "tag": "USERNAME", "value": "tiziano88" }, { "context": ", ( \"Punie/elm-reader\", 0.05430477 )\n , ( \"bburdette/cellme\", 0.05393641 )\n , ( \"samueldple/mat", "end": 24304, "score": 0.9579402804, "start": 24295, "tag": "USERNAME", "value": "bburdette" }, { "context": ", ( \"bburdette/cellme\", 0.05393641 )\n , ( \"samueldple/material-color\", 0.05370078 )\n , ( \"Bractl", "end": 24350, "score": 0.9696666002, "start": 24340, "tag": "USERNAME", "value": "samueldple" }, { "context": " \"Bractlet/elm-plot\", 0.05366476 )\n , ( \"jschomay/elm-bounded-number\", 0.05354281 )\n , ( \"ji", "end": 24448, "score": 0.7063724995, "start": 24442, "tag": "USERNAME", "value": "chomay" }, { "context": "ay/elm-bounded-number\", 0.05354281 )\n , ( \"jinjor/elm-contextmenu\", 0.05344282 )\n , ( \"proza", "end": 24502, "score": 0.8544000387, "start": 24496, "tag": "USERNAME", "value": "jinjor" }, { "context": "injor/elm-contextmenu\", 0.05344282 )\n , ( \"prozacchiwawa/elm-urlbase64\", 0.05340177 )\n , ( \"jluckyi", "end": 24560, "score": 0.8837836385, "start": 24547, "tag": "USERNAME", "value": "prozacchiwawa" }, { "context": "hiwawa/elm-urlbase64\", 0.05340177 )\n , ( \"jluckyiv/elm-utc-date-strings\", 0.0533887 )\n , ( \"m", "end": 24611, "score": 0.8356059194, "start": 24604, "tag": "USERNAME", "value": "luckyiv" }, { "context": "v/elm-utc-date-strings\", 0.0533887 )\n , ( \"mikaxyz/elm-cropper\", 0.05326306 )\n , ( \"TSFoster/", "end": 24667, "score": 0.8734818101, "start": 24660, "tag": "USERNAME", "value": "mikaxyz" }, { "context": " , ( \"ensoft/entrance\", 0.05284254 )\n , ( \"rgrempel/elm-http-decorators\", 0.05281988 )\n , ( \"C", "end": 24860, "score": 0.8459100127, "start": 24852, "tag": "USERNAME", "value": "rgrempel" }, { "context": " ( \"allo-media/canopy\", 0.05273208 )\n , ( \"harmboschloo/graphql-to-elm\", 0.05170478 )\n , ( \"rielas", "end": 25020, "score": 0.9469994903, "start": 25008, "tag": "USERNAME", "value": "harmboschloo" }, { "context": "schloo/graphql-to-elm\", 0.05170478 )\n , ( \"rielas/measurement\", 0.0516935 )\n , ( \"Chadtech/e", "end": 25070, "score": 0.6484588385, "start": 25064, "tag": "USERNAME", "value": "rielas" }, { "context": "m-relational-database\", 0.05164367 )\n , ( \"johnathanbostrom/elm-dice\", 0.05149376 )\n , ( \"jxxcarlson/e", "end": 25187, "score": 0.9927894473, "start": 25171, "tag": "USERNAME", "value": "johnathanbostrom" }, { "context": "athanbostrom/elm-dice\", 0.05149376 )\n , ( \"jxxcarlson/elm-editor\", 0.05141855 )\n , ( \"0ui/elm-ta", "end": 25235, "score": 0.9359415174, "start": 25225, "tag": "USERNAME", "value": "jxxcarlson" }, { "context": " \"the-sett/elm-refine\", 0.05067941 )\n , ( \"brian-watkins/elm-spec\", 0.04856381 )\n , ( \"avh4/elm-deb", "end": 25386, "score": 0.9711821079, "start": 25373, "tag": "USERNAME", "value": "brian-watkins" }, { "context": "( \"Janiczek/transform\", 0.04453779 )\n , ( \"hermanverschooten/ip\", 0.04416292 )\n , ( \"jfmengels/lint-unu", "end": 25882, "score": 0.9368117452, "start": 25865, "tag": "USERNAME", "value": "hermanverschooten" }, { "context": "\"hermanverschooten/ip\", 0.04416292 )\n , ( \"jfmengels/lint-unused\", 0.0439492 )\n , ( \"PaackEng/e", "end": 25923, "score": 0.9185887575, "start": 25914, "tag": "USERNAME", "value": "jfmengels" }, { "context": "\"jfmengels/lint-unused\", 0.0439492 )\n , ( \"PaackEng/elm-google-maps\", 0.04391243 )\n , ( \"ericg", "end": 25971, "score": 0.7954776883, "start": 25963, "tag": "USERNAME", "value": "PaackEng" }, { "context": "ckEng/elm-google-maps\", 0.04391243 )\n , ( \"ericgj/elm-uri-template\", 0.0434312 )\n , ( \"data-", "end": 26022, "score": 0.9833825827, "start": 26016, "tag": "USERNAME", "value": "ericgj" }, { "context": "b/elm-chart-builder\", 0.0433935 )\n , ( \"folkertdev/elm-paragraph\", 0.04272664 )\n , ( \"icidass", "end": 26135, "score": 0.8466079831, "start": 26128, "tag": "USERNAME", "value": "kertdev" }, { "context": "\"icidasset/elm-sha\", 0.04256028 )\n , ( \"dasch/levenshtein\", 0.04203807 )\n , ( \"wittjosia", "end": 26229, "score": 0.8166486025, "start": 26227, "tag": "USERNAME", "value": "ch" }, { "context": "dasch/levenshtein\", 0.04203807 )\n , ( \"wittjosiah/elm-ordered-dict\", 0.04175244 )\n , ( \"k", "end": 26277, "score": 0.5228324533, "start": 26274, "tag": "USERNAME", "value": "jos" }, { "context": "/elm-ordered-dict\", 0.04175244 )\n , ( \"ktonon/elm-test-extra\", 0.04152155 )\n , ( \"rl-kin", "end": 26332, "score": 0.6576750278, "start": 26330, "tag": "USERNAME", "value": "on" }, { "context": " \"rl-king/elm-masonry\", 0.04121287 )\n , ( \"billstclair/elm-custom-element\", 0.04093673 )\n , ( \"pr", "end": 26435, "score": 0.9091163874, "start": 26424, "tag": "USERNAME", "value": "billstclair" }, { "context": "khi/bootstrap-gallery\", 0.04035975 )\n , ( \"joshforisha/elm-inflect\", 0.04031402 )\n , ( \"bburdette", "end": 26547, "score": 0.9663299322, "start": 26536, "tag": "USERNAME", "value": "joshforisha" }, { "context": "shforisha/elm-inflect\", 0.04031402 )\n , ( \"bburdette/pdf-element\", 0.04019823 )\n , ( \"austinshe", "end": 26597, "score": 0.8177182674, "start": 26588, "tag": "USERNAME", "value": "bburdette" }, { "context": "burdette/pdf-element\", 0.04019823 )\n , ( \"austinshenk/elm-w3\", 0.04019579 )\n , ( \"json-tools/jso", "end": 26649, "score": 0.617702961, "start": 26639, "tag": "USERNAME", "value": "ustinshenk" }, { "context": " ( \"ccapndave/focus\", 0.04006861 )\n , ( \"gdamjan/elm-identicon\", 0.03951737 )\n , ( \"bemyak/", "end": 26846, "score": 0.8924225569, "start": 26841, "tag": "USERNAME", "value": "amjan" }, { "context": "damjan/elm-identicon\", 0.03951737 )\n , ( \"bemyak/elm-slider\", 0.03943666 )\n , ( \"FabienHeno", "end": 26895, "score": 0.7586838007, "start": 26890, "tag": "USERNAME", "value": "emyak" }, { "context": " ( \"bemyak/elm-slider\", 0.03943666 )\n , ( \"FabienHenon/jsonapi\", 0.03933752 )\n , ( \"NoRedInk/elm-", "end": 26946, "score": 0.7461665869, "start": 26935, "tag": "USERNAME", "value": "FabienHenon" }, { "context": "Ink/elm-plot-19\", 0.0389287 )\n , ( \"mercurymedia/elm-message-toast\", 0.03831063 )\n , ( \"cha", "end": 27043, "score": 0.5614990592, "start": 27038, "tag": "USERNAME", "value": "media" }, { "context": "-partners/elm-bignum\", 0.03819787 )\n , ( \"jouderianjr/elm-loaders\", 0.03811653 )\n , ( \"Punie/elm", "end": 27155, "score": 0.7889011502, "start": 27145, "tag": "USERNAME", "value": "ouderianjr" }, { "context": " , ( \"Punie/elm-id\", 0.03796811 )\n , ( \"drathier/elm-test-tables\", 0.03758749 )\n , ( \"Orasu", "end": 27245, "score": 0.8108875751, "start": 27239, "tag": "USERNAME", "value": "athier" }, { "context": "( \"w0rm/elm-slice-show\", 0.0373203 )\n , ( \"peterszerzo/elm-arborist\", 0.03731962 )\n , ( \"ThinkAle", "end": 27395, "score": 0.7995068431, "start": 27384, "tag": "USERNAME", "value": "peterszerzo" }, { "context": " , ( \"turboMaCk/queue\", 0.03708237 )\n , ( \"emilianobovetti/edit-distance\", 0.03704362 )\n , ( \"kuzzmi/", "end": 27556, "score": 0.7717673182, "start": 27541, "tag": "USERNAME", "value": "emilianobovetti" }, { "context": "vetti/edit-distance\", 0.03704362 )\n , ( \"kuzzmi/elm-gravatar\", 0.03697676 )\n , ( \"ThinkAle", "end": 27605, "score": 0.6915067434, "start": 27601, "tag": "USERNAME", "value": "zzmi" }, { "context": "m-drag-locations\", 0.03696538 )\n , ( \"dawehner/elm-colorbrewer\", 0.03695076 )\n , ( \"xarvh", "end": 27718, "score": 0.5691747069, "start": 27715, "tag": "USERNAME", "value": "ner" }, { "context": "/elm-oauth-middleware\", 0.03667292 )\n , ( \"alexkorban/uicards\", 0.03663732 )\n , ( \"folkertdev/el", "end": 27929, "score": 0.9817740917, "start": 27919, "tag": "USERNAME", "value": "alexkorban" }, { "context": "( \"alexkorban/uicards\", 0.03663732 )\n , ( \"folkertdev/elm-int64\", 0.03653192 )\n , ( \"billstclair", "end": 27976, "score": 0.7821297646, "start": 27966, "tag": "USERNAME", "value": "folkertdev" }, { "context": "r/elm-geolocation\", 0.03644241 )\n , ( \"justgook/elm-game-logic\", 0.03637282 )\n , ( \"zgohr/", "end": 28079, "score": 0.7110608816, "start": 28075, "tag": "USERNAME", "value": "gook" }, { "context": " , ( \"zgohr/elm-csv\", 0.03624985 )\n , ( \"gicentre/elm-vega\", 0.03597546 )\n , ( \"zwilias/elm-", "end": 28173, "score": 0.6124894023, "start": 28166, "tag": "USERNAME", "value": "icentre" }, { "context": " , ( \"ir4y/elm-dnd\", 0.03561684 )\n , ( \"xilnocas/step\", 0.03560819 )\n , ( \"stephenreddek/", "end": 28455, "score": 0.5460134745, "start": 28452, "tag": "USERNAME", "value": "noc" }, { "context": " , ( \"xilnocas/step\", 0.03560819 )\n , ( \"stephenreddek/elm-range-slider\", 0.03551443 )\n , ( \"fabi", "end": 28504, "score": 0.9679758549, "start": 28491, "tag": "USERNAME", "value": "stephenreddek" }, { "context": "ddek/elm-range-slider\", 0.03551443 )\n , ( \"fabiommendes/elm-iter\", 0.03545966 )\n , ( \"akoppela/elm", "end": 28562, "score": 0.9021388292, "start": 28550, "tag": "USERNAME", "value": "fabiommendes" }, { "context": "akoppela/elm-logo\", 0.03543891 )\n , ( \"billstclair/elm-crypto-string\", 0.03529601 )\n , ( \"aro", "end": 28657, "score": 0.8434632421, "start": 28650, "tag": "USERNAME", "value": "stclair" }, { "context": "r/elm-crypto-string\", 0.03529601 )\n , ( \"arowM/elm-form-validator\", 0.0352493 )\n , ( \"Elm", "end": 28709, "score": 0.6290262938, "start": 28706, "tag": "USERNAME", "value": "owM" }, { "context": " , ( \"ohanhi/lorem\", 0.03502294 )\n , ( \"stephenreddek/elm-time-picker\", 0.03500671 )\n , ( \"mercu", "end": 29001, "score": 0.9825167656, "start": 28988, "tag": "USERNAME", "value": "stephenreddek" }, { "context": "eddek/elm-time-picker\", 0.03500671 )\n , ( \"mercurymedia/elm-smart-select\", 0.03493208 )\n , ( \"elm-", "end": 29058, "score": 0.9236491323, "start": 29046, "tag": "USERNAME", "value": "mercurymedia" }, { "context": "tt/decode-generic\", 0.03406044 )\n , ( \"ljuglaret/fraction\", 0.03369673 )\n , ( \"folkertdev/e", "end": 29213, "score": 0.5904011726, "start": 29208, "tag": "USERNAME", "value": "laret" }, { "context": "( \"ljuglaret/fraction\", 0.03369673 )\n , ( \"folkertdev/elm-kmeans\", 0.03343474 )\n , ( \"nikita-vol", "end": 29261, "score": 0.9469152093, "start": 29251, "tag": "USERNAME", "value": "folkertdev" }, { "context": "folkertdev/elm-kmeans\", 0.03343474 )\n , ( \"nikita-volkov/typeclasses\", 0.03336435 )\n , ( \"miniBill/", "end": 29314, "score": 0.9816497564, "start": 29301, "tag": "USERNAME", "value": "nikita-volkov" }, { "context": "date-format-languages\", 0.03285717 )\n , ( \"jaredramirez/elm-s3\", 0.03251825 )\n , ( \"jonathanfishbe", "end": 29426, "score": 0.9785755873, "start": 29414, "tag": "USERNAME", "value": "jaredramirez" }, { "context": " \"jaredramirez/elm-s3\", 0.03251825 )\n , ( \"jonathanfishbein1/elm-field\", 0.03186558 )\n , ( \"bburdette/s", "end": 29479, "score": 0.9969155192, "start": 29462, "tag": "USERNAME", "value": "jonathanfishbein1" }, { "context": "shbein1/elm-field\", 0.03186558 )\n , ( \"bburdette/schelme\", 0.03103703 )\n , ( \"Chadtech/elm-", "end": 29527, "score": 0.5265033245, "start": 29522, "tag": "USERNAME", "value": "dette" }, { "context": "le/system-actor-model\", 0.02930445 )\n , ( \"nikita-volkov/hashing-containers\", 0.02926126 )\n , ( \"Or", "end": 29924, "score": 0.9553326368, "start": 29911, "tag": "USERNAME", "value": "nikita-volkov" }, { "context": "art/elm-scroll-to\", 0.02903803 )\n , ( \"MartinSStewart/elm-codec-bytes\", 0.02896827 )\n , ( \"", "end": 30089, "score": 0.6093129516, "start": 30084, "tag": "USERNAME", "value": "inSSt" }, { "context": " , ( \"tesk9/modal\", 0.02714795 )\n , ( \"RalfNorthman/elm-zoom-plot\", 0.0270936 )\n , ( \"jxxcarls", "end": 30334, "score": 0.9467837811, "start": 30322, "tag": "USERNAME", "value": "RalfNorthman" }, { "context": "orthman/elm-zoom-plot\", 0.0270936 )\n , ( \"jxxcarlson/htree\", 0.02683459 )\n , ( \"jxxcarlson/elm-", "end": 30386, "score": 0.6334677339, "start": 30377, "tag": "USERNAME", "value": "xxcarlson" }, { "context": " \"jxxcarlson/htree\", 0.02683459 )\n , ( \"jxxcarlson/elm-stat\", 0.02651257 )\n , ( \"billstcl", "end": 30427, "score": 0.5692353845, "start": 30424, "tag": "USERNAME", "value": "car" }, { "context": "xcarlson/htree\", 0.02683459 )\n , ( \"jxxcarlson/elm-stat\", 0.02651257 )\n , ( \"billstclair/", "end": 30431, "score": 0.5306042433, "start": 30428, "tag": "USERNAME", "value": "son" }, { "context": "xcarlson/elm-stat\", 0.02651257 )\n , ( \"billstclair/elm-svg-button\", 0.02644546 )\n , ( \"w", "end": 30475, "score": 0.5227921605, "start": 30473, "tag": "USERNAME", "value": "st" }, { "context": "ing/elm-modular-scale\", 0.02520116 )\n , ( \"bowbahdoe/elm-history\", 0.02476153 )\n , ( \"jxxcarlso", "end": 30854, "score": 0.9210796952, "start": 30845, "tag": "USERNAME", "value": "bowbahdoe" }, { "context": "bahdoe/elm-history\", 0.02476153 )\n , ( \"jxxcarlson/elm-widget\", 0.02457994 )\n , ( \"jackhp", "end": 30901, "score": 0.522783339, "start": 30898, "tag": "USERNAME", "value": "car" }, { "context": "jxxcarlson/elm-widget\", 0.02457994 )\n , ( \"jackhp95/elm-mapbox\", 0.02452827 )\n , ( \"alex-tan/t", "end": 30953, "score": 0.9555168152, "start": 30945, "tag": "USERNAME", "value": "jackhp95" }, { "context": " \"jackhp95/elm-mapbox\", 0.02452827 )\n , ( \"alex-tan/task-extra\", 0.02403581 )\n , ( \"jjant/elm-", "end": 31001, "score": 0.853102684, "start": 30993, "tag": "USERNAME", "value": "alex-tan" }, { "context": " \"alex-tan/task-extra\", 0.02403581 )\n , ( \"jjant/elm-printf\", 0.02393349 )\n , ( \"jigargosar", "end": 31046, "score": 0.675548315, "start": 31041, "tag": "USERNAME", "value": "jjant" }, { "context": ", ( \"jjant/elm-printf\", 0.02393349 )\n , ( \"jigargosar/elm-material-color\", 0.02343325 )\n , ( \"av", "end": 31096, "score": 0.7155293822, "start": 31086, "tag": "USERNAME", "value": "jigargosar" }, { "context": ", ( \"avh4/elm-dropbox\", 0.02328807 )\n , ( \"jonathanfishbein1/linear-algebra\", 0.0230214 )\n , ( \"tomjkid", "end": 31206, "score": 0.9926731586, "start": 31189, "tag": "USERNAME", "value": "jonathanfishbein1" }, { "context": "shbein1/linear-algebra\", 0.0230214 )\n , ( \"tomjkidd/elm-multiway-tree-zipper\", 0.0229576 )\n , ", "end": 31257, "score": 0.7857900262, "start": 31249, "tag": "USERNAME", "value": "tomjkidd" }, { "context": "nksgaard/elm-data-uri\", 0.02255611 )\n , ( \"billstclair/elm-id-search\", 0.02252655 )\n , ( \"thought", "end": 31423, "score": 0.9588493109, "start": 31412, "tag": "USERNAME", "value": "billstclair" }, { "context": "ught2/elm-interactive\", 0.02222094 )\n , ( \"brianvanburken/elm-list-date\", 0.02198079 )\n , ( \"andre-d", "end": 31533, "score": 0.9919584394, "start": 31519, "tag": "USERNAME", "value": "brianvanburken" }, { "context": "en/elm-list-date\", 0.02198079 )\n , ( \"andre-dietrich/elm-random-regex\", 0.02184853 )\n , ( \"flow", "end": 31590, "score": 0.9558051825, "start": 31582, "tag": "USERNAME", "value": "dietrich" }, { "context": "ng-cc/elm-audio-graph\", 0.02169063 )\n , ( \"andre-dietrich/elm-svgbob\", 0.0216694 )\n , ( \"rluiten/tri", "end": 31706, "score": 0.9628143311, "start": 31692, "tag": "USERNAME", "value": "andre-dietrich" }, { "context": "atrix/elm-input-extra\", 0.02068175 )\n , ( \"abadi199/elm-creditcard\", 0.02068162 )\n , ( \"arowM/", "end": 32064, "score": 0.8950325251, "start": 32056, "tag": "USERNAME", "value": "abadi199" }, { "context": "lm-css-modules-helper\", 0.02039772 )\n , ( \"alexanderkiel/elm-mdc-alpha\", 0.02028243 )\n , ( \"sparksp", "end": 32178, "score": 0.9539336562, "start": 32165, "tag": "USERNAME", "value": "alexanderkiel" }, { "context": "el/elm-mdc-alpha\", 0.02028243 )\n , ( \"sparksp/elm-review-camelcase\", 0.02010144 )\n , ( \"", "end": 32228, "score": 0.7302123904, "start": 32226, "tag": "USERNAME", "value": "sp" }, { "context": " ( \"dwyl/elm-criteria\", 0.02009551 )\n , ( \"ericgj/elm-validation\", 0.01997145 )\n , ( \"prikhi", "end": 32330, "score": 0.9738119841, "start": 32324, "tag": "USERNAME", "value": "ericgj" }, { "context": " , ( \"prikhi/paginate\", 0.01997109 )\n , ( \"romstad/elm-chess\", 0.01987651 )\n , ( \"basti1302/e", "end": 32425, "score": 0.7056459785, "start": 32418, "tag": "USERNAME", "value": "romstad" }, { "context": "2/elm-non-empty-array\", 0.01959109 )\n , ( \"MichaelCombs28/elm-base85\", 0.01958329 )\n , ( \"arnau/elm-", "end": 32536, "score": 0.8651401401, "start": 32522, "tag": "USERNAME", "value": "MichaelCombs28" }, { "context": "Combs28/elm-base85\", 0.01958329 )\n , ( \"arnau/elm-objecthash\", 0.01950411 )\n , ( \"NoRedI", "end": 32581, "score": 0.5071368814, "start": 32579, "tag": "USERNAME", "value": "au" }, { "context": "e-sett/ai-search\", 0.01942663 )\n , ( \"allenap/elm-json-decode-broken\", 0.01937762 )\n , (", "end": 32888, "score": 0.5767519474, "start": 32886, "tag": "USERNAME", "value": "ap" }, { "context": "lm-json-decode-broken\", 0.01937762 )\n , ( \"nathanjohnson320/base58\", 0.01908185 )\n , ( \"noahzgordon/el", "end": 32956, "score": 0.8635626435, "start": 32940, "tag": "USERNAME", "value": "nathanjohnson320" }, { "context": "thanjohnson320/base58\", 0.01908185 )\n , ( \"noahzgordon/elm-jsonapi\", 0.01893622 )\n , ( \"labzero/e", "end": 33003, "score": 0.8779035807, "start": 32992, "tag": "USERNAME", "value": "noahzgordon" }, { "context": "gordon/elm-jsonapi\", 0.01893622 )\n , ( \"labzero/elm-google-geocoding\", 0.01891308 )\n , ( \"", "end": 33051, "score": 0.9038095474, "start": 33047, "tag": "USERNAME", "value": "zero" }, { "context": "m-google-geocoding\", 0.01891308 )\n , ( \"pilatch/elm-chess\", 0.0186072 )\n , ( \"torreyatcitt", "end": 33108, "score": 0.7816448212, "start": 33104, "tag": "USERNAME", "value": "atch" }, { "context": "m-alert-timer-message\", 0.01807738 )\n , ( \"JohnBugner/elm-bag\", 0.01807483 )\n , ( \"Gizra/elm-com", "end": 33378, "score": 0.9953910708, "start": 33368, "tag": "USERNAME", "value": "JohnBugner" }, { "context": "izra/elm-compat-019\", 0.01797027 )\n , ( \"goilluminate/elm-fancy-daterangepicker\", 0.01784086 )\n ", "end": 33476, "score": 0.8960722685, "start": 33466, "tag": "USERNAME", "value": "illuminate" }, { "context": "fancy-daterangepicker\", 0.01784086 )\n , ( \"janjelinek/creditcard-validation\", 0.01781153 )\n , ( ", "end": 33541, "score": 0.9656574726, "start": 33531, "tag": "USERNAME", "value": "janjelinek" }, { "context": "Foster/elm-compare\", 0.01772745 )\n , ( \"fedragon/elm-typed-dropdown\", 0.01771295 )\n , ( \"", "end": 33741, "score": 0.6504362226, "start": 33738, "tag": "USERNAME", "value": "rag" }, { "context": "on/elm-typed-dropdown\", 0.01771295 )\n , ( \"emilianobovetti/elm-yajson\", 0.01770452 )\n , ( \"jjant/elm-", "end": 33806, "score": 0.9985491633, "start": 33791, "tag": "USERNAME", "value": "emilianobovetti" }, { "context": "obovetti/elm-yajson\", 0.01770452 )\n , ( \"jjant/elm-comonad-zipper\", 0.01770213 )\n , ( \"oz", "end": 33851, "score": 0.5383337736, "start": 33848, "tag": "USERNAME", "value": "ant" }, { "context": "\"ozmat/elm-validation\", 0.01766079 )\n , ( \"jackfranklin/elm-parse-link-header\", 0.0176503 )\n , ( \"", "end": 33960, "score": 0.9959312677, "start": 33948, "tag": "USERNAME", "value": "jackfranklin" }, { "context": "m-attribute-builder\", 0.01761218 )\n , ( \"kkpoon/elm-auth0-urlparser\", 0.01761196 )\n , ( \"1", "end": 34072, "score": 0.5421711802, "start": 34068, "tag": "USERNAME", "value": "poon" }, { "context": " , ( \"ggb/elm-bloom\", 0.0175877 )\n , ( \"peterszerzo/elm-porter\", 0.01756095 )\n , ( \"jweir/spar", "end": 34217, "score": 0.9544353485, "start": 34206, "tag": "USERNAME", "value": "peterszerzo" }, { "context": "ti/elm-geodesy\", 0.01754339 )\n , ( \"bChiquet/elm-accessors\", 0.01753197 )\n , ( \"tricycl", "end": 34358, "score": 0.5844017267, "start": 34357, "tag": "USERNAME", "value": "t" }, { "context": "or-framework-template\", 0.01638874 )\n , ( \"robinheghan/elm-warrior\", 0.01638874 )\n , ( \"wsowens/t", "end": 34478, "score": 0.9662877917, "start": 34467, "tag": "USERNAME", "value": "robinheghan" }, { "context": "illstclair/elm-dialog\", 0.01200416 )\n , ( \"jxxcarlson/meenylatex\", 0.01054695 )\n , ( \"the-sett/e", "end": 34813, "score": 0.841545105, "start": 34803, "tag": "USERNAME", "value": "jxxcarlson" }, { "context": " \"Gizra/elm-fetch\", 0.00830096 )\n , ( \"GoldentTuft/elm-japanese-typing\", 0.00819437 )\n , ( \"t", "end": 35157, "score": 0.5304365754, "start": 35150, "tag": "USERNAME", "value": "entTuft" }, { "context": "mework-template-html\", 0.00819437 )\n , ( \"groma84/elm-tachyons\", 0.00819437 )\n , ( \"shnewto/", "end": 35284, "score": 0.7024088502, "start": 35278, "tag": "USERNAME", "value": "roma84" }, { "context": "roma84/elm-tachyons\", 0.00819437 )\n , ( \"shnewto/pgn\", 0.00819437 )\n , ( \"ContaSystemer/elm", "end": 35333, "score": 0.65049088, "start": 35328, "tag": "USERNAME", "value": "newto" }, { "context": "lm-review-no-regex\", 0.00819437 )\n , ( \"tasuki/elm-punycode\", 0.00819437 )\n , ( \"billstcl", "end": 35434, "score": 0.7818417549, "start": 35431, "tag": "USERNAME", "value": "uki" }, { "context": " \"tasuki/elm-punycode\", 0.00819437 )\n , ( \"billstclair/elm-popup-picker\", 0.00819437 )\n , ( \"hall", "end": 35487, "score": 0.9692603946, "start": 35476, "tag": "USERNAME", "value": "billstclair" }, { "context": "air/elm-popup-picker\", 0.00819437 )\n , ( \"hallelujahdrive/elm-croppie\", 0.00819437 )\n , ( \"the-sett/", "end": 35548, "score": 0.752348423, "start": 35534, "tag": "USERNAME", "value": "allelujahdrive" }, { "context": "sett/elm-localstorage\", 0.00819437 )\n , ( \"mrpinsky/elm-keyed-list\", 0.00819437 )\n , ( \"choonk", "end": 35651, "score": 0.8370425701, "start": 35643, "tag": "USERNAME", "value": "mrpinsky" }, { "context": "y/elm-keyed-list\", 0.00819437 )\n , ( \"choonkeat/elm-fullstack\", 0.00819437 )\n , ( \"carwow/", "end": 35704, "score": 0.5383062363, "start": 35700, "tag": "USERNAME", "value": "keat" }, { "context": "keat/elm-fullstack\", 0.00819437 )\n , ( \"carwow/elm-review-rules\", 0.00819437 )\n , ( \"rl-k", "end": 35753, "score": 0.8213681579, "start": 35750, "tag": "USERNAME", "value": "wow" }, { "context": " \"rl-king/elm-index\", 0.00819437 )\n , ( \"shamansir/elm-aframe\", 0.00819437 )\n , ( \"opvasger/m", "end": 35854, "score": 0.7164378166, "start": 35847, "tag": "USERNAME", "value": "amansir" }, { "context": "hamansir/elm-aframe\", 0.00819437 )\n , ( \"opvasger/msg-replay\", 0.00819437 )\n , ( \"3kyro/xsrf", "end": 35902, "score": 0.6104108691, "start": 35896, "tag": "USERNAME", "value": "vasger" }, { "context": "/xsrf-protection\", 0.00819437 )\n , ( \"sparksp/elm-review-imports\", 0.00819437 )\n , ( \"jf", "end": 35999, "score": 0.507244885, "start": 35997, "tag": "USERNAME", "value": "sp" }, { "context": "sp/elm-review-imports\", 0.00819437 )\n , ( \"jfmengels/elm-review-license\", 0.00819437 )\n , ( \"Ju", "end": 36056, "score": 0.8145503998, "start": 36047, "tag": "USERNAME", "value": "jfmengels" }, { "context": "ls/elm-review-license\", 0.00819437 )\n , ( \"JustinLove/elm-twitch-api\", 0.00807273 )\n , ( \"billst", "end": 36114, "score": 0.9625350237, "start": 36104, "tag": "USERNAME", "value": "JustinLove" }, { "context": "inLove/elm-twitch-api\", 0.00807273 )\n , ( \"billstclair/elm-websocket-framework\", 0.00794594 )\n , ", "end": 36169, "score": 0.7702435851, "start": 36158, "tag": "USERNAME", "value": "billstclair" }, { "context": "oni/elm-phoenix-ports\", 0.00792254 )\n , ( \"chicode/lisa\", 0.00778186 )\n , ( \"leojpod/review-n", "end": 36329, "score": 0.9102351665, "start": 36322, "tag": "USERNAME", "value": "chicode" }, { "context": "o-empty-html-text\", 0.00777119 )\n , ( \"showell/meta-elm\", 0.00741073 )\n , ( \"dasch/crockf", "end": 36432, "score": 0.7049039602, "start": 36429, "tag": "USERNAME", "value": "ell" }, { "context": ", ( \"showell/meta-elm\", 0.00741073 )\n , ( \"dasch/crockford\", 0.00735675 )\n , ( \"billstclair", "end": 36475, "score": 0.9616863132, "start": 36470, "tag": "USERNAME", "value": "dasch" }, { "context": " , ( \"dasch/crockford\", 0.00735675 )\n , ( \"billstclair/elm-mastodon-websocket\", 0.00673705 )\n , (", "end": 36525, "score": 0.9975607395, "start": 36514, "tag": "USERNAME", "value": "billstclair" }, { "context": "stodon-websocket\", 0.00673705 )\n , ( \"sparksp/elm-review-ports\", 0.00650576 )\n , ( \"just", "end": 36584, "score": 0.7113980651, "start": 36582, "tag": "USERNAME", "value": "sp" }, { "context": "rksp/elm-review-ports\", 0.00650576 )\n , ( \"justgook/elm-tiled\", 0.00649709 )\n , ( \"matheus23/e", "end": 36638, "score": 0.9884403348, "start": 36630, "tag": "USERNAME", "value": "justgook" }, { "context": "( \"justgook/elm-tiled\", 0.00649709 )\n , ( \"matheus23/elm-markdown-transforms\", 0.00624748 )\n , ", "end": 36686, "score": 0.9915071726, "start": 36677, "tag": "USERNAME", "value": "matheus23" }, { "context": " , ( \"ursi/support\", 0.00623534 )\n , ( \"billstclair/elm-mastodon\", 0.00617322 )\n , ( \"TSFoster", "end": 36791, "score": 0.9412878752, "start": 36780, "tag": "USERNAME", "value": "billstclair" }, { "context": ", ( \"TSFoster/elm-md5\", 0.00589303 )\n , ( \"jxxcarlson/tree-extra\", 0.00585207 )\n , ( \"miyamoen/b", "end": 36888, "score": 0.9869503975, "start": 36878, "tag": "USERNAME", "value": "jxxcarlson" }, { "context": "xcarlson/tree-extra\", 0.00585207 )\n , ( \"miyamoen/bibliopola\", 0.00542674 )\n , ( \"ThinkAlexa", "end": 36936, "score": 0.5561974645, "start": 36930, "tag": "USERNAME", "value": "yamoen" }, { "context": "( \"r-k-b/no-float-ids\", 0.00528407 )\n , ( \"nishiurahiroki/elm-simple-pagenate\", 0.00525112 )\n , ( \"t", "end": 37092, "score": 0.8323541284, "start": 37078, "tag": "USERNAME", "value": "nishiurahiroki" }, { "context": "m-simple-pagenate\", 0.00525112 )\n , ( \"the-sett/elm-aws-cognito\", 0.00517803 )\n , ( \"arowM", "end": 37149, "score": 0.621496439, "start": 37145, "tag": "USERNAME", "value": "sett" }, { "context": "well/dict-dot-dot\", 0.00370657 )\n , ( \"MartinSStewart/elm-nonempty-string\", 0.00369952 )\n ,", "end": 37940, "score": 0.5380207896, "start": 37935, "tag": "USERNAME", "value": "inSSt" }, { "context": "\"rluiten/sparsevector\", 0.00339232 )\n , ( \"ChristophP/elm-mark\", 0.00337588 )\n , ( \"calions-app/", "end": 38356, "score": 0.8793616295, "start": 38346, "tag": "USERNAME", "value": "ChristophP" }, { "context": "ions-app/jsonapi-http\", 0.00323482 )\n , ( \"jfmengels/elm-lint-reporter\", 0.00313712 )\n , ( \"bri", "end": 38563, "score": 0.9971222878, "start": 38554, "tag": "USERNAME", "value": "jfmengels" }, { "context": "els/elm-lint-reporter\", 0.00313712 )\n , ( \"brian-watkins/elm-procedure\", 0.00312001 )\n , ( \"dosarf/", "end": 38623, "score": 0.9783076644, "start": 38610, "tag": "USERNAME", "value": "brian-watkins" }, { "context": "kins/elm-procedure\", 0.00312001 )\n , ( \"dosarf/elm-yet-another-polling\", 0.00298703 )\n , ", "end": 38672, "score": 0.9233857989, "start": 38669, "tag": "USERNAME", "value": "arf" }, { "context": "commonmind/elm-csexpr\", 0.00285553 )\n , ( \"folkertdev/elm-brotli\", 0.00282573 )\n , ( \"yumlonne/e", "end": 38785, "score": 0.996868968, "start": 38775, "tag": "USERNAME", "value": "folkertdev" }, { "context": "folkertdev/elm-brotli\", 0.00282573 )\n , ( \"yumlonne/elm-japanese-calendar\", 0.00280968 )\n , ( ", "end": 38833, "score": 0.937461555, "start": 38825, "tag": "USERNAME", "value": "yumlonne" }, { "context": "elm-japanese-calendar\", 0.00280968 )\n , ( \"jxxcarlson/math-markdown\", 0.00273225 )\n , ( \"billstc", "end": 38894, "score": 0.9824520946, "start": 38884, "tag": "USERNAME", "value": "jxxcarlson" }, { "context": "carlson/math-markdown\", 0.00273225 )\n , ( \"billstclair/elm-websocket-framework-server\", 0.00264942 )\n ", "end": 38948, "score": 0.9968286753, "start": 38937, "tag": "USERNAME", "value": "billstclair" }, { "context": "cket-framework-server\", 0.00264942 )\n , ( \"alex-tan/postgrest-client\", 0.00263226 )\n , ( \"prim", "end": 39016, "score": 0.979013145, "start": 39008, "tag": "USERNAME", "value": "alex-tan" }, { "context": "n/postgrest-client\", 0.00263226 )\n , ( \"primait/pyxis-components\", 0.00262437 )\n , ( \"maca", "end": 39069, "score": 0.5908994675, "start": 39065, "tag": "USERNAME", "value": "mait" }, { "context": "\"avh4/elm-desktop-app\", 0.00257613 )\n , ( \"ceddlyburge/elm-bootstrap-starter-master-view\", 0.00247544 )\n", "end": 39228, "score": 0.9965381622, "start": 39217, "tag": "USERNAME", "value": "ceddlyburge" }, { "context": "p-starter-master-view\", 0.00247544 )\n , ( \"dvberkel/microkanren\", 0.00243706 )\n , ( \"getto-sys", "end": 39299, "score": 0.9975013137, "start": 39291, "tag": "USERNAME", "value": "dvberkel" }, { "context": " , ( \"primait/forms\", 0.00230758 )\n , ( \"harmboschloo/elm-dict-intersect\", 0.00229488 )\n , ( \"an", "end": 39875, "score": 0.7391145229, "start": 39863, "tag": "USERNAME", "value": "harmboschloo" }, { "context": "dict-intersect\", 0.00229488 )\n , ( \"anhmiuhv/pannablevideo\", 0.00227733 )\n , ( \"Spaxe/e", "end": 39931, "score": 0.5844041705, "start": 39930, "tag": "USERNAME", "value": "v" }, { "context": " ( \"Spaxe/elm-lsystem\", 0.00218039 )\n , ( \"harmboschloo/elm-ecs\", 0.00202945 )\n , ( \"AuricSystemsI", "end": 40032, "score": 0.7999491096, "start": 40020, "tag": "USERNAME", "value": "harmboschloo" }, { "context": "/creditcard-validator\", 0.00195405 )\n , ( \"alex-tan/postgrest-queries\", 0.00194971 )\n , ( \"emp", "end": 40152, "score": 0.9084468484, "start": 40144, "tag": "USERNAME", "value": "alex-tan" }, { "context": "tyflash/typed-svg\", 0.00194846 )\n , ( \"billstclair/elm-crypto-aes\", 0.00193174 )\n , ( \"eelcoh", "end": 40259, "score": 0.5780572295, "start": 40252, "tag": "USERNAME", "value": "stclair" }, { "context": "\"eelcoh/parser-indent\", 0.00190639 )\n , ( \"benansell/lobo-elm-test-extra\", 0.00190501 )\n , ( \"m", "end": 40361, "score": 0.8218163848, "start": 40352, "tag": "USERNAME", "value": "benansell" }, { "context": "elm-primer-tooltips\", 0.00181717 )\n , ( \"ryan-senn/elm-compiler-error-sscce\", 0.00180921 )\n ,", "end": 40683, "score": 0.6349195838, "start": 40676, "tag": "USERNAME", "value": "an-senn" }, { "context": "e-sett/svg-text-fonts\", 0.00177048 )\n , ( \"billstclair/elm-chat\", 0.00176851 )\n , ( \"Libbum/elm-p", "end": 40949, "score": 0.7365373373, "start": 40938, "tag": "USERNAME", "value": "billstclair" }, { "context": "bbum/elm-partition\", 0.00176227 )\n , ( \"turboMaCk/elm-continue\", 0.00175979 )\n , ( \"imjo", "end": 41041, "score": 0.5383529663, "start": 41039, "tag": "USERNAME", "value": "bo" }, { "context": "boMaCk/elm-continue\", 0.00175979 )\n , ( \"imjoehaines/afinn-165-elm\", 0.00175817 )\n , ( \"the-set", "end": 41098, "score": 0.6882697344, "start": 41089, "tag": "USERNAME", "value": "joehaines" }, { "context": " , ( \"toastal/endo\", 0.00046685 )\n , ( \"jackhp95/palit\", 0.00045758 )\n , ( \"arowM/elm-html-", "end": 41241, "score": 0.9945743084, "start": 41233, "tag": "USERNAME", "value": "jackhp95" }, { "context": "sgaard/elm-media-type\", 0.00022552 )\n , ( \"jonathanfishbein1/complex-numbers\", 0.00022321 )\n ,", "end": 41497, "score": 0.9030066729, "start": 41489, "tag": "USERNAME", "value": "jonathan" }, { "context": "vh4/burndown-charts\", 0.00003663 )\n , ( \"mpizenberg/elm-placeholder-pkg\", 0.00003533 )\n , ( \"a", "end": 42247, "score": 0.6533954144, "start": 42239, "tag": "USERNAME", "value": "izenberg" }, { "context": "( \"avh4/elm-github-v3\", 0.00003187 )\n , ( \"justinmimbs/tzif\", 0.00002911 )\n , ( \"folkertdev/elm-c", "end": 42354, "score": 0.8571528196, "start": 42343, "tag": "USERNAME", "value": "justinmimbs" }, { "context": ", ( \"justinmimbs/tzif\", 0.00002911 )\n , ( \"folkertdev/elm-cff\", 0.00001785 )\n , ( \"the-sett/elm-", "end": 42398, "score": 0.9541404843, "start": 42388, "tag": "USERNAME", "value": "folkertdev" }, { "context": "\"the-sett/elm-one-many\", 0.0000177 )\n , ( \"ianmackenzie/elm-iso-10303\", 0.00001421 )\n , ( \"ianmack", "end": 42496, "score": 0.6283115149, "start": 42484, "tag": "USERNAME", "value": "ianmackenzie" }, { "context": "html-with-css-temp-19\", 0.00000819 )\n , ( \"folkertdev/elm-iris\", 0.00000767 )\n , ( \"lukewestby/h", "end": 42945, "score": 0.990960598, "start": 42935, "tag": "USERNAME", "value": "folkertdev" }, { "context": "lukewestby/http-extra\", 0.00000738 )\n , ( \"jfmengels/elm-review-reporter\", 0.00000692 )\n , ( \"t", "end": 43042, "score": 0.9482866526, "start": 43033, "tag": "USERNAME", "value": "jfmengels" }, { "context": "aniczek/browser-extra\", 0.00000461 )\n , ( \"jxxcarlson/toc-editor\", 0.00000418 )\n , ( \"billstclai", "end": 43249, "score": 0.969014287, "start": 43239, "tag": "USERNAME", "value": "jxxcarlson" }, { "context": "jxxcarlson/toc-editor\", 0.00000418 )\n , ( \"billstclair/elm-dev-random\", 0.0000038 )\n , ( \"miniBil", "end": 43300, "score": 0.9927520752, "start": 43289, "tag": "USERNAME", "value": "billstclair" }, { "context": "iBill/elm-avataaars\", 0.00000345 )\n , ( \"zwilias/elm-holey-zipper\", 0.00000282 )\n , ( \"TSFo", "end": 43447, "score": 0.676404953, "start": 43442, "tag": "USERNAME", "value": "ilias" }, { "context": "ndave/elm-statecharts\", 0.00000164 )\n , ( \"simonh1000/elm-sliding-menus\", 0.00000162 )\n , ( \"rl-", "end": 44932, "score": 0.9434283376, "start": 44922, "tag": "USERNAME", "value": "simonh1000" }, { "context": "d-andy/elm-limiter\", 0.00000159 )\n , ( \"joneshf/elm-these\", 0.00000145 )\n , ( \"arowM/elm-d", "end": 45095, "score": 0.6813117862, "start": 45091, "tag": "USERNAME", "value": "eshf" }, { "context": "( \"arowM/elm-data-url\", 0.00000143 )\n , ( \"robinheghan/elm-phone-numbers\", 0.00000136 )\n , ( \"aro", "end": 45192, "score": 0.9776428938, "start": 45181, "tag": "USERNAME", "value": "robinheghan" }, { "context": "arowM/elm-parser-test\", 0.00000129 )\n , ( \"miyamoen/elm-origami\", 0.00000128 )\n , ( \"jweir/cha", "end": 45402, "score": 0.8601973057, "start": 45394, "tag": "USERNAME", "value": "miyamoen" }, { "context": "miyamoen/elm-origami\", 0.00000128 )\n , ( \"jweir/charter\", 0.00000126 )\n , ( \"tricycle/elm-", "end": 45448, "score": 0.6127479672, "start": 45444, "tag": "USERNAME", "value": "weir" }, { "context": "parse-dont-validate\", 0.00000125 )\n , ( \"frandibar/elm-bootstrap\", 0.00000116 )\n , ( \"carwow/", "end": 45555, "score": 0.8241512179, "start": 45548, "tag": "USERNAME", "value": "andibar" }, { "context": "elm-glsl-generator\", 0.00000109 )\n , ( \"danhandrea/elm-router\", 0.00000098 )\n , ( \"lucamug/el", "end": 45712, "score": 0.7322355509, "start": 45705, "tag": "USERNAME", "value": "handrea" }, { "context": "handrea/elm-router\", 0.00000098 )\n , ( \"lucamug/elm-box-drawing\", 0.00000098 )\n , ( \"danha", "end": 45759, "score": 0.7955933809, "start": 45755, "tag": "USERNAME", "value": "amug" }, { "context": "andrea/elm-time-extra\", 0.00000098 )\n , ( \"justgook/elm-webdriver\", 0.00000095 )\n , ( \"ktonon/", "end": 45866, "score": 0.9319543839, "start": 45858, "tag": "USERNAME", "value": "justgook" }, { "context": "ustgook/elm-webdriver\", 0.00000095 )\n , ( \"ktonon/elm-jsonwebtoken\", 0.00000088 )\n , ( \"Mart", "end": 45915, "score": 0.9037656784, "start": 45909, "tag": "USERNAME", "value": "ktonon" }, { "context": "onon/elm-jsonwebtoken\", 0.00000088 )\n , ( \"MartinSStewart/elm-geometry-serialize\", 0.00000087 )\n , (", "end": 45975, "score": 0.8727396131, "start": 45961, "tag": "USERNAME", "value": "MartinSStewart" }, { "context": "lm-geometry-serialize\", 0.00000087 )\n , ( \"abadi199/intl-phone-input\", 0.00000078 )\n , ( \"stoe", "end": 46035, "score": 0.8183586001, "start": 46027, "tag": "USERNAME", "value": "abadi199" }, { "context": "i199/intl-phone-input\", 0.00000078 )\n , ( \"stoeffel/resetable\", 0.00000078 )\n , ( \"ahstro/elm-", "end": 46089, "score": 0.8977015018, "start": 46081, "tag": "USERNAME", "value": "stoeffel" }, { "context": "( \"stoeffel/resetable\", 0.00000078 )\n , ( \"ahstro/elm-luhn\", 0.00000077 )\n , ( \"FabienHenon/", "end": 46134, "score": 0.7460174561, "start": 46128, "tag": "USERNAME", "value": "ahstro" }, { "context": "( \"ahstro/elm-luhn\", 0.00000077 )\n , ( \"FabienHenon/elm-ckeditor5\", 0.00000072 )\n , ( \"Gl", "end": 46178, "score": 0.6302756667, "start": 46175, "tag": "USERNAME", "value": "ien" }, { "context": "tro/elm-luhn\", 0.00000077 )\n , ( \"FabienHenon/elm-ckeditor5\", 0.00000072 )\n , ( \"GlobalW", "end": 46183, "score": 0.5823595524, "start": 46181, "tag": "USERNAME", "value": "on" }, { "context": "dex/quantify\", 0.00000069 )\n , ( \"FabienHenon/elm-iso8601-date-strings\", 0.00000069 )\n ,", "end": 46289, "score": 0.5349671245, "start": 46287, "tag": "USERNAME", "value": "on" }, { "context": "( \"proda-ai/elm-css\", 0.00000066 )\n , ( \"jgrenat/regression-testing\", 0.00000064 )\n , ( \"Gl", "end": 46395, "score": 0.8261744976, "start": 46390, "tag": "USERNAME", "value": "renat" }, { "context": "class-namespaces\", 0.00000064 )\n , ( \"PaackEng/elm-alert-beta\", 0.00000063 )\n , ( \"tricyc", "end": 46511, "score": 0.5919149518, "start": 46508, "tag": "USERNAME", "value": "Eng" }, { "context": "le/elm-eventstream\", 0.00000055 )\n , ( \"panthershark/snackbar\", 0.00000054 )\n , ( \"alex-tan/loa", "end": 46913, "score": 0.8704278469, "start": 46904, "tag": "USERNAME", "value": "thershark" }, { "context": "panthershark/snackbar\", 0.00000054 )\n , ( \"alex-tan/loadable\", 0.00000054 )\n , ( \"WhileTruu/el", "end": 46959, "score": 0.9967579842, "start": 46951, "tag": "USERNAME", "value": "alex-tan" }, { "context": "Truu/elm-blurhash\", 0.00000052 )\n , ( \"MartinSStewart/send-grid\", 0.0000005 )\n , ( \"MartinSStewa", "end": 47062, "score": 0.795170784, "start": 47052, "tag": "USERNAME", "value": "inSStewart" }, { "context": "rtinSStewart/send-grid\", 0.0000005 )\n , ( \"MartinSStewart/elm-bayer-matrix\", 0.00000049 )\n , ( \"Hert", "end": 47114, "score": 0.8781191707, "start": 47100, "tag": "USERNAME", "value": "MartinSStewart" }, { "context": "wart/elm-bayer-matrix\", 0.00000049 )\n , ( \"Herteby/url-builder-plus\", 0.00000048 )\n , ( \"andr", "end": 47167, "score": 0.8020862937, "start": 47160, "tag": "USERNAME", "value": "Herteby" }, { "context": "teby/url-builder-plus\", 0.00000048 )\n , ( \"andre-dietrich/elm-mapbox\", 0.00000048 )\n , ( \"z5h/zipper", "end": 47227, "score": 0.9680813551, "start": 47213, "tag": "USERNAME", "value": "andre-dietrich" }, { "context": "tricycle/morty-api\", 0.00000044 )\n , ( \"mthadley/elm-typewriter\", 0.00000044 )\n , ( \"ggb", "end": 47358, "score": 0.6287189722, "start": 47356, "tag": "USERNAME", "value": "ad" }, { "context": " , ( \"bburdette/stl\", 0.00000033 )\n , ( \"jonathanfishbein1/numeric-typeclasses\", 0.00000033 )\n , ( \"g", "end": 47810, "score": 0.9947137833, "start": 47793, "tag": "USERNAME", "value": "jonathanfishbein1" }, { "context": "ribouille/elm-bulma\", 0.00000033 )\n , ( \"peterszerzo/elm-json-tree-view\", 0.00000031 )\n , ( \"al", "end": 48072, "score": 0.8169551492, "start": 48063, "tag": "USERNAME", "value": "terszerzo" }, { "context": "imple-query-string\", 0.00000029 )\n , ( \"prozacchiwawa/elm-json-codec\", 0.00000025 )\n , ( \"danhan", "end": 48199, "score": 0.8220659494, "start": 48189, "tag": "USERNAME", "value": "zacchiwawa" }, { "context": "awa/elm-json-codec\", 0.00000025 )\n , ( \"danhandrea/elm-foo\", 0.00000023 )\n , ( \"proda-ai/form", "end": 48253, "score": 0.7137540579, "start": 48246, "tag": "USERNAME", "value": "handrea" }, { "context": "-ai/elm-svg-loader\", 0.00000022 )\n , ( \"laserpants/elm-burrito-update\", 0.00000022 )\n , ( \"ha", "end": 48400, "score": 0.5790474415, "start": 48393, "tag": "USERNAME", "value": "erpants" }, { "context": " \"allo-media/fable\", 0.00000019 )\n , ( \"achutkiran/elm-material-color\", 0.00000018 )\n , ( \"ki", "end": 48558, "score": 0.7407593727, "start": 48551, "tag": "USERNAME", "value": "utkiran" }, { "context": "rm-validation\", 0.00000018 )\n , ( \"marshallformula/arrangeable-list\", 0.00000018 )\n , ( \"Ralf", "end": 48674, "score": 0.9138493538, "start": 48667, "tag": "USERNAME", "value": "formula" }, { "context": "mula/arrangeable-list\", 0.00000018 )\n , ( \"RalfNorthman/elm-lttb\", 0.00000018 )\n , ( \"malaire/elm-", "end": 48732, "score": 0.8513794541, "start": 48720, "tag": "USERNAME", "value": "RalfNorthman" }, { "context": "malaire/elm-safe-int\", 0.00000018 )\n , ( \"driebit/elm-ginger\", 0.00000017 )\n , ( \"MichaelCom", "end": 48826, "score": 0.8310016394, "start": 48820, "tag": "USERNAME", "value": "riebit" }, { "context": "( \"driebit/elm-ginger\", 0.00000017 )\n , ( \"MichaelCombs28/elm-css-bulma\", 0.00000016 )\n , ( \"league/", "end": 48880, "score": 0.9938604236, "start": 48866, "tag": "USERNAME", "value": "MichaelCombs28" }, { "context": "eague/difference-list\", 0.00000016 )\n , ( \"harrysarson/elm-hacky-unique\", 0.00000015 )\n , ( \"owan", "end": 48985, "score": 0.898064971, "start": 48974, "tag": "USERNAME", "value": "harrysarson" }, { "context": "rson/elm-hacky-unique\", 0.00000015 )\n , ( \"owanturist/elm-graphql\", 0.00000015 )\n , ( \"dosarf/el", "end": 49041, "score": 0.9231238365, "start": 49031, "tag": "USERNAME", "value": "owanturist" }, { "context": "turist/elm-graphql\", 0.00000015 )\n , ( \"dosarf/elm-activemq\", 0.00000013 )\n , ( \"SiriusSt", "end": 49088, "score": 0.7302545309, "start": 49085, "tag": "USERNAME", "value": "arf" }, { "context": " \"dosarf/elm-activemq\", 0.00000013 )\n , ( \"SiriusStarr/elm-spaced-repetition\", 0.00000012 )\n , ( ", "end": 49141, "score": 0.7457280159, "start": 49130, "tag": "USERNAME", "value": "SiriusStarr" }, { "context": "( \"r-k-b/elm-interval\", 0.00000011 )\n , ( \"SiriusStarr/elm-splat\", 0.0000001 )\n , ( \"calions-app/", "end": 49250, "score": 0.7624707222, "start": 49239, "tag": "USERNAME", "value": "SiriusStarr" }, { "context": "\"r-k-b/map-accumulate\", 0.00000008 )\n , ( \"JohnBugner/elm-loop\", 0.00000008 )\n , ( \"jjant/elm-di", "end": 49410, "score": 0.9981291294, "start": 49400, "tag": "USERNAME", "value": "JohnBugner" }, { "context": "pp/jsonapi-http-retry\", 0.00000007 )\n , ( \"bowbahdoe/lime-reset\", 0.00000007 )\n , ( \"ljuglaret/", "end": 49559, "score": 0.8938666582, "start": 49550, "tag": "USERNAME", "value": "bowbahdoe" }, { "context": "\"bowbahdoe/lime-reset\", 0.00000007 )\n , ( \"ljuglaret/combinatoire\", 0.00000007 )\n , ( \"harmbosc", "end": 49608, "score": 0.8021098971, "start": 49599, "tag": "USERNAME", "value": "ljuglaret" }, { "context": "laret/combinatoire\", 0.00000007 )\n , ( \"harmboschloo/graphql-to-elm-package\", 0.00000005 )\n , (", "end": 49662, "score": 0.6246879697, "start": 49653, "tag": "USERNAME", "value": "mboschloo" }, { "context": "elm-wikimedia-commons\", 0.00000004 )\n , ( \"afidegnum/elm-bulmanizer\", 0.00000004 )\n , ( \"alexan", "end": 49782, "score": 0.8251922727, "start": 49773, "tag": "USERNAME", "value": "afidegnum" }, { "context": "degnum/elm-bulmanizer\", 0.00000004 )\n , ( \"alexanderkiel/list-selection\", 0.00000004 )\n , ( \"Bernar", "end": 49839, "score": 0.9602124095, "start": 49826, "tag": "USERNAME", "value": "alexanderkiel" }, { "context": ", ( \"kkpoon/elm-auth0\", 0.00000004 )\n , ( \"jaredramirez/elm-field\", 0.00000004 )\n , ( \"showell/elm", "end": 50047, "score": 0.8838728666, "start": 50035, "tag": "USERNAME", "value": "jaredramirez" }, { "context": "ramirez/elm-field\", 0.00000004 )\n , ( \"showell/elm-data-util\", 0.00000003 )\n , ( \"hallelu", "end": 50093, "score": 0.5071052909, "start": 50090, "tag": "USERNAME", "value": "ell" }, { "context": "m-apex-charts-link\", 0.00000002 )\n , ( \"tasuki/elm-bloom\", 0.00000002 )\n , ( \"shamansir/t", "end": 50257, "score": 0.5460323691, "start": 50254, "tag": "USERNAME", "value": "uki" }, { "context": "\"ryan-senn/elm-tlds\", 0.00000001 )\n , ( \"ryan-senn/elm-readability\", 0.00000001 )\n , ( \"wolfa", "end": 50607, "score": 0.6099039912, "start": 50600, "tag": "USERNAME", "value": "an-senn" }, { "context": "\"Arkham/elm-chords\", 0.00000001 )\n , ( \"primait/elm-form\", 0.00000001 )\n , ( \"opvasger/amr", "end": 50872, "score": 0.7336864471, "start": 50868, "tag": "USERNAME", "value": "mait" }, { "context": ", ( \"primait/elm-form\", 0.00000001 )\n , ( \"opvasger/amr\", 0.00000001 )\n , ( \"choonkeat/elm-ret", "end": 50918, "score": 0.8236902356, "start": 50910, "tag": "USERNAME", "value": "opvasger" }, { "context": " , ( \"opvasger/amr\", 0.00000001 )\n , ( \"choonkeat/elm-retry\", 0.00000001 )\n , ( \"wolfadex/ti", "end": 50960, "score": 0.7444432378, "start": 50954, "tag": "USERNAME", "value": "onkeat" }, { "context": "\"choonkeat/elm-retry\", 0.00000001 )\n , ( \"wolfadex/tiler\", 0.0 )\n , ( \"iodevs/elm-validate\", ", "end": 51007, "score": 0.7109992504, "start": 51000, "tag": "USERNAME", "value": "olfadex" }, { "context": " \"Libbum/elm-redblacktrees\", 0.0 )\n , ( \"avh4-experimental/elm-transducers\", 0.0 )\n , ( \"ryan-senn/st", "end": 51139, "score": 0.7964779735, "start": 51124, "tag": "USERNAME", "value": "h4-experimental" }, { "context": "experimental/elm-transducers\", 0.0 )\n , ( \"ryan-senn/stellar-elm-sdk\", 0.0 )\n ]\n", "end": 51186, "score": 0.9411005974, "start": 51177, "tag": "USERNAME", "value": "ryan-senn" } ]
src/frontend/Utils/Popularity.elm
dmy/elm.dmy.fr
1
module Utils.Popularity exposing (get) import Dict exposing (Dict) get : String -> String -> Float get author project = popularity |> Dict.get (author ++ "/" ++ project) |> Maybe.withDefault 0 {-| Popularity ranking based on average usage per year in about 2000 GitHub open source Elm applications. -} popularity : Dict String Float popularity = Dict.fromList [ ( "elm/core", 100.0 ) , ( "elm/html", 97.34550643 ) , ( "elm/browser", 96.82660239 ) , ( "elm/json", 68.40488677 ) , ( "elm/http", 42.29543762 ) , ( "elm/time", 36.35605399 ) , ( "elm/url", 36.00172359 ) , ( "elm-explorations/test", 30.98760851 ) , ( "elm/random", 22.05868642 ) , ( "elm-community/list-extra", 21.28475703 ) , ( "mdgriffith/elm-ui", 21.01525279 ) , ( "elm/svg", 20.67103346 ) , ( "NoRedInk/elm-json-decode-pipeline", 18.8763277 ) , ( "rtfeldman/elm-css", 12.36916545 ) , ( "avh4/elm-color", 11.47447504 ) , ( "elm/parser", 9.97120987 ) , ( "elm/regex", 9.56505828 ) , ( "elm-community/maybe-extra", 8.38839645 ) , ( "krisajenkins/remotedata", 7.80414698 ) , ( "elm/file", 6.82690159 ) , ( "elm-explorations/markdown", 6.4791066 ) , ( "rtfeldman/elm-iso8601-date-strings", 6.22700287 ) , ( "elm-community/random-extra", 6.14534458 ) , ( "rundis/elm-bootstrap", 5.97488205 ) , ( "justinmimbs/date", 5.15831017 ) , ( "elm-community/json-extra", 4.6148592 ) , ( "elm-community/string-extra", 4.23226837 ) , ( "mpizenberg/elm-pointer-events", 3.77488665 ) , ( "elm-community/result-extra", 3.76826117 ) , ( "elm-explorations/linear-algebra", 3.45998535 ) , ( "elm/bytes", 3.40131264 ) , ( "dillonkearns/elm-pages", 3.28875762 ) , ( "myrho/elm-round", 3.24788501 ) , ( "elm/virtual-dom", 3.03890258 ) , ( "elm-community/typed-svg", 2.88877073 ) , ( "dillonkearns/elm-sitemap", 2.80172858 ) , ( "dillonkearns/elm-rss", 2.79940758 ) , ( "rtfeldman/elm-hex", 2.71486235 ) , ( "ryannhg/date-format", 2.69281928 ) , ( "elm-explorations/webgl", 2.67113902 ) , ( "dillonkearns/elm-markdown", 2.61302108 ) , ( "elm-community/dict-extra", 2.6126905 ) , ( "noahzgordon/elm-color-extra", 2.50191896 ) , ( "dillonkearns/elm-graphql", 2.43280404 ) , ( "lukewestby/elm-string-interpolate", 2.21887162 ) , ( "joakin/elm-canvas", 2.06071881 ) , ( "justinmimbs/time-extra", 2.02711878 ) , ( "ianmackenzie/elm-geometry", 1.93496966 ) , ( "elm-community/html-extra", 1.91841405 ) , ( "ohanhi/keyboard", 1.82651929 ) , ( "mdgriffith/elm-markup", 1.79477894 ) , ( "ianmackenzie/elm-units", 1.77692833 ) , ( "truqu/elm-base64", 1.65642656 ) , ( "gampleman/elm-visualization", 1.59352132 ) , ( "jfmengels/elm-review", 1.58147495 ) , ( "hecrj/html-parser", 1.54538153 ) , ( "mdgriffith/elm-animator", 1.54119939 ) , ( "stil4m/elm-syntax", 1.5343108 ) , ( "elm-community/array-extra", 1.5177429 ) , ( "evancz/elm-playground", 1.49471032 ) , ( "elm-explorations/benchmark", 1.43905721 ) , ( "danyx23/elm-uuid", 1.40987928 ) , ( "ianmackenzie/elm-3d-scene", 1.39304298 ) , ( "lukewestby/elm-http-builder", 1.38467299 ) , ( "rtfeldman/elm-validate", 1.37146825 ) , ( "elm/project-metadata-utils", 1.35373173 ) , ( "terezka/line-charts", 1.3095579 ) , ( "cuducos/elm-format-number", 1.21964339 ) , ( "mdgriffith/elm-style-animation", 1.21027623 ) , ( "Janiczek/cmd-extra", 1.16277179 ) , ( "pablohirafuji/elm-markdown", 1.16211273 ) , ( "feathericons/elm-feather", 1.14979216 ) , ( "lattyware/elm-fontawesome", 1.13694509 ) , ( "elm-community/basics-extra", 1.13686848 ) , ( "MacCASOutreach/graphicsvg", 1.118421 ) , ( "mgold/elm-nonempty-list", 1.06806795 ) , ( "timjs/elm-collage", 1.06749701 ) , ( "folkertdev/one-true-path-experiment", 1.03353175 ) , ( "avh4/elm-program-test", 1.01810543 ) , ( "surprisetalk/elm-bulma", 0.96419058 ) , ( "elm-community/graph", 0.93775505 ) , ( "ryannhg/elm-spa", 0.91699362 ) , ( "pzp1997/assoc-list", 0.9123035 ) , ( "elm-community/easing-functions", 0.85061093 ) , ( "elm-community/intdict", 0.8476579 ) , ( "bartavelle/json-helpers", 0.83941682 ) , ( "danfishgold/base64-bytes", 0.83681365 ) , ( "sparksp/elm-review-forbidden-words", 0.83367851 ) , ( "debois/elm-dom", 0.81170328 ) , ( "Fresheyeball/elm-return", 0.79142091 ) , ( "fapian/elm-html-aria", 0.74339424 ) , ( "Gizra/elm-keyboard-event", 0.70692863 ) , ( "truqu/elm-md5", 0.70189214 ) , ( "andrewMacmurray/elm-delay", 0.68450709 ) , ( "aforemny/material-components-web-elm", 0.67701128 ) , ( "justinmimbs/timezone-data", 0.67701033 ) , ( "cmditch/elm-bigint", 0.66515013 ) , ( "wernerdegroot/listzipper", 0.65981506 ) , ( "jinjor/elm-debounce", 0.65157382 ) , ( "PanagiotisGeorgiadis/elm-datetime", 0.64939135 ) , ( "ianmackenzie/elm-geometry-svg", 0.63453537 ) , ( "Chadtech/elm-bool-extra", 0.62067315 ) , ( "lynn/elm-arithmetic", 0.60440016 ) , ( "pablohirafuji/elm-syntax-highlight", 0.60259155 ) , ( "arturopala/elm-monocle", 0.59790553 ) , ( "frandibar/elm-font-awesome-5", 0.58007091 ) , ( "justgook/elm-image", 0.56065333 ) , ( "miniBill/elm-codec", 0.55814043 ) , ( "zaboco/elm-draggable", 0.55544337 ) , ( "billstclair/elm-port-funnel", 0.54505022 ) , ( "norpan/elm-html5-drag-drop", 0.54306867 ) , ( "TSFoster/elm-uuid", 0.53512402 ) , ( "ianmackenzie/elm-3d-camera", 0.52840696 ) , ( "jfmengels/elm-review-unused", 0.51706478 ) , ( "ohanhi/remotedata-http", 0.49473739 ) , ( "icidasset/elm-binary", 0.46635256 ) , ( "CurrySoftware/elm-datepicker", 0.46026974 ) , ( "abadi199/elm-input-extra", 0.45043369 ) , ( "tesk9/palette", 0.44476755 ) , ( "zwilias/elm-rosetree", 0.44070751 ) , ( "annaghi/dnd-list", 0.43962043 ) , ( "SwiftsNamesake/proper-keyboard", 0.43812191 ) , ( "lovasoa/elm-csv", 0.43385591 ) , ( "billstclair/elm-websocket-client", 0.4211239 ) , ( "ccapndave/elm-update-extra", 0.41977621 ) , ( "robinheghan/murmur3", 0.41709346 ) , ( "icidasset/elm-material-icons", 0.40716159 ) , ( "Orasund/elm-ui-widgets", 0.40258153 ) , ( "truqu/elm-review-noleftpizza", 0.39533714 ) , ( "turboMaCk/any-dict", 0.39102931 ) , ( "turboMaCk/non-empty-list-alias", 0.39042555 ) , ( "simonh1000/elm-jwt", 0.38886083 ) , ( "pablohirafuji/elm-qrcode", 0.38671063 ) , ( "j-panasiuk/elm-ionicons", 0.38431649 ) , ( "lattyware/elm-json-diff", 0.37994196 ) , ( "zwilias/elm-html-string", 0.37515704 ) , ( "arowM/elm-form-decoder", 0.37362769 ) , ( "mgold/elm-animation", 0.37188307 ) , ( "ianmackenzie/elm-triangular-mesh", 0.37009167 ) , ( "TSFoster/elm-tuple-extra", 0.36731534 ) , ( "tripokey/elm-fuzzy", 0.36692263 ) , ( "Punie/elm-parser-extras", 0.35297849 ) , ( "pablen/toasty", 0.35179729 ) , ( "elm-community/undo-redo", 0.34593754 ) , ( "truqu/elm-oauth2", 0.33816251 ) , ( "Gizra/elm-all-set", 0.3343813 ) , ( "jweir/elm-iso8601", 0.3339095 ) , ( "tortus/elm-array-2d", 0.33365387 ) , ( "NoRedInk/elm-random-pcg-extended", 0.33190522 ) , ( "webbhuset/elm-json-decode", 0.32811851 ) , ( "ktonon/elm-crypto", 0.32801593 ) , ( "elm-community/list-split", 0.32784106 ) , ( "Herteby/simplex-noise", 0.3219093 ) , ( "jzxhuang/http-extras", 0.32137401 ) , ( "folkertdev/elm-deque", 0.32109268 ) , ( "ianmackenzie/elm-1d-parameter", 0.32006002 ) , ( "ccapndave/elm-flat-map", 0.31981126 ) , ( "truqu/elm-review-nobooleancase", 0.3178199 ) , ( "toastal/either", 0.31746851 ) , ( "1602/elm-feather", 0.31660394 ) , ( "mdgriffith/style-elements", 0.31212673 ) , ( "NoRedInk/elm-uuid", 0.31183615 ) , ( "perzanko/elm-loading", 0.30855664 ) , ( "linuss/smooth-scroll", 0.3077922 ) , ( "etaque/elm-form", 0.30348605 ) , ( "gingko/time-distance", 0.30336385 ) , ( "GlobalWebIndex/cmd-extra", 0.302766 ) , ( "NoRedInk/elm-string-conversions", 0.29331575 ) , ( "AdrianRibao/elm-derberos-date", 0.28990482 ) , ( "kalutheo/elm-ui-explorer", 0.28612503 ) , ( "justgage/tachyons-elm", 0.28523698 ) , ( "Gizra/elm-debouncer", 0.28504558 ) , ( "turboMaCk/any-set", 0.28438649 ) , ( "the-sett/elm-color", 0.28403224 ) , ( "billstclair/elm-sortable-table", 0.28271317 ) , ( "capitalist/elm-octicons", 0.28195837 ) , ( "simonh1000/elm-colorpicker", 0.27117854 ) , ( "pilatch/flip", 0.26704357 ) , ( "folkertdev/elm-state", 0.26525221 ) , ( "jfmengels/elm-review-debug", 0.26221985 ) , ( "TSFoster/elm-sha1", 0.26165276 ) , ( "klazuka/elm-json-tree-view", 0.26067484 ) , ( "Janiczek/elm-bidict", 0.25968504 ) , ( "danmarcab/material-icons", 0.25622646 ) , ( "basti1302/elm-human-readable-filesize", 0.24826223 ) , ( "panthershark/email-parser", 0.24690589 ) , ( "fredcy/elm-parseint", 0.24670168 ) , ( "jorgengranseth/elm-string-format", 0.24568559 ) , ( "hecrj/composable-form", 0.24505523 ) , ( "ianmackenzie/elm-geometry-test", 0.24302217 ) , ( "billstclair/elm-sha256", 0.24141562 ) , ( "ianmackenzie/elm-geometry-linear-algebra-interop", 0.23533215 ) , ( "danhandrea/elm-date-format", 0.23529358 ) , ( "NoRedInk/elm-sortable-table", 0.23358588 ) , ( "kuon/elm-string-normalize", 0.23118365 ) , ( "dmy/elm-pratt-parser", 0.22989056 ) , ( "Chadtech/unique-list", 0.22899954 ) , ( "jamesmacaulay/elm-graphql", 0.22776995 ) , ( "ymtszw/elm-xml-decode", 0.22661962 ) , ( "billstclair/elm-localstorage", 0.22374157 ) , ( "mthadley/elm-hash-routing", 0.22155574 ) , ( "cappyzawa/elm-ui-colors", 0.22082952 ) , ( "the-sett/elm-syntax-dsl", 0.22020009 ) , ( "damienklinnert/elm-spinner", 0.21776168 ) , ( "matthewsj/elm-ordering", 0.21745709 ) , ( "folkertdev/elm-flate", 0.2170955 ) , ( "carwow/elm-slider", 0.21197636 ) , ( "jinjor/elm-diff", 0.21185364 ) , ( "ursi/elm-css-colors", 0.2108615 ) , ( "ContaSystemer/elm-menu", 0.21014847 ) , ( "tricycle/elm-embed-youtube", 0.20671199 ) , ( "PaackEng/elm-ui-dialog", 0.2006389 ) , ( "CoderDennis/elm-time-format", 0.19815286 ) , ( "gicentre/elm-vegalite", 0.19740117 ) , ( "yotamDvir/elm-pivot", 0.19665382 ) , ( "NoRedInk/elm-simple-fuzzy", 0.19456658 ) , ( "ggb/numeral-elm", 0.19337426 ) , ( "zwilias/json-decode-exploration", 0.1918353 ) , ( "jfmengels/elm-review-common", 0.18847052 ) , ( "BrianHicks/elm-css-reset", 0.18822892 ) , ( "Janiczek/elm-graph", 0.18803528 ) , ( "ericgj/elm-csv-decode", 0.1876914 ) , ( "periodic/elm-csv", 0.18684353 ) , ( "pd-andy/tuple-extra", 0.18558304 ) , ( "tesk9/accessible-html", 0.18279636 ) , ( "lovasoa/elm-rolling-list", 0.18097298 ) , ( "krisajenkins/elm-astar", 0.18017187 ) , ( "BrianHicks/elm-particle", 0.17786303 ) , ( "folkertdev/elm-sha2", 0.17785039 ) , ( "Garados007/elm-svg-parser", 0.17754484 ) , ( "gampleman/elm-mapbox", 0.17754114 ) , ( "NoRedInk/elm-compare", 0.17712889 ) , ( "joneshf/elm-tagged", 0.17681944 ) , ( "the-sett/lazy-list", 0.17264487 ) , ( "turboMaCk/lazy-tree-with-zipper", 0.17263832 ) , ( "jfmengels/elm-review-documentation", 0.17208178 ) , ( "y047aka/elm-reset-css", 0.17137837 ) , ( "Orasund/elm-ui-framework", 0.16892692 ) , ( "ianmackenzie/elm-units-prefixed", 0.16798459 ) , ( "jxxcarlson/elm-typed-time", 0.16708656 ) , ( "ianmackenzie/elm-float-extra", 0.16430595 ) , ( "matken11235/html-styled-extra", 0.16388741 ) , ( "supermacro/elm-antd", 0.16388741 ) , ( "jasonliang-dev/elm-heroicons", 0.16388741 ) , ( "robinheghan/keyboard-events", 0.16388741 ) , ( "MaybeJustJames/yaml", 0.16388741 ) , ( "coinop-logan/elm-format-number", 0.16350434 ) , ( "truqu/elm-review-noredundantconcat", 0.16279207 ) , ( "truqu/elm-review-noredundantcons", 0.16278661 ) , ( "ahstro/elm-bulma-classes", 0.16268257 ) , ( "rluiten/elm-text-search", 0.16195907 ) , ( "norpan/elm-json-patch", 0.1618311 ) , ( "avh4/elm-fifo", 0.16165577 ) , ( "eriktim/elm-protocol-buffers", 0.1569727 ) , ( "zwilias/elm-utf-tools", 0.15675438 ) , ( "fabhof/elm-ui-datepicker", 0.15601158 ) , ( "Kraxorax/elm-matrix-a", 0.1550815 ) , ( "Zinggi/elm-2d-game", 0.14786867 ) , ( "waratuman/time-extra", 0.14714351 ) , ( "pd-andy/elm-web-audio", 0.14559802 ) , ( "ianmackenzie/elm-units-interval", 0.14409245 ) , ( "alex-tan/elm-dialog", 0.14326271 ) , ( "joakin/elm-grid", 0.14239279 ) , ( "marcosh/elm-html-to-unicode", 0.14136611 ) , ( "K-Adam/elm-dom", 0.14100964 ) , ( "stoeffel/elm-verify", 0.14049657 ) , ( "thaterikperson/elm-strftime", 0.14048949 ) , ( "joshforisha/elm-html-entities", 0.14014579 ) , ( "ChristophP/elm-i18next", 0.14009583 ) , ( "WhileTruu/elm-smooth-scroll", 0.13550094 ) , ( "smucode/elm-flat-colors", 0.13390605 ) , ( "PaackEng/elm-ui-dropdown", 0.13349351 ) , ( "jinjor/elm-xml-parser", 0.13308261 ) , ( "Spaxe/svg-pathd", 0.13299764 ) , ( "Zinggi/elm-game-resources", 0.13123514 ) , ( "justgook/webgl-shape", 0.13025186 ) , ( "miyamoen/select-list", 0.12993603 ) , ( "cmditch/elm-ethereum", 0.12836444 ) , ( "visotype/elm-dom", 0.12812192 ) , ( "folkertdev/svg-path-lowlevel", 0.12684362 ) , ( "rtfeldman/elm-sorter-experiment", 0.12623643 ) , ( "stil4m/structured-writer", 0.12619772 ) , ( "lucamug/style-framework", 0.12605465 ) , ( "stoeffel/set-extra", 0.12571783 ) , ( "STTR13/ziplist", 0.12570977 ) , ( "FabienHenon/elm-infinite-list-view", 0.12559581 ) , ( "FabienHenon/elm-infinite-scroll", 0.12528226 ) , ( "sporto/time-distance", 0.12511912 ) , ( "dillonkearns/elm-cli-options-parser", 0.12476245 ) , ( "mcordova47/elm-natural-ordering", 0.12461905 ) , ( "hecrj/elm-slug", 0.12412494 ) , ( "NoRedInk/list-selection", 0.12398862 ) , ( "Voronchuk/hexagons", 0.12371057 ) , ( "y0hy0h/ordered-containers", 0.12369689 ) , ( "elm-athlete/athlete", 0.12274771 ) , ( "laserpants/elm-update-pipeline", 0.12193618 ) , ( "coinop-logan/phace", 0.12151759 ) , ( "BrianHicks/elm-trend", 0.12024157 ) , ( "MartinSStewart/elm-audio", 0.11849084 ) , ( "rl-king/elm-scroll-to", 0.11522835 ) , ( "erlandsona/assoc-set", 0.11493819 ) , ( "justgook/webgl-playground", 0.11294313 ) , ( "tesk9/accessible-html-with-css", 0.11217061 ) , ( "w0rm/elm-physics", 0.11193187 ) , ( "jgrenat/elm-html-test-runner", 0.1106782 ) , ( "krisajenkins/elm-exts", 0.11045032 ) , ( "ianmackenzie/elm-interval", 0.11014532 ) , ( "mhoare/elm-stack", 0.1099642 ) , ( "Punie/elm-matrix", 0.10890224 ) , ( "bburdette/websocket", 0.1081962 ) , ( "danyx23/elm-mimetype", 0.10773962 ) , ( "arowM/elm-mixin", 0.10755002 ) , ( "sporto/elm-select", 0.10669776 ) , ( "tricycle/elm-actor-framework", 0.10652682 ) , ( "ThinkAlexandria/elm-pretty-print-json", 0.1058547 ) , ( "arowM/elm-reference", 0.10549205 ) , ( "mdgriffith/stylish-elephants", 0.1052336 ) , ( "yotamDvir/elm-katex", 0.10459095 ) , ( "carmonw/elm-number-to-words", 0.10374789 ) , ( "dillonkearns/elm-oembed", 0.10209354 ) , ( "RomanErnst/erl", 0.09858579 ) , ( "w0rm/elm-obj-file", 0.09833245 ) , ( "lemol/ant-design-icons-elm-ui", 0.09833245 ) , ( "avh4/elm-beautiful-example", 0.09706569 ) , ( "arowM/elm-classname", 0.09479125 ) , ( "the-sett/elm-state-machines", 0.09395605 ) , ( "Orasund/pixelengine", 0.09394164 ) , ( "the-sett/elm-auth-aws", 0.09391371 ) , ( "rl-king/elm-gallery", 0.0936856 ) , ( "the-sett/elm-update-helper", 0.09360555 ) , ( "the-sett/elm-auth", 0.09360487 ) , ( "drathier/elm-graph", 0.09350995 ) , ( "arowM/elm-neat-layout", 0.09346707 ) , ( "bgrosse-midokura/composable-form", 0.09309911 ) , ( "jxxcarlson/elm-cell-grid", 0.0918109 ) , ( "indicatrix/elm-chartjs-webcomponent", 0.09174394 ) , ( "andre-dietrich/parser-combinators", 0.09165459 ) , ( "achutkiran/material-components-elm", 0.09163468 ) , ( "inkuzmin/elm-multiselect", 0.09139183 ) , ( "stoeffel/editable", 0.09126776 ) , ( "Chadtech/id", 0.09113307 ) , ( "jonoabroad/commatosed", 0.09054461 ) , ( "kirchner/elm-selectize", 0.0905111 ) , ( "phollyer/elm-phoenix-websocket", 0.09013808 ) , ( "hmsk/elm-css-modern-normalize", 0.09013808 ) , ( "gampleman/elm-examples-helper", 0.09013808 ) , ( "malaire/elm-uint64", 0.09013808 ) , ( "JohnBugner/elm-matrix", 0.09013808 ) , ( "TheSacredLipton/elm-ui-hexcolor", 0.09013808 ) , ( "jfmengels/elm-review-the-elm-architecture", 0.09013808 ) , ( "jschomay/elm-paginate", 0.08956332 ) , ( "alex-tan/elm-tree-diagram", 0.08945404 ) , ( "xarvh/elm-slides", 0.0892947 ) , ( "rluiten/stringdistance", 0.0892684 ) , ( "Orasund/elm-game-essentials", 0.08916985 ) , ( "mgold/elm-geojson", 0.08897403 ) , ( "marshallformula/elm-swiper", 0.0886618 ) , ( "jxxcarlson/elm-markdown", 0.08820943 ) , ( "Microsoft/elm-json-tree-view", 0.08814142 ) , ( "newmana/chroma-elm", 0.08810571 ) , ( "justgook/alt-linear-algebra", 0.08789221 ) , ( "larribas/elm-multi-input", 0.08787663 ) , ( "lukewestby/elm-template", 0.08760839 ) , ( "EdutainmentLIVE/elm-bootstrap", 0.08601373 ) , ( "vito/elm-ansi", 0.08564269 ) , ( "z5h/component-result", 0.08501743 ) , ( "BrianHicks/elm-string-graphemes", 0.08438992 ) , ( "proda-ai/elm-dropzone", 0.0839448 ) , ( "TSFoster/elm-bytes-extra", 0.0822685 ) , ( "tremlab/bugsnag-elm", 0.0819437 ) , ( "fredcy/elm-debouncer", 0.0819437 ) , ( "dzuk-mutant/elm-html-styled-aria", 0.0819437 ) , ( "proda-ai/murmur3", 0.0819437 ) , ( "oaalto/time-values", 0.0819437 ) , ( "chelovek0v/bbase64", 0.0819437 ) , ( "andre-dietrich/elm-conditional", 0.0819437 ) , ( "robinheghan/elm-deque", 0.0819437 ) , ( "MartinSStewart/elm-serialize", 0.0819437 ) , ( "jxxcarlson/hex", 0.08025377 ) , ( "prikhi/decimal", 0.07988138 ) , ( "league/unique-id", 0.07962549 ) , ( "jschomay/elm-narrative-engine", 0.07850368 ) , ( "blissfully/elm-chartjs-webcomponent", 0.07789183 ) , ( "jxxcarlson/elm-graph", 0.07777827 ) , ( "samhstn/time-format", 0.07741896 ) , ( "jxxcarlson/elm-pseudorandom", 0.0772143 ) , ( "the-sett/elm-pretty-printer", 0.07673811 ) , ( "cultureamp/elm-css-modules-loader", 0.07673201 ) , ( "Fresheyeball/deburr", 0.07607407 ) , ( "f0i/statistics", 0.07569493 ) , ( "ymtszw/elm-http-xml", 0.075543 ) , ( "PaackEng/elm-svg-string", 0.07533646 ) , ( "jouderianjr/elm-dialog", 0.07497169 ) , ( "newlandsvalley/elm-binary-base64", 0.07450259 ) , ( "the-sett/elm-string-case", 0.07417748 ) , ( "supermario/elm-countries", 0.07415019 ) , ( "gribouille/elm-treeview", 0.07393474 ) , ( "etaque/elm-response", 0.07385955 ) , ( "harrysarson/elm-complex", 0.07383846 ) , ( "FMFI-UK-1-AIN-412/elm-formula", 0.07383412 ) , ( "owanturist/elm-union-find", 0.07362182 ) , ( "z5h/jaro-winkler", 0.07331902 ) , ( "brandly/elm-dot-lang", 0.07330965 ) , ( "y047aka/elm-hsl-color", 0.0731552 ) , ( "ryry0/elm-numeric", 0.07297005 ) , ( "rogeriochaves/elm-test-bdd-style", 0.07295471 ) , ( "waratuman/elm-coder", 0.07280749 ) , ( "hrldcpr/elm-cons", 0.0725321 ) , ( "prozacchiwawa/elm-keccak", 0.07208187 ) , ( "jims/html-parser", 0.07206386 ) , ( "PanagiotisGeorgiadis/elm-datepicker", 0.07190215 ) , ( "LesleyLai/elm-grid", 0.07180881 ) , ( "mweiss/elm-rte-toolkit", 0.0716879 ) , ( "isaacseymour/deprecated-time", 0.07141021 ) , ( "sporto/qs", 0.07080009 ) , ( "Chadtech/elm-money", 0.07039523 ) , ( "kuzminadya/mogeefont", 0.07026973 ) , ( "fifth-postulate/priority-queue", 0.07018505 ) , ( "sudo-rushil/elm-cards", 0.07008874 ) , ( "bigardone/elm-css-placeholders", 0.06905357 ) , ( "ronanyeah/helpers", 0.0682312 ) , ( "YuyaAizawa/list-wrapper", 0.06783713 ) , ( "truqu/line-charts", 0.06764527 ) , ( "dmy/elm-imf-date-time", 0.06669301 ) , ( "SiriusStarr/elm-password-strength", 0.06574762 ) , ( "EdutainmentLIVE/elm-dropdown", 0.06568054 ) , ( "peterszerzo/line-charts", 0.06567449 ) , ( "ktonon/elm-word", 0.0656437 ) , ( "the-sett/elm-aws-core", 0.06546173 ) , ( "mercurymedia/elm-datetime-picker", 0.06484787 ) , ( "MartinSStewart/elm-box-packing", 0.06441992 ) , ( "GlobalWebIndex/elm-plural-rules", 0.06411989 ) , ( "lazamar/dict-parser", 0.0631332 ) , ( "savardd/elm-time-travel", 0.06297284 ) , ( "cappyzawa/elm-ui-onedark", 0.06209494 ) , ( "erosson/number-suffix", 0.06192027 ) , ( "NoRedInk/elm-random-general", 0.06178116 ) , ( "edkv/elm-generic-dict", 0.06134726 ) , ( "Chadtech/return", 0.06133436 ) , ( "skyqrose/assoc-list-extra", 0.06125807 ) , ( "prikhi/http-tasks", 0.06107279 ) , ( "cedric-h/elm-google-sign-in", 0.05997924 ) , ( "pehota/elm-zondicons", 0.05897221 ) , ( "JonRowe/elm-jwt", 0.05871744 ) , ( "etaque/elm-transit-style", 0.05866548 ) , ( "dosarf/elm-tree-view", 0.05857506 ) , ( "json-tools/json-value", 0.05840507 ) , ( "r-k-b/no-long-import-lines", 0.05826819 ) , ( "billstclair/elm-xml-eeue56", 0.0581776 ) , ( "etaque/elm-transit", 0.05797409 ) , ( "ursi/elm-throttle", 0.05764599 ) , ( "the-sett/elm-serverless", 0.05755903 ) , ( "commonmind/elm-csv-encode", 0.05710774 ) , ( "allo-media/elm-daterange-picker", 0.05695909 ) , ( "stephenreddek/elm-emoji", 0.05690545 ) , ( "driebit/elm-css-breakpoint", 0.0561004 ) , ( "f0i/iso8601", 0.05608734 ) , ( "jordymoos/pilf", 0.05585866 ) , ( "folq/review-rgb-ranges", 0.05536345 ) , ( "terezka/yaml", 0.05491881 ) , ( "kyasu1/elm-ulid", 0.05461156 ) , ( "Kinto/elm-kinto", 0.05458142 ) , ( "ghivert/elm-graphql", 0.05449382 ) , ( "ursi/elm-scroll", 0.0543715 ) , ( "tiziano88/elm-protobuf", 0.05431539 ) , ( "Punie/elm-reader", 0.05430477 ) , ( "bburdette/cellme", 0.05393641 ) , ( "samueldple/material-color", 0.05370078 ) , ( "Bractlet/elm-plot", 0.05366476 ) , ( "jschomay/elm-bounded-number", 0.05354281 ) , ( "jinjor/elm-contextmenu", 0.05344282 ) , ( "prozacchiwawa/elm-urlbase64", 0.05340177 ) , ( "jluckyiv/elm-utc-date-strings", 0.0533887 ) , ( "mikaxyz/elm-cropper", 0.05326306 ) , ( "TSFoster/elm-heap", 0.0530336 ) , ( "owanturist/elm-bulletproof", 0.05290947 ) , ( "ensoft/entrance", 0.05284254 ) , ( "rgrempel/elm-http-decorators", 0.05281988 ) , ( "Chadtech/random-pipeline", 0.05280586 ) , ( "allo-media/canopy", 0.05273208 ) , ( "harmboschloo/graphql-to-elm", 0.05170478 ) , ( "rielas/measurement", 0.0516935 ) , ( "Chadtech/elm-relational-database", 0.05164367 ) , ( "johnathanbostrom/elm-dice", 0.05149376 ) , ( "jxxcarlson/elm-editor", 0.05141855 ) , ( "0ui/elm-task-parallel", 0.05076761 ) , ( "the-sett/elm-refine", 0.05067941 ) , ( "brian-watkins/elm-spec", 0.04856381 ) , ( "avh4/elm-debug-controls", 0.04839202 ) , ( "phollyer/elm-ui-colors", 0.04822524 ) , ( "Herteby/enum", 0.04795936 ) , ( "kmbn/elm-hotkeys", 0.04743314 ) , ( "cultureamp/babel-elm-assets-plugin", 0.04742013 ) , ( "toastal/mailto", 0.04718736 ) , ( "zwilias/elm-bytes-parser", 0.04703769 ) , ( "tad-lispy/springs", 0.04607089 ) , ( "Janiczek/transform", 0.04453779 ) , ( "hermanverschooten/ip", 0.04416292 ) , ( "jfmengels/lint-unused", 0.0439492 ) , ( "PaackEng/elm-google-maps", 0.04391243 ) , ( "ericgj/elm-uri-template", 0.0434312 ) , ( "data-viz-lab/elm-chart-builder", 0.0433935 ) , ( "folkertdev/elm-paragraph", 0.04272664 ) , ( "icidasset/elm-sha", 0.04256028 ) , ( "dasch/levenshtein", 0.04203807 ) , ( "wittjosiah/elm-ordered-dict", 0.04175244 ) , ( "ktonon/elm-test-extra", 0.04152155 ) , ( "rl-king/elm-masonry", 0.04121287 ) , ( "billstclair/elm-custom-element", 0.04093673 ) , ( "prikhi/bootstrap-gallery", 0.04035975 ) , ( "joshforisha/elm-inflect", 0.04031402 ) , ( "bburdette/pdf-element", 0.04019823 ) , ( "austinshenk/elm-w3", 0.04019579 ) , ( "json-tools/json-schema", 0.04015367 ) , ( "NoRedInk/datetimepicker-legacy", 0.04012745 ) , ( "ccapndave/focus", 0.04006861 ) , ( "gdamjan/elm-identicon", 0.03951737 ) , ( "bemyak/elm-slider", 0.03943666 ) , ( "FabienHenon/jsonapi", 0.03933752 ) , ( "NoRedInk/elm-plot-19", 0.0389287 ) , ( "mercurymedia/elm-message-toast", 0.03831063 ) , ( "chain-partners/elm-bignum", 0.03819787 ) , ( "jouderianjr/elm-loaders", 0.03811653 ) , ( "Punie/elm-id", 0.03796811 ) , ( "drathier/elm-test-tables", 0.03758749 ) , ( "Orasund/elm-action", 0.03733808 ) , ( "w0rm/elm-slice-show", 0.0373203 ) , ( "peterszerzo/elm-arborist", 0.03731962 ) , ( "ThinkAlexandria/elm-html-in-elm", 0.03723739 ) , ( "turboMaCk/queue", 0.03708237 ) , ( "emilianobovetti/edit-distance", 0.03704362 ) , ( "kuzzmi/elm-gravatar", 0.03697676 ) , ( "ThinkAlexandria/elm-drag-locations", 0.03696538 ) , ( "dawehner/elm-colorbrewer", 0.03695076 ) , ( "xarvh/elm-gamepad", 0.036799 ) , ( "benthepoet/elm-purecss", 0.03679697 ) , ( "billstclair/elm-oauth-middleware", 0.03667292 ) , ( "alexkorban/uicards", 0.03663732 ) , ( "folkertdev/elm-int64", 0.03653192 ) , ( "billstclair/elm-geolocation", 0.03644241 ) , ( "justgook/elm-game-logic", 0.03637282 ) , ( "zgohr/elm-csv", 0.03624985 ) , ( "gicentre/elm-vega", 0.03597546 ) , ( "zwilias/elm-reorderable", 0.03593048 ) , ( "toastal/select-prism", 0.03586537 ) , ( "ronanyeah/calendar-dates", 0.03579998 ) , ( "kuon/elm-hsluv", 0.03563973 ) , ( "ir4y/elm-dnd", 0.03561684 ) , ( "xilnocas/step", 0.03560819 ) , ( "stephenreddek/elm-range-slider", 0.03551443 ) , ( "fabiommendes/elm-iter", 0.03545966 ) , ( "akoppela/elm-logo", 0.03543891 ) , ( "billstclair/elm-crypto-string", 0.03529601 ) , ( "arowM/elm-form-validator", 0.0352493 ) , ( "Elm-Canvas/raster-shapes", 0.03520682 ) , ( "1602/json-schema", 0.03520676 ) , ( "ohanhi/autoexpand", 0.03508831 ) , ( "pdamoc/elm-hashids", 0.03503357 ) , ( "ohanhi/lorem", 0.03502294 ) , ( "stephenreddek/elm-time-picker", 0.03500671 ) , ( "mercurymedia/elm-smart-select", 0.03493208 ) , ( "elm-in-elm/compiler", 0.03449337 ) , ( "the-sett/decode-generic", 0.03406044 ) , ( "ljuglaret/fraction", 0.03369673 ) , ( "folkertdev/elm-kmeans", 0.03343474 ) , ( "nikita-volkov/typeclasses", 0.03336435 ) , ( "miniBill/date-format-languages", 0.03285717 ) , ( "jaredramirez/elm-s3", 0.03251825 ) , ( "jonathanfishbein1/elm-field", 0.03186558 ) , ( "bburdette/schelme", 0.03103703 ) , ( "Chadtech/elm-css-grid", 0.03072801 ) , ( "eike/json-decode-complete", 0.03072334 ) , ( "webbhuset/elm-actor-model", 0.03041586 ) , ( "bburdette/toop", 0.02995369 ) , ( "lynn/elm-ordinal", 0.02956659 ) , ( "tricycle/elm-email", 0.029545 ) , ( "tricycle/system-actor-model", 0.02930445 ) , ( "nikita-volkov/hashing-containers", 0.02926126 ) , ( "Orasund/elm-cellautomata", 0.02913753 ) , ( "simplystuart/elm-scroll-to", 0.02903803 ) , ( "MartinSStewart/elm-codec-bytes", 0.02896827 ) , ( "Chadtech/elm-vector", 0.02871587 ) , ( "arowM/html-extra", 0.02849722 ) , ( "munksgaard/elm-charts", 0.02841668 ) , ( "tesk9/modal", 0.02714795 ) , ( "RalfNorthman/elm-zoom-plot", 0.0270936 ) , ( "jxxcarlson/htree", 0.02683459 ) , ( "jxxcarlson/elm-stat", 0.02651257 ) , ( "billstclair/elm-svg-button", 0.02644546 ) , ( "webbhuset/elm-actor-model-elm-ui", 0.02592043 ) , ( "folkertdev/elm-tiny-inflate", 0.025917 ) , ( "fifth-postulate/elm-csv-decode", 0.02586667 ) , ( "viir/simplegamedev", 0.02544128 ) , ( "elm-toulouse/cbor", 0.02530895 ) , ( "rl-king/elm-modular-scale", 0.02520116 ) , ( "bowbahdoe/elm-history", 0.02476153 ) , ( "jxxcarlson/elm-widget", 0.02457994 ) , ( "jackhp95/elm-mapbox", 0.02452827 ) , ( "alex-tan/task-extra", 0.02403581 ) , ( "jjant/elm-printf", 0.02393349 ) , ( "jigargosar/elm-material-color", 0.02343325 ) , ( "avh4/elm-dropbox", 0.02328807 ) , ( "jonathanfishbein1/linear-algebra", 0.0230214 ) , ( "tomjkidd/elm-multiway-tree-zipper", 0.0229576 ) , ( "munksgaard/char-extra", 0.02262327 ) , ( "munksgaard/elm-data-uri", 0.02255611 ) , ( "billstclair/elm-id-search", 0.02252655 ) , ( "thought2/elm-interactive", 0.02222094 ) , ( "brianvanburken/elm-list-date", 0.02198079 ) , ( "andre-dietrich/elm-random-regex", 0.02184853 ) , ( "flowlang-cc/elm-audio-graph", 0.02169063 ) , ( "andre-dietrich/elm-svgbob", 0.0216694 ) , ( "rluiten/trie", 0.02124813 ) , ( "ringvold/elm-iso8601-date-strings", 0.0211933 ) , ( "rl-king/elm-inview", 0.02118104 ) , ( "afidegnum/elm-tailwind", 0.02102643 ) , ( "fifth-postulate/combinatorics", 0.020755 ) , ( "indicatrix/elm-input-extra", 0.02068175 ) , ( "abadi199/elm-creditcard", 0.02068162 ) , ( "arowM/elm-css-modules-helper", 0.02039772 ) , ( "alexanderkiel/elm-mdc-alpha", 0.02028243 ) , ( "sparksp/elm-review-camelcase", 0.02010144 ) , ( "dwyl/elm-criteria", 0.02009551 ) , ( "ericgj/elm-validation", 0.01997145 ) , ( "prikhi/paginate", 0.01997109 ) , ( "romstad/elm-chess", 0.01987651 ) , ( "basti1302/elm-non-empty-array", 0.01959109 ) , ( "MichaelCombs28/elm-base85", 0.01958329 ) , ( "arnau/elm-objecthash", 0.01950411 ) , ( "NoRedInk/elm-debug-controls-without-datepicker", 0.01949173 ) , ( "dasch/parser", 0.01948486 ) , ( "NoRedInk/noredink-ui", 0.01944399 ) , ( "ozmat/elm-forms", 0.01943377 ) , ( "the-sett/ai-search", 0.01942663 ) , ( "allenap/elm-json-decode-broken", 0.01937762 ) , ( "nathanjohnson320/base58", 0.01908185 ) , ( "noahzgordon/elm-jsonapi", 0.01893622 ) , ( "labzero/elm-google-geocoding", 0.01891308 ) , ( "pilatch/elm-chess", 0.0186072 ) , ( "torreyatcitty/the-best-decimal", 0.01847113 ) , ( "NoRedInk/elm-rails", 0.01826369 ) , ( "FordLabs/elm-star-rating", 0.01819264 ) , ( "Bernardoow/elm-alert-timer-message", 0.01807738 ) , ( "JohnBugner/elm-bag", 0.01807483 ) , ( "Gizra/elm-compat-019", 0.01797027 ) , ( "goilluminate/elm-fancy-daterangepicker", 0.01784086 ) , ( "janjelinek/creditcard-validation", 0.01781153 ) , ( "r-k-b/complex", 0.01781103 ) , ( "NoRedInk/elm-sweet-poll", 0.01773511 ) , ( "TSFoster/elm-compare", 0.01772745 ) , ( "fedragon/elm-typed-dropdown", 0.01771295 ) , ( "emilianobovetti/elm-yajson", 0.01770452 ) , ( "jjant/elm-comonad-zipper", 0.01770213 ) , ( "ozmat/elm-validation", 0.01766079 ) , ( "jackfranklin/elm-parse-link-header", 0.0176503 ) , ( "Gizra/elm-attribute-builder", 0.01761218 ) , ( "kkpoon/elm-auth0-urlparser", 0.01761196 ) , ( "1602/json-value", 0.01760062 ) , ( "ggb/elm-bloom", 0.0175877 ) , ( "peterszerzo/elm-porter", 0.01756095 ) , ( "jweir/sparkline", 0.01754773 ) , ( "fbonetti/elm-geodesy", 0.01754339 ) , ( "bChiquet/elm-accessors", 0.01753197 ) , ( "tricycle/elm-actor-framework-template", 0.01638874 ) , ( "robinheghan/elm-warrior", 0.01638874 ) , ( "wsowens/term", 0.01638874 ) , ( "finos/morphir-elm", 0.01638874 ) , ( "sparksp/elm-review-always", 0.01390432 ) , ( "YuyaAizawa/peg", 0.01331966 ) , ( "jfmengels/lint-debug", 0.01255703 ) , ( "billstclair/elm-dialog", 0.01200416 ) , ( "jxxcarlson/meenylatex", 0.01054695 ) , ( "the-sett/elm-error-handling", 0.01024483 ) , ( "Arkham/elm-rttl", 0.00987257 ) , ( "jfmengels/elm-lint", 0.00982276 ) , ( "Chadtech/ct-colors", 0.00927074 ) , ( "lemol/ant-design-icons-elm", 0.00917769 ) , ( "Gizra/elm-fetch", 0.00830096 ) , ( "GoldentTuft/elm-japanese-typing", 0.00819437 ) , ( "tricycle/elm-actor-framework-template-html", 0.00819437 ) , ( "groma84/elm-tachyons", 0.00819437 ) , ( "shnewto/pgn", 0.00819437 ) , ( "ContaSystemer/elm-review-no-regex", 0.00819437 ) , ( "tasuki/elm-punycode", 0.00819437 ) , ( "billstclair/elm-popup-picker", 0.00819437 ) , ( "hallelujahdrive/elm-croppie", 0.00819437 ) , ( "the-sett/elm-localstorage", 0.00819437 ) , ( "mrpinsky/elm-keyed-list", 0.00819437 ) , ( "choonkeat/elm-fullstack", 0.00819437 ) , ( "carwow/elm-review-rules", 0.00819437 ) , ( "rl-king/elm-index", 0.00819437 ) , ( "shamansir/elm-aframe", 0.00819437 ) , ( "opvasger/msg-replay", 0.00819437 ) , ( "3kyro/xsrf-protection", 0.00819437 ) , ( "sparksp/elm-review-imports", 0.00819437 ) , ( "jfmengels/elm-review-license", 0.00819437 ) , ( "JustinLove/elm-twitch-api", 0.00807273 ) , ( "billstclair/elm-websocket-framework", 0.00794594 ) , ( "calions-app/env", 0.00793122 ) , ( "chazsconi/elm-phoenix-ports", 0.00792254 ) , ( "chicode/lisa", 0.00778186 ) , ( "leojpod/review-no-empty-html-text", 0.00777119 ) , ( "showell/meta-elm", 0.00741073 ) , ( "dasch/crockford", 0.00735675 ) , ( "billstclair/elm-mastodon-websocket", 0.00673705 ) , ( "sparksp/elm-review-ports", 0.00650576 ) , ( "justgook/elm-tiled", 0.00649709 ) , ( "matheus23/elm-markdown-transforms", 0.00624748 ) , ( "ursi/support", 0.00623534 ) , ( "billstclair/elm-mastodon", 0.00617322 ) , ( "TSFoster/elm-md5", 0.00589303 ) , ( "jxxcarlson/tree-extra", 0.00585207 ) , ( "miyamoen/bibliopola", 0.00542674 ) , ( "ThinkAlexandria/css-in-elm", 0.00528767 ) , ( "r-k-b/no-float-ids", 0.00528407 ) , ( "nishiurahiroki/elm-simple-pagenate", 0.00525112 ) , ( "the-sett/elm-aws-cognito", 0.00517803 ) , ( "arowM/html", 0.00497 ) , ( "owanturist/elm-avl-dict", 0.00491884 ) , ( "z5h/timeline", 0.00487916 ) , ( "JoshuaHall/elm-fraction", 0.00446122 ) , ( "jxxcarlson/elm-text-editor", 0.0043958 ) , ( "rjbma/elm-listview", 0.00428901 ) , ( "visotype/elm-eval", 0.00420946 ) , ( "waratuman/elm-standardapi", 0.00396777 ) , ( "calions-app/test-attribute", 0.00396646 ) , ( "jxxcarlson/elm-tar", 0.00392845 ) , ( "waratuman/json-extra", 0.00384724 ) , ( "vViktorPL/elm-jira-connector", 0.00384081 ) , ( "nicmr/compgeo", 0.00379181 ) , ( "showell/binary-tree-diagram", 0.00371631 ) , ( "showell/dict-dot-dot", 0.00370657 ) , ( "MartinSStewart/elm-nonempty-string", 0.00369952 ) , ( "Gizra/elm-editable-webdata", 0.00365077 ) , ( "Gizra/elm-storage-key", 0.00364737 ) , ( "bburdette/typed-collections", 0.00355881 ) , ( "wolfadex/elm-text-adventure", 0.00343428 ) , ( "sashaafm/eetf", 0.00341681 ) , ( "rluiten/stemmer", 0.00339661 ) , ( "rluiten/sparsevector", 0.00339232 ) , ( "ChristophP/elm-mark", 0.00337588 ) , ( "calions-app/app-object", 0.00324226 ) , ( "calions-app/remote-resource", 0.00323489 ) , ( "calions-app/jsonapi-http", 0.00323482 ) , ( "jfmengels/elm-lint-reporter", 0.00313712 ) , ( "brian-watkins/elm-procedure", 0.00312001 ) , ( "dosarf/elm-yet-another-polling", 0.00298703 ) , ( "commonmind/elm-csexpr", 0.00285553 ) , ( "folkertdev/elm-brotli", 0.00282573 ) , ( "yumlonne/elm-japanese-calendar", 0.00280968 ) , ( "jxxcarlson/math-markdown", 0.00273225 ) , ( "billstclair/elm-websocket-framework-server", 0.00264942 ) , ( "alex-tan/postgrest-client", 0.00263226 ) , ( "primait/pyxis-components", 0.00262437 ) , ( "maca/crdt-replicated-tree", 0.0026048 ) , ( "avh4/elm-desktop-app", 0.00257613 ) , ( "ceddlyburge/elm-bootstrap-starter-master-view", 0.00247544 ) , ( "dvberkel/microkanren", 0.00243706 ) , ( "getto-systems/elm-apply", 0.00234565 ) , ( "getto-systems/elm-field", 0.00234556 ) , ( "getto-systems/elm-html-table", 0.00232625 ) , ( "getto-systems/elm-http-part", 0.00232607 ) , ( "getto-systems/elm-http-header", 0.00232581 ) , ( "getto-systems/elm-url", 0.00232567 ) , ( "getto-systems/elm-json", 0.00232527 ) , ( "getto-systems/elm-sort", 0.00232362 ) , ( "getto-systems/elm-command", 0.00232005 ) , ( "primait/forms", 0.00230758 ) , ( "harmboschloo/elm-dict-intersect", 0.00229488 ) , ( "anhmiuhv/pannablevideo", 0.00227733 ) , ( "Spaxe/elm-lsystem", 0.00218039 ) , ( "harmboschloo/elm-ecs", 0.00202945 ) , ( "AuricSystemsInternational/creditcard-validator", 0.00195405 ) , ( "alex-tan/postgrest-queries", 0.00194971 ) , ( "emptyflash/typed-svg", 0.00194846 ) , ( "billstclair/elm-crypto-aes", 0.00193174 ) , ( "eelcoh/parser-indent", 0.00190639 ) , ( "benansell/lobo-elm-test-extra", 0.00190501 ) , ( "miyamoen/elm-command-pallet", 0.00188622 ) , ( "melon-love/elm-gab-api", 0.00188351 ) , ( "iodevs/elm-history", 0.00184775 ) , ( "ymtszw/elm-broker", 0.00184465 ) , ( "ThinkAlexandria/elm-primer-tooltips", 0.00181717 ) , ( "ryan-senn/elm-compiler-error-sscce", 0.00180921 ) , ( "genthaler/elm-enum", 0.00178685 ) , ( "bigbinary/elm-reader", 0.00178306 ) , ( "bigbinary/elm-form-field", 0.00178304 ) , ( "the-sett/svg-text-fonts", 0.00177048 ) , ( "billstclair/elm-chat", 0.00176851 ) , ( "Libbum/elm-partition", 0.00176227 ) , ( "turboMaCk/elm-continue", 0.00175979 ) , ( "imjoehaines/afinn-165-elm", 0.00175817 ) , ( "the-sett/json-optional", 0.00066868 ) , ( "toastal/endo", 0.00046685 ) , ( "jackhp95/palit", 0.00045758 ) , ( "arowM/elm-html-extra-internal", 0.00028486 ) , ( "arowM/elm-html-internal", 0.00028398 ) , ( "elm-toulouse/float16", 0.00024702 ) , ( "munksgaard/elm-media-type", 0.00022552 ) , ( "jonathanfishbein1/complex-numbers", 0.00022321 ) , ( "NoRedInk/style-elements", 0.00019386 ) , ( "truqu/elm-dictset", 0.00017581 ) , ( "Janiczek/architecture-test", 0.0001752 ) , ( "NoRedInk/http-upgrade-shim", 0.00006647 ) , ( "miyamoen/tree-with-zipper", 0.00005325 ) , ( "rtfeldman/count", 0.00005047 ) , ( "NoRedInk/elm-saved", 0.00004694 ) , ( "NoRedInk/elm-rfc5988-parser", 0.00004694 ) , ( "NoRedInk/elm-formatted-text-test-helpers", 0.00004606 ) , ( "NoRedInk/elm-formatted-text-19", 0.00004606 ) , ( "NoRedInk/elm-plot-rouge", 0.00004605 ) , ( "NoRedInk/elm-rollbar", 0.00003914 ) , ( "avh4/burndown-charts", 0.00003663 ) , ( "mpizenberg/elm-placeholder-pkg", 0.00003533 ) , ( "avh4/elm-github-v3", 0.00003187 ) , ( "justinmimbs/tzif", 0.00002911 ) , ( "folkertdev/elm-cff", 0.00001785 ) , ( "the-sett/elm-one-many", 0.0000177 ) , ( "ianmackenzie/elm-iso-10303", 0.00001421 ) , ( "ianmackenzie/elm-step-file", 0.00001421 ) , ( "ianmackenzie/elm-geometry-prerelease", 0.00001301 ) , ( "terezka/elm-charts-alpha", 0.00001213 ) , ( "terezka/charts", 0.00001213 ) , ( "the-sett/salix-aws-spec", 0.00001075 ) , ( "the-sett/parser-recoverable", 0.00001075 ) , ( "lukewestby/accessible-html-with-css-temp-19", 0.00000819 ) , ( "folkertdev/elm-iris", 0.00000767 ) , ( "lukewestby/http-extra", 0.00000738 ) , ( "jfmengels/elm-review-reporter", 0.00000692 ) , ( "the-sett/elm-enum", 0.00000476 ) , ( "Janiczek/elm-runescape", 0.00000465 ) , ( "Janiczek/browser-extra", 0.00000461 ) , ( "jxxcarlson/toc-editor", 0.00000418 ) , ( "billstclair/elm-dev-random", 0.0000038 ) , ( "miniBill/elm-bare", 0.00000357 ) , ( "miniBill/elm-avataaars", 0.00000345 ) , ( "zwilias/elm-holey-zipper", 0.00000282 ) , ( "TSFoster/elm-envfile", 0.0000028 ) , ( "PaackEng/paack-ui", 0.00000279 ) , ( "PaackEng/paack-remotedata", 0.00000279 ) , ( "the-sett/auth-elm", 0.00000263 ) , ( "Chadtech/dependent-text", 0.00000253 ) , ( "the-sett/tea-tree", 0.00000253 ) , ( "Chadtech/elm-imperative-porting", 0.00000246 ) , ( "Chadtech/elm-provider", 0.00000244 ) , ( "Chadtech/elm-us-state-abbreviations", 0.00000244 ) , ( "jinjor/elm-map-debug", 0.00000238 ) , ( "jinjor/elm-req", 0.00000236 ) , ( "jinjor/elm-insertable-key", 0.00000211 ) , ( "ContaSystemer/elm-review-no-missing-documentation", 0.000002 ) , ( "ContaSystemer/elm-angularjs-custom-element", 0.000002 ) , ( "ContaSystemer/elm-effects", 0.000002 ) , ( "ContaSystemer/elm-effects-time", 0.000002 ) , ( "ContaSystemer/elm-js-data", 0.000002 ) , ( "ContaSystemer/elm-error-message", 0.000002 ) , ( "ContaSystemer/elm-effects-msg-from-js", 0.000002 ) , ( "turboMaCk/glue", 0.00000197 ) , ( "tricycle/elm-actor-framework-template-markdown", 0.00000174 ) , ( "tricycle/elm-actor-framework-sandbox", 0.00000174 ) , ( "ccapndave/elm-eexl", 0.0000017 ) , ( "ccapndave/elm-typed-tree", 0.00000167 ) , ( "ccapndave/elm-translator", 0.00000164 ) , ( "ccapndave/elm-statecharts", 0.00000164 ) , ( "simonh1000/elm-sliding-menus", 0.00000162 ) , ( "rl-king/elm-iso3166-country-codes", 0.0000016 ) , ( "pd-andy/elm-limiter", 0.00000159 ) , ( "joneshf/elm-these", 0.00000145 ) , ( "arowM/elm-data-url", 0.00000143 ) , ( "robinheghan/elm-phone-numbers", 0.00000136 ) , ( "arowM/elm-html-with-context", 0.00000134 ) , ( "tricycle/elm-storage", 0.00000131 ) , ( "arowM/elm-parser-test", 0.00000129 ) , ( "miyamoen/elm-origami", 0.00000128 ) , ( "jweir/charter", 0.00000126 ) , ( "tricycle/elm-parse-dont-validate", 0.00000125 ) , ( "frandibar/elm-bootstrap", 0.00000116 ) , ( "carwow/elm-slider-old", 0.00000113 ) , ( "Zinggi/elm-glsl-generator", 0.00000109 ) , ( "danhandrea/elm-router", 0.00000098 ) , ( "lucamug/elm-box-drawing", 0.00000098 ) , ( "danhandrea/elm-time-extra", 0.00000098 ) , ( "justgook/elm-webdriver", 0.00000095 ) , ( "ktonon/elm-jsonwebtoken", 0.00000088 ) , ( "MartinSStewart/elm-geometry-serialize", 0.00000087 ) , ( "abadi199/intl-phone-input", 0.00000078 ) , ( "stoeffel/resetable", 0.00000078 ) , ( "ahstro/elm-luhn", 0.00000077 ) , ( "FabienHenon/elm-ckeditor5", 0.00000072 ) , ( "GlobalWebIndex/quantify", 0.00000069 ) , ( "FabienHenon/elm-iso8601-date-strings", 0.00000069 ) , ( "proda-ai/elm-css", 0.00000066 ) , ( "jgrenat/regression-testing", 0.00000064 ) , ( "GlobalWebIndex/class-namespaces", 0.00000064 ) , ( "PaackEng/elm-alert-beta", 0.00000063 ) , ( "tricycle/elm-infinite-gallery", 0.00000062 ) , ( "tricycle/elm-imgix", 0.00000062 ) , ( "sporto/elm-countries", 0.00000061 ) , ( "sporto/polylinear-scale", 0.0000006 ) , ( "gicentre/tidy", 0.00000056 ) , ( "rluiten/mailcheck", 0.00000056 ) , ( "tricycle/elm-eventstream", 0.00000055 ) , ( "panthershark/snackbar", 0.00000054 ) , ( "alex-tan/loadable", 0.00000054 ) , ( "WhileTruu/elm-blurhash", 0.00000052 ) , ( "MartinSStewart/send-grid", 0.0000005 ) , ( "MartinSStewart/elm-bayer-matrix", 0.00000049 ) , ( "Herteby/url-builder-plus", 0.00000048 ) , ( "andre-dietrich/elm-mapbox", 0.00000048 ) , ( "z5h/zipper", 0.00000046 ) , ( "tricycle/morty-api", 0.00000044 ) , ( "mthadley/elm-typewriter", 0.00000044 ) , ( "ggb/porterstemmer", 0.00000042 ) , ( "ggb/elm-trend", 0.00000042 ) , ( "ggb/elm-sentiment", 0.00000042 ) , ( "pd-andy/elm-audio-graph", 0.00000042 ) , ( "ThinkAlexandria/window-manager", 0.00000037 ) , ( "owanturist/elm-queue", 0.00000035 ) , ( "drathier/elm-test-graph", 0.00000035 ) , ( "bburdette/stl", 0.00000033 ) , ( "jonathanfishbein1/numeric-typeclasses", 0.00000033 ) , ( "gribouille/elm-spinner", 0.00000033 ) , ( "gribouille/elm-prelude", 0.00000033 ) , ( "gribouille/elm-graphql", 0.00000033 ) , ( "gribouille/elm-bulma", 0.00000033 ) , ( "peterszerzo/elm-json-tree-view", 0.00000031 ) , ( "allo-media/elm-es-simple-query-string", 0.00000029 ) , ( "prozacchiwawa/elm-json-codec", 0.00000025 ) , ( "danhandrea/elm-foo", 0.00000023 ) , ( "proda-ai/formatting", 0.00000022 ) , ( "proda-ai/elm-svg-loader", 0.00000022 ) , ( "laserpants/elm-burrito-update", 0.00000022 ) , ( "harrysarson/elm-decode-elmi", 0.0000002 ) , ( "allo-media/fable", 0.00000019 ) , ( "achutkiran/elm-material-color", 0.00000018 ) , ( "kirchner/form-validation", 0.00000018 ) , ( "marshallformula/arrangeable-list", 0.00000018 ) , ( "RalfNorthman/elm-lttb", 0.00000018 ) , ( "malaire/elm-safe-int", 0.00000018 ) , ( "driebit/elm-ginger", 0.00000017 ) , ( "MichaelCombs28/elm-css-bulma", 0.00000016 ) , ( "league/difference-list", 0.00000016 ) , ( "harrysarson/elm-hacky-unique", 0.00000015 ) , ( "owanturist/elm-graphql", 0.00000015 ) , ( "dosarf/elm-activemq", 0.00000013 ) , ( "SiriusStarr/elm-spaced-repetition", 0.00000012 ) , ( "r-k-b/elm-interval", 0.00000011 ) , ( "SiriusStarr/elm-splat", 0.0000001 ) , ( "calions-app/elm-placeholder-loading", 0.0000001 ) , ( "r-k-b/map-accumulate", 0.00000008 ) , ( "JohnBugner/elm-loop", 0.00000008 ) , ( "jjant/elm-dict", 0.00000007 ) , ( "calions-app/jsonapi-http-retry", 0.00000007 ) , ( "bowbahdoe/lime-reset", 0.00000007 ) , ( "ljuglaret/combinatoire", 0.00000007 ) , ( "harmboschloo/graphql-to-elm-package", 0.00000005 ) , ( "thought2/elm-wikimedia-commons", 0.00000004 ) , ( "afidegnum/elm-bulmanizer", 0.00000004 ) , ( "alexanderkiel/list-selection", 0.00000004 ) , ( "Bernardoow/elm-rating-component", 0.00000004 ) , ( "kkpoon/elm-echarts", 0.00000004 ) , ( "kkpoon/elm-auth0", 0.00000004 ) , ( "jaredramirez/elm-field", 0.00000004 ) , ( "showell/elm-data-util", 0.00000003 ) , ( "hallelujahdrive/elm-accordion", 0.00000002 ) , ( "leojpod/elm-apex-charts-link", 0.00000002 ) , ( "tasuki/elm-bloom", 0.00000002 ) , ( "shamansir/tron-gui", 0.00000002 ) , ( "leojpod/elm-keyboard-shortcut", 0.00000002 ) , ( "choonkeat/elm-aws", 0.00000002 ) , ( "shamansir/bin-pack", 0.00000002 ) , ( "ryan-senn/elm-google-domains", 0.00000001 ) , ( "ryan-senn/elm-tlds", 0.00000001 ) , ( "ryan-senn/elm-readability", 0.00000001 ) , ( "wolfadex/locale-negotiation", 0.00000001 ) , ( "matheus23/elm-figma-api", 0.00000001 ) , ( "vViktorPL/elm-incremental-list", 0.00000001 ) , ( "Arkham/elm-chords", 0.00000001 ) , ( "primait/elm-form", 0.00000001 ) , ( "opvasger/amr", 0.00000001 ) , ( "choonkeat/elm-retry", 0.00000001 ) , ( "wolfadex/tiler", 0.0 ) , ( "iodevs/elm-validate", 0.0 ) , ( "Libbum/elm-redblacktrees", 0.0 ) , ( "avh4-experimental/elm-transducers", 0.0 ) , ( "ryan-senn/stellar-elm-sdk", 0.0 ) ]
50922
module Utils.Popularity exposing (get) import Dict exposing (Dict) get : String -> String -> Float get author project = popularity |> Dict.get (author ++ "/" ++ project) |> Maybe.withDefault 0 {-| Popularity ranking based on average usage per year in about 2000 GitHub open source Elm applications. -} popularity : Dict String Float popularity = Dict.fromList [ ( "elm/core", 100.0 ) , ( "elm/html", 97.34550643 ) , ( "elm/browser", 96.82660239 ) , ( "elm/json", 68.40488677 ) , ( "elm/http", 42.29543762 ) , ( "elm/time", 36.35605399 ) , ( "elm/url", 36.00172359 ) , ( "elm-explorations/test", 30.98760851 ) , ( "elm/random", 22.05868642 ) , ( "elm-community/list-extra", 21.28475703 ) , ( "mdgriffith/elm-ui", 21.01525279 ) , ( "elm/svg", 20.67103346 ) , ( "NoRedInk/elm-json-decode-pipeline", 18.8763277 ) , ( "rtfeldman/elm-css", 12.36916545 ) , ( "avh4/elm-color", 11.47447504 ) , ( "elm/parser", 9.97120987 ) , ( "elm/regex", 9.56505828 ) , ( "elm-community/maybe-extra", 8.38839645 ) , ( "krisajenkins/remotedata", 7.80414698 ) , ( "elm/file", 6.82690159 ) , ( "elm-explorations/markdown", 6.4791066 ) , ( "rtfeldman/elm-iso8601-date-strings", 6.22700287 ) , ( "elm-community/random-extra", 6.14534458 ) , ( "rundis/elm-bootstrap", 5.97488205 ) , ( "justinmimbs/date", 5.15831017 ) , ( "elm-community/json-extra", 4.6148592 ) , ( "elm-community/string-extra", 4.23226837 ) , ( "mpizenberg/elm-pointer-events", 3.77488665 ) , ( "elm-community/result-extra", 3.76826117 ) , ( "elm-explorations/linear-algebra", 3.45998535 ) , ( "elm/bytes", 3.40131264 ) , ( "dillonkearns/elm-pages", 3.28875762 ) , ( "myrho/elm-round", 3.24788501 ) , ( "elm/virtual-dom", 3.03890258 ) , ( "elm-community/typed-svg", 2.88877073 ) , ( "dillonkearns/elm-sitemap", 2.80172858 ) , ( "dillonkearns/elm-rss", 2.79940758 ) , ( "rtfeldman/elm-hex", 2.71486235 ) , ( "ryannhg/date-format", 2.69281928 ) , ( "elm-explorations/webgl", 2.67113902 ) , ( "dillonkearns/elm-markdown", 2.61302108 ) , ( "elm-community/dict-extra", 2.6126905 ) , ( "noahzgordon/elm-color-extra", 2.50191896 ) , ( "dillonkearns/elm-graphql", 2.43280404 ) , ( "lukewestby/elm-string-interpolate", 2.21887162 ) , ( "joakin/elm-canvas", 2.06071881 ) , ( "justinmimbs/time-extra", 2.02711878 ) , ( "ianmackenzie/elm-geometry", 1.93496966 ) , ( "elm-community/html-extra", 1.91841405 ) , ( "ohanhi/keyboard", 1.82651929 ) , ( "mdgriffith/elm-markup", 1.79477894 ) , ( "ianmackenzie/elm-units", 1.77692833 ) , ( "truqu/elm-base64", 1.65642656 ) , ( "gampleman/elm-visualization", 1.59352132 ) , ( "jfmengels/elm-review", 1.58147495 ) , ( "hecrj/html-parser", 1.54538153 ) , ( "mdgriffith/elm-animator", 1.54119939 ) , ( "stil4m/elm-syntax", 1.5343108 ) , ( "elm-community/array-extra", 1.5177429 ) , ( "evancz/elm-playground", 1.49471032 ) , ( "elm-explorations/benchmark", 1.43905721 ) , ( "danyx23/elm-uuid", 1.40987928 ) , ( "ianmackenzie/elm-3d-scene", 1.39304298 ) , ( "lukewestby/elm-http-builder", 1.38467299 ) , ( "rtfeldman/elm-validate", 1.37146825 ) , ( "elm/project-metadata-utils", 1.35373173 ) , ( "terezka/line-charts", 1.3095579 ) , ( "cuducos/elm-format-number", 1.21964339 ) , ( "mdgriffith/elm-style-animation", 1.21027623 ) , ( "Janiczek/cmd-extra", 1.16277179 ) , ( "pablohirafuji/elm-markdown", 1.16211273 ) , ( "feathericons/elm-feather", 1.14979216 ) , ( "lattyware/elm-fontawesome", 1.13694509 ) , ( "elm-community/basics-extra", 1.13686848 ) , ( "MacCASOutreach/graphicsvg", 1.118421 ) , ( "mgold/elm-nonempty-list", 1.06806795 ) , ( "timjs/elm-collage", 1.06749701 ) , ( "folkertdev/one-true-path-experiment", 1.03353175 ) , ( "avh4/elm-program-test", 1.01810543 ) , ( "surprisetalk/elm-bulma", 0.96419058 ) , ( "elm-community/graph", 0.93775505 ) , ( "ryannhg/elm-spa", 0.91699362 ) , ( "pzp1997/assoc-list", 0.9123035 ) , ( "elm-community/easing-functions", 0.85061093 ) , ( "elm-community/intdict", 0.8476579 ) , ( "bartavelle/json-helpers", 0.83941682 ) , ( "danfishgold/base64-bytes", 0.83681365 ) , ( "sparksp/elm-review-forbidden-words", 0.83367851 ) , ( "debois/elm-dom", 0.81170328 ) , ( "Fresheyeball/elm-return", 0.79142091 ) , ( "fapian/elm-html-aria", 0.74339424 ) , ( "Gizra/elm-keyboard-event", 0.70692863 ) , ( "truqu/elm-md5", 0.70189214 ) , ( "andrewMacmurray/elm-delay", 0.68450709 ) , ( "aforemny/material-components-web-elm", 0.67701128 ) , ( "justinmimbs/timezone-data", 0.67701033 ) , ( "cmditch/elm-bigint", 0.66515013 ) , ( "wernerdegroot/listzipper", 0.65981506 ) , ( "jinjor/elm-debounce", 0.65157382 ) , ( "PanagiotisGeorgiadis/elm-datetime", 0.64939135 ) , ( "ianmackenzie/elm-geometry-svg", 0.63453537 ) , ( "Chadtech/elm-bool-extra", 0.62067315 ) , ( "lynn/elm-arithmetic", 0.60440016 ) , ( "pablohirafuji/elm-syntax-highlight", 0.60259155 ) , ( "arturopala/elm-monocle", 0.59790553 ) , ( "frandibar/elm-font-awesome-5", 0.58007091 ) , ( "justgook/elm-image", 0.56065333 ) , ( "miniBill/elm-codec", 0.55814043 ) , ( "zaboco/elm-draggable", 0.55544337 ) , ( "billstclair/elm-port-funnel", 0.54505022 ) , ( "norpan/elm-html5-drag-drop", 0.54306867 ) , ( "TSFoster/elm-uuid", 0.53512402 ) , ( "ianmackenzie/elm-3d-camera", 0.52840696 ) , ( "jfmengels/elm-review-unused", 0.51706478 ) , ( "ohanhi/remotedata-http", 0.49473739 ) , ( "icidasset/elm-binary", 0.46635256 ) , ( "CurrySoftware/elm-datepicker", 0.46026974 ) , ( "abadi199/elm-input-extra", 0.45043369 ) , ( "tesk9/palette", 0.44476755 ) , ( "zwilias/elm-rosetree", 0.44070751 ) , ( "annaghi/dnd-list", 0.43962043 ) , ( "SwiftsNamesake/proper-keyboard", 0.43812191 ) , ( "lovasoa/elm-csv", 0.43385591 ) , ( "billstclair/elm-websocket-client", 0.4211239 ) , ( "ccapndave/elm-update-extra", 0.41977621 ) , ( "robinheghan/murmur3", 0.41709346 ) , ( "icidasset/elm-material-icons", 0.40716159 ) , ( "Orasund/elm-ui-widgets", 0.40258153 ) , ( "truqu/elm-review-noleftpizza", 0.39533714 ) , ( "turboMaCk/any-dict", 0.39102931 ) , ( "turboMaCk/non-empty-list-alias", 0.39042555 ) , ( "simonh1000/elm-jwt", 0.38886083 ) , ( "pablohirafuji/elm-qrcode", 0.38671063 ) , ( "j-panasiuk/elm-ionicons", 0.38431649 ) , ( "lattyware/elm-json-diff", 0.37994196 ) , ( "zwilias/elm-html-string", 0.37515704 ) , ( "arowM/elm-form-decoder", 0.37362769 ) , ( "mgold/elm-animation", 0.37188307 ) , ( "ianmackenzie/elm-triangular-mesh", 0.37009167 ) , ( "TSFoster/elm-tuple-extra", 0.36731534 ) , ( "tripokey/elm-fuzzy", 0.36692263 ) , ( "Punie/elm-parser-extras", 0.35297849 ) , ( "pablen/toasty", 0.35179729 ) , ( "elm-community/undo-redo", 0.34593754 ) , ( "truqu/elm-oauth2", 0.33816251 ) , ( "Gizra/elm-all-set", 0.3343813 ) , ( "jweir/elm-iso8601", 0.3339095 ) , ( "tortus/elm-array-2d", 0.33365387 ) , ( "NoRedInk/elm-random-pcg-extended", 0.33190522 ) , ( "webbhuset/elm-json-decode", 0.32811851 ) , ( "ktonon/elm-crypto", 0.32801593 ) , ( "elm-community/list-split", 0.32784106 ) , ( "Herteby/simplex-noise", 0.3219093 ) , ( "jzxhuang/http-extras", 0.32137401 ) , ( "folkertdev/elm-deque", 0.32109268 ) , ( "ianmackenzie/elm-1d-parameter", 0.32006002 ) , ( "ccapndave/elm-flat-map", 0.31981126 ) , ( "truqu/elm-review-nobooleancase", 0.3178199 ) , ( "toastal/either", 0.31746851 ) , ( "1602/elm-feather", 0.31660394 ) , ( "mdgriffith/style-elements", 0.31212673 ) , ( "NoRedInk/elm-uuid", 0.31183615 ) , ( "perzanko/elm-loading", 0.30855664 ) , ( "linuss/smooth-scroll", 0.3077922 ) , ( "etaque/elm-form", 0.30348605 ) , ( "gingko/time-distance", 0.30336385 ) , ( "GlobalWebIndex/cmd-extra", 0.302766 ) , ( "NoRedInk/elm-string-conversions", 0.29331575 ) , ( "AdrianRibao/elm-derberos-date", 0.28990482 ) , ( "kalutheo/elm-ui-explorer", 0.28612503 ) , ( "justgage/tachyons-elm", 0.28523698 ) , ( "Gizra/elm-debouncer", 0.28504558 ) , ( "turboMaCk/any-set", 0.28438649 ) , ( "the-sett/elm-color", 0.28403224 ) , ( "billstclair/elm-sortable-table", 0.28271317 ) , ( "capitalist/elm-octicons", 0.28195837 ) , ( "simonh1000/elm-colorpicker", 0.27117854 ) , ( "pilatch/flip", 0.26704357 ) , ( "folkertdev/elm-state", 0.26525221 ) , ( "jfmengels/elm-review-debug", 0.26221985 ) , ( "TSFoster/elm-sha1", 0.26165276 ) , ( "klazuka/elm-json-tree-view", 0.26067484 ) , ( "Janiczek/elm-bidict", 0.25968504 ) , ( "danmarcab/material-icons", 0.25622646 ) , ( "basti1302/elm-human-readable-filesize", 0.24826223 ) , ( "panthershark/email-parser", 0.24690589 ) , ( "fredcy/elm-parseint", 0.24670168 ) , ( "jorgengranseth/elm-string-format", 0.24568559 ) , ( "hecrj/composable-form", 0.24505523 ) , ( "ianmackenzie/elm-geometry-test", 0.24302217 ) , ( "billstclair/elm-sha256", 0.24141562 ) , ( "ianmackenzie/elm-geometry-linear-algebra-interop", 0.23533215 ) , ( "danhandrea/elm-date-format", 0.23529358 ) , ( "NoRedInk/elm-sortable-table", 0.23358588 ) , ( "kuon/elm-string-normalize", 0.23118365 ) , ( "dmy/elm-pratt-parser", 0.22989056 ) , ( "Chadtech/unique-list", 0.22899954 ) , ( "jamesmacaulay/elm-graphql", 0.22776995 ) , ( "ymtszw/elm-xml-decode", 0.22661962 ) , ( "billstclair/elm-localstorage", 0.22374157 ) , ( "mthadley/elm-hash-routing", 0.22155574 ) , ( "cappyzawa/elm-ui-colors", 0.22082952 ) , ( "the-sett/elm-syntax-dsl", 0.22020009 ) , ( "damienklinnert/elm-spinner", 0.21776168 ) , ( "matthewsj/elm-ordering", 0.21745709 ) , ( "folkertdev/elm-flate", 0.2170955 ) , ( "carwow/elm-slider", 0.21197636 ) , ( "jinjor/elm-diff", 0.21185364 ) , ( "ursi/elm-css-colors", 0.2108615 ) , ( "ContaSystemer/elm-menu", 0.21014847 ) , ( "tricycle/elm-embed-youtube", 0.20671199 ) , ( "PaackEng/elm-ui-dialog", 0.2006389 ) , ( "CoderDennis/elm-time-format", 0.19815286 ) , ( "gicentre/elm-vegalite", 0.19740117 ) , ( "yotamDvir/elm-pivot", 0.19665382 ) , ( "NoRedInk/elm-simple-fuzzy", 0.19456658 ) , ( "ggb/numeral-elm", 0.19337426 ) , ( "zwilias/json-decode-exploration", 0.1918353 ) , ( "jfmengels/elm-review-common", 0.18847052 ) , ( "BrianHicks/elm-css-reset", 0.18822892 ) , ( "Janiczek/elm-graph", 0.18803528 ) , ( "ericgj/elm-csv-decode", 0.1876914 ) , ( "periodic/elm-csv", 0.18684353 ) , ( "pd-andy/tuple-extra", 0.18558304 ) , ( "tesk9/accessible-html", 0.18279636 ) , ( "lovasoa/elm-rolling-list", 0.18097298 ) , ( "krisajenkins/elm-astar", 0.18017187 ) , ( "BrianHicks/elm-particle", 0.17786303 ) , ( "folkertdev/elm-sha2", 0.17785039 ) , ( "Garados007/elm-svg-parser", 0.17754484 ) , ( "gampleman/elm-mapbox", 0.17754114 ) , ( "NoRedInk/elm-compare", 0.17712889 ) , ( "joneshf/elm-tagged", 0.17681944 ) , ( "the-sett/lazy-list", 0.17264487 ) , ( "turboMaCk/lazy-tree-with-zipper", 0.17263832 ) , ( "jfmengels/elm-review-documentation", 0.17208178 ) , ( "y047aka/elm-reset-css", 0.17137837 ) , ( "Orasund/elm-ui-framework", 0.16892692 ) , ( "ianmackenzie/elm-units-prefixed", 0.16798459 ) , ( "jxxcarlson/elm-typed-time", 0.16708656 ) , ( "ianmackenzie/elm-float-extra", 0.16430595 ) , ( "matken11235/html-styled-extra", 0.16388741 ) , ( "supermacro/elm-antd", 0.16388741 ) , ( "jasonliang-dev/elm-heroicons", 0.16388741 ) , ( "robinheghan/keyboard-events", 0.16388741 ) , ( "MaybeJustJames/yaml", 0.16388741 ) , ( "coinop-logan/elm-format-number", 0.16350434 ) , ( "truqu/elm-review-noredundantconcat", 0.16279207 ) , ( "truqu/elm-review-noredundantcons", 0.16278661 ) , ( "ahstro/elm-bulma-classes", 0.16268257 ) , ( "rluiten/elm-text-search", 0.16195907 ) , ( "norpan/elm-json-patch", 0.1618311 ) , ( "avh4/elm-fifo", 0.16165577 ) , ( "eriktim/elm-protocol-buffers", 0.1569727 ) , ( "zwilias/elm-utf-tools", 0.15675438 ) , ( "fabhof/elm-ui-datepicker", 0.15601158 ) , ( "Kraxorax/elm-matrix-a", 0.1550815 ) , ( "Zinggi/elm-2d-game", 0.14786867 ) , ( "waratuman/time-extra", 0.14714351 ) , ( "pd-andy/elm-web-audio", 0.14559802 ) , ( "ianmackenzie/elm-units-interval", 0.14409245 ) , ( "alex-tan/elm-dialog", 0.14326271 ) , ( "joakin/elm-grid", 0.14239279 ) , ( "marcosh/elm-html-to-unicode", 0.14136611 ) , ( "K-Adam/elm-dom", 0.14100964 ) , ( "stoeffel/elm-verify", 0.14049657 ) , ( "thaterikperson/elm-strftime", 0.14048949 ) , ( "joshforisha/elm-html-entities", 0.14014579 ) , ( "ChristophP/elm-i18next", 0.14009583 ) , ( "WhileTruu/elm-smooth-scroll", 0.13550094 ) , ( "smucode/elm-flat-colors", 0.13390605 ) , ( "PaackEng/elm-ui-dropdown", 0.13349351 ) , ( "jinjor/elm-xml-parser", 0.13308261 ) , ( "Spaxe/svg-pathd", 0.13299764 ) , ( "Zinggi/elm-game-resources", 0.13123514 ) , ( "justgook/webgl-shape", 0.13025186 ) , ( "miyamoen/select-list", 0.12993603 ) , ( "cmditch/elm-ethereum", 0.12836444 ) , ( "visotype/elm-dom", 0.12812192 ) , ( "folkertdev/svg-path-lowlevel", 0.12684362 ) , ( "rtfeldman/elm-sorter-experiment", 0.12623643 ) , ( "stil4m/structured-writer", 0.12619772 ) , ( "lucamug/style-framework", 0.12605465 ) , ( "stoeffel/set-extra", 0.12571783 ) , ( "STTR13/ziplist", 0.12570977 ) , ( "<NAME>ienH<NAME>on/elm-infinite-list-view", 0.12559581 ) , ( "<NAME>H<NAME>on/elm-infinite-scroll", 0.12528226 ) , ( "sporto/time-distance", 0.12511912 ) , ( "dillonkearns/elm-cli-options-parser", 0.12476245 ) , ( "mcordova47/elm-natural-ordering", 0.12461905 ) , ( "hecrj/elm-slug", 0.12412494 ) , ( "NoRedInk/list-selection", 0.12398862 ) , ( "Voronchuk/hexagons", 0.12371057 ) , ( "y0hy0h/ordered-containers", 0.12369689 ) , ( "elm-athlete/athlete", 0.12274771 ) , ( "laserpants/elm-update-pipeline", 0.12193618 ) , ( "coinop-logan/phace", 0.12151759 ) , ( "BrianHicks/elm-trend", 0.12024157 ) , ( "MartinSStewart/elm-audio", 0.11849084 ) , ( "rl-king/elm-scroll-to", 0.11522835 ) , ( "erlandsona/assoc-set", 0.11493819 ) , ( "justgook/webgl-playground", 0.11294313 ) , ( "tesk9/accessible-html-with-css", 0.11217061 ) , ( "w0rm/elm-physics", 0.11193187 ) , ( "jgrenat/elm-html-test-runner", 0.1106782 ) , ( "krisajenkins/elm-exts", 0.11045032 ) , ( "ianmackenzie/elm-interval", 0.11014532 ) , ( "mhoare/elm-stack", 0.1099642 ) , ( "Punie/elm-matrix", 0.10890224 ) , ( "bburdette/websocket", 0.1081962 ) , ( "danyx23/elm-mimetype", 0.10773962 ) , ( "arowM/elm-mixin", 0.10755002 ) , ( "sporto/elm-select", 0.10669776 ) , ( "tricycle/elm-actor-framework", 0.10652682 ) , ( "ThinkAlexandria/elm-pretty-print-json", 0.1058547 ) , ( "arowM/elm-reference", 0.10549205 ) , ( "mdgriffith/stylish-elephants", 0.1052336 ) , ( "yotamDvir/elm-katex", 0.10459095 ) , ( "carmonw/elm-number-to-words", 0.10374789 ) , ( "dillonkearns/elm-oembed", 0.10209354 ) , ( "RomanErnst/erl", 0.09858579 ) , ( "w0rm/elm-obj-file", 0.09833245 ) , ( "lemol/ant-design-icons-elm-ui", 0.09833245 ) , ( "avh4/elm-beautiful-example", 0.09706569 ) , ( "arowM/elm-classname", 0.09479125 ) , ( "the-sett/elm-state-machines", 0.09395605 ) , ( "Orasund/pixelengine", 0.09394164 ) , ( "the-sett/elm-auth-aws", 0.09391371 ) , ( "rl-king/elm-gallery", 0.0936856 ) , ( "the-sett/elm-update-helper", 0.09360555 ) , ( "the-sett/elm-auth", 0.09360487 ) , ( "drathier/elm-graph", 0.09350995 ) , ( "arowM/elm-neat-layout", 0.09346707 ) , ( "bgrosse-midokura/composable-form", 0.09309911 ) , ( "jxxcarlson/elm-cell-grid", 0.0918109 ) , ( "indicatrix/elm-chartjs-webcomponent", 0.09174394 ) , ( "andre-dietrich/parser-combinators", 0.09165459 ) , ( "achutkiran/material-components-elm", 0.09163468 ) , ( "inkuzmin/elm-multiselect", 0.09139183 ) , ( "stoeffel/editable", 0.09126776 ) , ( "Chadtech/id", 0.09113307 ) , ( "jonoabroad/commatosed", 0.09054461 ) , ( "kirchner/elm-selectize", 0.0905111 ) , ( "phollyer/elm-phoenix-websocket", 0.09013808 ) , ( "hmsk/elm-css-modern-normalize", 0.09013808 ) , ( "gampleman/elm-examples-helper", 0.09013808 ) , ( "malaire/elm-uint64", 0.09013808 ) , ( "JohnBugner/elm-matrix", 0.09013808 ) , ( "TheSacredLipton/elm-ui-hexcolor", 0.09013808 ) , ( "jfmengels/elm-review-the-elm-architecture", 0.09013808 ) , ( "jschomay/elm-paginate", 0.08956332 ) , ( "alex-tan/elm-tree-diagram", 0.08945404 ) , ( "xarvh/elm-slides", 0.0892947 ) , ( "rluiten/stringdistance", 0.0892684 ) , ( "Orasund/elm-game-essentials", 0.08916985 ) , ( "mgold/elm-geojson", 0.08897403 ) , ( "marshallformula/elm-swiper", 0.0886618 ) , ( "jxxcarlson/elm-markdown", 0.08820943 ) , ( "Microsoft/elm-json-tree-view", 0.08814142 ) , ( "newmana/chroma-elm", 0.08810571 ) , ( "justgook/alt-linear-algebra", 0.08789221 ) , ( "larribas/elm-multi-input", 0.08787663 ) , ( "lukewestby/elm-template", 0.08760839 ) , ( "EdutainmentLIVE/elm-bootstrap", 0.08601373 ) , ( "vito/elm-ansi", 0.08564269 ) , ( "z5h/component-result", 0.08501743 ) , ( "BrianHicks/elm-string-graphemes", 0.08438992 ) , ( "proda-ai/elm-dropzone", 0.0839448 ) , ( "TSFoster/elm-bytes-extra", 0.0822685 ) , ( "tremlab/bugsnag-elm", 0.0819437 ) , ( "fredcy/elm-debouncer", 0.0819437 ) , ( "dzuk-mutant/elm-html-styled-aria", 0.0819437 ) , ( "proda-ai/murmur3", 0.0819437 ) , ( "oaalto/time-values", 0.0819437 ) , ( "chelovek0v/bbase64", 0.0819437 ) , ( "andre-dietrich/elm-conditional", 0.0819437 ) , ( "robinheghan/elm-deque", 0.0819437 ) , ( "MartinSStewart/elm-serialize", 0.0819437 ) , ( "jxxcarlson/hex", 0.08025377 ) , ( "prikhi/decimal", 0.07988138 ) , ( "league/unique-id", 0.07962549 ) , ( "jschomay/elm-narrative-engine", 0.07850368 ) , ( "blissfully/elm-chartjs-webcomponent", 0.07789183 ) , ( "jxxcarlson/elm-graph", 0.07777827 ) , ( "samhstn/time-format", 0.07741896 ) , ( "jxxcarlson/elm-pseudorandom", 0.0772143 ) , ( "the-sett/elm-pretty-printer", 0.07673811 ) , ( "cultureamp/elm-css-modules-loader", 0.07673201 ) , ( "Fresheyeball/deburr", 0.07607407 ) , ( "f0i/statistics", 0.07569493 ) , ( "ymtszw/elm-http-xml", 0.075543 ) , ( "PaackEng/elm-svg-string", 0.07533646 ) , ( "jouderianjr/elm-dialog", 0.07497169 ) , ( "newlandsvalley/elm-binary-base64", 0.07450259 ) , ( "the-sett/elm-string-case", 0.07417748 ) , ( "supermario/elm-countries", 0.07415019 ) , ( "gribouille/elm-treeview", 0.07393474 ) , ( "etaque/elm-response", 0.07385955 ) , ( "harrysarson/elm-complex", 0.07383846 ) , ( "FMFI-UK-1-AIN-412/elm-formula", 0.07383412 ) , ( "owanturist/elm-union-find", 0.07362182 ) , ( "z5h/jaro-winkler", 0.07331902 ) , ( "brandly/elm-dot-lang", 0.07330965 ) , ( "y047aka/elm-hsl-color", 0.0731552 ) , ( "ryry0/elm-numeric", 0.07297005 ) , ( "rogeriochaves/elm-test-bdd-style", 0.07295471 ) , ( "waratuman/elm-coder", 0.07280749 ) , ( "hrldcpr/elm-cons", 0.0725321 ) , ( "prozacchiwawa/elm-keccak", 0.07208187 ) , ( "jims/html-parser", 0.07206386 ) , ( "PanagiotisGeorgiadis/elm-datepicker", 0.07190215 ) , ( "LesleyLai/elm-grid", 0.07180881 ) , ( "mweiss/elm-rte-toolkit", 0.0716879 ) , ( "isaacseymour/deprecated-time", 0.07141021 ) , ( "sporto/qs", 0.07080009 ) , ( "Chadtech/elm-money", 0.07039523 ) , ( "kuzminadya/mogeefont", 0.07026973 ) , ( "fifth-postulate/priority-queue", 0.07018505 ) , ( "sudo-rushil/elm-cards", 0.07008874 ) , ( "bigardone/elm-css-placeholders", 0.06905357 ) , ( "ronanyeah/helpers", 0.0682312 ) , ( "YuyaAizawa/list-wrapper", 0.06783713 ) , ( "truqu/line-charts", 0.06764527 ) , ( "dmy/elm-imf-date-time", 0.06669301 ) , ( "SiriusStarr/elm-password-strength", 0.06574762 ) , ( "EdutainmentLIVE/elm-dropdown", 0.06568054 ) , ( "peterszerzo/line-charts", 0.06567449 ) , ( "ktonon/elm-word", 0.0656437 ) , ( "the-sett/elm-aws-core", 0.06546173 ) , ( "mercurymedia/elm-datetime-picker", 0.06484787 ) , ( "MartinSStewart/elm-box-packing", 0.06441992 ) , ( "GlobalWebIndex/elm-plural-rules", 0.06411989 ) , ( "lazamar/dict-parser", 0.0631332 ) , ( "savardd/elm-time-travel", 0.06297284 ) , ( "cappyzawa/elm-ui-onedark", 0.06209494 ) , ( "erosson/number-suffix", 0.06192027 ) , ( "NoRedInk/elm-random-general", 0.06178116 ) , ( "edkv/elm-generic-dict", 0.06134726 ) , ( "Chadtech/return", 0.06133436 ) , ( "skyqrose/assoc-list-extra", 0.06125807 ) , ( "prikhi/http-tasks", 0.06107279 ) , ( "cedric-h/elm-google-sign-in", 0.05997924 ) , ( "pehota/elm-zondicons", 0.05897221 ) , ( "JonRowe/elm-jwt", 0.05871744 ) , ( "etaque/elm-transit-style", 0.05866548 ) , ( "dosarf/elm-tree-view", 0.05857506 ) , ( "json-tools/json-value", 0.05840507 ) , ( "r-k-b/no-long-import-lines", 0.05826819 ) , ( "billstclair/elm-xml-eeue56", 0.0581776 ) , ( "etaque/elm-transit", 0.05797409 ) , ( "ursi/elm-throttle", 0.05764599 ) , ( "the-sett/elm-serverless", 0.05755903 ) , ( "commonmind/elm-csv-encode", 0.05710774 ) , ( "allo-media/elm-daterange-picker", 0.05695909 ) , ( "stephenreddek/elm-emoji", 0.05690545 ) , ( "driebit/elm-css-breakpoint", 0.0561004 ) , ( "f0i/iso8601", 0.05608734 ) , ( "jordymoos/pilf", 0.05585866 ) , ( "folq/review-rgb-ranges", 0.05536345 ) , ( "terezka/yaml", 0.05491881 ) , ( "kyasu1/elm-ulid", 0.05461156 ) , ( "Kinto/elm-kinto", 0.05458142 ) , ( "ghivert/elm-graphql", 0.05449382 ) , ( "ursi/elm-scroll", 0.0543715 ) , ( "tiziano88/elm-protobuf", 0.05431539 ) , ( "Punie/elm-reader", 0.05430477 ) , ( "bburdette/cellme", 0.05393641 ) , ( "samueldple/material-color", 0.05370078 ) , ( "Bractlet/elm-plot", 0.05366476 ) , ( "jschomay/elm-bounded-number", 0.05354281 ) , ( "jinjor/elm-contextmenu", 0.05344282 ) , ( "prozacchiwawa/elm-urlbase64", 0.05340177 ) , ( "jluckyiv/elm-utc-date-strings", 0.0533887 ) , ( "mikaxyz/elm-cropper", 0.05326306 ) , ( "TSFoster/elm-heap", 0.0530336 ) , ( "owanturist/elm-bulletproof", 0.05290947 ) , ( "ensoft/entrance", 0.05284254 ) , ( "rgrempel/elm-http-decorators", 0.05281988 ) , ( "Chadtech/random-pipeline", 0.05280586 ) , ( "allo-media/canopy", 0.05273208 ) , ( "harmboschloo/graphql-to-elm", 0.05170478 ) , ( "rielas/measurement", 0.0516935 ) , ( "Chadtech/elm-relational-database", 0.05164367 ) , ( "johnathanbostrom/elm-dice", 0.05149376 ) , ( "jxxcarlson/elm-editor", 0.05141855 ) , ( "0ui/elm-task-parallel", 0.05076761 ) , ( "the-sett/elm-refine", 0.05067941 ) , ( "brian-watkins/elm-spec", 0.04856381 ) , ( "avh4/elm-debug-controls", 0.04839202 ) , ( "phollyer/elm-ui-colors", 0.04822524 ) , ( "Herteby/enum", 0.04795936 ) , ( "kmbn/elm-hotkeys", 0.04743314 ) , ( "cultureamp/babel-elm-assets-plugin", 0.04742013 ) , ( "toastal/mailto", 0.04718736 ) , ( "zwilias/elm-bytes-parser", 0.04703769 ) , ( "tad-lispy/springs", 0.04607089 ) , ( "Janiczek/transform", 0.04453779 ) , ( "hermanverschooten/ip", 0.04416292 ) , ( "jfmengels/lint-unused", 0.0439492 ) , ( "PaackEng/elm-google-maps", 0.04391243 ) , ( "ericgj/elm-uri-template", 0.0434312 ) , ( "data-viz-lab/elm-chart-builder", 0.0433935 ) , ( "folkertdev/elm-paragraph", 0.04272664 ) , ( "icidasset/elm-sha", 0.04256028 ) , ( "dasch/levenshtein", 0.04203807 ) , ( "wittjosiah/elm-ordered-dict", 0.04175244 ) , ( "ktonon/elm-test-extra", 0.04152155 ) , ( "rl-king/elm-masonry", 0.04121287 ) , ( "billstclair/elm-custom-element", 0.04093673 ) , ( "prikhi/bootstrap-gallery", 0.04035975 ) , ( "joshforisha/elm-inflect", 0.04031402 ) , ( "bburdette/pdf-element", 0.04019823 ) , ( "austinshenk/elm-w3", 0.04019579 ) , ( "json-tools/json-schema", 0.04015367 ) , ( "NoRedInk/datetimepicker-legacy", 0.04012745 ) , ( "ccapndave/focus", 0.04006861 ) , ( "gdamjan/elm-identicon", 0.03951737 ) , ( "bemyak/elm-slider", 0.03943666 ) , ( "FabienHenon/jsonapi", 0.03933752 ) , ( "NoRedInk/elm-plot-19", 0.0389287 ) , ( "mercurymedia/elm-message-toast", 0.03831063 ) , ( "chain-partners/elm-bignum", 0.03819787 ) , ( "jouderianjr/elm-loaders", 0.03811653 ) , ( "Punie/elm-id", 0.03796811 ) , ( "drathier/elm-test-tables", 0.03758749 ) , ( "Orasund/elm-action", 0.03733808 ) , ( "w0rm/elm-slice-show", 0.0373203 ) , ( "peterszerzo/elm-arborist", 0.03731962 ) , ( "ThinkAlexandria/elm-html-in-elm", 0.03723739 ) , ( "turboMaCk/queue", 0.03708237 ) , ( "emilianobovetti/edit-distance", 0.03704362 ) , ( "kuzzmi/elm-gravatar", 0.03697676 ) , ( "ThinkAlexandria/elm-drag-locations", 0.03696538 ) , ( "dawehner/elm-colorbrewer", 0.03695076 ) , ( "xarvh/elm-gamepad", 0.036799 ) , ( "benthepoet/elm-purecss", 0.03679697 ) , ( "billstclair/elm-oauth-middleware", 0.03667292 ) , ( "alexkorban/uicards", 0.03663732 ) , ( "folkertdev/elm-int64", 0.03653192 ) , ( "billstclair/elm-geolocation", 0.03644241 ) , ( "justgook/elm-game-logic", 0.03637282 ) , ( "zgohr/elm-csv", 0.03624985 ) , ( "gicentre/elm-vega", 0.03597546 ) , ( "zwilias/elm-reorderable", 0.03593048 ) , ( "toastal/select-prism", 0.03586537 ) , ( "ronanyeah/calendar-dates", 0.03579998 ) , ( "kuon/elm-hsluv", 0.03563973 ) , ( "ir4y/elm-dnd", 0.03561684 ) , ( "xilnocas/step", 0.03560819 ) , ( "stephenreddek/elm-range-slider", 0.03551443 ) , ( "fabiommendes/elm-iter", 0.03545966 ) , ( "akoppela/elm-logo", 0.03543891 ) , ( "billstclair/elm-crypto-string", 0.03529601 ) , ( "arowM/elm-form-validator", 0.0352493 ) , ( "Elm-Canvas/raster-shapes", 0.03520682 ) , ( "1602/json-schema", 0.03520676 ) , ( "ohanhi/autoexpand", 0.03508831 ) , ( "pdamoc/elm-hashids", 0.03503357 ) , ( "ohanhi/lorem", 0.03502294 ) , ( "stephenreddek/elm-time-picker", 0.03500671 ) , ( "mercurymedia/elm-smart-select", 0.03493208 ) , ( "elm-in-elm/compiler", 0.03449337 ) , ( "the-sett/decode-generic", 0.03406044 ) , ( "ljuglaret/fraction", 0.03369673 ) , ( "folkertdev/elm-kmeans", 0.03343474 ) , ( "nikita-volkov/typeclasses", 0.03336435 ) , ( "miniBill/date-format-languages", 0.03285717 ) , ( "jaredramirez/elm-s3", 0.03251825 ) , ( "jonathanfishbein1/elm-field", 0.03186558 ) , ( "bburdette/schelme", 0.03103703 ) , ( "Chadtech/elm-css-grid", 0.03072801 ) , ( "eike/json-decode-complete", 0.03072334 ) , ( "webbhuset/elm-actor-model", 0.03041586 ) , ( "bburdette/toop", 0.02995369 ) , ( "lynn/elm-ordinal", 0.02956659 ) , ( "tricycle/elm-email", 0.029545 ) , ( "tricycle/system-actor-model", 0.02930445 ) , ( "nikita-volkov/hashing-containers", 0.02926126 ) , ( "Orasund/elm-cellautomata", 0.02913753 ) , ( "simplystuart/elm-scroll-to", 0.02903803 ) , ( "MartinSStewart/elm-codec-bytes", 0.02896827 ) , ( "Chadtech/elm-vector", 0.02871587 ) , ( "arowM/html-extra", 0.02849722 ) , ( "munksgaard/elm-charts", 0.02841668 ) , ( "tesk9/modal", 0.02714795 ) , ( "RalfNorthman/elm-zoom-plot", 0.0270936 ) , ( "jxxcarlson/htree", 0.02683459 ) , ( "jxxcarlson/elm-stat", 0.02651257 ) , ( "billstclair/elm-svg-button", 0.02644546 ) , ( "webbhuset/elm-actor-model-elm-ui", 0.02592043 ) , ( "folkertdev/elm-tiny-inflate", 0.025917 ) , ( "fifth-postulate/elm-csv-decode", 0.02586667 ) , ( "viir/simplegamedev", 0.02544128 ) , ( "elm-toulouse/cbor", 0.02530895 ) , ( "rl-king/elm-modular-scale", 0.02520116 ) , ( "bowbahdoe/elm-history", 0.02476153 ) , ( "jxxcarlson/elm-widget", 0.02457994 ) , ( "jackhp95/elm-mapbox", 0.02452827 ) , ( "alex-tan/task-extra", 0.02403581 ) , ( "jjant/elm-printf", 0.02393349 ) , ( "jigargosar/elm-material-color", 0.02343325 ) , ( "avh4/elm-dropbox", 0.02328807 ) , ( "jonathanfishbein1/linear-algebra", 0.0230214 ) , ( "tomjkidd/elm-multiway-tree-zipper", 0.0229576 ) , ( "munksgaard/char-extra", 0.02262327 ) , ( "munksgaard/elm-data-uri", 0.02255611 ) , ( "billstclair/elm-id-search", 0.02252655 ) , ( "thought2/elm-interactive", 0.02222094 ) , ( "brianvanburken/elm-list-date", 0.02198079 ) , ( "andre-dietrich/elm-random-regex", 0.02184853 ) , ( "flowlang-cc/elm-audio-graph", 0.02169063 ) , ( "andre-dietrich/elm-svgbob", 0.0216694 ) , ( "rluiten/trie", 0.02124813 ) , ( "ringvold/elm-iso8601-date-strings", 0.0211933 ) , ( "rl-king/elm-inview", 0.02118104 ) , ( "afidegnum/elm-tailwind", 0.02102643 ) , ( "fifth-postulate/combinatorics", 0.020755 ) , ( "indicatrix/elm-input-extra", 0.02068175 ) , ( "abadi199/elm-creditcard", 0.02068162 ) , ( "arowM/elm-css-modules-helper", 0.02039772 ) , ( "alexanderkiel/elm-mdc-alpha", 0.02028243 ) , ( "sparksp/elm-review-camelcase", 0.02010144 ) , ( "dwyl/elm-criteria", 0.02009551 ) , ( "ericgj/elm-validation", 0.01997145 ) , ( "prikhi/paginate", 0.01997109 ) , ( "romstad/elm-chess", 0.01987651 ) , ( "basti1302/elm-non-empty-array", 0.01959109 ) , ( "MichaelCombs28/elm-base85", 0.01958329 ) , ( "arnau/elm-objecthash", 0.01950411 ) , ( "NoRedInk/elm-debug-controls-without-datepicker", 0.01949173 ) , ( "dasch/parser", 0.01948486 ) , ( "NoRedInk/noredink-ui", 0.01944399 ) , ( "ozmat/elm-forms", 0.01943377 ) , ( "the-sett/ai-search", 0.01942663 ) , ( "allenap/elm-json-decode-broken", 0.01937762 ) , ( "nathanjohnson320/base58", 0.01908185 ) , ( "noahzgordon/elm-jsonapi", 0.01893622 ) , ( "labzero/elm-google-geocoding", 0.01891308 ) , ( "pilatch/elm-chess", 0.0186072 ) , ( "torreyatcitty/the-best-decimal", 0.01847113 ) , ( "NoRedInk/elm-rails", 0.01826369 ) , ( "FordLabs/elm-star-rating", 0.01819264 ) , ( "Bernardoow/elm-alert-timer-message", 0.01807738 ) , ( "JohnBugner/elm-bag", 0.01807483 ) , ( "Gizra/elm-compat-019", 0.01797027 ) , ( "goilluminate/elm-fancy-daterangepicker", 0.01784086 ) , ( "janjelinek/creditcard-validation", 0.01781153 ) , ( "r-k-b/complex", 0.01781103 ) , ( "NoRedInk/elm-sweet-poll", 0.01773511 ) , ( "TSFoster/elm-compare", 0.01772745 ) , ( "fedragon/elm-typed-dropdown", 0.01771295 ) , ( "emilianobovetti/elm-yajson", 0.01770452 ) , ( "jjant/elm-comonad-zipper", 0.01770213 ) , ( "ozmat/elm-validation", 0.01766079 ) , ( "jackfranklin/elm-parse-link-header", 0.0176503 ) , ( "Gizra/elm-attribute-builder", 0.01761218 ) , ( "kkpoon/elm-auth0-urlparser", 0.01761196 ) , ( "1602/json-value", 0.01760062 ) , ( "ggb/elm-bloom", 0.0175877 ) , ( "peterszerzo/elm-porter", 0.01756095 ) , ( "jweir/sparkline", 0.01754773 ) , ( "fbonetti/elm-geodesy", 0.01754339 ) , ( "bChiquet/elm-accessors", 0.01753197 ) , ( "tricycle/elm-actor-framework-template", 0.01638874 ) , ( "robinheghan/elm-warrior", 0.01638874 ) , ( "wsowens/term", 0.01638874 ) , ( "finos/morphir-elm", 0.01638874 ) , ( "sparksp/elm-review-always", 0.01390432 ) , ( "YuyaAizawa/peg", 0.01331966 ) , ( "jfmengels/lint-debug", 0.01255703 ) , ( "billstclair/elm-dialog", 0.01200416 ) , ( "jxxcarlson/meenylatex", 0.01054695 ) , ( "the-sett/elm-error-handling", 0.01024483 ) , ( "Arkham/elm-rttl", 0.00987257 ) , ( "jfmengels/elm-lint", 0.00982276 ) , ( "Chadtech/ct-colors", 0.00927074 ) , ( "lemol/ant-design-icons-elm", 0.00917769 ) , ( "Gizra/elm-fetch", 0.00830096 ) , ( "GoldentTuft/elm-japanese-typing", 0.00819437 ) , ( "tricycle/elm-actor-framework-template-html", 0.00819437 ) , ( "groma84/elm-tachyons", 0.00819437 ) , ( "shnewto/pgn", 0.00819437 ) , ( "ContaSystemer/elm-review-no-regex", 0.00819437 ) , ( "tasuki/elm-punycode", 0.00819437 ) , ( "billstclair/elm-popup-picker", 0.00819437 ) , ( "hallelujahdrive/elm-croppie", 0.00819437 ) , ( "the-sett/elm-localstorage", 0.00819437 ) , ( "mrpinsky/elm-keyed-list", 0.00819437 ) , ( "choonkeat/elm-fullstack", 0.00819437 ) , ( "carwow/elm-review-rules", 0.00819437 ) , ( "rl-king/elm-index", 0.00819437 ) , ( "shamansir/elm-aframe", 0.00819437 ) , ( "opvasger/msg-replay", 0.00819437 ) , ( "3kyro/xsrf-protection", 0.00819437 ) , ( "sparksp/elm-review-imports", 0.00819437 ) , ( "jfmengels/elm-review-license", 0.00819437 ) , ( "JustinLove/elm-twitch-api", 0.00807273 ) , ( "billstclair/elm-websocket-framework", 0.00794594 ) , ( "calions-app/env", 0.00793122 ) , ( "chazsconi/elm-phoenix-ports", 0.00792254 ) , ( "chicode/lisa", 0.00778186 ) , ( "leojpod/review-no-empty-html-text", 0.00777119 ) , ( "showell/meta-elm", 0.00741073 ) , ( "dasch/crockford", 0.00735675 ) , ( "billstclair/elm-mastodon-websocket", 0.00673705 ) , ( "sparksp/elm-review-ports", 0.00650576 ) , ( "justgook/elm-tiled", 0.00649709 ) , ( "matheus23/elm-markdown-transforms", 0.00624748 ) , ( "ursi/support", 0.00623534 ) , ( "billstclair/elm-mastodon", 0.00617322 ) , ( "TSFoster/elm-md5", 0.00589303 ) , ( "jxxcarlson/tree-extra", 0.00585207 ) , ( "miyamoen/bibliopola", 0.00542674 ) , ( "ThinkAlexandria/css-in-elm", 0.00528767 ) , ( "r-k-b/no-float-ids", 0.00528407 ) , ( "nishiurahiroki/elm-simple-pagenate", 0.00525112 ) , ( "the-sett/elm-aws-cognito", 0.00517803 ) , ( "arowM/html", 0.00497 ) , ( "owanturist/elm-avl-dict", 0.00491884 ) , ( "z5h/timeline", 0.00487916 ) , ( "JoshuaHall/elm-fraction", 0.00446122 ) , ( "jxxcarlson/elm-text-editor", 0.0043958 ) , ( "rjbma/elm-listview", 0.00428901 ) , ( "visotype/elm-eval", 0.00420946 ) , ( "waratuman/elm-standardapi", 0.00396777 ) , ( "calions-app/test-attribute", 0.00396646 ) , ( "jxxcarlson/elm-tar", 0.00392845 ) , ( "waratuman/json-extra", 0.00384724 ) , ( "vViktorPL/elm-jira-connector", 0.00384081 ) , ( "nicmr/compgeo", 0.00379181 ) , ( "showell/binary-tree-diagram", 0.00371631 ) , ( "showell/dict-dot-dot", 0.00370657 ) , ( "MartinSStewart/elm-nonempty-string", 0.00369952 ) , ( "Gizra/elm-editable-webdata", 0.00365077 ) , ( "Gizra/elm-storage-key", 0.00364737 ) , ( "bburdette/typed-collections", 0.00355881 ) , ( "wolfadex/elm-text-adventure", 0.00343428 ) , ( "sashaafm/eetf", 0.00341681 ) , ( "rluiten/stemmer", 0.00339661 ) , ( "rluiten/sparsevector", 0.00339232 ) , ( "ChristophP/elm-mark", 0.00337588 ) , ( "calions-app/app-object", 0.00324226 ) , ( "calions-app/remote-resource", 0.00323489 ) , ( "calions-app/jsonapi-http", 0.00323482 ) , ( "jfmengels/elm-lint-reporter", 0.00313712 ) , ( "brian-watkins/elm-procedure", 0.00312001 ) , ( "dosarf/elm-yet-another-polling", 0.00298703 ) , ( "commonmind/elm-csexpr", 0.00285553 ) , ( "folkertdev/elm-brotli", 0.00282573 ) , ( "yumlonne/elm-japanese-calendar", 0.00280968 ) , ( "jxxcarlson/math-markdown", 0.00273225 ) , ( "billstclair/elm-websocket-framework-server", 0.00264942 ) , ( "alex-tan/postgrest-client", 0.00263226 ) , ( "primait/pyxis-components", 0.00262437 ) , ( "maca/crdt-replicated-tree", 0.0026048 ) , ( "avh4/elm-desktop-app", 0.00257613 ) , ( "ceddlyburge/elm-bootstrap-starter-master-view", 0.00247544 ) , ( "dvberkel/microkanren", 0.00243706 ) , ( "getto-systems/elm-apply", 0.00234565 ) , ( "getto-systems/elm-field", 0.00234556 ) , ( "getto-systems/elm-html-table", 0.00232625 ) , ( "getto-systems/elm-http-part", 0.00232607 ) , ( "getto-systems/elm-http-header", 0.00232581 ) , ( "getto-systems/elm-url", 0.00232567 ) , ( "getto-systems/elm-json", 0.00232527 ) , ( "getto-systems/elm-sort", 0.00232362 ) , ( "getto-systems/elm-command", 0.00232005 ) , ( "primait/forms", 0.00230758 ) , ( "harmboschloo/elm-dict-intersect", 0.00229488 ) , ( "anhmiuhv/pannablevideo", 0.00227733 ) , ( "Spaxe/elm-lsystem", 0.00218039 ) , ( "harmboschloo/elm-ecs", 0.00202945 ) , ( "AuricSystemsInternational/creditcard-validator", 0.00195405 ) , ( "alex-tan/postgrest-queries", 0.00194971 ) , ( "emptyflash/typed-svg", 0.00194846 ) , ( "billstclair/elm-crypto-aes", 0.00193174 ) , ( "eelcoh/parser-indent", 0.00190639 ) , ( "benansell/lobo-elm-test-extra", 0.00190501 ) , ( "miyamoen/elm-command-pallet", 0.00188622 ) , ( "melon-love/elm-gab-api", 0.00188351 ) , ( "iodevs/elm-history", 0.00184775 ) , ( "ymtszw/elm-broker", 0.00184465 ) , ( "ThinkAlexandria/elm-primer-tooltips", 0.00181717 ) , ( "ryan-senn/elm-compiler-error-sscce", 0.00180921 ) , ( "genthaler/elm-enum", 0.00178685 ) , ( "bigbinary/elm-reader", 0.00178306 ) , ( "bigbinary/elm-form-field", 0.00178304 ) , ( "the-sett/svg-text-fonts", 0.00177048 ) , ( "billstclair/elm-chat", 0.00176851 ) , ( "Libbum/elm-partition", 0.00176227 ) , ( "turboMaCk/elm-continue", 0.00175979 ) , ( "imjoehaines/afinn-165-elm", 0.00175817 ) , ( "the-sett/json-optional", 0.00066868 ) , ( "toastal/endo", 0.00046685 ) , ( "jackhp95/palit", 0.00045758 ) , ( "arowM/elm-html-extra-internal", 0.00028486 ) , ( "arowM/elm-html-internal", 0.00028398 ) , ( "elm-toulouse/float16", 0.00024702 ) , ( "munksgaard/elm-media-type", 0.00022552 ) , ( "jonathanfishbein1/complex-numbers", 0.00022321 ) , ( "NoRedInk/style-elements", 0.00019386 ) , ( "truqu/elm-dictset", 0.00017581 ) , ( "Janiczek/architecture-test", 0.0001752 ) , ( "NoRedInk/http-upgrade-shim", 0.00006647 ) , ( "miyamoen/tree-with-zipper", 0.00005325 ) , ( "rtfeldman/count", 0.00005047 ) , ( "NoRedInk/elm-saved", 0.00004694 ) , ( "NoRedInk/elm-rfc5988-parser", 0.00004694 ) , ( "NoRedInk/elm-formatted-text-test-helpers", 0.00004606 ) , ( "NoRedInk/elm-formatted-text-19", 0.00004606 ) , ( "NoRedInk/elm-plot-rouge", 0.00004605 ) , ( "NoRedInk/elm-rollbar", 0.00003914 ) , ( "avh4/burndown-charts", 0.00003663 ) , ( "mpizenberg/elm-placeholder-pkg", 0.00003533 ) , ( "avh4/elm-github-v3", 0.00003187 ) , ( "justinmimbs/tzif", 0.00002911 ) , ( "folkertdev/elm-cff", 0.00001785 ) , ( "the-sett/elm-one-many", 0.0000177 ) , ( "ianmackenzie/elm-iso-10303", 0.00001421 ) , ( "ianmackenzie/elm-step-file", 0.00001421 ) , ( "ianmackenzie/elm-geometry-prerelease", 0.00001301 ) , ( "terezka/elm-charts-alpha", 0.00001213 ) , ( "terezka/charts", 0.00001213 ) , ( "the-sett/salix-aws-spec", 0.00001075 ) , ( "the-sett/parser-recoverable", 0.00001075 ) , ( "lukewestby/accessible-html-with-css-temp-19", 0.00000819 ) , ( "folkertdev/elm-iris", 0.00000767 ) , ( "lukewestby/http-extra", 0.00000738 ) , ( "jfmengels/elm-review-reporter", 0.00000692 ) , ( "the-sett/elm-enum", 0.00000476 ) , ( "Janiczek/elm-runescape", 0.00000465 ) , ( "Janiczek/browser-extra", 0.00000461 ) , ( "jxxcarlson/toc-editor", 0.00000418 ) , ( "billstclair/elm-dev-random", 0.0000038 ) , ( "miniBill/elm-bare", 0.00000357 ) , ( "miniBill/elm-avataaars", 0.00000345 ) , ( "zwilias/elm-holey-zipper", 0.00000282 ) , ( "TSFoster/elm-envfile", 0.0000028 ) , ( "PaackEng/paack-ui", 0.00000279 ) , ( "PaackEng/paack-remotedata", 0.00000279 ) , ( "the-sett/auth-elm", 0.00000263 ) , ( "Chadtech/dependent-text", 0.00000253 ) , ( "the-sett/tea-tree", 0.00000253 ) , ( "Chadtech/elm-imperative-porting", 0.00000246 ) , ( "Chadtech/elm-provider", 0.00000244 ) , ( "Chadtech/elm-us-state-abbreviations", 0.00000244 ) , ( "jinjor/elm-map-debug", 0.00000238 ) , ( "jinjor/elm-req", 0.00000236 ) , ( "jinjor/elm-insertable-key", 0.00000211 ) , ( "ContaSystemer/elm-review-no-missing-documentation", 0.000002 ) , ( "ContaSystemer/elm-angularjs-custom-element", 0.000002 ) , ( "ContaSystemer/elm-effects", 0.000002 ) , ( "ContaSystemer/elm-effects-time", 0.000002 ) , ( "ContaSystemer/elm-js-data", 0.000002 ) , ( "ContaSystemer/elm-error-message", 0.000002 ) , ( "ContaSystemer/elm-effects-msg-from-js", 0.000002 ) , ( "turboMaCk/glue", 0.00000197 ) , ( "tricycle/elm-actor-framework-template-markdown", 0.00000174 ) , ( "tricycle/elm-actor-framework-sandbox", 0.00000174 ) , ( "ccapndave/elm-eexl", 0.0000017 ) , ( "ccapndave/elm-typed-tree", 0.00000167 ) , ( "ccapndave/elm-translator", 0.00000164 ) , ( "ccapndave/elm-statecharts", 0.00000164 ) , ( "simonh1000/elm-sliding-menus", 0.00000162 ) , ( "rl-king/elm-iso3166-country-codes", 0.0000016 ) , ( "pd-andy/elm-limiter", 0.00000159 ) , ( "joneshf/elm-these", 0.00000145 ) , ( "arowM/elm-data-url", 0.00000143 ) , ( "robinheghan/elm-phone-numbers", 0.00000136 ) , ( "arowM/elm-html-with-context", 0.00000134 ) , ( "tricycle/elm-storage", 0.00000131 ) , ( "arowM/elm-parser-test", 0.00000129 ) , ( "miyamoen/elm-origami", 0.00000128 ) , ( "jweir/charter", 0.00000126 ) , ( "tricycle/elm-parse-dont-validate", 0.00000125 ) , ( "frandibar/elm-bootstrap", 0.00000116 ) , ( "carwow/elm-slider-old", 0.00000113 ) , ( "Zinggi/elm-glsl-generator", 0.00000109 ) , ( "danhandrea/elm-router", 0.00000098 ) , ( "lucamug/elm-box-drawing", 0.00000098 ) , ( "danhandrea/elm-time-extra", 0.00000098 ) , ( "justgook/elm-webdriver", 0.00000095 ) , ( "ktonon/elm-jsonwebtoken", 0.00000088 ) , ( "MartinSStewart/elm-geometry-serialize", 0.00000087 ) , ( "abadi199/intl-phone-input", 0.00000078 ) , ( "stoeffel/resetable", 0.00000078 ) , ( "ahstro/elm-luhn", 0.00000077 ) , ( "FabienHenon/elm-ckeditor5", 0.00000072 ) , ( "GlobalWebIndex/quantify", 0.00000069 ) , ( "FabienHenon/elm-iso8601-date-strings", 0.00000069 ) , ( "proda-ai/elm-css", 0.00000066 ) , ( "jgrenat/regression-testing", 0.00000064 ) , ( "GlobalWebIndex/class-namespaces", 0.00000064 ) , ( "PaackEng/elm-alert-beta", 0.00000063 ) , ( "tricycle/elm-infinite-gallery", 0.00000062 ) , ( "tricycle/elm-imgix", 0.00000062 ) , ( "sporto/elm-countries", 0.00000061 ) , ( "sporto/polylinear-scale", 0.0000006 ) , ( "gicentre/tidy", 0.00000056 ) , ( "rluiten/mailcheck", 0.00000056 ) , ( "tricycle/elm-eventstream", 0.00000055 ) , ( "panthershark/snackbar", 0.00000054 ) , ( "alex-tan/loadable", 0.00000054 ) , ( "WhileTruu/elm-blurhash", 0.00000052 ) , ( "MartinSStewart/send-grid", 0.0000005 ) , ( "MartinSStewart/elm-bayer-matrix", 0.00000049 ) , ( "Herteby/url-builder-plus", 0.00000048 ) , ( "andre-dietrich/elm-mapbox", 0.00000048 ) , ( "z5h/zipper", 0.00000046 ) , ( "tricycle/morty-api", 0.00000044 ) , ( "mthadley/elm-typewriter", 0.00000044 ) , ( "ggb/porterstemmer", 0.00000042 ) , ( "ggb/elm-trend", 0.00000042 ) , ( "ggb/elm-sentiment", 0.00000042 ) , ( "pd-andy/elm-audio-graph", 0.00000042 ) , ( "ThinkAlexandria/window-manager", 0.00000037 ) , ( "owanturist/elm-queue", 0.00000035 ) , ( "drathier/elm-test-graph", 0.00000035 ) , ( "bburdette/stl", 0.00000033 ) , ( "jonathanfishbein1/numeric-typeclasses", 0.00000033 ) , ( "gribouille/elm-spinner", 0.00000033 ) , ( "gribouille/elm-prelude", 0.00000033 ) , ( "gribouille/elm-graphql", 0.00000033 ) , ( "gribouille/elm-bulma", 0.00000033 ) , ( "peterszerzo/elm-json-tree-view", 0.00000031 ) , ( "allo-media/elm-es-simple-query-string", 0.00000029 ) , ( "prozacchiwawa/elm-json-codec", 0.00000025 ) , ( "danhandrea/elm-foo", 0.00000023 ) , ( "proda-ai/formatting", 0.00000022 ) , ( "proda-ai/elm-svg-loader", 0.00000022 ) , ( "laserpants/elm-burrito-update", 0.00000022 ) , ( "harrysarson/elm-decode-elmi", 0.0000002 ) , ( "allo-media/fable", 0.00000019 ) , ( "achutkiran/elm-material-color", 0.00000018 ) , ( "kirchner/form-validation", 0.00000018 ) , ( "marshallformula/arrangeable-list", 0.00000018 ) , ( "RalfNorthman/elm-lttb", 0.00000018 ) , ( "malaire/elm-safe-int", 0.00000018 ) , ( "driebit/elm-ginger", 0.00000017 ) , ( "MichaelCombs28/elm-css-bulma", 0.00000016 ) , ( "league/difference-list", 0.00000016 ) , ( "harrysarson/elm-hacky-unique", 0.00000015 ) , ( "owanturist/elm-graphql", 0.00000015 ) , ( "dosarf/elm-activemq", 0.00000013 ) , ( "SiriusStarr/elm-spaced-repetition", 0.00000012 ) , ( "r-k-b/elm-interval", 0.00000011 ) , ( "SiriusStarr/elm-splat", 0.0000001 ) , ( "calions-app/elm-placeholder-loading", 0.0000001 ) , ( "r-k-b/map-accumulate", 0.00000008 ) , ( "JohnBugner/elm-loop", 0.00000008 ) , ( "jjant/elm-dict", 0.00000007 ) , ( "calions-app/jsonapi-http-retry", 0.00000007 ) , ( "bowbahdoe/lime-reset", 0.00000007 ) , ( "ljuglaret/combinatoire", 0.00000007 ) , ( "harmboschloo/graphql-to-elm-package", 0.00000005 ) , ( "thought2/elm-wikimedia-commons", 0.00000004 ) , ( "afidegnum/elm-bulmanizer", 0.00000004 ) , ( "alexanderkiel/list-selection", 0.00000004 ) , ( "Bernardoow/elm-rating-component", 0.00000004 ) , ( "kkpoon/elm-echarts", 0.00000004 ) , ( "kkpoon/elm-auth0", 0.00000004 ) , ( "jaredramirez/elm-field", 0.00000004 ) , ( "showell/elm-data-util", 0.00000003 ) , ( "hallelujahdrive/elm-accordion", 0.00000002 ) , ( "leojpod/elm-apex-charts-link", 0.00000002 ) , ( "tasuki/elm-bloom", 0.00000002 ) , ( "shamansir/tron-gui", 0.00000002 ) , ( "leojpod/elm-keyboard-shortcut", 0.00000002 ) , ( "choonkeat/elm-aws", 0.00000002 ) , ( "shamansir/bin-pack", 0.00000002 ) , ( "ryan-senn/elm-google-domains", 0.00000001 ) , ( "ryan-senn/elm-tlds", 0.00000001 ) , ( "ryan-senn/elm-readability", 0.00000001 ) , ( "wolfadex/locale-negotiation", 0.00000001 ) , ( "matheus23/elm-figma-api", 0.00000001 ) , ( "vViktorPL/elm-incremental-list", 0.00000001 ) , ( "Arkham/elm-chords", 0.00000001 ) , ( "primait/elm-form", 0.00000001 ) , ( "opvasger/amr", 0.00000001 ) , ( "choonkeat/elm-retry", 0.00000001 ) , ( "wolfadex/tiler", 0.0 ) , ( "iodevs/elm-validate", 0.0 ) , ( "Libbum/elm-redblacktrees", 0.0 ) , ( "avh4-experimental/elm-transducers", 0.0 ) , ( "ryan-senn/stellar-elm-sdk", 0.0 ) ]
true
module Utils.Popularity exposing (get) import Dict exposing (Dict) get : String -> String -> Float get author project = popularity |> Dict.get (author ++ "/" ++ project) |> Maybe.withDefault 0 {-| Popularity ranking based on average usage per year in about 2000 GitHub open source Elm applications. -} popularity : Dict String Float popularity = Dict.fromList [ ( "elm/core", 100.0 ) , ( "elm/html", 97.34550643 ) , ( "elm/browser", 96.82660239 ) , ( "elm/json", 68.40488677 ) , ( "elm/http", 42.29543762 ) , ( "elm/time", 36.35605399 ) , ( "elm/url", 36.00172359 ) , ( "elm-explorations/test", 30.98760851 ) , ( "elm/random", 22.05868642 ) , ( "elm-community/list-extra", 21.28475703 ) , ( "mdgriffith/elm-ui", 21.01525279 ) , ( "elm/svg", 20.67103346 ) , ( "NoRedInk/elm-json-decode-pipeline", 18.8763277 ) , ( "rtfeldman/elm-css", 12.36916545 ) , ( "avh4/elm-color", 11.47447504 ) , ( "elm/parser", 9.97120987 ) , ( "elm/regex", 9.56505828 ) , ( "elm-community/maybe-extra", 8.38839645 ) , ( "krisajenkins/remotedata", 7.80414698 ) , ( "elm/file", 6.82690159 ) , ( "elm-explorations/markdown", 6.4791066 ) , ( "rtfeldman/elm-iso8601-date-strings", 6.22700287 ) , ( "elm-community/random-extra", 6.14534458 ) , ( "rundis/elm-bootstrap", 5.97488205 ) , ( "justinmimbs/date", 5.15831017 ) , ( "elm-community/json-extra", 4.6148592 ) , ( "elm-community/string-extra", 4.23226837 ) , ( "mpizenberg/elm-pointer-events", 3.77488665 ) , ( "elm-community/result-extra", 3.76826117 ) , ( "elm-explorations/linear-algebra", 3.45998535 ) , ( "elm/bytes", 3.40131264 ) , ( "dillonkearns/elm-pages", 3.28875762 ) , ( "myrho/elm-round", 3.24788501 ) , ( "elm/virtual-dom", 3.03890258 ) , ( "elm-community/typed-svg", 2.88877073 ) , ( "dillonkearns/elm-sitemap", 2.80172858 ) , ( "dillonkearns/elm-rss", 2.79940758 ) , ( "rtfeldman/elm-hex", 2.71486235 ) , ( "ryannhg/date-format", 2.69281928 ) , ( "elm-explorations/webgl", 2.67113902 ) , ( "dillonkearns/elm-markdown", 2.61302108 ) , ( "elm-community/dict-extra", 2.6126905 ) , ( "noahzgordon/elm-color-extra", 2.50191896 ) , ( "dillonkearns/elm-graphql", 2.43280404 ) , ( "lukewestby/elm-string-interpolate", 2.21887162 ) , ( "joakin/elm-canvas", 2.06071881 ) , ( "justinmimbs/time-extra", 2.02711878 ) , ( "ianmackenzie/elm-geometry", 1.93496966 ) , ( "elm-community/html-extra", 1.91841405 ) , ( "ohanhi/keyboard", 1.82651929 ) , ( "mdgriffith/elm-markup", 1.79477894 ) , ( "ianmackenzie/elm-units", 1.77692833 ) , ( "truqu/elm-base64", 1.65642656 ) , ( "gampleman/elm-visualization", 1.59352132 ) , ( "jfmengels/elm-review", 1.58147495 ) , ( "hecrj/html-parser", 1.54538153 ) , ( "mdgriffith/elm-animator", 1.54119939 ) , ( "stil4m/elm-syntax", 1.5343108 ) , ( "elm-community/array-extra", 1.5177429 ) , ( "evancz/elm-playground", 1.49471032 ) , ( "elm-explorations/benchmark", 1.43905721 ) , ( "danyx23/elm-uuid", 1.40987928 ) , ( "ianmackenzie/elm-3d-scene", 1.39304298 ) , ( "lukewestby/elm-http-builder", 1.38467299 ) , ( "rtfeldman/elm-validate", 1.37146825 ) , ( "elm/project-metadata-utils", 1.35373173 ) , ( "terezka/line-charts", 1.3095579 ) , ( "cuducos/elm-format-number", 1.21964339 ) , ( "mdgriffith/elm-style-animation", 1.21027623 ) , ( "Janiczek/cmd-extra", 1.16277179 ) , ( "pablohirafuji/elm-markdown", 1.16211273 ) , ( "feathericons/elm-feather", 1.14979216 ) , ( "lattyware/elm-fontawesome", 1.13694509 ) , ( "elm-community/basics-extra", 1.13686848 ) , ( "MacCASOutreach/graphicsvg", 1.118421 ) , ( "mgold/elm-nonempty-list", 1.06806795 ) , ( "timjs/elm-collage", 1.06749701 ) , ( "folkertdev/one-true-path-experiment", 1.03353175 ) , ( "avh4/elm-program-test", 1.01810543 ) , ( "surprisetalk/elm-bulma", 0.96419058 ) , ( "elm-community/graph", 0.93775505 ) , ( "ryannhg/elm-spa", 0.91699362 ) , ( "pzp1997/assoc-list", 0.9123035 ) , ( "elm-community/easing-functions", 0.85061093 ) , ( "elm-community/intdict", 0.8476579 ) , ( "bartavelle/json-helpers", 0.83941682 ) , ( "danfishgold/base64-bytes", 0.83681365 ) , ( "sparksp/elm-review-forbidden-words", 0.83367851 ) , ( "debois/elm-dom", 0.81170328 ) , ( "Fresheyeball/elm-return", 0.79142091 ) , ( "fapian/elm-html-aria", 0.74339424 ) , ( "Gizra/elm-keyboard-event", 0.70692863 ) , ( "truqu/elm-md5", 0.70189214 ) , ( "andrewMacmurray/elm-delay", 0.68450709 ) , ( "aforemny/material-components-web-elm", 0.67701128 ) , ( "justinmimbs/timezone-data", 0.67701033 ) , ( "cmditch/elm-bigint", 0.66515013 ) , ( "wernerdegroot/listzipper", 0.65981506 ) , ( "jinjor/elm-debounce", 0.65157382 ) , ( "PanagiotisGeorgiadis/elm-datetime", 0.64939135 ) , ( "ianmackenzie/elm-geometry-svg", 0.63453537 ) , ( "Chadtech/elm-bool-extra", 0.62067315 ) , ( "lynn/elm-arithmetic", 0.60440016 ) , ( "pablohirafuji/elm-syntax-highlight", 0.60259155 ) , ( "arturopala/elm-monocle", 0.59790553 ) , ( "frandibar/elm-font-awesome-5", 0.58007091 ) , ( "justgook/elm-image", 0.56065333 ) , ( "miniBill/elm-codec", 0.55814043 ) , ( "zaboco/elm-draggable", 0.55544337 ) , ( "billstclair/elm-port-funnel", 0.54505022 ) , ( "norpan/elm-html5-drag-drop", 0.54306867 ) , ( "TSFoster/elm-uuid", 0.53512402 ) , ( "ianmackenzie/elm-3d-camera", 0.52840696 ) , ( "jfmengels/elm-review-unused", 0.51706478 ) , ( "ohanhi/remotedata-http", 0.49473739 ) , ( "icidasset/elm-binary", 0.46635256 ) , ( "CurrySoftware/elm-datepicker", 0.46026974 ) , ( "abadi199/elm-input-extra", 0.45043369 ) , ( "tesk9/palette", 0.44476755 ) , ( "zwilias/elm-rosetree", 0.44070751 ) , ( "annaghi/dnd-list", 0.43962043 ) , ( "SwiftsNamesake/proper-keyboard", 0.43812191 ) , ( "lovasoa/elm-csv", 0.43385591 ) , ( "billstclair/elm-websocket-client", 0.4211239 ) , ( "ccapndave/elm-update-extra", 0.41977621 ) , ( "robinheghan/murmur3", 0.41709346 ) , ( "icidasset/elm-material-icons", 0.40716159 ) , ( "Orasund/elm-ui-widgets", 0.40258153 ) , ( "truqu/elm-review-noleftpizza", 0.39533714 ) , ( "turboMaCk/any-dict", 0.39102931 ) , ( "turboMaCk/non-empty-list-alias", 0.39042555 ) , ( "simonh1000/elm-jwt", 0.38886083 ) , ( "pablohirafuji/elm-qrcode", 0.38671063 ) , ( "j-panasiuk/elm-ionicons", 0.38431649 ) , ( "lattyware/elm-json-diff", 0.37994196 ) , ( "zwilias/elm-html-string", 0.37515704 ) , ( "arowM/elm-form-decoder", 0.37362769 ) , ( "mgold/elm-animation", 0.37188307 ) , ( "ianmackenzie/elm-triangular-mesh", 0.37009167 ) , ( "TSFoster/elm-tuple-extra", 0.36731534 ) , ( "tripokey/elm-fuzzy", 0.36692263 ) , ( "Punie/elm-parser-extras", 0.35297849 ) , ( "pablen/toasty", 0.35179729 ) , ( "elm-community/undo-redo", 0.34593754 ) , ( "truqu/elm-oauth2", 0.33816251 ) , ( "Gizra/elm-all-set", 0.3343813 ) , ( "jweir/elm-iso8601", 0.3339095 ) , ( "tortus/elm-array-2d", 0.33365387 ) , ( "NoRedInk/elm-random-pcg-extended", 0.33190522 ) , ( "webbhuset/elm-json-decode", 0.32811851 ) , ( "ktonon/elm-crypto", 0.32801593 ) , ( "elm-community/list-split", 0.32784106 ) , ( "Herteby/simplex-noise", 0.3219093 ) , ( "jzxhuang/http-extras", 0.32137401 ) , ( "folkertdev/elm-deque", 0.32109268 ) , ( "ianmackenzie/elm-1d-parameter", 0.32006002 ) , ( "ccapndave/elm-flat-map", 0.31981126 ) , ( "truqu/elm-review-nobooleancase", 0.3178199 ) , ( "toastal/either", 0.31746851 ) , ( "1602/elm-feather", 0.31660394 ) , ( "mdgriffith/style-elements", 0.31212673 ) , ( "NoRedInk/elm-uuid", 0.31183615 ) , ( "perzanko/elm-loading", 0.30855664 ) , ( "linuss/smooth-scroll", 0.3077922 ) , ( "etaque/elm-form", 0.30348605 ) , ( "gingko/time-distance", 0.30336385 ) , ( "GlobalWebIndex/cmd-extra", 0.302766 ) , ( "NoRedInk/elm-string-conversions", 0.29331575 ) , ( "AdrianRibao/elm-derberos-date", 0.28990482 ) , ( "kalutheo/elm-ui-explorer", 0.28612503 ) , ( "justgage/tachyons-elm", 0.28523698 ) , ( "Gizra/elm-debouncer", 0.28504558 ) , ( "turboMaCk/any-set", 0.28438649 ) , ( "the-sett/elm-color", 0.28403224 ) , ( "billstclair/elm-sortable-table", 0.28271317 ) , ( "capitalist/elm-octicons", 0.28195837 ) , ( "simonh1000/elm-colorpicker", 0.27117854 ) , ( "pilatch/flip", 0.26704357 ) , ( "folkertdev/elm-state", 0.26525221 ) , ( "jfmengels/elm-review-debug", 0.26221985 ) , ( "TSFoster/elm-sha1", 0.26165276 ) , ( "klazuka/elm-json-tree-view", 0.26067484 ) , ( "Janiczek/elm-bidict", 0.25968504 ) , ( "danmarcab/material-icons", 0.25622646 ) , ( "basti1302/elm-human-readable-filesize", 0.24826223 ) , ( "panthershark/email-parser", 0.24690589 ) , ( "fredcy/elm-parseint", 0.24670168 ) , ( "jorgengranseth/elm-string-format", 0.24568559 ) , ( "hecrj/composable-form", 0.24505523 ) , ( "ianmackenzie/elm-geometry-test", 0.24302217 ) , ( "billstclair/elm-sha256", 0.24141562 ) , ( "ianmackenzie/elm-geometry-linear-algebra-interop", 0.23533215 ) , ( "danhandrea/elm-date-format", 0.23529358 ) , ( "NoRedInk/elm-sortable-table", 0.23358588 ) , ( "kuon/elm-string-normalize", 0.23118365 ) , ( "dmy/elm-pratt-parser", 0.22989056 ) , ( "Chadtech/unique-list", 0.22899954 ) , ( "jamesmacaulay/elm-graphql", 0.22776995 ) , ( "ymtszw/elm-xml-decode", 0.22661962 ) , ( "billstclair/elm-localstorage", 0.22374157 ) , ( "mthadley/elm-hash-routing", 0.22155574 ) , ( "cappyzawa/elm-ui-colors", 0.22082952 ) , ( "the-sett/elm-syntax-dsl", 0.22020009 ) , ( "damienklinnert/elm-spinner", 0.21776168 ) , ( "matthewsj/elm-ordering", 0.21745709 ) , ( "folkertdev/elm-flate", 0.2170955 ) , ( "carwow/elm-slider", 0.21197636 ) , ( "jinjor/elm-diff", 0.21185364 ) , ( "ursi/elm-css-colors", 0.2108615 ) , ( "ContaSystemer/elm-menu", 0.21014847 ) , ( "tricycle/elm-embed-youtube", 0.20671199 ) , ( "PaackEng/elm-ui-dialog", 0.2006389 ) , ( "CoderDennis/elm-time-format", 0.19815286 ) , ( "gicentre/elm-vegalite", 0.19740117 ) , ( "yotamDvir/elm-pivot", 0.19665382 ) , ( "NoRedInk/elm-simple-fuzzy", 0.19456658 ) , ( "ggb/numeral-elm", 0.19337426 ) , ( "zwilias/json-decode-exploration", 0.1918353 ) , ( "jfmengels/elm-review-common", 0.18847052 ) , ( "BrianHicks/elm-css-reset", 0.18822892 ) , ( "Janiczek/elm-graph", 0.18803528 ) , ( "ericgj/elm-csv-decode", 0.1876914 ) , ( "periodic/elm-csv", 0.18684353 ) , ( "pd-andy/tuple-extra", 0.18558304 ) , ( "tesk9/accessible-html", 0.18279636 ) , ( "lovasoa/elm-rolling-list", 0.18097298 ) , ( "krisajenkins/elm-astar", 0.18017187 ) , ( "BrianHicks/elm-particle", 0.17786303 ) , ( "folkertdev/elm-sha2", 0.17785039 ) , ( "Garados007/elm-svg-parser", 0.17754484 ) , ( "gampleman/elm-mapbox", 0.17754114 ) , ( "NoRedInk/elm-compare", 0.17712889 ) , ( "joneshf/elm-tagged", 0.17681944 ) , ( "the-sett/lazy-list", 0.17264487 ) , ( "turboMaCk/lazy-tree-with-zipper", 0.17263832 ) , ( "jfmengels/elm-review-documentation", 0.17208178 ) , ( "y047aka/elm-reset-css", 0.17137837 ) , ( "Orasund/elm-ui-framework", 0.16892692 ) , ( "ianmackenzie/elm-units-prefixed", 0.16798459 ) , ( "jxxcarlson/elm-typed-time", 0.16708656 ) , ( "ianmackenzie/elm-float-extra", 0.16430595 ) , ( "matken11235/html-styled-extra", 0.16388741 ) , ( "supermacro/elm-antd", 0.16388741 ) , ( "jasonliang-dev/elm-heroicons", 0.16388741 ) , ( "robinheghan/keyboard-events", 0.16388741 ) , ( "MaybeJustJames/yaml", 0.16388741 ) , ( "coinop-logan/elm-format-number", 0.16350434 ) , ( "truqu/elm-review-noredundantconcat", 0.16279207 ) , ( "truqu/elm-review-noredundantcons", 0.16278661 ) , ( "ahstro/elm-bulma-classes", 0.16268257 ) , ( "rluiten/elm-text-search", 0.16195907 ) , ( "norpan/elm-json-patch", 0.1618311 ) , ( "avh4/elm-fifo", 0.16165577 ) , ( "eriktim/elm-protocol-buffers", 0.1569727 ) , ( "zwilias/elm-utf-tools", 0.15675438 ) , ( "fabhof/elm-ui-datepicker", 0.15601158 ) , ( "Kraxorax/elm-matrix-a", 0.1550815 ) , ( "Zinggi/elm-2d-game", 0.14786867 ) , ( "waratuman/time-extra", 0.14714351 ) , ( "pd-andy/elm-web-audio", 0.14559802 ) , ( "ianmackenzie/elm-units-interval", 0.14409245 ) , ( "alex-tan/elm-dialog", 0.14326271 ) , ( "joakin/elm-grid", 0.14239279 ) , ( "marcosh/elm-html-to-unicode", 0.14136611 ) , ( "K-Adam/elm-dom", 0.14100964 ) , ( "stoeffel/elm-verify", 0.14049657 ) , ( "thaterikperson/elm-strftime", 0.14048949 ) , ( "joshforisha/elm-html-entities", 0.14014579 ) , ( "ChristophP/elm-i18next", 0.14009583 ) , ( "WhileTruu/elm-smooth-scroll", 0.13550094 ) , ( "smucode/elm-flat-colors", 0.13390605 ) , ( "PaackEng/elm-ui-dropdown", 0.13349351 ) , ( "jinjor/elm-xml-parser", 0.13308261 ) , ( "Spaxe/svg-pathd", 0.13299764 ) , ( "Zinggi/elm-game-resources", 0.13123514 ) , ( "justgook/webgl-shape", 0.13025186 ) , ( "miyamoen/select-list", 0.12993603 ) , ( "cmditch/elm-ethereum", 0.12836444 ) , ( "visotype/elm-dom", 0.12812192 ) , ( "folkertdev/svg-path-lowlevel", 0.12684362 ) , ( "rtfeldman/elm-sorter-experiment", 0.12623643 ) , ( "stil4m/structured-writer", 0.12619772 ) , ( "lucamug/style-framework", 0.12605465 ) , ( "stoeffel/set-extra", 0.12571783 ) , ( "STTR13/ziplist", 0.12570977 ) , ( "PI:NAME:<NAME>END_PIienHPI:NAME:<NAME>END_PIon/elm-infinite-list-view", 0.12559581 ) , ( "PI:NAME:<NAME>END_PIHPI:NAME:<NAME>END_PIon/elm-infinite-scroll", 0.12528226 ) , ( "sporto/time-distance", 0.12511912 ) , ( "dillonkearns/elm-cli-options-parser", 0.12476245 ) , ( "mcordova47/elm-natural-ordering", 0.12461905 ) , ( "hecrj/elm-slug", 0.12412494 ) , ( "NoRedInk/list-selection", 0.12398862 ) , ( "Voronchuk/hexagons", 0.12371057 ) , ( "y0hy0h/ordered-containers", 0.12369689 ) , ( "elm-athlete/athlete", 0.12274771 ) , ( "laserpants/elm-update-pipeline", 0.12193618 ) , ( "coinop-logan/phace", 0.12151759 ) , ( "BrianHicks/elm-trend", 0.12024157 ) , ( "MartinSStewart/elm-audio", 0.11849084 ) , ( "rl-king/elm-scroll-to", 0.11522835 ) , ( "erlandsona/assoc-set", 0.11493819 ) , ( "justgook/webgl-playground", 0.11294313 ) , ( "tesk9/accessible-html-with-css", 0.11217061 ) , ( "w0rm/elm-physics", 0.11193187 ) , ( "jgrenat/elm-html-test-runner", 0.1106782 ) , ( "krisajenkins/elm-exts", 0.11045032 ) , ( "ianmackenzie/elm-interval", 0.11014532 ) , ( "mhoare/elm-stack", 0.1099642 ) , ( "Punie/elm-matrix", 0.10890224 ) , ( "bburdette/websocket", 0.1081962 ) , ( "danyx23/elm-mimetype", 0.10773962 ) , ( "arowM/elm-mixin", 0.10755002 ) , ( "sporto/elm-select", 0.10669776 ) , ( "tricycle/elm-actor-framework", 0.10652682 ) , ( "ThinkAlexandria/elm-pretty-print-json", 0.1058547 ) , ( "arowM/elm-reference", 0.10549205 ) , ( "mdgriffith/stylish-elephants", 0.1052336 ) , ( "yotamDvir/elm-katex", 0.10459095 ) , ( "carmonw/elm-number-to-words", 0.10374789 ) , ( "dillonkearns/elm-oembed", 0.10209354 ) , ( "RomanErnst/erl", 0.09858579 ) , ( "w0rm/elm-obj-file", 0.09833245 ) , ( "lemol/ant-design-icons-elm-ui", 0.09833245 ) , ( "avh4/elm-beautiful-example", 0.09706569 ) , ( "arowM/elm-classname", 0.09479125 ) , ( "the-sett/elm-state-machines", 0.09395605 ) , ( "Orasund/pixelengine", 0.09394164 ) , ( "the-sett/elm-auth-aws", 0.09391371 ) , ( "rl-king/elm-gallery", 0.0936856 ) , ( "the-sett/elm-update-helper", 0.09360555 ) , ( "the-sett/elm-auth", 0.09360487 ) , ( "drathier/elm-graph", 0.09350995 ) , ( "arowM/elm-neat-layout", 0.09346707 ) , ( "bgrosse-midokura/composable-form", 0.09309911 ) , ( "jxxcarlson/elm-cell-grid", 0.0918109 ) , ( "indicatrix/elm-chartjs-webcomponent", 0.09174394 ) , ( "andre-dietrich/parser-combinators", 0.09165459 ) , ( "achutkiran/material-components-elm", 0.09163468 ) , ( "inkuzmin/elm-multiselect", 0.09139183 ) , ( "stoeffel/editable", 0.09126776 ) , ( "Chadtech/id", 0.09113307 ) , ( "jonoabroad/commatosed", 0.09054461 ) , ( "kirchner/elm-selectize", 0.0905111 ) , ( "phollyer/elm-phoenix-websocket", 0.09013808 ) , ( "hmsk/elm-css-modern-normalize", 0.09013808 ) , ( "gampleman/elm-examples-helper", 0.09013808 ) , ( "malaire/elm-uint64", 0.09013808 ) , ( "JohnBugner/elm-matrix", 0.09013808 ) , ( "TheSacredLipton/elm-ui-hexcolor", 0.09013808 ) , ( "jfmengels/elm-review-the-elm-architecture", 0.09013808 ) , ( "jschomay/elm-paginate", 0.08956332 ) , ( "alex-tan/elm-tree-diagram", 0.08945404 ) , ( "xarvh/elm-slides", 0.0892947 ) , ( "rluiten/stringdistance", 0.0892684 ) , ( "Orasund/elm-game-essentials", 0.08916985 ) , ( "mgold/elm-geojson", 0.08897403 ) , ( "marshallformula/elm-swiper", 0.0886618 ) , ( "jxxcarlson/elm-markdown", 0.08820943 ) , ( "Microsoft/elm-json-tree-view", 0.08814142 ) , ( "newmana/chroma-elm", 0.08810571 ) , ( "justgook/alt-linear-algebra", 0.08789221 ) , ( "larribas/elm-multi-input", 0.08787663 ) , ( "lukewestby/elm-template", 0.08760839 ) , ( "EdutainmentLIVE/elm-bootstrap", 0.08601373 ) , ( "vito/elm-ansi", 0.08564269 ) , ( "z5h/component-result", 0.08501743 ) , ( "BrianHicks/elm-string-graphemes", 0.08438992 ) , ( "proda-ai/elm-dropzone", 0.0839448 ) , ( "TSFoster/elm-bytes-extra", 0.0822685 ) , ( "tremlab/bugsnag-elm", 0.0819437 ) , ( "fredcy/elm-debouncer", 0.0819437 ) , ( "dzuk-mutant/elm-html-styled-aria", 0.0819437 ) , ( "proda-ai/murmur3", 0.0819437 ) , ( "oaalto/time-values", 0.0819437 ) , ( "chelovek0v/bbase64", 0.0819437 ) , ( "andre-dietrich/elm-conditional", 0.0819437 ) , ( "robinheghan/elm-deque", 0.0819437 ) , ( "MartinSStewart/elm-serialize", 0.0819437 ) , ( "jxxcarlson/hex", 0.08025377 ) , ( "prikhi/decimal", 0.07988138 ) , ( "league/unique-id", 0.07962549 ) , ( "jschomay/elm-narrative-engine", 0.07850368 ) , ( "blissfully/elm-chartjs-webcomponent", 0.07789183 ) , ( "jxxcarlson/elm-graph", 0.07777827 ) , ( "samhstn/time-format", 0.07741896 ) , ( "jxxcarlson/elm-pseudorandom", 0.0772143 ) , ( "the-sett/elm-pretty-printer", 0.07673811 ) , ( "cultureamp/elm-css-modules-loader", 0.07673201 ) , ( "Fresheyeball/deburr", 0.07607407 ) , ( "f0i/statistics", 0.07569493 ) , ( "ymtszw/elm-http-xml", 0.075543 ) , ( "PaackEng/elm-svg-string", 0.07533646 ) , ( "jouderianjr/elm-dialog", 0.07497169 ) , ( "newlandsvalley/elm-binary-base64", 0.07450259 ) , ( "the-sett/elm-string-case", 0.07417748 ) , ( "supermario/elm-countries", 0.07415019 ) , ( "gribouille/elm-treeview", 0.07393474 ) , ( "etaque/elm-response", 0.07385955 ) , ( "harrysarson/elm-complex", 0.07383846 ) , ( "FMFI-UK-1-AIN-412/elm-formula", 0.07383412 ) , ( "owanturist/elm-union-find", 0.07362182 ) , ( "z5h/jaro-winkler", 0.07331902 ) , ( "brandly/elm-dot-lang", 0.07330965 ) , ( "y047aka/elm-hsl-color", 0.0731552 ) , ( "ryry0/elm-numeric", 0.07297005 ) , ( "rogeriochaves/elm-test-bdd-style", 0.07295471 ) , ( "waratuman/elm-coder", 0.07280749 ) , ( "hrldcpr/elm-cons", 0.0725321 ) , ( "prozacchiwawa/elm-keccak", 0.07208187 ) , ( "jims/html-parser", 0.07206386 ) , ( "PanagiotisGeorgiadis/elm-datepicker", 0.07190215 ) , ( "LesleyLai/elm-grid", 0.07180881 ) , ( "mweiss/elm-rte-toolkit", 0.0716879 ) , ( "isaacseymour/deprecated-time", 0.07141021 ) , ( "sporto/qs", 0.07080009 ) , ( "Chadtech/elm-money", 0.07039523 ) , ( "kuzminadya/mogeefont", 0.07026973 ) , ( "fifth-postulate/priority-queue", 0.07018505 ) , ( "sudo-rushil/elm-cards", 0.07008874 ) , ( "bigardone/elm-css-placeholders", 0.06905357 ) , ( "ronanyeah/helpers", 0.0682312 ) , ( "YuyaAizawa/list-wrapper", 0.06783713 ) , ( "truqu/line-charts", 0.06764527 ) , ( "dmy/elm-imf-date-time", 0.06669301 ) , ( "SiriusStarr/elm-password-strength", 0.06574762 ) , ( "EdutainmentLIVE/elm-dropdown", 0.06568054 ) , ( "peterszerzo/line-charts", 0.06567449 ) , ( "ktonon/elm-word", 0.0656437 ) , ( "the-sett/elm-aws-core", 0.06546173 ) , ( "mercurymedia/elm-datetime-picker", 0.06484787 ) , ( "MartinSStewart/elm-box-packing", 0.06441992 ) , ( "GlobalWebIndex/elm-plural-rules", 0.06411989 ) , ( "lazamar/dict-parser", 0.0631332 ) , ( "savardd/elm-time-travel", 0.06297284 ) , ( "cappyzawa/elm-ui-onedark", 0.06209494 ) , ( "erosson/number-suffix", 0.06192027 ) , ( "NoRedInk/elm-random-general", 0.06178116 ) , ( "edkv/elm-generic-dict", 0.06134726 ) , ( "Chadtech/return", 0.06133436 ) , ( "skyqrose/assoc-list-extra", 0.06125807 ) , ( "prikhi/http-tasks", 0.06107279 ) , ( "cedric-h/elm-google-sign-in", 0.05997924 ) , ( "pehota/elm-zondicons", 0.05897221 ) , ( "JonRowe/elm-jwt", 0.05871744 ) , ( "etaque/elm-transit-style", 0.05866548 ) , ( "dosarf/elm-tree-view", 0.05857506 ) , ( "json-tools/json-value", 0.05840507 ) , ( "r-k-b/no-long-import-lines", 0.05826819 ) , ( "billstclair/elm-xml-eeue56", 0.0581776 ) , ( "etaque/elm-transit", 0.05797409 ) , ( "ursi/elm-throttle", 0.05764599 ) , ( "the-sett/elm-serverless", 0.05755903 ) , ( "commonmind/elm-csv-encode", 0.05710774 ) , ( "allo-media/elm-daterange-picker", 0.05695909 ) , ( "stephenreddek/elm-emoji", 0.05690545 ) , ( "driebit/elm-css-breakpoint", 0.0561004 ) , ( "f0i/iso8601", 0.05608734 ) , ( "jordymoos/pilf", 0.05585866 ) , ( "folq/review-rgb-ranges", 0.05536345 ) , ( "terezka/yaml", 0.05491881 ) , ( "kyasu1/elm-ulid", 0.05461156 ) , ( "Kinto/elm-kinto", 0.05458142 ) , ( "ghivert/elm-graphql", 0.05449382 ) , ( "ursi/elm-scroll", 0.0543715 ) , ( "tiziano88/elm-protobuf", 0.05431539 ) , ( "Punie/elm-reader", 0.05430477 ) , ( "bburdette/cellme", 0.05393641 ) , ( "samueldple/material-color", 0.05370078 ) , ( "Bractlet/elm-plot", 0.05366476 ) , ( "jschomay/elm-bounded-number", 0.05354281 ) , ( "jinjor/elm-contextmenu", 0.05344282 ) , ( "prozacchiwawa/elm-urlbase64", 0.05340177 ) , ( "jluckyiv/elm-utc-date-strings", 0.0533887 ) , ( "mikaxyz/elm-cropper", 0.05326306 ) , ( "TSFoster/elm-heap", 0.0530336 ) , ( "owanturist/elm-bulletproof", 0.05290947 ) , ( "ensoft/entrance", 0.05284254 ) , ( "rgrempel/elm-http-decorators", 0.05281988 ) , ( "Chadtech/random-pipeline", 0.05280586 ) , ( "allo-media/canopy", 0.05273208 ) , ( "harmboschloo/graphql-to-elm", 0.05170478 ) , ( "rielas/measurement", 0.0516935 ) , ( "Chadtech/elm-relational-database", 0.05164367 ) , ( "johnathanbostrom/elm-dice", 0.05149376 ) , ( "jxxcarlson/elm-editor", 0.05141855 ) , ( "0ui/elm-task-parallel", 0.05076761 ) , ( "the-sett/elm-refine", 0.05067941 ) , ( "brian-watkins/elm-spec", 0.04856381 ) , ( "avh4/elm-debug-controls", 0.04839202 ) , ( "phollyer/elm-ui-colors", 0.04822524 ) , ( "Herteby/enum", 0.04795936 ) , ( "kmbn/elm-hotkeys", 0.04743314 ) , ( "cultureamp/babel-elm-assets-plugin", 0.04742013 ) , ( "toastal/mailto", 0.04718736 ) , ( "zwilias/elm-bytes-parser", 0.04703769 ) , ( "tad-lispy/springs", 0.04607089 ) , ( "Janiczek/transform", 0.04453779 ) , ( "hermanverschooten/ip", 0.04416292 ) , ( "jfmengels/lint-unused", 0.0439492 ) , ( "PaackEng/elm-google-maps", 0.04391243 ) , ( "ericgj/elm-uri-template", 0.0434312 ) , ( "data-viz-lab/elm-chart-builder", 0.0433935 ) , ( "folkertdev/elm-paragraph", 0.04272664 ) , ( "icidasset/elm-sha", 0.04256028 ) , ( "dasch/levenshtein", 0.04203807 ) , ( "wittjosiah/elm-ordered-dict", 0.04175244 ) , ( "ktonon/elm-test-extra", 0.04152155 ) , ( "rl-king/elm-masonry", 0.04121287 ) , ( "billstclair/elm-custom-element", 0.04093673 ) , ( "prikhi/bootstrap-gallery", 0.04035975 ) , ( "joshforisha/elm-inflect", 0.04031402 ) , ( "bburdette/pdf-element", 0.04019823 ) , ( "austinshenk/elm-w3", 0.04019579 ) , ( "json-tools/json-schema", 0.04015367 ) , ( "NoRedInk/datetimepicker-legacy", 0.04012745 ) , ( "ccapndave/focus", 0.04006861 ) , ( "gdamjan/elm-identicon", 0.03951737 ) , ( "bemyak/elm-slider", 0.03943666 ) , ( "FabienHenon/jsonapi", 0.03933752 ) , ( "NoRedInk/elm-plot-19", 0.0389287 ) , ( "mercurymedia/elm-message-toast", 0.03831063 ) , ( "chain-partners/elm-bignum", 0.03819787 ) , ( "jouderianjr/elm-loaders", 0.03811653 ) , ( "Punie/elm-id", 0.03796811 ) , ( "drathier/elm-test-tables", 0.03758749 ) , ( "Orasund/elm-action", 0.03733808 ) , ( "w0rm/elm-slice-show", 0.0373203 ) , ( "peterszerzo/elm-arborist", 0.03731962 ) , ( "ThinkAlexandria/elm-html-in-elm", 0.03723739 ) , ( "turboMaCk/queue", 0.03708237 ) , ( "emilianobovetti/edit-distance", 0.03704362 ) , ( "kuzzmi/elm-gravatar", 0.03697676 ) , ( "ThinkAlexandria/elm-drag-locations", 0.03696538 ) , ( "dawehner/elm-colorbrewer", 0.03695076 ) , ( "xarvh/elm-gamepad", 0.036799 ) , ( "benthepoet/elm-purecss", 0.03679697 ) , ( "billstclair/elm-oauth-middleware", 0.03667292 ) , ( "alexkorban/uicards", 0.03663732 ) , ( "folkertdev/elm-int64", 0.03653192 ) , ( "billstclair/elm-geolocation", 0.03644241 ) , ( "justgook/elm-game-logic", 0.03637282 ) , ( "zgohr/elm-csv", 0.03624985 ) , ( "gicentre/elm-vega", 0.03597546 ) , ( "zwilias/elm-reorderable", 0.03593048 ) , ( "toastal/select-prism", 0.03586537 ) , ( "ronanyeah/calendar-dates", 0.03579998 ) , ( "kuon/elm-hsluv", 0.03563973 ) , ( "ir4y/elm-dnd", 0.03561684 ) , ( "xilnocas/step", 0.03560819 ) , ( "stephenreddek/elm-range-slider", 0.03551443 ) , ( "fabiommendes/elm-iter", 0.03545966 ) , ( "akoppela/elm-logo", 0.03543891 ) , ( "billstclair/elm-crypto-string", 0.03529601 ) , ( "arowM/elm-form-validator", 0.0352493 ) , ( "Elm-Canvas/raster-shapes", 0.03520682 ) , ( "1602/json-schema", 0.03520676 ) , ( "ohanhi/autoexpand", 0.03508831 ) , ( "pdamoc/elm-hashids", 0.03503357 ) , ( "ohanhi/lorem", 0.03502294 ) , ( "stephenreddek/elm-time-picker", 0.03500671 ) , ( "mercurymedia/elm-smart-select", 0.03493208 ) , ( "elm-in-elm/compiler", 0.03449337 ) , ( "the-sett/decode-generic", 0.03406044 ) , ( "ljuglaret/fraction", 0.03369673 ) , ( "folkertdev/elm-kmeans", 0.03343474 ) , ( "nikita-volkov/typeclasses", 0.03336435 ) , ( "miniBill/date-format-languages", 0.03285717 ) , ( "jaredramirez/elm-s3", 0.03251825 ) , ( "jonathanfishbein1/elm-field", 0.03186558 ) , ( "bburdette/schelme", 0.03103703 ) , ( "Chadtech/elm-css-grid", 0.03072801 ) , ( "eike/json-decode-complete", 0.03072334 ) , ( "webbhuset/elm-actor-model", 0.03041586 ) , ( "bburdette/toop", 0.02995369 ) , ( "lynn/elm-ordinal", 0.02956659 ) , ( "tricycle/elm-email", 0.029545 ) , ( "tricycle/system-actor-model", 0.02930445 ) , ( "nikita-volkov/hashing-containers", 0.02926126 ) , ( "Orasund/elm-cellautomata", 0.02913753 ) , ( "simplystuart/elm-scroll-to", 0.02903803 ) , ( "MartinSStewart/elm-codec-bytes", 0.02896827 ) , ( "Chadtech/elm-vector", 0.02871587 ) , ( "arowM/html-extra", 0.02849722 ) , ( "munksgaard/elm-charts", 0.02841668 ) , ( "tesk9/modal", 0.02714795 ) , ( "RalfNorthman/elm-zoom-plot", 0.0270936 ) , ( "jxxcarlson/htree", 0.02683459 ) , ( "jxxcarlson/elm-stat", 0.02651257 ) , ( "billstclair/elm-svg-button", 0.02644546 ) , ( "webbhuset/elm-actor-model-elm-ui", 0.02592043 ) , ( "folkertdev/elm-tiny-inflate", 0.025917 ) , ( "fifth-postulate/elm-csv-decode", 0.02586667 ) , ( "viir/simplegamedev", 0.02544128 ) , ( "elm-toulouse/cbor", 0.02530895 ) , ( "rl-king/elm-modular-scale", 0.02520116 ) , ( "bowbahdoe/elm-history", 0.02476153 ) , ( "jxxcarlson/elm-widget", 0.02457994 ) , ( "jackhp95/elm-mapbox", 0.02452827 ) , ( "alex-tan/task-extra", 0.02403581 ) , ( "jjant/elm-printf", 0.02393349 ) , ( "jigargosar/elm-material-color", 0.02343325 ) , ( "avh4/elm-dropbox", 0.02328807 ) , ( "jonathanfishbein1/linear-algebra", 0.0230214 ) , ( "tomjkidd/elm-multiway-tree-zipper", 0.0229576 ) , ( "munksgaard/char-extra", 0.02262327 ) , ( "munksgaard/elm-data-uri", 0.02255611 ) , ( "billstclair/elm-id-search", 0.02252655 ) , ( "thought2/elm-interactive", 0.02222094 ) , ( "brianvanburken/elm-list-date", 0.02198079 ) , ( "andre-dietrich/elm-random-regex", 0.02184853 ) , ( "flowlang-cc/elm-audio-graph", 0.02169063 ) , ( "andre-dietrich/elm-svgbob", 0.0216694 ) , ( "rluiten/trie", 0.02124813 ) , ( "ringvold/elm-iso8601-date-strings", 0.0211933 ) , ( "rl-king/elm-inview", 0.02118104 ) , ( "afidegnum/elm-tailwind", 0.02102643 ) , ( "fifth-postulate/combinatorics", 0.020755 ) , ( "indicatrix/elm-input-extra", 0.02068175 ) , ( "abadi199/elm-creditcard", 0.02068162 ) , ( "arowM/elm-css-modules-helper", 0.02039772 ) , ( "alexanderkiel/elm-mdc-alpha", 0.02028243 ) , ( "sparksp/elm-review-camelcase", 0.02010144 ) , ( "dwyl/elm-criteria", 0.02009551 ) , ( "ericgj/elm-validation", 0.01997145 ) , ( "prikhi/paginate", 0.01997109 ) , ( "romstad/elm-chess", 0.01987651 ) , ( "basti1302/elm-non-empty-array", 0.01959109 ) , ( "MichaelCombs28/elm-base85", 0.01958329 ) , ( "arnau/elm-objecthash", 0.01950411 ) , ( "NoRedInk/elm-debug-controls-without-datepicker", 0.01949173 ) , ( "dasch/parser", 0.01948486 ) , ( "NoRedInk/noredink-ui", 0.01944399 ) , ( "ozmat/elm-forms", 0.01943377 ) , ( "the-sett/ai-search", 0.01942663 ) , ( "allenap/elm-json-decode-broken", 0.01937762 ) , ( "nathanjohnson320/base58", 0.01908185 ) , ( "noahzgordon/elm-jsonapi", 0.01893622 ) , ( "labzero/elm-google-geocoding", 0.01891308 ) , ( "pilatch/elm-chess", 0.0186072 ) , ( "torreyatcitty/the-best-decimal", 0.01847113 ) , ( "NoRedInk/elm-rails", 0.01826369 ) , ( "FordLabs/elm-star-rating", 0.01819264 ) , ( "Bernardoow/elm-alert-timer-message", 0.01807738 ) , ( "JohnBugner/elm-bag", 0.01807483 ) , ( "Gizra/elm-compat-019", 0.01797027 ) , ( "goilluminate/elm-fancy-daterangepicker", 0.01784086 ) , ( "janjelinek/creditcard-validation", 0.01781153 ) , ( "r-k-b/complex", 0.01781103 ) , ( "NoRedInk/elm-sweet-poll", 0.01773511 ) , ( "TSFoster/elm-compare", 0.01772745 ) , ( "fedragon/elm-typed-dropdown", 0.01771295 ) , ( "emilianobovetti/elm-yajson", 0.01770452 ) , ( "jjant/elm-comonad-zipper", 0.01770213 ) , ( "ozmat/elm-validation", 0.01766079 ) , ( "jackfranklin/elm-parse-link-header", 0.0176503 ) , ( "Gizra/elm-attribute-builder", 0.01761218 ) , ( "kkpoon/elm-auth0-urlparser", 0.01761196 ) , ( "1602/json-value", 0.01760062 ) , ( "ggb/elm-bloom", 0.0175877 ) , ( "peterszerzo/elm-porter", 0.01756095 ) , ( "jweir/sparkline", 0.01754773 ) , ( "fbonetti/elm-geodesy", 0.01754339 ) , ( "bChiquet/elm-accessors", 0.01753197 ) , ( "tricycle/elm-actor-framework-template", 0.01638874 ) , ( "robinheghan/elm-warrior", 0.01638874 ) , ( "wsowens/term", 0.01638874 ) , ( "finos/morphir-elm", 0.01638874 ) , ( "sparksp/elm-review-always", 0.01390432 ) , ( "YuyaAizawa/peg", 0.01331966 ) , ( "jfmengels/lint-debug", 0.01255703 ) , ( "billstclair/elm-dialog", 0.01200416 ) , ( "jxxcarlson/meenylatex", 0.01054695 ) , ( "the-sett/elm-error-handling", 0.01024483 ) , ( "Arkham/elm-rttl", 0.00987257 ) , ( "jfmengels/elm-lint", 0.00982276 ) , ( "Chadtech/ct-colors", 0.00927074 ) , ( "lemol/ant-design-icons-elm", 0.00917769 ) , ( "Gizra/elm-fetch", 0.00830096 ) , ( "GoldentTuft/elm-japanese-typing", 0.00819437 ) , ( "tricycle/elm-actor-framework-template-html", 0.00819437 ) , ( "groma84/elm-tachyons", 0.00819437 ) , ( "shnewto/pgn", 0.00819437 ) , ( "ContaSystemer/elm-review-no-regex", 0.00819437 ) , ( "tasuki/elm-punycode", 0.00819437 ) , ( "billstclair/elm-popup-picker", 0.00819437 ) , ( "hallelujahdrive/elm-croppie", 0.00819437 ) , ( "the-sett/elm-localstorage", 0.00819437 ) , ( "mrpinsky/elm-keyed-list", 0.00819437 ) , ( "choonkeat/elm-fullstack", 0.00819437 ) , ( "carwow/elm-review-rules", 0.00819437 ) , ( "rl-king/elm-index", 0.00819437 ) , ( "shamansir/elm-aframe", 0.00819437 ) , ( "opvasger/msg-replay", 0.00819437 ) , ( "3kyro/xsrf-protection", 0.00819437 ) , ( "sparksp/elm-review-imports", 0.00819437 ) , ( "jfmengels/elm-review-license", 0.00819437 ) , ( "JustinLove/elm-twitch-api", 0.00807273 ) , ( "billstclair/elm-websocket-framework", 0.00794594 ) , ( "calions-app/env", 0.00793122 ) , ( "chazsconi/elm-phoenix-ports", 0.00792254 ) , ( "chicode/lisa", 0.00778186 ) , ( "leojpod/review-no-empty-html-text", 0.00777119 ) , ( "showell/meta-elm", 0.00741073 ) , ( "dasch/crockford", 0.00735675 ) , ( "billstclair/elm-mastodon-websocket", 0.00673705 ) , ( "sparksp/elm-review-ports", 0.00650576 ) , ( "justgook/elm-tiled", 0.00649709 ) , ( "matheus23/elm-markdown-transforms", 0.00624748 ) , ( "ursi/support", 0.00623534 ) , ( "billstclair/elm-mastodon", 0.00617322 ) , ( "TSFoster/elm-md5", 0.00589303 ) , ( "jxxcarlson/tree-extra", 0.00585207 ) , ( "miyamoen/bibliopola", 0.00542674 ) , ( "ThinkAlexandria/css-in-elm", 0.00528767 ) , ( "r-k-b/no-float-ids", 0.00528407 ) , ( "nishiurahiroki/elm-simple-pagenate", 0.00525112 ) , ( "the-sett/elm-aws-cognito", 0.00517803 ) , ( "arowM/html", 0.00497 ) , ( "owanturist/elm-avl-dict", 0.00491884 ) , ( "z5h/timeline", 0.00487916 ) , ( "JoshuaHall/elm-fraction", 0.00446122 ) , ( "jxxcarlson/elm-text-editor", 0.0043958 ) , ( "rjbma/elm-listview", 0.00428901 ) , ( "visotype/elm-eval", 0.00420946 ) , ( "waratuman/elm-standardapi", 0.00396777 ) , ( "calions-app/test-attribute", 0.00396646 ) , ( "jxxcarlson/elm-tar", 0.00392845 ) , ( "waratuman/json-extra", 0.00384724 ) , ( "vViktorPL/elm-jira-connector", 0.00384081 ) , ( "nicmr/compgeo", 0.00379181 ) , ( "showell/binary-tree-diagram", 0.00371631 ) , ( "showell/dict-dot-dot", 0.00370657 ) , ( "MartinSStewart/elm-nonempty-string", 0.00369952 ) , ( "Gizra/elm-editable-webdata", 0.00365077 ) , ( "Gizra/elm-storage-key", 0.00364737 ) , ( "bburdette/typed-collections", 0.00355881 ) , ( "wolfadex/elm-text-adventure", 0.00343428 ) , ( "sashaafm/eetf", 0.00341681 ) , ( "rluiten/stemmer", 0.00339661 ) , ( "rluiten/sparsevector", 0.00339232 ) , ( "ChristophP/elm-mark", 0.00337588 ) , ( "calions-app/app-object", 0.00324226 ) , ( "calions-app/remote-resource", 0.00323489 ) , ( "calions-app/jsonapi-http", 0.00323482 ) , ( "jfmengels/elm-lint-reporter", 0.00313712 ) , ( "brian-watkins/elm-procedure", 0.00312001 ) , ( "dosarf/elm-yet-another-polling", 0.00298703 ) , ( "commonmind/elm-csexpr", 0.00285553 ) , ( "folkertdev/elm-brotli", 0.00282573 ) , ( "yumlonne/elm-japanese-calendar", 0.00280968 ) , ( "jxxcarlson/math-markdown", 0.00273225 ) , ( "billstclair/elm-websocket-framework-server", 0.00264942 ) , ( "alex-tan/postgrest-client", 0.00263226 ) , ( "primait/pyxis-components", 0.00262437 ) , ( "maca/crdt-replicated-tree", 0.0026048 ) , ( "avh4/elm-desktop-app", 0.00257613 ) , ( "ceddlyburge/elm-bootstrap-starter-master-view", 0.00247544 ) , ( "dvberkel/microkanren", 0.00243706 ) , ( "getto-systems/elm-apply", 0.00234565 ) , ( "getto-systems/elm-field", 0.00234556 ) , ( "getto-systems/elm-html-table", 0.00232625 ) , ( "getto-systems/elm-http-part", 0.00232607 ) , ( "getto-systems/elm-http-header", 0.00232581 ) , ( "getto-systems/elm-url", 0.00232567 ) , ( "getto-systems/elm-json", 0.00232527 ) , ( "getto-systems/elm-sort", 0.00232362 ) , ( "getto-systems/elm-command", 0.00232005 ) , ( "primait/forms", 0.00230758 ) , ( "harmboschloo/elm-dict-intersect", 0.00229488 ) , ( "anhmiuhv/pannablevideo", 0.00227733 ) , ( "Spaxe/elm-lsystem", 0.00218039 ) , ( "harmboschloo/elm-ecs", 0.00202945 ) , ( "AuricSystemsInternational/creditcard-validator", 0.00195405 ) , ( "alex-tan/postgrest-queries", 0.00194971 ) , ( "emptyflash/typed-svg", 0.00194846 ) , ( "billstclair/elm-crypto-aes", 0.00193174 ) , ( "eelcoh/parser-indent", 0.00190639 ) , ( "benansell/lobo-elm-test-extra", 0.00190501 ) , ( "miyamoen/elm-command-pallet", 0.00188622 ) , ( "melon-love/elm-gab-api", 0.00188351 ) , ( "iodevs/elm-history", 0.00184775 ) , ( "ymtszw/elm-broker", 0.00184465 ) , ( "ThinkAlexandria/elm-primer-tooltips", 0.00181717 ) , ( "ryan-senn/elm-compiler-error-sscce", 0.00180921 ) , ( "genthaler/elm-enum", 0.00178685 ) , ( "bigbinary/elm-reader", 0.00178306 ) , ( "bigbinary/elm-form-field", 0.00178304 ) , ( "the-sett/svg-text-fonts", 0.00177048 ) , ( "billstclair/elm-chat", 0.00176851 ) , ( "Libbum/elm-partition", 0.00176227 ) , ( "turboMaCk/elm-continue", 0.00175979 ) , ( "imjoehaines/afinn-165-elm", 0.00175817 ) , ( "the-sett/json-optional", 0.00066868 ) , ( "toastal/endo", 0.00046685 ) , ( "jackhp95/palit", 0.00045758 ) , ( "arowM/elm-html-extra-internal", 0.00028486 ) , ( "arowM/elm-html-internal", 0.00028398 ) , ( "elm-toulouse/float16", 0.00024702 ) , ( "munksgaard/elm-media-type", 0.00022552 ) , ( "jonathanfishbein1/complex-numbers", 0.00022321 ) , ( "NoRedInk/style-elements", 0.00019386 ) , ( "truqu/elm-dictset", 0.00017581 ) , ( "Janiczek/architecture-test", 0.0001752 ) , ( "NoRedInk/http-upgrade-shim", 0.00006647 ) , ( "miyamoen/tree-with-zipper", 0.00005325 ) , ( "rtfeldman/count", 0.00005047 ) , ( "NoRedInk/elm-saved", 0.00004694 ) , ( "NoRedInk/elm-rfc5988-parser", 0.00004694 ) , ( "NoRedInk/elm-formatted-text-test-helpers", 0.00004606 ) , ( "NoRedInk/elm-formatted-text-19", 0.00004606 ) , ( "NoRedInk/elm-plot-rouge", 0.00004605 ) , ( "NoRedInk/elm-rollbar", 0.00003914 ) , ( "avh4/burndown-charts", 0.00003663 ) , ( "mpizenberg/elm-placeholder-pkg", 0.00003533 ) , ( "avh4/elm-github-v3", 0.00003187 ) , ( "justinmimbs/tzif", 0.00002911 ) , ( "folkertdev/elm-cff", 0.00001785 ) , ( "the-sett/elm-one-many", 0.0000177 ) , ( "ianmackenzie/elm-iso-10303", 0.00001421 ) , ( "ianmackenzie/elm-step-file", 0.00001421 ) , ( "ianmackenzie/elm-geometry-prerelease", 0.00001301 ) , ( "terezka/elm-charts-alpha", 0.00001213 ) , ( "terezka/charts", 0.00001213 ) , ( "the-sett/salix-aws-spec", 0.00001075 ) , ( "the-sett/parser-recoverable", 0.00001075 ) , ( "lukewestby/accessible-html-with-css-temp-19", 0.00000819 ) , ( "folkertdev/elm-iris", 0.00000767 ) , ( "lukewestby/http-extra", 0.00000738 ) , ( "jfmengels/elm-review-reporter", 0.00000692 ) , ( "the-sett/elm-enum", 0.00000476 ) , ( "Janiczek/elm-runescape", 0.00000465 ) , ( "Janiczek/browser-extra", 0.00000461 ) , ( "jxxcarlson/toc-editor", 0.00000418 ) , ( "billstclair/elm-dev-random", 0.0000038 ) , ( "miniBill/elm-bare", 0.00000357 ) , ( "miniBill/elm-avataaars", 0.00000345 ) , ( "zwilias/elm-holey-zipper", 0.00000282 ) , ( "TSFoster/elm-envfile", 0.0000028 ) , ( "PaackEng/paack-ui", 0.00000279 ) , ( "PaackEng/paack-remotedata", 0.00000279 ) , ( "the-sett/auth-elm", 0.00000263 ) , ( "Chadtech/dependent-text", 0.00000253 ) , ( "the-sett/tea-tree", 0.00000253 ) , ( "Chadtech/elm-imperative-porting", 0.00000246 ) , ( "Chadtech/elm-provider", 0.00000244 ) , ( "Chadtech/elm-us-state-abbreviations", 0.00000244 ) , ( "jinjor/elm-map-debug", 0.00000238 ) , ( "jinjor/elm-req", 0.00000236 ) , ( "jinjor/elm-insertable-key", 0.00000211 ) , ( "ContaSystemer/elm-review-no-missing-documentation", 0.000002 ) , ( "ContaSystemer/elm-angularjs-custom-element", 0.000002 ) , ( "ContaSystemer/elm-effects", 0.000002 ) , ( "ContaSystemer/elm-effects-time", 0.000002 ) , ( "ContaSystemer/elm-js-data", 0.000002 ) , ( "ContaSystemer/elm-error-message", 0.000002 ) , ( "ContaSystemer/elm-effects-msg-from-js", 0.000002 ) , ( "turboMaCk/glue", 0.00000197 ) , ( "tricycle/elm-actor-framework-template-markdown", 0.00000174 ) , ( "tricycle/elm-actor-framework-sandbox", 0.00000174 ) , ( "ccapndave/elm-eexl", 0.0000017 ) , ( "ccapndave/elm-typed-tree", 0.00000167 ) , ( "ccapndave/elm-translator", 0.00000164 ) , ( "ccapndave/elm-statecharts", 0.00000164 ) , ( "simonh1000/elm-sliding-menus", 0.00000162 ) , ( "rl-king/elm-iso3166-country-codes", 0.0000016 ) , ( "pd-andy/elm-limiter", 0.00000159 ) , ( "joneshf/elm-these", 0.00000145 ) , ( "arowM/elm-data-url", 0.00000143 ) , ( "robinheghan/elm-phone-numbers", 0.00000136 ) , ( "arowM/elm-html-with-context", 0.00000134 ) , ( "tricycle/elm-storage", 0.00000131 ) , ( "arowM/elm-parser-test", 0.00000129 ) , ( "miyamoen/elm-origami", 0.00000128 ) , ( "jweir/charter", 0.00000126 ) , ( "tricycle/elm-parse-dont-validate", 0.00000125 ) , ( "frandibar/elm-bootstrap", 0.00000116 ) , ( "carwow/elm-slider-old", 0.00000113 ) , ( "Zinggi/elm-glsl-generator", 0.00000109 ) , ( "danhandrea/elm-router", 0.00000098 ) , ( "lucamug/elm-box-drawing", 0.00000098 ) , ( "danhandrea/elm-time-extra", 0.00000098 ) , ( "justgook/elm-webdriver", 0.00000095 ) , ( "ktonon/elm-jsonwebtoken", 0.00000088 ) , ( "MartinSStewart/elm-geometry-serialize", 0.00000087 ) , ( "abadi199/intl-phone-input", 0.00000078 ) , ( "stoeffel/resetable", 0.00000078 ) , ( "ahstro/elm-luhn", 0.00000077 ) , ( "FabienHenon/elm-ckeditor5", 0.00000072 ) , ( "GlobalWebIndex/quantify", 0.00000069 ) , ( "FabienHenon/elm-iso8601-date-strings", 0.00000069 ) , ( "proda-ai/elm-css", 0.00000066 ) , ( "jgrenat/regression-testing", 0.00000064 ) , ( "GlobalWebIndex/class-namespaces", 0.00000064 ) , ( "PaackEng/elm-alert-beta", 0.00000063 ) , ( "tricycle/elm-infinite-gallery", 0.00000062 ) , ( "tricycle/elm-imgix", 0.00000062 ) , ( "sporto/elm-countries", 0.00000061 ) , ( "sporto/polylinear-scale", 0.0000006 ) , ( "gicentre/tidy", 0.00000056 ) , ( "rluiten/mailcheck", 0.00000056 ) , ( "tricycle/elm-eventstream", 0.00000055 ) , ( "panthershark/snackbar", 0.00000054 ) , ( "alex-tan/loadable", 0.00000054 ) , ( "WhileTruu/elm-blurhash", 0.00000052 ) , ( "MartinSStewart/send-grid", 0.0000005 ) , ( "MartinSStewart/elm-bayer-matrix", 0.00000049 ) , ( "Herteby/url-builder-plus", 0.00000048 ) , ( "andre-dietrich/elm-mapbox", 0.00000048 ) , ( "z5h/zipper", 0.00000046 ) , ( "tricycle/morty-api", 0.00000044 ) , ( "mthadley/elm-typewriter", 0.00000044 ) , ( "ggb/porterstemmer", 0.00000042 ) , ( "ggb/elm-trend", 0.00000042 ) , ( "ggb/elm-sentiment", 0.00000042 ) , ( "pd-andy/elm-audio-graph", 0.00000042 ) , ( "ThinkAlexandria/window-manager", 0.00000037 ) , ( "owanturist/elm-queue", 0.00000035 ) , ( "drathier/elm-test-graph", 0.00000035 ) , ( "bburdette/stl", 0.00000033 ) , ( "jonathanfishbein1/numeric-typeclasses", 0.00000033 ) , ( "gribouille/elm-spinner", 0.00000033 ) , ( "gribouille/elm-prelude", 0.00000033 ) , ( "gribouille/elm-graphql", 0.00000033 ) , ( "gribouille/elm-bulma", 0.00000033 ) , ( "peterszerzo/elm-json-tree-view", 0.00000031 ) , ( "allo-media/elm-es-simple-query-string", 0.00000029 ) , ( "prozacchiwawa/elm-json-codec", 0.00000025 ) , ( "danhandrea/elm-foo", 0.00000023 ) , ( "proda-ai/formatting", 0.00000022 ) , ( "proda-ai/elm-svg-loader", 0.00000022 ) , ( "laserpants/elm-burrito-update", 0.00000022 ) , ( "harrysarson/elm-decode-elmi", 0.0000002 ) , ( "allo-media/fable", 0.00000019 ) , ( "achutkiran/elm-material-color", 0.00000018 ) , ( "kirchner/form-validation", 0.00000018 ) , ( "marshallformula/arrangeable-list", 0.00000018 ) , ( "RalfNorthman/elm-lttb", 0.00000018 ) , ( "malaire/elm-safe-int", 0.00000018 ) , ( "driebit/elm-ginger", 0.00000017 ) , ( "MichaelCombs28/elm-css-bulma", 0.00000016 ) , ( "league/difference-list", 0.00000016 ) , ( "harrysarson/elm-hacky-unique", 0.00000015 ) , ( "owanturist/elm-graphql", 0.00000015 ) , ( "dosarf/elm-activemq", 0.00000013 ) , ( "SiriusStarr/elm-spaced-repetition", 0.00000012 ) , ( "r-k-b/elm-interval", 0.00000011 ) , ( "SiriusStarr/elm-splat", 0.0000001 ) , ( "calions-app/elm-placeholder-loading", 0.0000001 ) , ( "r-k-b/map-accumulate", 0.00000008 ) , ( "JohnBugner/elm-loop", 0.00000008 ) , ( "jjant/elm-dict", 0.00000007 ) , ( "calions-app/jsonapi-http-retry", 0.00000007 ) , ( "bowbahdoe/lime-reset", 0.00000007 ) , ( "ljuglaret/combinatoire", 0.00000007 ) , ( "harmboschloo/graphql-to-elm-package", 0.00000005 ) , ( "thought2/elm-wikimedia-commons", 0.00000004 ) , ( "afidegnum/elm-bulmanizer", 0.00000004 ) , ( "alexanderkiel/list-selection", 0.00000004 ) , ( "Bernardoow/elm-rating-component", 0.00000004 ) , ( "kkpoon/elm-echarts", 0.00000004 ) , ( "kkpoon/elm-auth0", 0.00000004 ) , ( "jaredramirez/elm-field", 0.00000004 ) , ( "showell/elm-data-util", 0.00000003 ) , ( "hallelujahdrive/elm-accordion", 0.00000002 ) , ( "leojpod/elm-apex-charts-link", 0.00000002 ) , ( "tasuki/elm-bloom", 0.00000002 ) , ( "shamansir/tron-gui", 0.00000002 ) , ( "leojpod/elm-keyboard-shortcut", 0.00000002 ) , ( "choonkeat/elm-aws", 0.00000002 ) , ( "shamansir/bin-pack", 0.00000002 ) , ( "ryan-senn/elm-google-domains", 0.00000001 ) , ( "ryan-senn/elm-tlds", 0.00000001 ) , ( "ryan-senn/elm-readability", 0.00000001 ) , ( "wolfadex/locale-negotiation", 0.00000001 ) , ( "matheus23/elm-figma-api", 0.00000001 ) , ( "vViktorPL/elm-incremental-list", 0.00000001 ) , ( "Arkham/elm-chords", 0.00000001 ) , ( "primait/elm-form", 0.00000001 ) , ( "opvasger/amr", 0.00000001 ) , ( "choonkeat/elm-retry", 0.00000001 ) , ( "wolfadex/tiler", 0.0 ) , ( "iodevs/elm-validate", 0.0 ) , ( "Libbum/elm-redblacktrees", 0.0 ) , ( "avh4-experimental/elm-transducers", 0.0 ) , ( "ryan-senn/stellar-elm-sdk", 0.0 ) ]
elm
[ { "context": "Cmd Msg )\n\ninit : (Model, Cmd Msg)\ninit = (Model \"Giorgio\", Cmd.none)\n\n\n\n\n\n-- VIEW\n\n\nview : Model -> Html M", "end": 501, "score": 0.7743318677, "start": 494, "tag": "NAME", "value": "Giorgio" } ]
src/Main.elm
gDelgado14/elm-boilerplate
1
module Main exposing (..) import Html exposing (Html, text, div) import Html.Attributes exposing (class) main = Html.program { init = init , view = view , update = update , subscriptions = \_ -> Sub.none } -- MODEL type alias Model = { name : String } -- MSG type Msg = NoOp -- INIT -- js interop -- type alias Flags = -- { user : String -- , token : String -- } -- init : Flags -> ( Model, Cmd Msg ) init : (Model, Cmd Msg) init = (Model "Giorgio", Cmd.none) -- VIEW view : Model -> Html Msg view model = div [ ] [ text "Hello world!" ] -- UPDATE update : Msg -> Model -> (Model, Cmd Msg) update msg model = (model, Cmd.none)
55807
module Main exposing (..) import Html exposing (Html, text, div) import Html.Attributes exposing (class) main = Html.program { init = init , view = view , update = update , subscriptions = \_ -> Sub.none } -- MODEL type alias Model = { name : String } -- MSG type Msg = NoOp -- INIT -- js interop -- type alias Flags = -- { user : String -- , token : String -- } -- init : Flags -> ( Model, Cmd Msg ) init : (Model, Cmd Msg) init = (Model "<NAME>", Cmd.none) -- VIEW view : Model -> Html Msg view model = div [ ] [ text "Hello world!" ] -- UPDATE update : Msg -> Model -> (Model, Cmd Msg) update msg model = (model, Cmd.none)
true
module Main exposing (..) import Html exposing (Html, text, div) import Html.Attributes exposing (class) main = Html.program { init = init , view = view , update = update , subscriptions = \_ -> Sub.none } -- MODEL type alias Model = { name : String } -- MSG type Msg = NoOp -- INIT -- js interop -- type alias Flags = -- { user : String -- , token : String -- } -- init : Flags -> ( Model, Cmd Msg ) init : (Model, Cmd Msg) init = (Model "PI:NAME:<NAME>END_PI", Cmd.none) -- VIEW view : Model -> Html Msg view model = div [ ] [ text "Hello world!" ] -- UPDATE update : Msg -> Model -> (Model, Cmd Msg) update msg model = (model, Cmd.none)
elm
[ { "context": " )\n\n\naddToken : Token\naddToken =\n { name = \"AdderalCoin\"\n , symbol = \"ADD\"\n , contractAccount = \"eo", "end": 522, "score": 0.9864141345, "start": 511, "tag": "USERNAME", "value": "AdderalCoin" }, { "context": "in\"\n , symbol = \"ADD\"\n , contractAccount = \"eosadddddddd\"\n , precision = 4\n }\n\n\nblackToken : Token\nb", "end": 582, "score": 0.8676561117, "start": 570, "tag": "KEY", "value": "eosadddddddd" }, { "context": "}\n\n\nblackToken : Token\nblackToken =\n { name = \"eosBLACK\"\n , symbol = \"BLACK\"\n , contractAccount = \"", "end": 666, "score": 0.9261196852, "start": 658, "tag": "USERNAME", "value": "eosBLACK" }, { "context": " [ ( \"account\", JE.string \"eosadddddddd\" )\n , ( \"actio", "end": 1697, "score": 0.781164825, "start": 1688, "tag": "KEY", "value": "adddddddd" }, { "context": " newToken =\n { name = \"BLACK\"\n , symbol = \"BLACK\"\n ", "end": 2664, "score": 0.4546558261, "start": 2659, "tag": "KEY", "value": "BLACK" }, { "context": " \"BLACK\"\n , contractAccount = \"testblack\"\n , precision = 4\n ", "end": 2755, "score": 0.828512907, "start": 2746, "tag": "KEY", "value": "testblack" }, { "context": " Dict.insert \"BLACK\" ( blackToken, \"40.0000 BLACK\" ) model.possessingTokens\n ", "end": 4546, "score": 0.38336128, "start": 4545, "tag": "KEY", "value": "4" }, { "context": " Dict.insert \"BLACK\" ( blackToken, \"40.0000 BLACK\" ) model.possessingTokens\n ", "end": 4558, "score": 0.5083524585, "start": 4546, "tag": "PASSWORD", "value": "0.0000 BLACK" }, { "context": " Dict.insert \"ADD\" ( addToken, \"30.0000 ADD\" ) model.possessingTokens\n ", "end": 5068, "score": 0.7885026932, "start": 5057, "tag": "PASSWORD", "value": "30.0000 ADD" } ]
test/frontend/elm/Test/Component/Main/Page/Transfer.elm
EOSYS-io/eoshub.io
11
module Test.Component.Main.Page.Transfer exposing ( balance , model , tests ) import Component.Main.Page.Transfer exposing (..) import Data.Table import Dict import Expect import Http import Json.Encode as JE import Port import Test exposing (..) import Util.Token exposing (Token) import Util.Validation exposing ( AccountStatus(..) , MemoStatus(..) , QuantityStatus(..) , VerificationRequestStatus(..) ) addToken : Token addToken = { name = "AdderalCoin" , symbol = "ADD" , contractAccount = "eosadddddddd" , precision = 4 } blackToken : Token blackToken = { name = "eosBLACK" , symbol = "BLACK" , contractAccount = "eosblackteam" , precision = 4 } model : Model model = { accountValidation = ValidAccount , quantityValidation = ValidQuantity , memoValidation = ValidMemo , isFormValid = True , transfer = { from = "from" , to = "to" , quantity = "3.0" , memo = "memo" } , possessingTokens = Dict.fromList [ ( "ADD", ( addToken, "3.0123 ADD" ) ) ] , currentSymbol = "ADD" , modalOpened = True , tokensLoaded = False , tokenSearchInput = "" } balance : Float balance = 300.0 tests : Test tests = let submitActionTest = let expectedJson = JE.object [ ( "actionName", JE.string "transfer" ) , ( "actions" , JE.list [ JE.object [ ( "account", JE.string "eosadddddddd" ) , ( "action", JE.string "transfer" ) , ( "payload" , JE.object [ ( "from", JE.string "from" ) , ( "to", JE.string "to" ) , ( "quantity", JE.string "3.0000 ADD" ) , ( "memo", JE.string "memo" ) ] ) ] ] ) ] in test "SubmitAction" <| \() -> Expect.equal ( model, Port.pushAction expectedJson ) (update SubmitAction model "from" 300.0) switchTokenTest = let newToken = { name = "BLACK" , symbol = "BLACK" , contractAccount = "testblack" , precision = 4 } in test "SwitchToken" <| \() -> Expect.equal { model | modalOpened = False , transfer = { from = "", to = "", quantity = "", memo = "" } , accountValidation = EmptyAccount , quantityValidation = EmptyQuantity , memoValidation = EmptyMemo , currentSymbol = "BLACK" } (Tuple.first (update (SwitchToken "BLACK") model "from" 300.0 ) ) onFetchTableRowsTest = let addBalance = Data.Table.Accounts { balance = "30.0000 ADD" } blackBalance = Data.Table.Accounts { balance = "40.0000 BLACK" } bchBalance = Data.Table.Accounts { balance = "1.0000 BCH" } in describe "OnFetchTableRows" [ test "Ok with empty rows" <| \() -> Expect.equal ( model, Cmd.none ) (update (OnFetchTableRows (Ok [])) model "from" 300.0) , test "Ok with matched symbol" <| \() -> Expect.equal ( { model | possessingTokens = Dict.insert "BLACK" ( blackToken, "40.0000 BLACK" ) model.possessingTokens } , Cmd.none ) (update (OnFetchTableRows (Ok [ blackBalance ])) model "from" 300.0) , test "Ok with existing symbol" <| \() -> Expect.equal ( { model | possessingTokens = Dict.insert "ADD" ( addToken, "30.0000 ADD" ) model.possessingTokens } , Cmd.none ) (update (OnFetchTableRows (Ok [ addBalance ])) model "from" 300.0) , test "Ok with no matched symbol" <| \() -> Expect.equal ( model, Cmd.none ) (update (OnFetchTableRows (Ok [ bchBalance ])) model "from" 300.0) , test "Err" <| \() -> Expect.equal ( model, Cmd.none ) (update (OnFetchTableRows (Err Http.Timeout)) model "from" 300.0) ] in describe "Transfer page module" [ describe "update" [ submitActionTest , switchTokenTest , onFetchTableRowsTest ] , describe "setTransferMessageField" (let { transfer } = model in [ test "To" <| \() -> Expect.equal { model | transfer = { transfer | to = "newto" } , accountValidation = AccountToBeVerified , isFormValid = False } (Tuple.first (setTransferMessageField To "newto" model balance)) , test "Quantity" <| \() -> Expect.equal { model | transfer = { transfer | quantity = "0.1" } , quantityValidation = ValidQuantity } (Tuple.first (setTransferMessageField Quantity "0.1" model balance) ) , test "Memo" <| \() -> Expect.equal { model | transfer = { transfer | memo = "newMemo" } , quantityValidation = ValidQuantity } (Tuple.first (setTransferMessageField Memo "newMemo" model balance) ) ] ) , describe "validation" (let { transfer } = model in [ describe "validateToField" [ test "AccountToBeVerified" <| \() -> Expect.equal { model | transfer = { transfer | to = "eosio.ram" } , accountValidation = AccountToBeVerified , isFormValid = False } (Tuple.first (validateToField { model | transfer = { transfer | to = "eosio.ram" } } NotSent ) ) , test "ValidAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "eosio.ram" } , isFormValid = True , accountValidation = ValidAccount } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "eosio.ram" } } Succeed ) , test "InexistentAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "eosio.ran" } , accountValidation = InexistentAccount , isFormValid = False } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "eosio.ran" } } Fail ) , test "InvalidAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "INVALID" } , accountValidation = InvalidAccount , isFormValid = False } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "INVALID" } } Fail ) , test "EmptyAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "" } , accountValidation = EmptyAccount , isFormValid = False } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "" } } Fail ) ] ] ) ]
55180
module Test.Component.Main.Page.Transfer exposing ( balance , model , tests ) import Component.Main.Page.Transfer exposing (..) import Data.Table import Dict import Expect import Http import Json.Encode as JE import Port import Test exposing (..) import Util.Token exposing (Token) import Util.Validation exposing ( AccountStatus(..) , MemoStatus(..) , QuantityStatus(..) , VerificationRequestStatus(..) ) addToken : Token addToken = { name = "AdderalCoin" , symbol = "ADD" , contractAccount = "<KEY>" , precision = 4 } blackToken : Token blackToken = { name = "eosBLACK" , symbol = "BLACK" , contractAccount = "eosblackteam" , precision = 4 } model : Model model = { accountValidation = ValidAccount , quantityValidation = ValidQuantity , memoValidation = ValidMemo , isFormValid = True , transfer = { from = "from" , to = "to" , quantity = "3.0" , memo = "memo" } , possessingTokens = Dict.fromList [ ( "ADD", ( addToken, "3.0123 ADD" ) ) ] , currentSymbol = "ADD" , modalOpened = True , tokensLoaded = False , tokenSearchInput = "" } balance : Float balance = 300.0 tests : Test tests = let submitActionTest = let expectedJson = JE.object [ ( "actionName", JE.string "transfer" ) , ( "actions" , JE.list [ JE.object [ ( "account", JE.string "eos<KEY>" ) , ( "action", JE.string "transfer" ) , ( "payload" , JE.object [ ( "from", JE.string "from" ) , ( "to", JE.string "to" ) , ( "quantity", JE.string "3.0000 ADD" ) , ( "memo", JE.string "memo" ) ] ) ] ] ) ] in test "SubmitAction" <| \() -> Expect.equal ( model, Port.pushAction expectedJson ) (update SubmitAction model "from" 300.0) switchTokenTest = let newToken = { name = "<KEY>" , symbol = "BLACK" , contractAccount = "<KEY>" , precision = 4 } in test "SwitchToken" <| \() -> Expect.equal { model | modalOpened = False , transfer = { from = "", to = "", quantity = "", memo = "" } , accountValidation = EmptyAccount , quantityValidation = EmptyQuantity , memoValidation = EmptyMemo , currentSymbol = "BLACK" } (Tuple.first (update (SwitchToken "BLACK") model "from" 300.0 ) ) onFetchTableRowsTest = let addBalance = Data.Table.Accounts { balance = "30.0000 ADD" } blackBalance = Data.Table.Accounts { balance = "40.0000 BLACK" } bchBalance = Data.Table.Accounts { balance = "1.0000 BCH" } in describe "OnFetchTableRows" [ test "Ok with empty rows" <| \() -> Expect.equal ( model, Cmd.none ) (update (OnFetchTableRows (Ok [])) model "from" 300.0) , test "Ok with matched symbol" <| \() -> Expect.equal ( { model | possessingTokens = Dict.insert "BLACK" ( blackToken, "<KEY> <PASSWORD>" ) model.possessingTokens } , Cmd.none ) (update (OnFetchTableRows (Ok [ blackBalance ])) model "from" 300.0) , test "Ok with existing symbol" <| \() -> Expect.equal ( { model | possessingTokens = Dict.insert "ADD" ( addToken, "<PASSWORD>" ) model.possessingTokens } , Cmd.none ) (update (OnFetchTableRows (Ok [ addBalance ])) model "from" 300.0) , test "Ok with no matched symbol" <| \() -> Expect.equal ( model, Cmd.none ) (update (OnFetchTableRows (Ok [ bchBalance ])) model "from" 300.0) , test "Err" <| \() -> Expect.equal ( model, Cmd.none ) (update (OnFetchTableRows (Err Http.Timeout)) model "from" 300.0) ] in describe "Transfer page module" [ describe "update" [ submitActionTest , switchTokenTest , onFetchTableRowsTest ] , describe "setTransferMessageField" (let { transfer } = model in [ test "To" <| \() -> Expect.equal { model | transfer = { transfer | to = "newto" } , accountValidation = AccountToBeVerified , isFormValid = False } (Tuple.first (setTransferMessageField To "newto" model balance)) , test "Quantity" <| \() -> Expect.equal { model | transfer = { transfer | quantity = "0.1" } , quantityValidation = ValidQuantity } (Tuple.first (setTransferMessageField Quantity "0.1" model balance) ) , test "Memo" <| \() -> Expect.equal { model | transfer = { transfer | memo = "newMemo" } , quantityValidation = ValidQuantity } (Tuple.first (setTransferMessageField Memo "newMemo" model balance) ) ] ) , describe "validation" (let { transfer } = model in [ describe "validateToField" [ test "AccountToBeVerified" <| \() -> Expect.equal { model | transfer = { transfer | to = "eosio.ram" } , accountValidation = AccountToBeVerified , isFormValid = False } (Tuple.first (validateToField { model | transfer = { transfer | to = "eosio.ram" } } NotSent ) ) , test "ValidAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "eosio.ram" } , isFormValid = True , accountValidation = ValidAccount } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "eosio.ram" } } Succeed ) , test "InexistentAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "eosio.ran" } , accountValidation = InexistentAccount , isFormValid = False } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "eosio.ran" } } Fail ) , test "InvalidAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "INVALID" } , accountValidation = InvalidAccount , isFormValid = False } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "INVALID" } } Fail ) , test "EmptyAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "" } , accountValidation = EmptyAccount , isFormValid = False } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "" } } Fail ) ] ] ) ]
true
module Test.Component.Main.Page.Transfer exposing ( balance , model , tests ) import Component.Main.Page.Transfer exposing (..) import Data.Table import Dict import Expect import Http import Json.Encode as JE import Port import Test exposing (..) import Util.Token exposing (Token) import Util.Validation exposing ( AccountStatus(..) , MemoStatus(..) , QuantityStatus(..) , VerificationRequestStatus(..) ) addToken : Token addToken = { name = "AdderalCoin" , symbol = "ADD" , contractAccount = "PI:KEY:<KEY>END_PI" , precision = 4 } blackToken : Token blackToken = { name = "eosBLACK" , symbol = "BLACK" , contractAccount = "eosblackteam" , precision = 4 } model : Model model = { accountValidation = ValidAccount , quantityValidation = ValidQuantity , memoValidation = ValidMemo , isFormValid = True , transfer = { from = "from" , to = "to" , quantity = "3.0" , memo = "memo" } , possessingTokens = Dict.fromList [ ( "ADD", ( addToken, "3.0123 ADD" ) ) ] , currentSymbol = "ADD" , modalOpened = True , tokensLoaded = False , tokenSearchInput = "" } balance : Float balance = 300.0 tests : Test tests = let submitActionTest = let expectedJson = JE.object [ ( "actionName", JE.string "transfer" ) , ( "actions" , JE.list [ JE.object [ ( "account", JE.string "eosPI:KEY:<KEY>END_PI" ) , ( "action", JE.string "transfer" ) , ( "payload" , JE.object [ ( "from", JE.string "from" ) , ( "to", JE.string "to" ) , ( "quantity", JE.string "3.0000 ADD" ) , ( "memo", JE.string "memo" ) ] ) ] ] ) ] in test "SubmitAction" <| \() -> Expect.equal ( model, Port.pushAction expectedJson ) (update SubmitAction model "from" 300.0) switchTokenTest = let newToken = { name = "PI:KEY:<KEY>END_PI" , symbol = "BLACK" , contractAccount = "PI:KEY:<KEY>END_PI" , precision = 4 } in test "SwitchToken" <| \() -> Expect.equal { model | modalOpened = False , transfer = { from = "", to = "", quantity = "", memo = "" } , accountValidation = EmptyAccount , quantityValidation = EmptyQuantity , memoValidation = EmptyMemo , currentSymbol = "BLACK" } (Tuple.first (update (SwitchToken "BLACK") model "from" 300.0 ) ) onFetchTableRowsTest = let addBalance = Data.Table.Accounts { balance = "30.0000 ADD" } blackBalance = Data.Table.Accounts { balance = "40.0000 BLACK" } bchBalance = Data.Table.Accounts { balance = "1.0000 BCH" } in describe "OnFetchTableRows" [ test "Ok with empty rows" <| \() -> Expect.equal ( model, Cmd.none ) (update (OnFetchTableRows (Ok [])) model "from" 300.0) , test "Ok with matched symbol" <| \() -> Expect.equal ( { model | possessingTokens = Dict.insert "BLACK" ( blackToken, "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI" ) model.possessingTokens } , Cmd.none ) (update (OnFetchTableRows (Ok [ blackBalance ])) model "from" 300.0) , test "Ok with existing symbol" <| \() -> Expect.equal ( { model | possessingTokens = Dict.insert "ADD" ( addToken, "PI:PASSWORD:<PASSWORD>END_PI" ) model.possessingTokens } , Cmd.none ) (update (OnFetchTableRows (Ok [ addBalance ])) model "from" 300.0) , test "Ok with no matched symbol" <| \() -> Expect.equal ( model, Cmd.none ) (update (OnFetchTableRows (Ok [ bchBalance ])) model "from" 300.0) , test "Err" <| \() -> Expect.equal ( model, Cmd.none ) (update (OnFetchTableRows (Err Http.Timeout)) model "from" 300.0) ] in describe "Transfer page module" [ describe "update" [ submitActionTest , switchTokenTest , onFetchTableRowsTest ] , describe "setTransferMessageField" (let { transfer } = model in [ test "To" <| \() -> Expect.equal { model | transfer = { transfer | to = "newto" } , accountValidation = AccountToBeVerified , isFormValid = False } (Tuple.first (setTransferMessageField To "newto" model balance)) , test "Quantity" <| \() -> Expect.equal { model | transfer = { transfer | quantity = "0.1" } , quantityValidation = ValidQuantity } (Tuple.first (setTransferMessageField Quantity "0.1" model balance) ) , test "Memo" <| \() -> Expect.equal { model | transfer = { transfer | memo = "newMemo" } , quantityValidation = ValidQuantity } (Tuple.first (setTransferMessageField Memo "newMemo" model balance) ) ] ) , describe "validation" (let { transfer } = model in [ describe "validateToField" [ test "AccountToBeVerified" <| \() -> Expect.equal { model | transfer = { transfer | to = "eosio.ram" } , accountValidation = AccountToBeVerified , isFormValid = False } (Tuple.first (validateToField { model | transfer = { transfer | to = "eosio.ram" } } NotSent ) ) , test "ValidAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "eosio.ram" } , isFormValid = True , accountValidation = ValidAccount } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "eosio.ram" } } Succeed ) , test "InexistentAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "eosio.ran" } , accountValidation = InexistentAccount , isFormValid = False } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "eosio.ran" } } Fail ) , test "InvalidAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "INVALID" } , accountValidation = InvalidAccount , isFormValid = False } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "INVALID" } } Fail ) , test "EmptyAccount" <| \() -> Expect.equal ( { model | transfer = { transfer | to = "" } , accountValidation = EmptyAccount , isFormValid = False } , Cmd.none ) (validateToField { model | transfer = { transfer | to = "" } } Fail ) ] ] ) ]
elm
[ { "context": "tml Msg\ncopyright =\n block Right [ text \"© 2018 Anton Shvein aka war1and\" ]\n\n\nblock : Align -> List (Html Msg)", "end": 1617, "score": 0.9998663664, "start": 1605, "tag": "NAME", "value": "Anton Shvein" }, { "context": " =\n block Right [ text \"© 2018 Anton Shvein aka war1and\" ]\n\n\nblock : Align -> List (Html Msg) -> Html Msg", "end": 1629, "score": 0.9664791226, "start": 1622, "tag": "USERNAME", "value": "war1and" } ]
View.elm
Ealhad/elm-screen-router
0
module View exposing (view) import Html exposing (..) import Html.Attributes exposing (..) import Model exposing (Model) import Update exposing (Msg) import Router exposing (Screen(..)) import First.View import Second.View import Third.View type Align = Left | Right | Center view model = case model.screen of Main -> div [ style [ ( "border", "#000 1px solid" ) ] ] [ firstLink , secondLink , thirdLink , copyright ] First -> wrapScreen Update.FirstEvent <| First.View.view model Second -> wrapScreen Update.SecondEvent <| Second.View.view model Third -> wrapScreen Update.ThirdEvent <| Third.View.view model logo : Html Msg logo = block Center [ img [ src "/static/img/logo_full.png" , style [ ( "width", "100%" ) ] ] [] ] backLink : Html Msg backLink = block Left [ a [ href <| Router.url Main ] [ text "< Back" ] ] firstLink : Html Msg firstLink = block Center [ a [ href <| Router.url First ] [ text "First" ] ] thirdLink : Html Msg thirdLink = block Center [ a [ href <| Router.url Third ] [ text "Third" ] ] secondLink : Html Msg secondLink = block Center [ a [ href <| Router.url Second ] [ text "Second" ] ] copyright : Html Msg copyright = block Right [ text "© 2018 Anton Shvein aka war1and" ] block : Align -> List (Html Msg) -> Html Msg block align elements = let textAlign = case align of Left -> "left" Right -> "right" Center -> "center" in div [ style [ ( "width", "80%" ) , ( "margin", "10%" ) , ( "text-align", textAlign ) ] ] elements wrapScreen : (msg -> Msg) -> Html msg -> Html Msg wrapScreen = Html.map
270
module View exposing (view) import Html exposing (..) import Html.Attributes exposing (..) import Model exposing (Model) import Update exposing (Msg) import Router exposing (Screen(..)) import First.View import Second.View import Third.View type Align = Left | Right | Center view model = case model.screen of Main -> div [ style [ ( "border", "#000 1px solid" ) ] ] [ firstLink , secondLink , thirdLink , copyright ] First -> wrapScreen Update.FirstEvent <| First.View.view model Second -> wrapScreen Update.SecondEvent <| Second.View.view model Third -> wrapScreen Update.ThirdEvent <| Third.View.view model logo : Html Msg logo = block Center [ img [ src "/static/img/logo_full.png" , style [ ( "width", "100%" ) ] ] [] ] backLink : Html Msg backLink = block Left [ a [ href <| Router.url Main ] [ text "< Back" ] ] firstLink : Html Msg firstLink = block Center [ a [ href <| Router.url First ] [ text "First" ] ] thirdLink : Html Msg thirdLink = block Center [ a [ href <| Router.url Third ] [ text "Third" ] ] secondLink : Html Msg secondLink = block Center [ a [ href <| Router.url Second ] [ text "Second" ] ] copyright : Html Msg copyright = block Right [ text "© 2018 <NAME> aka war1and" ] block : Align -> List (Html Msg) -> Html Msg block align elements = let textAlign = case align of Left -> "left" Right -> "right" Center -> "center" in div [ style [ ( "width", "80%" ) , ( "margin", "10%" ) , ( "text-align", textAlign ) ] ] elements wrapScreen : (msg -> Msg) -> Html msg -> Html Msg wrapScreen = Html.map
true
module View exposing (view) import Html exposing (..) import Html.Attributes exposing (..) import Model exposing (Model) import Update exposing (Msg) import Router exposing (Screen(..)) import First.View import Second.View import Third.View type Align = Left | Right | Center view model = case model.screen of Main -> div [ style [ ( "border", "#000 1px solid" ) ] ] [ firstLink , secondLink , thirdLink , copyright ] First -> wrapScreen Update.FirstEvent <| First.View.view model Second -> wrapScreen Update.SecondEvent <| Second.View.view model Third -> wrapScreen Update.ThirdEvent <| Third.View.view model logo : Html Msg logo = block Center [ img [ src "/static/img/logo_full.png" , style [ ( "width", "100%" ) ] ] [] ] backLink : Html Msg backLink = block Left [ a [ href <| Router.url Main ] [ text "< Back" ] ] firstLink : Html Msg firstLink = block Center [ a [ href <| Router.url First ] [ text "First" ] ] thirdLink : Html Msg thirdLink = block Center [ a [ href <| Router.url Third ] [ text "Third" ] ] secondLink : Html Msg secondLink = block Center [ a [ href <| Router.url Second ] [ text "Second" ] ] copyright : Html Msg copyright = block Right [ text "© 2018 PI:NAME:<NAME>END_PI aka war1and" ] block : Align -> List (Html Msg) -> Html Msg block align elements = let textAlign = case align of Left -> "left" Right -> "right" Center -> "center" in div [ style [ ( "width", "80%" ) , ( "margin", "10%" ) , ( "text-align", textAlign ) ] ] elements wrapScreen : (msg -> Msg) -> Html msg -> Html Msg wrapScreen = Html.map
elm
[ { "context": "{-\nCopyright 2020 Morgan Stanley\n\nLicensed under the Apache License, Version 2.0 (", "end": 32, "score": 0.9998018146, "start": 18, "tag": "NAME", "value": "Morgan Stanley" } ]
src/Morphir/Sample/Apps/Upstream/Trading/App.elm
maoo/morphir-examples
0
{- 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 Morphir.Sample.Apps.Upstream.Trading.App exposing (..) {-| This is a stub for an external Trading app. Normally this would live in an external library but it's included for simplicity. The application's API is exposed here and in the external library the implementation would be included as well. -} import Dict exposing (Dict) import Morphir.Sample.Apps.Shared.Product as Product import Morphir.Sample.Apps.Shared.Client as Client import Morphir.Sample.Apps.Shared.Rate exposing (Rate) type alias DealID = String type alias Loan = { productID : Product.ID , borrower : Client.ID , quantity : Int , rate : Rate } type alias Borrow = { productID : Product.ID , lender : Client.ID , quantity : Int , rate : Rate } type alias State = { loans : Dict DealID Loan , borrows : Dict DealID Borrow }
50234
{- 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 Morphir.Sample.Apps.Upstream.Trading.App exposing (..) {-| This is a stub for an external Trading app. Normally this would live in an external library but it's included for simplicity. The application's API is exposed here and in the external library the implementation would be included as well. -} import Dict exposing (Dict) import Morphir.Sample.Apps.Shared.Product as Product import Morphir.Sample.Apps.Shared.Client as Client import Morphir.Sample.Apps.Shared.Rate exposing (Rate) type alias DealID = String type alias Loan = { productID : Product.ID , borrower : Client.ID , quantity : Int , rate : Rate } type alias Borrow = { productID : Product.ID , lender : Client.ID , quantity : Int , rate : Rate } type alias State = { loans : Dict DealID Loan , borrows : Dict DealID Borrow }
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 Morphir.Sample.Apps.Upstream.Trading.App exposing (..) {-| This is a stub for an external Trading app. Normally this would live in an external library but it's included for simplicity. The application's API is exposed here and in the external library the implementation would be included as well. -} import Dict exposing (Dict) import Morphir.Sample.Apps.Shared.Product as Product import Morphir.Sample.Apps.Shared.Client as Client import Morphir.Sample.Apps.Shared.Rate exposing (Rate) type alias DealID = String type alias Loan = { productID : Product.ID , borrower : Client.ID , quantity : Int , rate : Rate } type alias Borrow = { productID : Product.ID , lender : Client.ID , quantity : Int , rate : Rate } type alias State = { loans : Dict DealID Loan , borrows : Dict DealID Borrow }
elm
[ { "context": " , creator = name\n , player ", "end": 13303, "score": 0.9619118571, "start": 13299, "tag": "NAME", "value": "name" } ]
src/Agog/Server/Server.elm
billstclair/agog
0
port module Agog.Server.Server exposing (main) import Agog.EncodeDecode as ED import Agog.Interface as Interface import Agog.Types as Types exposing ( GameState , Message(..) , Participant(..) , Player , PlayerNames , PublicType(..) , ServerState , SubscriptionSet ) import List.Extra as LE import Set exposing (Set) import Time exposing (Posix) import WebSocketFramework.Server exposing ( Msg , ServerMessageSender , Socket , UserFunctions , program , verbose ) import WebSocketFramework.ServerInterface as ServerInterface import WebSocketFramework.Types exposing ( EncodeDecode , Error , ErrorKind(..) , GameId , InputPort , OutputPort ) type alias Model = WebSocketFramework.Server.Model ServerModel Message GameState Participant type alias ServerModel = () serverModel : ServerModel serverModel = () tos : Int -> String tos x = String.fromInt x errorWrapper : Error Message -> Message errorWrapper { kind, description, message } = case kind of JsonParseError -> let err = case message of Err msg -> msg Ok msg -> Debug.toString msg in ErrorRsp { request = description , text = "JSON parser error: " ++ err } _ -> ErrorRsp { request = "" , text = Debug.toString message } encodeDecode : EncodeDecode Message encodeDecode = { encoder = ED.messageEncoder , decoder = ED.messageDecoder , errorWrapper = Just errorWrapper } {-| Two weeks -} deathRowDuration : Int deathRowDuration = 14 * 24 * 60 * 60 * 1000 messageSender : ServerMessageSender ServerModel Message GameState Participant messageSender mdl socket state request response = let time = WebSocketFramework.Server.getTime mdl state2 = let gs = case state.state of Nothing -> Interface.emptyGameState <| PlayerNames "" "" Just gs2 -> gs2 private = gs.private in if private.startTime /= Nothing then state else let verb = WebSocketFramework.Server.verbose mdl verbose = if verb then Debug.log "verbose" verb else verb in { state | state = Just { gs | private = { private | startTime = Just time , verbose = Just verbose } } } model = if WebSocketFramework.Server.getDeathRowDuration mdl == deathRowDuration then mdl else WebSocketFramework.Server.setDeathRowDuration mdl deathRowDuration ( state3, cmd3 ) = case request of PublicGamesReq { subscribe, forName } -> ( handlePublicGamesSubscription subscribe forName socket state2 , Cmd.none ) StatisticsReq { subscribe } -> ( handleStatisticsSubscription subscribe socket state2 , Cmd.none ) _ -> case response of LeaveRsp { gameid, participant } -> let ( model2, cmd2 ) = case participant of PlayingParticipant _ -> gamesDeleter model [ gameid ] state2 _ -> ( model, Cmd.none ) in ( WebSocketFramework.Server.getState model2, cmd2 ) _ -> ( state2, Cmd.none ) ( state4, cmd4 ) = computeStatisticsSubscriberSends time state3 cmd5 = case response of JoinRsp { gameid } -> sendToPublicGameSubscribers gameid state PlayRsp { gameid } -> sendToPublicGameSubscribers gameid state _ -> Cmd.none sender = case request of UpdateReq _ -> sendToOne PublicGamesReq { subscribe, forName } -> sendToOne _ -> case response of NewRsp { gameid } -> sendNewRsp model state4 JoinRsp { gameid } -> sendJoinRsp model state4 AnotherGameRsp record -> \_ _ -> Cmd.batch [ sendToOne response socket , sendToOthers model (AnotherGameRsp { record | player = Types.otherPlayer record.player } ) socket ] _ -> sendToAll model in ( WebSocketFramework.Server.setState model state4 , Cmd.batch [ cmd3, cmd4, cmd5, sender response socket ] ) sendToPublicGameSubscribers : GameId -> ServerState -> Cmd Msg sendToPublicGameSubscribers gameid state = case LE.find (.gameid >> (==) gameid) state.publicGames of Nothing -> Cmd.none Just publicGame -> case state.state of Nothing -> Cmd.none Just gs -> case ED.frameworkToPublicGame publicGame of Nothing -> Cmd.none Just pg -> let pgap = Interface.publicGameAddPlayers state pg notification = sendToOne (PublicGamesUpdateRsp { added = [ pgap ] , removed = [ publicGame.gameid ] } ) in gs.private.subscribers |> Set.toList |> List.map (\( sock, _ ) -> notification sock ) |> Cmd.batch getStatisticsTimes : Maybe Int -> ServerState -> ( ServerState, Maybe Int, Maybe Int ) getStatisticsTimes newUpdateTime state = case state.state of Nothing -> -- Can't happen ( state, Nothing, Nothing ) Just gs -> let private = gs.private newPrivate = case newUpdateTime of Nothing -> private _ -> { private | updateTime = newUpdateTime } newState = case newUpdateTime of Nothing -> state _ -> { state | state = Just { gs | private = newPrivate } } in ( newState, newPrivate.startTime, newPrivate.updateTime ) computeStatisticsSubscriberSends : Int -> ServerState -> ( ServerState, Cmd Msg ) computeStatisticsSubscriberSends time state = if not <| Interface.getStatisticsChanged state then ( state, Cmd.none ) else let ( state2, startTime, updateTime ) = getStatisticsTimes (Just time) state message = StatisticsRsp { statistics = state.statistics , startTime = startTime , updateTime = updateTime } in ( Interface.setStatisticsChanged False state2 , (List.map (sendToOne message) <| getStatisticsSubscribers state) |> Cmd.batch ) getStatisticsSubscribers : ServerState -> List Socket getStatisticsSubscribers state = case state.state of Nothing -> [] Just gameState -> gameState.private.statisticsSubscribers |> Set.toList handleStatisticsSubscription : Bool -> String -> ServerState -> ServerState handleStatisticsSubscription subscribe socket state = let gs = case state.state of Nothing -> Interface.emptyGameState <| PlayerNames "" "" Just gameState -> gameState private = gs.private subscribers = private.statisticsSubscribers in { state | state = Just { gs | private = { private | statisticsSubscribers = if subscribe then Set.insert socket subscribers else Set.filter ((/=) socket) subscribers } } } handlePublicGamesSubscription : Bool -> String -> Socket -> ServerState -> ServerState handlePublicGamesSubscription subscribe forName socket state = let gs = case state.state of Nothing -> Interface.emptyGameState <| PlayerNames "" "" Just gameState -> gameState private = gs.private subscribers = Set.filter (\( sock, _ ) -> socket /= sock) private.subscribers in { state | state = Just { gs | private = { private | subscribers = if subscribe then Set.insert ( socket, forName ) subscribers else subscribers } } } sendToOne : Message -> Socket -> Cmd Msg sendToOne response socket = WebSocketFramework.Server.sendToOne ED.messageEncoder response outputPort socket sendToAll : Model -> Message -> Socket -> Cmd Msg sendToAll model response socket = case Types.messageToGameid response of Nothing -> sendToOne response socket Just gameid -> WebSocketFramework.Server.sendToAll gameid model ED.messageEncoder response sendToOthers : Model -> Message -> Socket -> Cmd Msg sendToOthers model response socket = case Types.messageToGameid response of Nothing -> Cmd.none Just gameid -> WebSocketFramework.Server.sendToOthers gameid socket model ED.messageEncoder response sendNewRsp : Model -> ServerState -> Message -> Socket -> Cmd Msg sendNewRsp model state response socket = -- Need to send new public game to subscribers. let notifications = case state.state of Nothing -> [] Just gs -> case response of NewRsp { gameid, player, name, publicType, gameState } -> if publicType == NotPublic then [] else let publicGame = { gameid = gameid , creator = name , player = player , forName = case publicType of PublicFor for -> Just for _ -> Nothing } publicGameAndPlayers = { publicGame = publicGame , players = gameState.players , watchers = 0 , moves = 0 , startTime = Types.posixZero , endTime = Types.posixZero } notification = sendToOne (PublicGamesUpdateRsp { added = [ publicGameAndPlayers ] , removed = [] } ) in gs.private.subscribers |> Set.toList |> List.filterMap (\( sock, forName ) -> case publicType of EntirelyPublic -> Just <| notification sock PublicFor for -> if forName == for then Just <| notification sock else Nothing _ -> Nothing ) _ -> [] in Cmd.batch <| sendToOne response socket :: notifications removedGameNotifications : GameId -> ServerState -> Cmd Msg removedGameNotifications gameid state = case state.state of Nothing -> Cmd.none Just gs -> let notification = sendToOne <| PublicGamesUpdateRsp { added = [] , removed = [ gameid ] } in gs.private.subscribers |> Set.toList |> List.map (\( sock, _ ) -> notification sock ) |> Cmd.batch sendJoinRsp : Model -> ServerState -> Message -> Socket -> Cmd Msg sendJoinRsp model state response socket = let notifications = case response of JoinRsp { gameid } -> removedGameNotifications gameid state _ -> Cmd.none in [ notifications , case response of JoinRsp record -> [ sendToOne response socket , sendToOthers model (JoinRsp { record | playerid = Nothing }) socket ] |> Cmd.batch _ -> sendToAll model response socket ] |> Cmd.batch gamesDeleter : Model -> List GameId -> ServerState -> ( Model, Cmd Msg ) gamesDeleter model gameids state = case state.state of Nothing -> ( model, Cmd.none ) Just gs -> let private = gs.private subscribers = private.subscribers loop : GameId -> ( SubscriptionSet, Cmd Msg ) -> ( SubscriptionSet, Cmd Msg ) loop gameid ( subscribers2, notifications ) = let inner : Socket -> ( SubscriptionSet, Cmd Msg ) -> ( SubscriptionSet, Cmd Msg ) inner socket ( subscribers3, notifications2 ) = ( Set.filter (\( sock, _ ) -> sock /= socket) subscribers3 , [ removedGameNotifications gameid state , notifications2 ] |> Cmd.batch ) sockets = WebSocketFramework.Server.otherSockets gameid "" model in List.foldl inner ( subscribers2, notifications ) sockets ( subscribers4, notifications3 ) = List.foldl loop ( subscribers, Cmd.none ) gameids state2 = { state | state = Just { gs | private = { private | subscribers = subscribers4 } } } in ( WebSocketFramework.Server.setState model state2 , notifications3 ) userFunctions : UserFunctions ServerModel Message GameState Participant userFunctions = { encodeDecode = encodeDecode , messageProcessor = Interface.messageProcessor , messageSender = messageSender , messageToGameid = Just Types.messageToGameid , messageToPlayerid = Just Types.messageToPlayerid , autoDeleteGame = Just (\gameid serverState -> False) , gamesDeleter = Just gamesDeleter , playersDeleter = Nothing , inputPort = inputPort , outputPort = outputPort } {-| Debugging version -} messageProcessor : ServerState -> Message -> ( ServerState, Maybe Message ) messageProcessor state message = Interface.messageProcessor (Debug.log "messageProcessor" state) (Debug.log " message" message) |> Debug.log " output" main = program serverModel userFunctions Nothing -- PORTS port inputPort : InputPort msg port outputPort : OutputPort msg
47599
port module Agog.Server.Server exposing (main) import Agog.EncodeDecode as ED import Agog.Interface as Interface import Agog.Types as Types exposing ( GameState , Message(..) , Participant(..) , Player , PlayerNames , PublicType(..) , ServerState , SubscriptionSet ) import List.Extra as LE import Set exposing (Set) import Time exposing (Posix) import WebSocketFramework.Server exposing ( Msg , ServerMessageSender , Socket , UserFunctions , program , verbose ) import WebSocketFramework.ServerInterface as ServerInterface import WebSocketFramework.Types exposing ( EncodeDecode , Error , ErrorKind(..) , GameId , InputPort , OutputPort ) type alias Model = WebSocketFramework.Server.Model ServerModel Message GameState Participant type alias ServerModel = () serverModel : ServerModel serverModel = () tos : Int -> String tos x = String.fromInt x errorWrapper : Error Message -> Message errorWrapper { kind, description, message } = case kind of JsonParseError -> let err = case message of Err msg -> msg Ok msg -> Debug.toString msg in ErrorRsp { request = description , text = "JSON parser error: " ++ err } _ -> ErrorRsp { request = "" , text = Debug.toString message } encodeDecode : EncodeDecode Message encodeDecode = { encoder = ED.messageEncoder , decoder = ED.messageDecoder , errorWrapper = Just errorWrapper } {-| Two weeks -} deathRowDuration : Int deathRowDuration = 14 * 24 * 60 * 60 * 1000 messageSender : ServerMessageSender ServerModel Message GameState Participant messageSender mdl socket state request response = let time = WebSocketFramework.Server.getTime mdl state2 = let gs = case state.state of Nothing -> Interface.emptyGameState <| PlayerNames "" "" Just gs2 -> gs2 private = gs.private in if private.startTime /= Nothing then state else let verb = WebSocketFramework.Server.verbose mdl verbose = if verb then Debug.log "verbose" verb else verb in { state | state = Just { gs | private = { private | startTime = Just time , verbose = Just verbose } } } model = if WebSocketFramework.Server.getDeathRowDuration mdl == deathRowDuration then mdl else WebSocketFramework.Server.setDeathRowDuration mdl deathRowDuration ( state3, cmd3 ) = case request of PublicGamesReq { subscribe, forName } -> ( handlePublicGamesSubscription subscribe forName socket state2 , Cmd.none ) StatisticsReq { subscribe } -> ( handleStatisticsSubscription subscribe socket state2 , Cmd.none ) _ -> case response of LeaveRsp { gameid, participant } -> let ( model2, cmd2 ) = case participant of PlayingParticipant _ -> gamesDeleter model [ gameid ] state2 _ -> ( model, Cmd.none ) in ( WebSocketFramework.Server.getState model2, cmd2 ) _ -> ( state2, Cmd.none ) ( state4, cmd4 ) = computeStatisticsSubscriberSends time state3 cmd5 = case response of JoinRsp { gameid } -> sendToPublicGameSubscribers gameid state PlayRsp { gameid } -> sendToPublicGameSubscribers gameid state _ -> Cmd.none sender = case request of UpdateReq _ -> sendToOne PublicGamesReq { subscribe, forName } -> sendToOne _ -> case response of NewRsp { gameid } -> sendNewRsp model state4 JoinRsp { gameid } -> sendJoinRsp model state4 AnotherGameRsp record -> \_ _ -> Cmd.batch [ sendToOne response socket , sendToOthers model (AnotherGameRsp { record | player = Types.otherPlayer record.player } ) socket ] _ -> sendToAll model in ( WebSocketFramework.Server.setState model state4 , Cmd.batch [ cmd3, cmd4, cmd5, sender response socket ] ) sendToPublicGameSubscribers : GameId -> ServerState -> Cmd Msg sendToPublicGameSubscribers gameid state = case LE.find (.gameid >> (==) gameid) state.publicGames of Nothing -> Cmd.none Just publicGame -> case state.state of Nothing -> Cmd.none Just gs -> case ED.frameworkToPublicGame publicGame of Nothing -> Cmd.none Just pg -> let pgap = Interface.publicGameAddPlayers state pg notification = sendToOne (PublicGamesUpdateRsp { added = [ pgap ] , removed = [ publicGame.gameid ] } ) in gs.private.subscribers |> Set.toList |> List.map (\( sock, _ ) -> notification sock ) |> Cmd.batch getStatisticsTimes : Maybe Int -> ServerState -> ( ServerState, Maybe Int, Maybe Int ) getStatisticsTimes newUpdateTime state = case state.state of Nothing -> -- Can't happen ( state, Nothing, Nothing ) Just gs -> let private = gs.private newPrivate = case newUpdateTime of Nothing -> private _ -> { private | updateTime = newUpdateTime } newState = case newUpdateTime of Nothing -> state _ -> { state | state = Just { gs | private = newPrivate } } in ( newState, newPrivate.startTime, newPrivate.updateTime ) computeStatisticsSubscriberSends : Int -> ServerState -> ( ServerState, Cmd Msg ) computeStatisticsSubscriberSends time state = if not <| Interface.getStatisticsChanged state then ( state, Cmd.none ) else let ( state2, startTime, updateTime ) = getStatisticsTimes (Just time) state message = StatisticsRsp { statistics = state.statistics , startTime = startTime , updateTime = updateTime } in ( Interface.setStatisticsChanged False state2 , (List.map (sendToOne message) <| getStatisticsSubscribers state) |> Cmd.batch ) getStatisticsSubscribers : ServerState -> List Socket getStatisticsSubscribers state = case state.state of Nothing -> [] Just gameState -> gameState.private.statisticsSubscribers |> Set.toList handleStatisticsSubscription : Bool -> String -> ServerState -> ServerState handleStatisticsSubscription subscribe socket state = let gs = case state.state of Nothing -> Interface.emptyGameState <| PlayerNames "" "" Just gameState -> gameState private = gs.private subscribers = private.statisticsSubscribers in { state | state = Just { gs | private = { private | statisticsSubscribers = if subscribe then Set.insert socket subscribers else Set.filter ((/=) socket) subscribers } } } handlePublicGamesSubscription : Bool -> String -> Socket -> ServerState -> ServerState handlePublicGamesSubscription subscribe forName socket state = let gs = case state.state of Nothing -> Interface.emptyGameState <| PlayerNames "" "" Just gameState -> gameState private = gs.private subscribers = Set.filter (\( sock, _ ) -> socket /= sock) private.subscribers in { state | state = Just { gs | private = { private | subscribers = if subscribe then Set.insert ( socket, forName ) subscribers else subscribers } } } sendToOne : Message -> Socket -> Cmd Msg sendToOne response socket = WebSocketFramework.Server.sendToOne ED.messageEncoder response outputPort socket sendToAll : Model -> Message -> Socket -> Cmd Msg sendToAll model response socket = case Types.messageToGameid response of Nothing -> sendToOne response socket Just gameid -> WebSocketFramework.Server.sendToAll gameid model ED.messageEncoder response sendToOthers : Model -> Message -> Socket -> Cmd Msg sendToOthers model response socket = case Types.messageToGameid response of Nothing -> Cmd.none Just gameid -> WebSocketFramework.Server.sendToOthers gameid socket model ED.messageEncoder response sendNewRsp : Model -> ServerState -> Message -> Socket -> Cmd Msg sendNewRsp model state response socket = -- Need to send new public game to subscribers. let notifications = case state.state of Nothing -> [] Just gs -> case response of NewRsp { gameid, player, name, publicType, gameState } -> if publicType == NotPublic then [] else let publicGame = { gameid = gameid , creator = <NAME> , player = player , forName = case publicType of PublicFor for -> Just for _ -> Nothing } publicGameAndPlayers = { publicGame = publicGame , players = gameState.players , watchers = 0 , moves = 0 , startTime = Types.posixZero , endTime = Types.posixZero } notification = sendToOne (PublicGamesUpdateRsp { added = [ publicGameAndPlayers ] , removed = [] } ) in gs.private.subscribers |> Set.toList |> List.filterMap (\( sock, forName ) -> case publicType of EntirelyPublic -> Just <| notification sock PublicFor for -> if forName == for then Just <| notification sock else Nothing _ -> Nothing ) _ -> [] in Cmd.batch <| sendToOne response socket :: notifications removedGameNotifications : GameId -> ServerState -> Cmd Msg removedGameNotifications gameid state = case state.state of Nothing -> Cmd.none Just gs -> let notification = sendToOne <| PublicGamesUpdateRsp { added = [] , removed = [ gameid ] } in gs.private.subscribers |> Set.toList |> List.map (\( sock, _ ) -> notification sock ) |> Cmd.batch sendJoinRsp : Model -> ServerState -> Message -> Socket -> Cmd Msg sendJoinRsp model state response socket = let notifications = case response of JoinRsp { gameid } -> removedGameNotifications gameid state _ -> Cmd.none in [ notifications , case response of JoinRsp record -> [ sendToOne response socket , sendToOthers model (JoinRsp { record | playerid = Nothing }) socket ] |> Cmd.batch _ -> sendToAll model response socket ] |> Cmd.batch gamesDeleter : Model -> List GameId -> ServerState -> ( Model, Cmd Msg ) gamesDeleter model gameids state = case state.state of Nothing -> ( model, Cmd.none ) Just gs -> let private = gs.private subscribers = private.subscribers loop : GameId -> ( SubscriptionSet, Cmd Msg ) -> ( SubscriptionSet, Cmd Msg ) loop gameid ( subscribers2, notifications ) = let inner : Socket -> ( SubscriptionSet, Cmd Msg ) -> ( SubscriptionSet, Cmd Msg ) inner socket ( subscribers3, notifications2 ) = ( Set.filter (\( sock, _ ) -> sock /= socket) subscribers3 , [ removedGameNotifications gameid state , notifications2 ] |> Cmd.batch ) sockets = WebSocketFramework.Server.otherSockets gameid "" model in List.foldl inner ( subscribers2, notifications ) sockets ( subscribers4, notifications3 ) = List.foldl loop ( subscribers, Cmd.none ) gameids state2 = { state | state = Just { gs | private = { private | subscribers = subscribers4 } } } in ( WebSocketFramework.Server.setState model state2 , notifications3 ) userFunctions : UserFunctions ServerModel Message GameState Participant userFunctions = { encodeDecode = encodeDecode , messageProcessor = Interface.messageProcessor , messageSender = messageSender , messageToGameid = Just Types.messageToGameid , messageToPlayerid = Just Types.messageToPlayerid , autoDeleteGame = Just (\gameid serverState -> False) , gamesDeleter = Just gamesDeleter , playersDeleter = Nothing , inputPort = inputPort , outputPort = outputPort } {-| Debugging version -} messageProcessor : ServerState -> Message -> ( ServerState, Maybe Message ) messageProcessor state message = Interface.messageProcessor (Debug.log "messageProcessor" state) (Debug.log " message" message) |> Debug.log " output" main = program serverModel userFunctions Nothing -- PORTS port inputPort : InputPort msg port outputPort : OutputPort msg
true
port module Agog.Server.Server exposing (main) import Agog.EncodeDecode as ED import Agog.Interface as Interface import Agog.Types as Types exposing ( GameState , Message(..) , Participant(..) , Player , PlayerNames , PublicType(..) , ServerState , SubscriptionSet ) import List.Extra as LE import Set exposing (Set) import Time exposing (Posix) import WebSocketFramework.Server exposing ( Msg , ServerMessageSender , Socket , UserFunctions , program , verbose ) import WebSocketFramework.ServerInterface as ServerInterface import WebSocketFramework.Types exposing ( EncodeDecode , Error , ErrorKind(..) , GameId , InputPort , OutputPort ) type alias Model = WebSocketFramework.Server.Model ServerModel Message GameState Participant type alias ServerModel = () serverModel : ServerModel serverModel = () tos : Int -> String tos x = String.fromInt x errorWrapper : Error Message -> Message errorWrapper { kind, description, message } = case kind of JsonParseError -> let err = case message of Err msg -> msg Ok msg -> Debug.toString msg in ErrorRsp { request = description , text = "JSON parser error: " ++ err } _ -> ErrorRsp { request = "" , text = Debug.toString message } encodeDecode : EncodeDecode Message encodeDecode = { encoder = ED.messageEncoder , decoder = ED.messageDecoder , errorWrapper = Just errorWrapper } {-| Two weeks -} deathRowDuration : Int deathRowDuration = 14 * 24 * 60 * 60 * 1000 messageSender : ServerMessageSender ServerModel Message GameState Participant messageSender mdl socket state request response = let time = WebSocketFramework.Server.getTime mdl state2 = let gs = case state.state of Nothing -> Interface.emptyGameState <| PlayerNames "" "" Just gs2 -> gs2 private = gs.private in if private.startTime /= Nothing then state else let verb = WebSocketFramework.Server.verbose mdl verbose = if verb then Debug.log "verbose" verb else verb in { state | state = Just { gs | private = { private | startTime = Just time , verbose = Just verbose } } } model = if WebSocketFramework.Server.getDeathRowDuration mdl == deathRowDuration then mdl else WebSocketFramework.Server.setDeathRowDuration mdl deathRowDuration ( state3, cmd3 ) = case request of PublicGamesReq { subscribe, forName } -> ( handlePublicGamesSubscription subscribe forName socket state2 , Cmd.none ) StatisticsReq { subscribe } -> ( handleStatisticsSubscription subscribe socket state2 , Cmd.none ) _ -> case response of LeaveRsp { gameid, participant } -> let ( model2, cmd2 ) = case participant of PlayingParticipant _ -> gamesDeleter model [ gameid ] state2 _ -> ( model, Cmd.none ) in ( WebSocketFramework.Server.getState model2, cmd2 ) _ -> ( state2, Cmd.none ) ( state4, cmd4 ) = computeStatisticsSubscriberSends time state3 cmd5 = case response of JoinRsp { gameid } -> sendToPublicGameSubscribers gameid state PlayRsp { gameid } -> sendToPublicGameSubscribers gameid state _ -> Cmd.none sender = case request of UpdateReq _ -> sendToOne PublicGamesReq { subscribe, forName } -> sendToOne _ -> case response of NewRsp { gameid } -> sendNewRsp model state4 JoinRsp { gameid } -> sendJoinRsp model state4 AnotherGameRsp record -> \_ _ -> Cmd.batch [ sendToOne response socket , sendToOthers model (AnotherGameRsp { record | player = Types.otherPlayer record.player } ) socket ] _ -> sendToAll model in ( WebSocketFramework.Server.setState model state4 , Cmd.batch [ cmd3, cmd4, cmd5, sender response socket ] ) sendToPublicGameSubscribers : GameId -> ServerState -> Cmd Msg sendToPublicGameSubscribers gameid state = case LE.find (.gameid >> (==) gameid) state.publicGames of Nothing -> Cmd.none Just publicGame -> case state.state of Nothing -> Cmd.none Just gs -> case ED.frameworkToPublicGame publicGame of Nothing -> Cmd.none Just pg -> let pgap = Interface.publicGameAddPlayers state pg notification = sendToOne (PublicGamesUpdateRsp { added = [ pgap ] , removed = [ publicGame.gameid ] } ) in gs.private.subscribers |> Set.toList |> List.map (\( sock, _ ) -> notification sock ) |> Cmd.batch getStatisticsTimes : Maybe Int -> ServerState -> ( ServerState, Maybe Int, Maybe Int ) getStatisticsTimes newUpdateTime state = case state.state of Nothing -> -- Can't happen ( state, Nothing, Nothing ) Just gs -> let private = gs.private newPrivate = case newUpdateTime of Nothing -> private _ -> { private | updateTime = newUpdateTime } newState = case newUpdateTime of Nothing -> state _ -> { state | state = Just { gs | private = newPrivate } } in ( newState, newPrivate.startTime, newPrivate.updateTime ) computeStatisticsSubscriberSends : Int -> ServerState -> ( ServerState, Cmd Msg ) computeStatisticsSubscriberSends time state = if not <| Interface.getStatisticsChanged state then ( state, Cmd.none ) else let ( state2, startTime, updateTime ) = getStatisticsTimes (Just time) state message = StatisticsRsp { statistics = state.statistics , startTime = startTime , updateTime = updateTime } in ( Interface.setStatisticsChanged False state2 , (List.map (sendToOne message) <| getStatisticsSubscribers state) |> Cmd.batch ) getStatisticsSubscribers : ServerState -> List Socket getStatisticsSubscribers state = case state.state of Nothing -> [] Just gameState -> gameState.private.statisticsSubscribers |> Set.toList handleStatisticsSubscription : Bool -> String -> ServerState -> ServerState handleStatisticsSubscription subscribe socket state = let gs = case state.state of Nothing -> Interface.emptyGameState <| PlayerNames "" "" Just gameState -> gameState private = gs.private subscribers = private.statisticsSubscribers in { state | state = Just { gs | private = { private | statisticsSubscribers = if subscribe then Set.insert socket subscribers else Set.filter ((/=) socket) subscribers } } } handlePublicGamesSubscription : Bool -> String -> Socket -> ServerState -> ServerState handlePublicGamesSubscription subscribe forName socket state = let gs = case state.state of Nothing -> Interface.emptyGameState <| PlayerNames "" "" Just gameState -> gameState private = gs.private subscribers = Set.filter (\( sock, _ ) -> socket /= sock) private.subscribers in { state | state = Just { gs | private = { private | subscribers = if subscribe then Set.insert ( socket, forName ) subscribers else subscribers } } } sendToOne : Message -> Socket -> Cmd Msg sendToOne response socket = WebSocketFramework.Server.sendToOne ED.messageEncoder response outputPort socket sendToAll : Model -> Message -> Socket -> Cmd Msg sendToAll model response socket = case Types.messageToGameid response of Nothing -> sendToOne response socket Just gameid -> WebSocketFramework.Server.sendToAll gameid model ED.messageEncoder response sendToOthers : Model -> Message -> Socket -> Cmd Msg sendToOthers model response socket = case Types.messageToGameid response of Nothing -> Cmd.none Just gameid -> WebSocketFramework.Server.sendToOthers gameid socket model ED.messageEncoder response sendNewRsp : Model -> ServerState -> Message -> Socket -> Cmd Msg sendNewRsp model state response socket = -- Need to send new public game to subscribers. let notifications = case state.state of Nothing -> [] Just gs -> case response of NewRsp { gameid, player, name, publicType, gameState } -> if publicType == NotPublic then [] else let publicGame = { gameid = gameid , creator = PI:NAME:<NAME>END_PI , player = player , forName = case publicType of PublicFor for -> Just for _ -> Nothing } publicGameAndPlayers = { publicGame = publicGame , players = gameState.players , watchers = 0 , moves = 0 , startTime = Types.posixZero , endTime = Types.posixZero } notification = sendToOne (PublicGamesUpdateRsp { added = [ publicGameAndPlayers ] , removed = [] } ) in gs.private.subscribers |> Set.toList |> List.filterMap (\( sock, forName ) -> case publicType of EntirelyPublic -> Just <| notification sock PublicFor for -> if forName == for then Just <| notification sock else Nothing _ -> Nothing ) _ -> [] in Cmd.batch <| sendToOne response socket :: notifications removedGameNotifications : GameId -> ServerState -> Cmd Msg removedGameNotifications gameid state = case state.state of Nothing -> Cmd.none Just gs -> let notification = sendToOne <| PublicGamesUpdateRsp { added = [] , removed = [ gameid ] } in gs.private.subscribers |> Set.toList |> List.map (\( sock, _ ) -> notification sock ) |> Cmd.batch sendJoinRsp : Model -> ServerState -> Message -> Socket -> Cmd Msg sendJoinRsp model state response socket = let notifications = case response of JoinRsp { gameid } -> removedGameNotifications gameid state _ -> Cmd.none in [ notifications , case response of JoinRsp record -> [ sendToOne response socket , sendToOthers model (JoinRsp { record | playerid = Nothing }) socket ] |> Cmd.batch _ -> sendToAll model response socket ] |> Cmd.batch gamesDeleter : Model -> List GameId -> ServerState -> ( Model, Cmd Msg ) gamesDeleter model gameids state = case state.state of Nothing -> ( model, Cmd.none ) Just gs -> let private = gs.private subscribers = private.subscribers loop : GameId -> ( SubscriptionSet, Cmd Msg ) -> ( SubscriptionSet, Cmd Msg ) loop gameid ( subscribers2, notifications ) = let inner : Socket -> ( SubscriptionSet, Cmd Msg ) -> ( SubscriptionSet, Cmd Msg ) inner socket ( subscribers3, notifications2 ) = ( Set.filter (\( sock, _ ) -> sock /= socket) subscribers3 , [ removedGameNotifications gameid state , notifications2 ] |> Cmd.batch ) sockets = WebSocketFramework.Server.otherSockets gameid "" model in List.foldl inner ( subscribers2, notifications ) sockets ( subscribers4, notifications3 ) = List.foldl loop ( subscribers, Cmd.none ) gameids state2 = { state | state = Just { gs | private = { private | subscribers = subscribers4 } } } in ( WebSocketFramework.Server.setState model state2 , notifications3 ) userFunctions : UserFunctions ServerModel Message GameState Participant userFunctions = { encodeDecode = encodeDecode , messageProcessor = Interface.messageProcessor , messageSender = messageSender , messageToGameid = Just Types.messageToGameid , messageToPlayerid = Just Types.messageToPlayerid , autoDeleteGame = Just (\gameid serverState -> False) , gamesDeleter = Just gamesDeleter , playersDeleter = Nothing , inputPort = inputPort , outputPort = outputPort } {-| Debugging version -} messageProcessor : ServerState -> Message -> ( ServerState, Maybe Message ) messageProcessor state message = Interface.messageProcessor (Debug.log "messageProcessor" state) (Debug.log " message" message) |> Debug.log " output" main = program serverModel userFunctions Nothing -- PORTS port inputPort : InputPort msg port outputPort : OutputPort msg
elm
[ { "context": " (\n [ input [ placeholder \"Dabson XD\"\n , onInput UpdateText", "end": 40839, "score": 0.9205116034, "start": 40830, "tag": "NAME", "value": "Dabson XD" } ]
Elm/Source/Main.elm
loovjo/Traffic
12
module Main exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Html.Lazy exposing (..) import Http import Task import Json.Decode as Decode exposing (decodeString) import Json.Encode exposing (encode) import Svg as S import Svg.Attributes as Sa import Window import Time exposing (Time) import Mouse import Keyboard import WebSocket import List.Extra exposing (isSuffixOf) import Base exposing (..) import TrafficRenderer exposing (..) import MenuRenderer exposing (renderMenu) import JsonParser exposing (..) import Debug type alias Flags = { webSocketUrl : String , controls : Controls } main = Html.programWithFlags { init = init, view = view, update = update, subscriptions = subscriptions } init : Flags -> ( Model, Cmd Msg ) init flags = ( { cars = [] , roads = [] , err = Nothing , size = Nothing , lasttime = Nothing , scroll = {x=0, y=0} , dragMouse = Nothing , mouse = Nothing , renderScale = 40.0 , webSocketUrl = flags.webSocketUrl , ip = Nothing , accelRate = 6.0 , steerRate = 200.0 , lastClickTime = Nothing , trackingCar = Nothing , controls = flags.controls , others = [] , keyCombo = [] , keyComboTimeLeft = 0 , currentDragCar = Nothing , hiddenRoads = [] , snap = False , buildingRoad = False , buildingRoadStart = Nothing , selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing , cmdLog = [] , popup = NoPopup , menu = defaultMenu } , Task.perform identity <| Task.succeed CheckSize ) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ServerSync json -> let result = decodeString decodeTraffic json in case result of Ok traffic -> ( { model | cars = traffic.cars , roads = traffic.roads , others = traffic.others , ip = Just traffic.ip , err = Nothing , menu = let menu = model.menu in { menu | buttons = generateMenuButtons traffic } } , Task.perform identity <| Task.succeed FixScroll ) Err error -> let cmdRes = decodeString decodeRes json in case cmdRes of Ok res -> ( { model | cmdLog = model.cmdLog ++ [" " ++ res.cmd] } , Cmd.none ) Err _ -> ( { model | err = Just error } , Cmd.none ) Resize size -> ( { model | size = Just { x = toFloat size.width, y = toFloat size.height } }, Cmd.none ) CheckSize -> ( model, Task.perform Resize <| Window.size ) UpdateClient time -> case model.lasttime of Nothing -> ( { model | lasttime = Just time }, Cmd.none ) Just lasttime -> let delta = Time.inSeconds (time - lasttime) in ( { model | lasttime = Just time , keyComboTimeLeft = if model.keyComboTimeLeft > 0 then model.keyComboTimeLeft - delta else 0 , keyCombo = if model.keyComboTimeLeft > 0 then model.keyCombo else [] , cars = List.map (\car -> { car | pos = pAdd car.pos <| (\( x, y ) -> { x = x, y = y }) <| fromPolar ( car.speed * delta, degrees car.rot ) , speed = (if car.handBreaks then car.speed * (car.breakStrength ^ delta) else car.speed) + car.accel * delta , rot = car.rot + car.steering * delta , steering = case model.err of Just _ -> car.steering / (2 ^ delta) Nothing -> car.steering } ) model.cars , menu = let menu = model.menu in { menu | rotation = case menu.state of In -> if menu.rotation > 0 then menu.rotation - delta * 5 else 0 Out -> if menu.rotation < 1 then menu.rotation + delta * 5 else 1 } } , Task.perform identity <| Task.succeed FixScroll ) FixScroll -> ( {model | scroll = case (model.size, model.trackingCar) of (Just size, Just carName) -> let car_ = List.head <| List.filter (\car -> car.name == carName) model.cars in case car_ of Just car -> { x = -car.pos.x * model.renderScale + size.x / 2, y = -car.pos.y * model.renderScale + size.y / 2 } Nothing -> model.scroll _ -> model.scroll }, Cmd.none ) MouseRelease _ -> case model.popup of NoPopup -> ( {model | dragMouse = Nothing, lastClickTime = model.lasttime}, Cmd.none ) _ -> ( model, Cmd.none ) MousePress pos -> case model.popup of NoPopup -> if model.buildingRoad then case model.buildingRoadStart of Nothing -> let start = { x = (toFloat pos.x - model.scroll.x) / model.renderScale , y = (toFloat pos.y - model.scroll.y) / model.renderScale } start_ = if model.snap then pRound start else start in ( { model | buildingRoadStart = Just start_ }, Cmd.none ) Just start -> ( { model | buildingRoadStart = Nothing , buildingRoad = False }, case model.mouse of Just mouse -> let mouse_ = if model.snap then pRound mouse else mouse in WebSocket.send model.webSocketUrl <| String.join "/" [ "rbuild" , toString <| start.x , toString <| start.y , toString <| mouse_.x , toString <| mouse_.y ] Nothing -> Cmd.none ) else case model.selectState of CombineSelecting -> case (model.currentSelectedRoad, model.otherRoad) of (Just road, Nothing) -> ( { model | otherRoad = Just road } , Cmd.none ) (Just road, Just other) -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing } , WebSocket.send model.webSocketUrl <| String.join "/" [ "rconn" , other.id , road.id ] ) _ -> ( model, Cmd.none ) RemoveSelecting -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing } , WebSocket.send model.webSocketUrl <| "rrm/" ++ road.id ) FlipSelecting -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing } , WebSocket.send model.webSocketUrl <| "rflip/" ++ road.id ) HideSelecting -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , hiddenRoads = if List.member road.id model.hiddenRoads then List.filter (\x -> x /= road.id) model.hiddenRoads else List.append model.hiddenRoads [road.id] } , Cmd.none ) LightSelecting lState -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing } , WebSocket.send model.webSocketUrl <| case lState of AddLight -> "lbuild/" ++ road.id RemoveLight -> "lrm/" ++ road.id FlipLight -> "lflip/" ++ road.id ) TrackSelecting -> case model.mouse of Nothing -> ( model, Cmd.none ) Just pos -> let closest = getClosestCar pos model.cars in case closest of Nothing -> ( model, Cmd.none ) Just car -> ( { model | selectState = NotSelecting , trackingCar = Just car.name } , Cmd.none ) IntersectionMakeSelecting -> case (model.currentSelectedRoad, model.otherRoad) of (Just road, Nothing) -> ( { model | otherRoad = Just road } , Cmd.none ) (Just road, Just other) -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing } , WebSocket.send model.webSocketUrl <| String.join "/" [ "intermake" , other.id , road.id ] ) _ -> ( model, Cmd.none ) AICarSelecting -> case (model.currentSelectedRoad, model.otherRoad) of (Just road, Nothing) -> ( { model | otherRoad = Just road } , Cmd.none ) (Just road, Just other) -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing } , WebSocket.send model.webSocketUrl <| String.join "/" [ "createai" , other.id , road.id ] ) _ -> ( model, Cmd.none ) NotSelecting -> ( {model | dragMouse = Just {x = toFloat pos.x, y = toFloat pos.y} , currentDragCar = Nothing} , case model.currentDragCar of Just car -> WebSocket.send model.webSocketUrl <| "create/" ++ (Http.encodeUri <| encode 0 <| encodeProtoCar car) Nothing -> Cmd.none ) _ -> ( model, Cmd.none ) MouseMove pos -> case model.popup of NoPopup -> let track = case model.trackingCar of Nothing -> False Just name -> List.length (List.filter (\car -> car.name == name) model.cars) > 0 mouse = { x = (toFloat pos.x - model.scroll.x) / model.renderScale , y = (toFloat pos.y - model.scroll.y) / model.renderScale } model_ = {model | mouse = Just mouse , currentSelectedRoad = if model.selectState /= NotSelecting && model.selectState /= TrackSelecting then getClosestRoad mouse <| List.filter (\road -> not <| List.member road.id model.hiddenRoads) model.roads else model.currentSelectedRoad } in if not track then case model_.dragMouse of Just mousePos -> let delta = {x = toFloat pos.x - mousePos.x, y = toFloat pos.y - mousePos.y} in ( {model_ | scroll = {x = model_.scroll.x + delta.x, y = model_.scroll.y + delta.y}, dragMouse = Just {x = toFloat pos.x, y = toFloat pos.y}}, Cmd.none ) Nothing -> case model_.currentDragCar of Just car -> ( { model_ | currentDragCar = Just {car | pos = {x = (toFloat pos.x - model_.scroll.x) / model_.renderScale, y = (toFloat pos.y - model_.scroll.y) / model_.renderScale}} }, Cmd.none ) Nothing -> ( model_, Cmd.none ) else ( model_, Cmd.none ) _ -> ( model, Cmd.none ) KeyCodeDown code -> case keyboardMap !! code of Just key -> update (KeyDown key) model Nothing -> ( model, Cmd.none ) KeyCodeUp code -> case keyboardMap !! code of Just key -> update (KeyUp key) model Nothing -> ( model, Cmd.none ) KeyDown key -> if key == model.controls.free then ( {model | trackingCar = Nothing , currentDragCar = Nothing , buildingRoad = False , buildingRoadStart = Nothing , selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing , popup = NoPopup , keyCombo = [] , menu = let menu = model.menu in { menu | state = In } }, Cmd.none ) else case model.popup of NoPopup -> if key == model.controls.zoomIn then -- Plus key ( {model | renderScale = model.renderScale * zoomFactor , scroll = case model.size of Just size -> {x = (model.scroll.x - size.x / 2) * zoomFactor + size.x / 2, y = (model.scroll.y - size.y / 2) * zoomFactor + size.y / 2} Nothing -> model.scroll }, Cmd.none ) else if key == model.controls.zoomOut then -- Minus key ( {model | renderScale = model.renderScale / zoomFactor , scroll = case model.size of Just size -> {x = (model.scroll.x - size.x / 2) / zoomFactor + size.x / 2, y = (model.scroll.y - size.y / 2) / zoomFactor + size.y / 2} Nothing -> model.scroll }, Cmd.none ) else case model.ip of Just myIp -> if key == model.controls.remove then ( model , let distToScroll car = Tuple.first <| toPolar <| (car.pos.x - model.scroll.x, car.pos.y - model.scroll.y) closestCar = List.head <| List.sortWith (\c1 c2 -> compare (distToScroll c2) (distToScroll c1) ) <| List.filter (\c -> c.controlledBy == model.ip) model.cars in case closestCar of Just {name} -> WebSocket.send model.webSocketUrl <| "remove/" ++ name Nothing -> Cmd.none ) else if key == model.controls.break then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = True, accel = 0} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "breaks" ) else if key == model.controls.up then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = False, accel = model.accelRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "accel/" ++ (toString model.accelRate) ) ) else if key == model.controls.back then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = False, accel = negate model.accelRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "accel/" ++ (toString <| negate model.accelRate) ) ) else if key == model.controls.left then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | steering = negate model.steerRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "steer/" ++ (toString <| negate model.steerRate)) ) else if key == model.controls.right then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | steering = model.steerRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "steer/" ++ (toString model.steerRate))) else if key == model.controls.carUp || key == model.controls.carDown then ( { model | trackingCar = let controlledByMe = List.sortWith (\car1 car2 -> compare car1.pos.x car2.pos.x) <| case model.ip of Just ip -> List.filter (\car -> case car.controlledBy of Just c -> c == ip Nothing -> False) model.cars Nothing -> [] in case model.trackingCar of Nothing -> Maybe.map .name <| List.head controlledByMe Just trackName -> let track = List.head <| List.filter (\(idx, car) -> car.name == trackName) (List.indexedMap (,) controlledByMe) in case track of Just (idx, car) -> let res = if key == model.controls.carUp then Maybe.map .name <| List.head <| List.drop (idx+1) controlledByMe else if idx == 0 then Nothing else Maybe.map .name <| List.head <| List.drop (idx-1) <| controlledByMe in case res of Just x -> Just x Nothing -> if key == model.controls.carUp then Maybe.map .name <| List.head controlledByMe else Maybe.map .name <| List.head <| List.reverse controlledByMe Nothing -> Maybe.map .name <| List.head controlledByMe } , Cmd.none ) else if key == model.controls.snap then ( { model | snap = True }, Cmd.none ) else if key == model.controls.hide && model.currentSelectedRoad /= Nothing then case model.currentSelectedRoad of Just road -> ( { model | hiddenRoads = model.hiddenRoads ++ [road.id]} , Cmd.none ) Nothing -> ( model, Cmd.none ) else if key == model.controls.help then ( { model | popup = InfoPopup False }, Cmd.none ) else let currentCombo = if model.keyComboTimeLeft > 0 then model.keyCombo else [] combo = Debug.log "Combo" <| currentCombo ++ [key] matching = Debug.log "Matching" <| List.filter (\button -> case button.hotKey of Just hotKey -> isSuffixOf hotKey combo Nothing -> False) model.menu.buttons sorted = Debug.log "Sorted" <| List.sortBy (negate << List.length << (Maybe.withDefault []) << .hotKey) matching first = List.head sorted in case first of Just button -> ( {model | keyCombo = [], keyComboTimeLeft = 1}, Task.perform identity <| Task.succeed button.message ) Nothing -> (always ({model | keyCombo = combo, keyComboTimeLeft = 1}, Cmd.none)) <| Debug.log "Key Down" key Nothing -> ( model, Cmd.none ) _ -> ( model, Cmd.none ) KeyUp key -> case model.popup of NoPopup -> case model.ip of Just myIp -> if key == model.controls.break then -- k ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = False} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "no_breaks" ) else if key == model.controls.up || key == model.controls.back then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | accel = 0} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "accel/0" ) else if key == model.controls.left || key == model.controls.right then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | steering = 0} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "steer/0" ) else if key == model.controls.snap then ( { model | snap = False }, Cmd.none ) else (always (model, Cmd.none)) <| Debug.log "Key Up" key Nothing -> ( model, Cmd.none ) _ -> ( model, Cmd.none ) MenuBallClicked -> ( { model | menu = let menu = model.menu in { menu | state = case model.menu.state of In -> Out Out -> In } }, Cmd.none ) MenuButtonClicked msg -> ( { model | menu = let menu = model.menu in { menu | state = In } }, Task.perform identity <| Task.succeed msg ) AddCarClicked police -> ( { model | currentDragCar = Just {pos = {x = 0, y = 0}, img = if police then "CarPolis" else "Car1", isPolice = police} }, Cmd.none ) AddRoadClicked -> ( { model | buildingRoad = True } , Cmd.none ) SelectStateChange state -> ( { model | selectState = state } , Cmd.none ) ShowRoadClicked -> ( { model | hiddenRoads = [] } , Cmd.none ) ClosePopup -> ( { model | popup = NoPopup } , Cmd.none ) OpenPopup pop -> ( { model | popup = pop } , Cmd.none) InfoToggleDebug -> ( { model | popup = case model.popup of InfoPopup debug -> InfoPopup <| not debug _ -> model.popup } , Cmd.none ) UpdateText text -> case model.popup of LoginPopup _ -> ( { model | popup = LoginPopup text } , Cmd.none ) CommandPopup _ -> ( { model | popup = CommandPopup text } , Cmd.none ) _ -> ( model, Cmd.none ) SendCommand -> case model.popup of CommandPopup cmd -> ( { model | popup = CommandPopup "" , cmdLog = model.cmdLog ++ [cmd] } , WebSocket.send model.webSocketUrl <| "cmd/" ++ cmd) _ -> ( model, Cmd.none ) ClearLogs -> ( { model | cmdLog = []} , Cmd.none ) Login -> case model.popup of LoginPopup name -> if String.length name < nameLengthMax && String.length name > 0 then ( { model | popup = NoPopup } , WebSocket.send model.webSocketUrl <| "login/" ++ name) else ( model, Cmd.none ) _ -> ( model, Cmd.none ) view : Model -> Html Msg view model = div [ style [ ("margin-top", "0px") , ("padding-top", "0px") ] ] ([ div ( [ style [ ("margin", "0px") , ("top", "0px") , ("position", "fixed")] ] ++ case model.popup of NoPopup -> [] _ -> [ class "blur" ] ) [ -- Generate svg! S.svg [ Sa.width <| Maybe.withDefault "10" <| Maybe.map (toString << .x) model.size , Sa.height <| Maybe.withDefault "10" <| Maybe.map (toString << .y) model.size , Sa.style "background: #227722" ] (let cars_ = case (model.selectState, model.mouse) of (TrackSelecting, Just pos) -> case getClosestCar pos model.cars of Just closest -> List.map (\car -> if car == closest then { car | size = car.size * 1.3 } else car) model.cars Nothing -> model.cars _ -> model.cars lines = renderBackgroundLines model roads = renderRoads model model.roads cars = renderCars model cars_ trafficLights = renderTrafficLights model model.roads menu = renderMenu model in lines ++ roads ++ cars ++ trafficLights ++ menu ++ ( List.concatMap (\road -> [ S.line [ Sa.x1 <| toString <| (road.start.x * model.renderScale) + model.scroll.x , Sa.y1 <| toString <| (road.start.y * model.renderScale) + model.scroll.y , Sa.x2 <| toString <| (road.end.x * model.renderScale) + model.scroll.x , Sa.y2 <| toString <| (road.end.y * model.renderScale) + model.scroll.y , Sa.strokeWidth <| toString <| model.renderScale * 0.3 , Sa.stroke "green" ] [] , S.circle [ Sa.cx <| toString <| (road.end.x * model.renderScale) + model.scroll.x , Sa.cy <| toString <| (road.end.y * model.renderScale) + model.scroll.y , Sa.fill "yellow" , Sa.r <| toString <| model.renderScale / 2 , Sa.stroke "black" , Sa.strokeWidth <| toString <| model.renderScale / 20 ] [] ] ) (( case model.currentSelectedRoad of Just road -> [road] Nothing -> [] ) ++ ( case model.otherRoad of Just road -> [road] Nothing -> [] )) ) ++ ( case model.currentDragCar of Just car -> renderCars model [toCar car] Nothing -> [] ) ++ ( case (model.buildingRoadStart, model.mouse) of (Just start, Just mouse) -> let f = if model.snap then pRound else identity road = Road "" (f start) (f mouse) [] Nothing 1.5 in renderRoads model [road] _ -> [] ) ) ] ] ++ ( if model.popup == NoPopup then [] else [ div [ style <| centerFill model ] [div [ style (centerFill model ++ [ ("background-color", "#A64") , ("opacity", "0.6")] )] [] , generatePopup model.popup model ] ] ) ) centerFill model = [ ("position", "absolute") , ("width", "100%") , ("height", (Maybe.withDefault "10" <| Maybe.map (toString << .y) model.size) ++ "px")] generatePopup : Popup -> Model -> Html Msg generatePopup popup model = div [style <| centerFill model] <| case popup of NoPopup -> [] InfoPopup debug -> [ div [style [("text-align", "center")]] ( [ h3 [] [pre [] [text "Keys:"]] , pre [] [text "+ Zoom in"] , pre [] [text "- Zoom out"] , pre [] [text "w Accelerate"] , pre [] [text "s Active breaks"] , pre [] [text "a/d Steer left/right"] , pre [] [text "q Drive backwards"] ] ++ List.filterMap (\button -> case button.hotKey of Just hotKey -> Just <| pre [] [text <| button.image ++ ": " ++ String.join "-" hotKey] Nothing -> Nothing ) model.menu.buttons ++ [ button [ onClick InfoToggleDebug ] [text <| if debug then "Hide Debug" else "Show Debug"] , br [] [] ] ++ (if debug then [ h3 [] [pre [] [text "Debug info:"]] ] ++ ( List.filterMap (\(prop, name) -> case prop of Just val -> Just (pre [] [text <| name ++ ": " ++ (toString val)]) Nothing -> Nothing ) ( [ (Maybe.map toString model.ip, "Ip") , (Maybe.map toString model.size, "Screen size") , (Maybe.map toString model.trackingCar, "Tracking car") , (Maybe.map toString model.currentSelectedRoad, "Current selected road") , (Just <| toString model.keyCombo, "Current combo") , (Just <| toString model.keyComboTimeLeft, "Time left on combo") ] ) ++ ( case model.err of Just err -> [ p [style [("color", "red")]] [text <| "An error occured. Error was: " ++ toString err] ] Nothing -> [] ) ) else []) ++ [ button [ onClick ClosePopup ] [text "Done!"] ] )] LoginPopup name -> [ div [style [ ("text-align", "center") , ("margin-top", "200px") ]] [ h1 [style [("font-family", "Impact")]] [text "Username:"] , Html.form [ onSubmit Login ] ( [ input [ placeholder "Dabson XD" , onInput UpdateText , style [("font-size", "40px")] ] [] , br [] [] , button [disabled <| String.length name <= 0 || String.length name >= nameLengthMax] [text "Login!"] ] ++ [ if String.length name >= nameLengthMax then p [style [("color", "red")]] [text "u boot too big 4 me big boi. u need 2 b less fat pls."] else br [] [] ] ) ] ] CommandPopup cmd -> [ div [ class "cmd" ] [ div [ class "cmdLog" ] <| List.map (\log -> pre [] [text log]) model.cmdLog , div [] [ Html.form [ onSubmit SendCommand ] [ button [ class "rightButton" ] [text "Send command"] , span [ class "wrapper" ] [ input [ class "cmdInp" , placeholder "DENY * view" , onInput UpdateText , value cmd ] [] ] ] , button [ onClick ClosePopup ] [text "Done"] , button [ onClick ClearLogs ] [text "Clear"] ] ] ] subscriptions : Model -> Sub Msg subscriptions model = Sub.batch [ Window.resizes Resize , Time.every (Time.second / 30) UpdateClient , Mouse.downs MousePress , Mouse.ups MouseRelease , Mouse.moves MouseMove , Keyboard.downs KeyCodeDown , Keyboard.ups KeyCodeUp , WebSocket.listen model.webSocketUrl ServerSync ]
49194
module Main exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Html.Lazy exposing (..) import Http import Task import Json.Decode as Decode exposing (decodeString) import Json.Encode exposing (encode) import Svg as S import Svg.Attributes as Sa import Window import Time exposing (Time) import Mouse import Keyboard import WebSocket import List.Extra exposing (isSuffixOf) import Base exposing (..) import TrafficRenderer exposing (..) import MenuRenderer exposing (renderMenu) import JsonParser exposing (..) import Debug type alias Flags = { webSocketUrl : String , controls : Controls } main = Html.programWithFlags { init = init, view = view, update = update, subscriptions = subscriptions } init : Flags -> ( Model, Cmd Msg ) init flags = ( { cars = [] , roads = [] , err = Nothing , size = Nothing , lasttime = Nothing , scroll = {x=0, y=0} , dragMouse = Nothing , mouse = Nothing , renderScale = 40.0 , webSocketUrl = flags.webSocketUrl , ip = Nothing , accelRate = 6.0 , steerRate = 200.0 , lastClickTime = Nothing , trackingCar = Nothing , controls = flags.controls , others = [] , keyCombo = [] , keyComboTimeLeft = 0 , currentDragCar = Nothing , hiddenRoads = [] , snap = False , buildingRoad = False , buildingRoadStart = Nothing , selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing , cmdLog = [] , popup = NoPopup , menu = defaultMenu } , Task.perform identity <| Task.succeed CheckSize ) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ServerSync json -> let result = decodeString decodeTraffic json in case result of Ok traffic -> ( { model | cars = traffic.cars , roads = traffic.roads , others = traffic.others , ip = Just traffic.ip , err = Nothing , menu = let menu = model.menu in { menu | buttons = generateMenuButtons traffic } } , Task.perform identity <| Task.succeed FixScroll ) Err error -> let cmdRes = decodeString decodeRes json in case cmdRes of Ok res -> ( { model | cmdLog = model.cmdLog ++ [" " ++ res.cmd] } , Cmd.none ) Err _ -> ( { model | err = Just error } , Cmd.none ) Resize size -> ( { model | size = Just { x = toFloat size.width, y = toFloat size.height } }, Cmd.none ) CheckSize -> ( model, Task.perform Resize <| Window.size ) UpdateClient time -> case model.lasttime of Nothing -> ( { model | lasttime = Just time }, Cmd.none ) Just lasttime -> let delta = Time.inSeconds (time - lasttime) in ( { model | lasttime = Just time , keyComboTimeLeft = if model.keyComboTimeLeft > 0 then model.keyComboTimeLeft - delta else 0 , keyCombo = if model.keyComboTimeLeft > 0 then model.keyCombo else [] , cars = List.map (\car -> { car | pos = pAdd car.pos <| (\( x, y ) -> { x = x, y = y }) <| fromPolar ( car.speed * delta, degrees car.rot ) , speed = (if car.handBreaks then car.speed * (car.breakStrength ^ delta) else car.speed) + car.accel * delta , rot = car.rot + car.steering * delta , steering = case model.err of Just _ -> car.steering / (2 ^ delta) Nothing -> car.steering } ) model.cars , menu = let menu = model.menu in { menu | rotation = case menu.state of In -> if menu.rotation > 0 then menu.rotation - delta * 5 else 0 Out -> if menu.rotation < 1 then menu.rotation + delta * 5 else 1 } } , Task.perform identity <| Task.succeed FixScroll ) FixScroll -> ( {model | scroll = case (model.size, model.trackingCar) of (Just size, Just carName) -> let car_ = List.head <| List.filter (\car -> car.name == carName) model.cars in case car_ of Just car -> { x = -car.pos.x * model.renderScale + size.x / 2, y = -car.pos.y * model.renderScale + size.y / 2 } Nothing -> model.scroll _ -> model.scroll }, Cmd.none ) MouseRelease _ -> case model.popup of NoPopup -> ( {model | dragMouse = Nothing, lastClickTime = model.lasttime}, Cmd.none ) _ -> ( model, Cmd.none ) MousePress pos -> case model.popup of NoPopup -> if model.buildingRoad then case model.buildingRoadStart of Nothing -> let start = { x = (toFloat pos.x - model.scroll.x) / model.renderScale , y = (toFloat pos.y - model.scroll.y) / model.renderScale } start_ = if model.snap then pRound start else start in ( { model | buildingRoadStart = Just start_ }, Cmd.none ) Just start -> ( { model | buildingRoadStart = Nothing , buildingRoad = False }, case model.mouse of Just mouse -> let mouse_ = if model.snap then pRound mouse else mouse in WebSocket.send model.webSocketUrl <| String.join "/" [ "rbuild" , toString <| start.x , toString <| start.y , toString <| mouse_.x , toString <| mouse_.y ] Nothing -> Cmd.none ) else case model.selectState of CombineSelecting -> case (model.currentSelectedRoad, model.otherRoad) of (Just road, Nothing) -> ( { model | otherRoad = Just road } , Cmd.none ) (Just road, Just other) -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing } , WebSocket.send model.webSocketUrl <| String.join "/" [ "rconn" , other.id , road.id ] ) _ -> ( model, Cmd.none ) RemoveSelecting -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing } , WebSocket.send model.webSocketUrl <| "rrm/" ++ road.id ) FlipSelecting -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing } , WebSocket.send model.webSocketUrl <| "rflip/" ++ road.id ) HideSelecting -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , hiddenRoads = if List.member road.id model.hiddenRoads then List.filter (\x -> x /= road.id) model.hiddenRoads else List.append model.hiddenRoads [road.id] } , Cmd.none ) LightSelecting lState -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing } , WebSocket.send model.webSocketUrl <| case lState of AddLight -> "lbuild/" ++ road.id RemoveLight -> "lrm/" ++ road.id FlipLight -> "lflip/" ++ road.id ) TrackSelecting -> case model.mouse of Nothing -> ( model, Cmd.none ) Just pos -> let closest = getClosestCar pos model.cars in case closest of Nothing -> ( model, Cmd.none ) Just car -> ( { model | selectState = NotSelecting , trackingCar = Just car.name } , Cmd.none ) IntersectionMakeSelecting -> case (model.currentSelectedRoad, model.otherRoad) of (Just road, Nothing) -> ( { model | otherRoad = Just road } , Cmd.none ) (Just road, Just other) -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing } , WebSocket.send model.webSocketUrl <| String.join "/" [ "intermake" , other.id , road.id ] ) _ -> ( model, Cmd.none ) AICarSelecting -> case (model.currentSelectedRoad, model.otherRoad) of (Just road, Nothing) -> ( { model | otherRoad = Just road } , Cmd.none ) (Just road, Just other) -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing } , WebSocket.send model.webSocketUrl <| String.join "/" [ "createai" , other.id , road.id ] ) _ -> ( model, Cmd.none ) NotSelecting -> ( {model | dragMouse = Just {x = toFloat pos.x, y = toFloat pos.y} , currentDragCar = Nothing} , case model.currentDragCar of Just car -> WebSocket.send model.webSocketUrl <| "create/" ++ (Http.encodeUri <| encode 0 <| encodeProtoCar car) Nothing -> Cmd.none ) _ -> ( model, Cmd.none ) MouseMove pos -> case model.popup of NoPopup -> let track = case model.trackingCar of Nothing -> False Just name -> List.length (List.filter (\car -> car.name == name) model.cars) > 0 mouse = { x = (toFloat pos.x - model.scroll.x) / model.renderScale , y = (toFloat pos.y - model.scroll.y) / model.renderScale } model_ = {model | mouse = Just mouse , currentSelectedRoad = if model.selectState /= NotSelecting && model.selectState /= TrackSelecting then getClosestRoad mouse <| List.filter (\road -> not <| List.member road.id model.hiddenRoads) model.roads else model.currentSelectedRoad } in if not track then case model_.dragMouse of Just mousePos -> let delta = {x = toFloat pos.x - mousePos.x, y = toFloat pos.y - mousePos.y} in ( {model_ | scroll = {x = model_.scroll.x + delta.x, y = model_.scroll.y + delta.y}, dragMouse = Just {x = toFloat pos.x, y = toFloat pos.y}}, Cmd.none ) Nothing -> case model_.currentDragCar of Just car -> ( { model_ | currentDragCar = Just {car | pos = {x = (toFloat pos.x - model_.scroll.x) / model_.renderScale, y = (toFloat pos.y - model_.scroll.y) / model_.renderScale}} }, Cmd.none ) Nothing -> ( model_, Cmd.none ) else ( model_, Cmd.none ) _ -> ( model, Cmd.none ) KeyCodeDown code -> case keyboardMap !! code of Just key -> update (KeyDown key) model Nothing -> ( model, Cmd.none ) KeyCodeUp code -> case keyboardMap !! code of Just key -> update (KeyUp key) model Nothing -> ( model, Cmd.none ) KeyDown key -> if key == model.controls.free then ( {model | trackingCar = Nothing , currentDragCar = Nothing , buildingRoad = False , buildingRoadStart = Nothing , selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing , popup = NoPopup , keyCombo = [] , menu = let menu = model.menu in { menu | state = In } }, Cmd.none ) else case model.popup of NoPopup -> if key == model.controls.zoomIn then -- Plus key ( {model | renderScale = model.renderScale * zoomFactor , scroll = case model.size of Just size -> {x = (model.scroll.x - size.x / 2) * zoomFactor + size.x / 2, y = (model.scroll.y - size.y / 2) * zoomFactor + size.y / 2} Nothing -> model.scroll }, Cmd.none ) else if key == model.controls.zoomOut then -- Minus key ( {model | renderScale = model.renderScale / zoomFactor , scroll = case model.size of Just size -> {x = (model.scroll.x - size.x / 2) / zoomFactor + size.x / 2, y = (model.scroll.y - size.y / 2) / zoomFactor + size.y / 2} Nothing -> model.scroll }, Cmd.none ) else case model.ip of Just myIp -> if key == model.controls.remove then ( model , let distToScroll car = Tuple.first <| toPolar <| (car.pos.x - model.scroll.x, car.pos.y - model.scroll.y) closestCar = List.head <| List.sortWith (\c1 c2 -> compare (distToScroll c2) (distToScroll c1) ) <| List.filter (\c -> c.controlledBy == model.ip) model.cars in case closestCar of Just {name} -> WebSocket.send model.webSocketUrl <| "remove/" ++ name Nothing -> Cmd.none ) else if key == model.controls.break then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = True, accel = 0} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "breaks" ) else if key == model.controls.up then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = False, accel = model.accelRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "accel/" ++ (toString model.accelRate) ) ) else if key == model.controls.back then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = False, accel = negate model.accelRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "accel/" ++ (toString <| negate model.accelRate) ) ) else if key == model.controls.left then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | steering = negate model.steerRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "steer/" ++ (toString <| negate model.steerRate)) ) else if key == model.controls.right then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | steering = model.steerRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "steer/" ++ (toString model.steerRate))) else if key == model.controls.carUp || key == model.controls.carDown then ( { model | trackingCar = let controlledByMe = List.sortWith (\car1 car2 -> compare car1.pos.x car2.pos.x) <| case model.ip of Just ip -> List.filter (\car -> case car.controlledBy of Just c -> c == ip Nothing -> False) model.cars Nothing -> [] in case model.trackingCar of Nothing -> Maybe.map .name <| List.head controlledByMe Just trackName -> let track = List.head <| List.filter (\(idx, car) -> car.name == trackName) (List.indexedMap (,) controlledByMe) in case track of Just (idx, car) -> let res = if key == model.controls.carUp then Maybe.map .name <| List.head <| List.drop (idx+1) controlledByMe else if idx == 0 then Nothing else Maybe.map .name <| List.head <| List.drop (idx-1) <| controlledByMe in case res of Just x -> Just x Nothing -> if key == model.controls.carUp then Maybe.map .name <| List.head controlledByMe else Maybe.map .name <| List.head <| List.reverse controlledByMe Nothing -> Maybe.map .name <| List.head controlledByMe } , Cmd.none ) else if key == model.controls.snap then ( { model | snap = True }, Cmd.none ) else if key == model.controls.hide && model.currentSelectedRoad /= Nothing then case model.currentSelectedRoad of Just road -> ( { model | hiddenRoads = model.hiddenRoads ++ [road.id]} , Cmd.none ) Nothing -> ( model, Cmd.none ) else if key == model.controls.help then ( { model | popup = InfoPopup False }, Cmd.none ) else let currentCombo = if model.keyComboTimeLeft > 0 then model.keyCombo else [] combo = Debug.log "Combo" <| currentCombo ++ [key] matching = Debug.log "Matching" <| List.filter (\button -> case button.hotKey of Just hotKey -> isSuffixOf hotKey combo Nothing -> False) model.menu.buttons sorted = Debug.log "Sorted" <| List.sortBy (negate << List.length << (Maybe.withDefault []) << .hotKey) matching first = List.head sorted in case first of Just button -> ( {model | keyCombo = [], keyComboTimeLeft = 1}, Task.perform identity <| Task.succeed button.message ) Nothing -> (always ({model | keyCombo = combo, keyComboTimeLeft = 1}, Cmd.none)) <| Debug.log "Key Down" key Nothing -> ( model, Cmd.none ) _ -> ( model, Cmd.none ) KeyUp key -> case model.popup of NoPopup -> case model.ip of Just myIp -> if key == model.controls.break then -- k ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = False} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "no_breaks" ) else if key == model.controls.up || key == model.controls.back then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | accel = 0} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "accel/0" ) else if key == model.controls.left || key == model.controls.right then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | steering = 0} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "steer/0" ) else if key == model.controls.snap then ( { model | snap = False }, Cmd.none ) else (always (model, Cmd.none)) <| Debug.log "Key Up" key Nothing -> ( model, Cmd.none ) _ -> ( model, Cmd.none ) MenuBallClicked -> ( { model | menu = let menu = model.menu in { menu | state = case model.menu.state of In -> Out Out -> In } }, Cmd.none ) MenuButtonClicked msg -> ( { model | menu = let menu = model.menu in { menu | state = In } }, Task.perform identity <| Task.succeed msg ) AddCarClicked police -> ( { model | currentDragCar = Just {pos = {x = 0, y = 0}, img = if police then "CarPolis" else "Car1", isPolice = police} }, Cmd.none ) AddRoadClicked -> ( { model | buildingRoad = True } , Cmd.none ) SelectStateChange state -> ( { model | selectState = state } , Cmd.none ) ShowRoadClicked -> ( { model | hiddenRoads = [] } , Cmd.none ) ClosePopup -> ( { model | popup = NoPopup } , Cmd.none ) OpenPopup pop -> ( { model | popup = pop } , Cmd.none) InfoToggleDebug -> ( { model | popup = case model.popup of InfoPopup debug -> InfoPopup <| not debug _ -> model.popup } , Cmd.none ) UpdateText text -> case model.popup of LoginPopup _ -> ( { model | popup = LoginPopup text } , Cmd.none ) CommandPopup _ -> ( { model | popup = CommandPopup text } , Cmd.none ) _ -> ( model, Cmd.none ) SendCommand -> case model.popup of CommandPopup cmd -> ( { model | popup = CommandPopup "" , cmdLog = model.cmdLog ++ [cmd] } , WebSocket.send model.webSocketUrl <| "cmd/" ++ cmd) _ -> ( model, Cmd.none ) ClearLogs -> ( { model | cmdLog = []} , Cmd.none ) Login -> case model.popup of LoginPopup name -> if String.length name < nameLengthMax && String.length name > 0 then ( { model | popup = NoPopup } , WebSocket.send model.webSocketUrl <| "login/" ++ name) else ( model, Cmd.none ) _ -> ( model, Cmd.none ) view : Model -> Html Msg view model = div [ style [ ("margin-top", "0px") , ("padding-top", "0px") ] ] ([ div ( [ style [ ("margin", "0px") , ("top", "0px") , ("position", "fixed")] ] ++ case model.popup of NoPopup -> [] _ -> [ class "blur" ] ) [ -- Generate svg! S.svg [ Sa.width <| Maybe.withDefault "10" <| Maybe.map (toString << .x) model.size , Sa.height <| Maybe.withDefault "10" <| Maybe.map (toString << .y) model.size , Sa.style "background: #227722" ] (let cars_ = case (model.selectState, model.mouse) of (TrackSelecting, Just pos) -> case getClosestCar pos model.cars of Just closest -> List.map (\car -> if car == closest then { car | size = car.size * 1.3 } else car) model.cars Nothing -> model.cars _ -> model.cars lines = renderBackgroundLines model roads = renderRoads model model.roads cars = renderCars model cars_ trafficLights = renderTrafficLights model model.roads menu = renderMenu model in lines ++ roads ++ cars ++ trafficLights ++ menu ++ ( List.concatMap (\road -> [ S.line [ Sa.x1 <| toString <| (road.start.x * model.renderScale) + model.scroll.x , Sa.y1 <| toString <| (road.start.y * model.renderScale) + model.scroll.y , Sa.x2 <| toString <| (road.end.x * model.renderScale) + model.scroll.x , Sa.y2 <| toString <| (road.end.y * model.renderScale) + model.scroll.y , Sa.strokeWidth <| toString <| model.renderScale * 0.3 , Sa.stroke "green" ] [] , S.circle [ Sa.cx <| toString <| (road.end.x * model.renderScale) + model.scroll.x , Sa.cy <| toString <| (road.end.y * model.renderScale) + model.scroll.y , Sa.fill "yellow" , Sa.r <| toString <| model.renderScale / 2 , Sa.stroke "black" , Sa.strokeWidth <| toString <| model.renderScale / 20 ] [] ] ) (( case model.currentSelectedRoad of Just road -> [road] Nothing -> [] ) ++ ( case model.otherRoad of Just road -> [road] Nothing -> [] )) ) ++ ( case model.currentDragCar of Just car -> renderCars model [toCar car] Nothing -> [] ) ++ ( case (model.buildingRoadStart, model.mouse) of (Just start, Just mouse) -> let f = if model.snap then pRound else identity road = Road "" (f start) (f mouse) [] Nothing 1.5 in renderRoads model [road] _ -> [] ) ) ] ] ++ ( if model.popup == NoPopup then [] else [ div [ style <| centerFill model ] [div [ style (centerFill model ++ [ ("background-color", "#A64") , ("opacity", "0.6")] )] [] , generatePopup model.popup model ] ] ) ) centerFill model = [ ("position", "absolute") , ("width", "100%") , ("height", (Maybe.withDefault "10" <| Maybe.map (toString << .y) model.size) ++ "px")] generatePopup : Popup -> Model -> Html Msg generatePopup popup model = div [style <| centerFill model] <| case popup of NoPopup -> [] InfoPopup debug -> [ div [style [("text-align", "center")]] ( [ h3 [] [pre [] [text "Keys:"]] , pre [] [text "+ Zoom in"] , pre [] [text "- Zoom out"] , pre [] [text "w Accelerate"] , pre [] [text "s Active breaks"] , pre [] [text "a/d Steer left/right"] , pre [] [text "q Drive backwards"] ] ++ List.filterMap (\button -> case button.hotKey of Just hotKey -> Just <| pre [] [text <| button.image ++ ": " ++ String.join "-" hotKey] Nothing -> Nothing ) model.menu.buttons ++ [ button [ onClick InfoToggleDebug ] [text <| if debug then "Hide Debug" else "Show Debug"] , br [] [] ] ++ (if debug then [ h3 [] [pre [] [text "Debug info:"]] ] ++ ( List.filterMap (\(prop, name) -> case prop of Just val -> Just (pre [] [text <| name ++ ": " ++ (toString val)]) Nothing -> Nothing ) ( [ (Maybe.map toString model.ip, "Ip") , (Maybe.map toString model.size, "Screen size") , (Maybe.map toString model.trackingCar, "Tracking car") , (Maybe.map toString model.currentSelectedRoad, "Current selected road") , (Just <| toString model.keyCombo, "Current combo") , (Just <| toString model.keyComboTimeLeft, "Time left on combo") ] ) ++ ( case model.err of Just err -> [ p [style [("color", "red")]] [text <| "An error occured. Error was: " ++ toString err] ] Nothing -> [] ) ) else []) ++ [ button [ onClick ClosePopup ] [text "Done!"] ] )] LoginPopup name -> [ div [style [ ("text-align", "center") , ("margin-top", "200px") ]] [ h1 [style [("font-family", "Impact")]] [text "Username:"] , Html.form [ onSubmit Login ] ( [ input [ placeholder "<NAME>" , onInput UpdateText , style [("font-size", "40px")] ] [] , br [] [] , button [disabled <| String.length name <= 0 || String.length name >= nameLengthMax] [text "Login!"] ] ++ [ if String.length name >= nameLengthMax then p [style [("color", "red")]] [text "u boot too big 4 me big boi. u need 2 b less fat pls."] else br [] [] ] ) ] ] CommandPopup cmd -> [ div [ class "cmd" ] [ div [ class "cmdLog" ] <| List.map (\log -> pre [] [text log]) model.cmdLog , div [] [ Html.form [ onSubmit SendCommand ] [ button [ class "rightButton" ] [text "Send command"] , span [ class "wrapper" ] [ input [ class "cmdInp" , placeholder "DENY * view" , onInput UpdateText , value cmd ] [] ] ] , button [ onClick ClosePopup ] [text "Done"] , button [ onClick ClearLogs ] [text "Clear"] ] ] ] subscriptions : Model -> Sub Msg subscriptions model = Sub.batch [ Window.resizes Resize , Time.every (Time.second / 30) UpdateClient , Mouse.downs MousePress , Mouse.ups MouseRelease , Mouse.moves MouseMove , Keyboard.downs KeyCodeDown , Keyboard.ups KeyCodeUp , WebSocket.listen model.webSocketUrl ServerSync ]
true
module Main exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Html.Lazy exposing (..) import Http import Task import Json.Decode as Decode exposing (decodeString) import Json.Encode exposing (encode) import Svg as S import Svg.Attributes as Sa import Window import Time exposing (Time) import Mouse import Keyboard import WebSocket import List.Extra exposing (isSuffixOf) import Base exposing (..) import TrafficRenderer exposing (..) import MenuRenderer exposing (renderMenu) import JsonParser exposing (..) import Debug type alias Flags = { webSocketUrl : String , controls : Controls } main = Html.programWithFlags { init = init, view = view, update = update, subscriptions = subscriptions } init : Flags -> ( Model, Cmd Msg ) init flags = ( { cars = [] , roads = [] , err = Nothing , size = Nothing , lasttime = Nothing , scroll = {x=0, y=0} , dragMouse = Nothing , mouse = Nothing , renderScale = 40.0 , webSocketUrl = flags.webSocketUrl , ip = Nothing , accelRate = 6.0 , steerRate = 200.0 , lastClickTime = Nothing , trackingCar = Nothing , controls = flags.controls , others = [] , keyCombo = [] , keyComboTimeLeft = 0 , currentDragCar = Nothing , hiddenRoads = [] , snap = False , buildingRoad = False , buildingRoadStart = Nothing , selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing , cmdLog = [] , popup = NoPopup , menu = defaultMenu } , Task.perform identity <| Task.succeed CheckSize ) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ServerSync json -> let result = decodeString decodeTraffic json in case result of Ok traffic -> ( { model | cars = traffic.cars , roads = traffic.roads , others = traffic.others , ip = Just traffic.ip , err = Nothing , menu = let menu = model.menu in { menu | buttons = generateMenuButtons traffic } } , Task.perform identity <| Task.succeed FixScroll ) Err error -> let cmdRes = decodeString decodeRes json in case cmdRes of Ok res -> ( { model | cmdLog = model.cmdLog ++ [" " ++ res.cmd] } , Cmd.none ) Err _ -> ( { model | err = Just error } , Cmd.none ) Resize size -> ( { model | size = Just { x = toFloat size.width, y = toFloat size.height } }, Cmd.none ) CheckSize -> ( model, Task.perform Resize <| Window.size ) UpdateClient time -> case model.lasttime of Nothing -> ( { model | lasttime = Just time }, Cmd.none ) Just lasttime -> let delta = Time.inSeconds (time - lasttime) in ( { model | lasttime = Just time , keyComboTimeLeft = if model.keyComboTimeLeft > 0 then model.keyComboTimeLeft - delta else 0 , keyCombo = if model.keyComboTimeLeft > 0 then model.keyCombo else [] , cars = List.map (\car -> { car | pos = pAdd car.pos <| (\( x, y ) -> { x = x, y = y }) <| fromPolar ( car.speed * delta, degrees car.rot ) , speed = (if car.handBreaks then car.speed * (car.breakStrength ^ delta) else car.speed) + car.accel * delta , rot = car.rot + car.steering * delta , steering = case model.err of Just _ -> car.steering / (2 ^ delta) Nothing -> car.steering } ) model.cars , menu = let menu = model.menu in { menu | rotation = case menu.state of In -> if menu.rotation > 0 then menu.rotation - delta * 5 else 0 Out -> if menu.rotation < 1 then menu.rotation + delta * 5 else 1 } } , Task.perform identity <| Task.succeed FixScroll ) FixScroll -> ( {model | scroll = case (model.size, model.trackingCar) of (Just size, Just carName) -> let car_ = List.head <| List.filter (\car -> car.name == carName) model.cars in case car_ of Just car -> { x = -car.pos.x * model.renderScale + size.x / 2, y = -car.pos.y * model.renderScale + size.y / 2 } Nothing -> model.scroll _ -> model.scroll }, Cmd.none ) MouseRelease _ -> case model.popup of NoPopup -> ( {model | dragMouse = Nothing, lastClickTime = model.lasttime}, Cmd.none ) _ -> ( model, Cmd.none ) MousePress pos -> case model.popup of NoPopup -> if model.buildingRoad then case model.buildingRoadStart of Nothing -> let start = { x = (toFloat pos.x - model.scroll.x) / model.renderScale , y = (toFloat pos.y - model.scroll.y) / model.renderScale } start_ = if model.snap then pRound start else start in ( { model | buildingRoadStart = Just start_ }, Cmd.none ) Just start -> ( { model | buildingRoadStart = Nothing , buildingRoad = False }, case model.mouse of Just mouse -> let mouse_ = if model.snap then pRound mouse else mouse in WebSocket.send model.webSocketUrl <| String.join "/" [ "rbuild" , toString <| start.x , toString <| start.y , toString <| mouse_.x , toString <| mouse_.y ] Nothing -> Cmd.none ) else case model.selectState of CombineSelecting -> case (model.currentSelectedRoad, model.otherRoad) of (Just road, Nothing) -> ( { model | otherRoad = Just road } , Cmd.none ) (Just road, Just other) -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing } , WebSocket.send model.webSocketUrl <| String.join "/" [ "rconn" , other.id , road.id ] ) _ -> ( model, Cmd.none ) RemoveSelecting -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing } , WebSocket.send model.webSocketUrl <| "rrm/" ++ road.id ) FlipSelecting -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing } , WebSocket.send model.webSocketUrl <| "rflip/" ++ road.id ) HideSelecting -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , hiddenRoads = if List.member road.id model.hiddenRoads then List.filter (\x -> x /= road.id) model.hiddenRoads else List.append model.hiddenRoads [road.id] } , Cmd.none ) LightSelecting lState -> case model.currentSelectedRoad of Nothing -> ( model, Cmd.none ) Just road -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing } , WebSocket.send model.webSocketUrl <| case lState of AddLight -> "lbuild/" ++ road.id RemoveLight -> "lrm/" ++ road.id FlipLight -> "lflip/" ++ road.id ) TrackSelecting -> case model.mouse of Nothing -> ( model, Cmd.none ) Just pos -> let closest = getClosestCar pos model.cars in case closest of Nothing -> ( model, Cmd.none ) Just car -> ( { model | selectState = NotSelecting , trackingCar = Just car.name } , Cmd.none ) IntersectionMakeSelecting -> case (model.currentSelectedRoad, model.otherRoad) of (Just road, Nothing) -> ( { model | otherRoad = Just road } , Cmd.none ) (Just road, Just other) -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing } , WebSocket.send model.webSocketUrl <| String.join "/" [ "intermake" , other.id , road.id ] ) _ -> ( model, Cmd.none ) AICarSelecting -> case (model.currentSelectedRoad, model.otherRoad) of (Just road, Nothing) -> ( { model | otherRoad = Just road } , Cmd.none ) (Just road, Just other) -> ( { model | selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing } , WebSocket.send model.webSocketUrl <| String.join "/" [ "createai" , other.id , road.id ] ) _ -> ( model, Cmd.none ) NotSelecting -> ( {model | dragMouse = Just {x = toFloat pos.x, y = toFloat pos.y} , currentDragCar = Nothing} , case model.currentDragCar of Just car -> WebSocket.send model.webSocketUrl <| "create/" ++ (Http.encodeUri <| encode 0 <| encodeProtoCar car) Nothing -> Cmd.none ) _ -> ( model, Cmd.none ) MouseMove pos -> case model.popup of NoPopup -> let track = case model.trackingCar of Nothing -> False Just name -> List.length (List.filter (\car -> car.name == name) model.cars) > 0 mouse = { x = (toFloat pos.x - model.scroll.x) / model.renderScale , y = (toFloat pos.y - model.scroll.y) / model.renderScale } model_ = {model | mouse = Just mouse , currentSelectedRoad = if model.selectState /= NotSelecting && model.selectState /= TrackSelecting then getClosestRoad mouse <| List.filter (\road -> not <| List.member road.id model.hiddenRoads) model.roads else model.currentSelectedRoad } in if not track then case model_.dragMouse of Just mousePos -> let delta = {x = toFloat pos.x - mousePos.x, y = toFloat pos.y - mousePos.y} in ( {model_ | scroll = {x = model_.scroll.x + delta.x, y = model_.scroll.y + delta.y}, dragMouse = Just {x = toFloat pos.x, y = toFloat pos.y}}, Cmd.none ) Nothing -> case model_.currentDragCar of Just car -> ( { model_ | currentDragCar = Just {car | pos = {x = (toFloat pos.x - model_.scroll.x) / model_.renderScale, y = (toFloat pos.y - model_.scroll.y) / model_.renderScale}} }, Cmd.none ) Nothing -> ( model_, Cmd.none ) else ( model_, Cmd.none ) _ -> ( model, Cmd.none ) KeyCodeDown code -> case keyboardMap !! code of Just key -> update (KeyDown key) model Nothing -> ( model, Cmd.none ) KeyCodeUp code -> case keyboardMap !! code of Just key -> update (KeyUp key) model Nothing -> ( model, Cmd.none ) KeyDown key -> if key == model.controls.free then ( {model | trackingCar = Nothing , currentDragCar = Nothing , buildingRoad = False , buildingRoadStart = Nothing , selectState = NotSelecting , currentSelectedRoad = Nothing , otherRoad = Nothing , popup = NoPopup , keyCombo = [] , menu = let menu = model.menu in { menu | state = In } }, Cmd.none ) else case model.popup of NoPopup -> if key == model.controls.zoomIn then -- Plus key ( {model | renderScale = model.renderScale * zoomFactor , scroll = case model.size of Just size -> {x = (model.scroll.x - size.x / 2) * zoomFactor + size.x / 2, y = (model.scroll.y - size.y / 2) * zoomFactor + size.y / 2} Nothing -> model.scroll }, Cmd.none ) else if key == model.controls.zoomOut then -- Minus key ( {model | renderScale = model.renderScale / zoomFactor , scroll = case model.size of Just size -> {x = (model.scroll.x - size.x / 2) / zoomFactor + size.x / 2, y = (model.scroll.y - size.y / 2) / zoomFactor + size.y / 2} Nothing -> model.scroll }, Cmd.none ) else case model.ip of Just myIp -> if key == model.controls.remove then ( model , let distToScroll car = Tuple.first <| toPolar <| (car.pos.x - model.scroll.x, car.pos.y - model.scroll.y) closestCar = List.head <| List.sortWith (\c1 c2 -> compare (distToScroll c2) (distToScroll c1) ) <| List.filter (\c -> c.controlledBy == model.ip) model.cars in case closestCar of Just {name} -> WebSocket.send model.webSocketUrl <| "remove/" ++ name Nothing -> Cmd.none ) else if key == model.controls.break then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = True, accel = 0} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "breaks" ) else if key == model.controls.up then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = False, accel = model.accelRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "accel/" ++ (toString model.accelRate) ) ) else if key == model.controls.back then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = False, accel = negate model.accelRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "accel/" ++ (toString <| negate model.accelRate) ) ) else if key == model.controls.left then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | steering = negate model.steerRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "steer/" ++ (toString <| negate model.steerRate)) ) else if key == model.controls.right then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | steering = model.steerRate} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl ( "steer/" ++ (toString model.steerRate))) else if key == model.controls.carUp || key == model.controls.carDown then ( { model | trackingCar = let controlledByMe = List.sortWith (\car1 car2 -> compare car1.pos.x car2.pos.x) <| case model.ip of Just ip -> List.filter (\car -> case car.controlledBy of Just c -> c == ip Nothing -> False) model.cars Nothing -> [] in case model.trackingCar of Nothing -> Maybe.map .name <| List.head controlledByMe Just trackName -> let track = List.head <| List.filter (\(idx, car) -> car.name == trackName) (List.indexedMap (,) controlledByMe) in case track of Just (idx, car) -> let res = if key == model.controls.carUp then Maybe.map .name <| List.head <| List.drop (idx+1) controlledByMe else if idx == 0 then Nothing else Maybe.map .name <| List.head <| List.drop (idx-1) <| controlledByMe in case res of Just x -> Just x Nothing -> if key == model.controls.carUp then Maybe.map .name <| List.head controlledByMe else Maybe.map .name <| List.head <| List.reverse controlledByMe Nothing -> Maybe.map .name <| List.head controlledByMe } , Cmd.none ) else if key == model.controls.snap then ( { model | snap = True }, Cmd.none ) else if key == model.controls.hide && model.currentSelectedRoad /= Nothing then case model.currentSelectedRoad of Just road -> ( { model | hiddenRoads = model.hiddenRoads ++ [road.id]} , Cmd.none ) Nothing -> ( model, Cmd.none ) else if key == model.controls.help then ( { model | popup = InfoPopup False }, Cmd.none ) else let currentCombo = if model.keyComboTimeLeft > 0 then model.keyCombo else [] combo = Debug.log "Combo" <| currentCombo ++ [key] matching = Debug.log "Matching" <| List.filter (\button -> case button.hotKey of Just hotKey -> isSuffixOf hotKey combo Nothing -> False) model.menu.buttons sorted = Debug.log "Sorted" <| List.sortBy (negate << List.length << (Maybe.withDefault []) << .hotKey) matching first = List.head sorted in case first of Just button -> ( {model | keyCombo = [], keyComboTimeLeft = 1}, Task.perform identity <| Task.succeed button.message ) Nothing -> (always ({model | keyCombo = combo, keyComboTimeLeft = 1}, Cmd.none)) <| Debug.log "Key Down" key Nothing -> ( model, Cmd.none ) _ -> ( model, Cmd.none ) KeyUp key -> case model.popup of NoPopup -> case model.ip of Just myIp -> if key == model.controls.break then -- k ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | handBreaks = False} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "no_breaks" ) else if key == model.controls.up || key == model.controls.back then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | accel = 0} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "accel/0" ) else if key == model.controls.left || key == model.controls.right then ( { model | cars = List.map (\car -> case car.controlledBy of Just ip -> if ip /= myIp then car else {car | steering = 0} Nothing -> car ) model.cars}, WebSocket.send model.webSocketUrl "steer/0" ) else if key == model.controls.snap then ( { model | snap = False }, Cmd.none ) else (always (model, Cmd.none)) <| Debug.log "Key Up" key Nothing -> ( model, Cmd.none ) _ -> ( model, Cmd.none ) MenuBallClicked -> ( { model | menu = let menu = model.menu in { menu | state = case model.menu.state of In -> Out Out -> In } }, Cmd.none ) MenuButtonClicked msg -> ( { model | menu = let menu = model.menu in { menu | state = In } }, Task.perform identity <| Task.succeed msg ) AddCarClicked police -> ( { model | currentDragCar = Just {pos = {x = 0, y = 0}, img = if police then "CarPolis" else "Car1", isPolice = police} }, Cmd.none ) AddRoadClicked -> ( { model | buildingRoad = True } , Cmd.none ) SelectStateChange state -> ( { model | selectState = state } , Cmd.none ) ShowRoadClicked -> ( { model | hiddenRoads = [] } , Cmd.none ) ClosePopup -> ( { model | popup = NoPopup } , Cmd.none ) OpenPopup pop -> ( { model | popup = pop } , Cmd.none) InfoToggleDebug -> ( { model | popup = case model.popup of InfoPopup debug -> InfoPopup <| not debug _ -> model.popup } , Cmd.none ) UpdateText text -> case model.popup of LoginPopup _ -> ( { model | popup = LoginPopup text } , Cmd.none ) CommandPopup _ -> ( { model | popup = CommandPopup text } , Cmd.none ) _ -> ( model, Cmd.none ) SendCommand -> case model.popup of CommandPopup cmd -> ( { model | popup = CommandPopup "" , cmdLog = model.cmdLog ++ [cmd] } , WebSocket.send model.webSocketUrl <| "cmd/" ++ cmd) _ -> ( model, Cmd.none ) ClearLogs -> ( { model | cmdLog = []} , Cmd.none ) Login -> case model.popup of LoginPopup name -> if String.length name < nameLengthMax && String.length name > 0 then ( { model | popup = NoPopup } , WebSocket.send model.webSocketUrl <| "login/" ++ name) else ( model, Cmd.none ) _ -> ( model, Cmd.none ) view : Model -> Html Msg view model = div [ style [ ("margin-top", "0px") , ("padding-top", "0px") ] ] ([ div ( [ style [ ("margin", "0px") , ("top", "0px") , ("position", "fixed")] ] ++ case model.popup of NoPopup -> [] _ -> [ class "blur" ] ) [ -- Generate svg! S.svg [ Sa.width <| Maybe.withDefault "10" <| Maybe.map (toString << .x) model.size , Sa.height <| Maybe.withDefault "10" <| Maybe.map (toString << .y) model.size , Sa.style "background: #227722" ] (let cars_ = case (model.selectState, model.mouse) of (TrackSelecting, Just pos) -> case getClosestCar pos model.cars of Just closest -> List.map (\car -> if car == closest then { car | size = car.size * 1.3 } else car) model.cars Nothing -> model.cars _ -> model.cars lines = renderBackgroundLines model roads = renderRoads model model.roads cars = renderCars model cars_ trafficLights = renderTrafficLights model model.roads menu = renderMenu model in lines ++ roads ++ cars ++ trafficLights ++ menu ++ ( List.concatMap (\road -> [ S.line [ Sa.x1 <| toString <| (road.start.x * model.renderScale) + model.scroll.x , Sa.y1 <| toString <| (road.start.y * model.renderScale) + model.scroll.y , Sa.x2 <| toString <| (road.end.x * model.renderScale) + model.scroll.x , Sa.y2 <| toString <| (road.end.y * model.renderScale) + model.scroll.y , Sa.strokeWidth <| toString <| model.renderScale * 0.3 , Sa.stroke "green" ] [] , S.circle [ Sa.cx <| toString <| (road.end.x * model.renderScale) + model.scroll.x , Sa.cy <| toString <| (road.end.y * model.renderScale) + model.scroll.y , Sa.fill "yellow" , Sa.r <| toString <| model.renderScale / 2 , Sa.stroke "black" , Sa.strokeWidth <| toString <| model.renderScale / 20 ] [] ] ) (( case model.currentSelectedRoad of Just road -> [road] Nothing -> [] ) ++ ( case model.otherRoad of Just road -> [road] Nothing -> [] )) ) ++ ( case model.currentDragCar of Just car -> renderCars model [toCar car] Nothing -> [] ) ++ ( case (model.buildingRoadStart, model.mouse) of (Just start, Just mouse) -> let f = if model.snap then pRound else identity road = Road "" (f start) (f mouse) [] Nothing 1.5 in renderRoads model [road] _ -> [] ) ) ] ] ++ ( if model.popup == NoPopup then [] else [ div [ style <| centerFill model ] [div [ style (centerFill model ++ [ ("background-color", "#A64") , ("opacity", "0.6")] )] [] , generatePopup model.popup model ] ] ) ) centerFill model = [ ("position", "absolute") , ("width", "100%") , ("height", (Maybe.withDefault "10" <| Maybe.map (toString << .y) model.size) ++ "px")] generatePopup : Popup -> Model -> Html Msg generatePopup popup model = div [style <| centerFill model] <| case popup of NoPopup -> [] InfoPopup debug -> [ div [style [("text-align", "center")]] ( [ h3 [] [pre [] [text "Keys:"]] , pre [] [text "+ Zoom in"] , pre [] [text "- Zoom out"] , pre [] [text "w Accelerate"] , pre [] [text "s Active breaks"] , pre [] [text "a/d Steer left/right"] , pre [] [text "q Drive backwards"] ] ++ List.filterMap (\button -> case button.hotKey of Just hotKey -> Just <| pre [] [text <| button.image ++ ": " ++ String.join "-" hotKey] Nothing -> Nothing ) model.menu.buttons ++ [ button [ onClick InfoToggleDebug ] [text <| if debug then "Hide Debug" else "Show Debug"] , br [] [] ] ++ (if debug then [ h3 [] [pre [] [text "Debug info:"]] ] ++ ( List.filterMap (\(prop, name) -> case prop of Just val -> Just (pre [] [text <| name ++ ": " ++ (toString val)]) Nothing -> Nothing ) ( [ (Maybe.map toString model.ip, "Ip") , (Maybe.map toString model.size, "Screen size") , (Maybe.map toString model.trackingCar, "Tracking car") , (Maybe.map toString model.currentSelectedRoad, "Current selected road") , (Just <| toString model.keyCombo, "Current combo") , (Just <| toString model.keyComboTimeLeft, "Time left on combo") ] ) ++ ( case model.err of Just err -> [ p [style [("color", "red")]] [text <| "An error occured. Error was: " ++ toString err] ] Nothing -> [] ) ) else []) ++ [ button [ onClick ClosePopup ] [text "Done!"] ] )] LoginPopup name -> [ div [style [ ("text-align", "center") , ("margin-top", "200px") ]] [ h1 [style [("font-family", "Impact")]] [text "Username:"] , Html.form [ onSubmit Login ] ( [ input [ placeholder "PI:NAME:<NAME>END_PI" , onInput UpdateText , style [("font-size", "40px")] ] [] , br [] [] , button [disabled <| String.length name <= 0 || String.length name >= nameLengthMax] [text "Login!"] ] ++ [ if String.length name >= nameLengthMax then p [style [("color", "red")]] [text "u boot too big 4 me big boi. u need 2 b less fat pls."] else br [] [] ] ) ] ] CommandPopup cmd -> [ div [ class "cmd" ] [ div [ class "cmdLog" ] <| List.map (\log -> pre [] [text log]) model.cmdLog , div [] [ Html.form [ onSubmit SendCommand ] [ button [ class "rightButton" ] [text "Send command"] , span [ class "wrapper" ] [ input [ class "cmdInp" , placeholder "DENY * view" , onInput UpdateText , value cmd ] [] ] ] , button [ onClick ClosePopup ] [text "Done"] , button [ onClick ClearLogs ] [text "Clear"] ] ] ] subscriptions : Model -> Sub Msg subscriptions model = Sub.batch [ Window.resizes Resize , Time.every (Time.second / 30) UpdateClient , Mouse.downs MousePress , Mouse.ups MouseRelease , Mouse.moves MouseMove , Keyboard.downs KeyCodeDown , Keyboard.ups KeyCodeUp , WebSocket.listen model.webSocketUrl ServerSync ]
elm
[ { "context": "\n Evaluation contexts for Haskelite expressions\n Pedro Vasconcelos, 2021\n-} \nmodule Context exposing (..)\n\nimport AS", "end": 70, "score": 0.9998725057, "start": 53, "tag": "NAME", "value": "Pedro Vasconcelos" } ]
src/Context.elm
pbv/haskelite
0
{- Evaluation contexts for Haskelite expressions Pedro Vasconcelos, 2021 -} module Context exposing (..) import AST exposing (Expr(..)) import Monocle.Common as Monocle import Monocle.Optional exposing (Optional) -- * evaluation contexts type alias Context = Optional Expr Expr -- empty context hole : Context hole = { getOption = \expr -> Just expr , set = \new _ -> new } -- contexts for list construtor cons0 : Context cons0 = { getOption= \e -> case e of App (Var ":") [e0, _] -> Just e0 _ -> Nothing , set= \e0 e -> case e of App (Var ":") [_, e1] -> App (Var ":") [e0,e1] _ -> e } cons1 : Context cons1 = { getOption= \e -> case e of App (Var ":") [_, e1] -> Just e1 _ -> Nothing , set= \e1 e -> case e of App (Var ":") [e0, _] -> App (Var ":") [e0, e1] _ -> e } -- contexts for looking into infix operators infixOp0 : Context infixOp0 = { getOption= \e -> case e of InfixOp _ e0 _ -> Just e0 _ -> Nothing , set= \e0 e -> case e of InfixOp op _ e1 -> InfixOp op e0 e1 _ -> e } infixOp1 : Context infixOp1 = { getOption = \e -> case e of InfixOp _ _ e1 -> Just e1 _ -> Nothing , set = \e1 e -> case e of InfixOp op e0 _ -> InfixOp op e0 e1 _ -> e } -- contexts for looking into applications app0 : Context app0 = { getOption = \e -> case e of App e0 _ -> Just e0 _ -> Nothing , set = \e0 e -> case e of App _ args -> App e0 args _ -> e } appArg : Int -> Context appArg i = { getOption = \e -> case e of App _ args -> .getOption (Monocle.list i) args _ -> Nothing , set = \n e -> case e of App e0 args -> App e0 (.set (Monocle.list i) n args) _ -> e } -- contexts for literal lists and tuples listItem : Int -> Context listItem i = { getOption = \e -> case e of ListLit items -> .getOption (Monocle.list i) items _ -> Nothing , set = \n e -> case e of ListLit items -> ListLit (.set (Monocle.list i) n items) _ -> e } tupleItem : Int -> Context tupleItem i = { getOption = \e -> case e of TupleLit items -> .getOption (Monocle.list i) items _ -> Nothing , set = \n e -> case e of TupleLit items -> TupleLit (.set (Monocle.list i) n items) _ -> e } --- contexts for if expressions if0 : Context if0 = { getOption = \e -> case e of IfThenElse e0 e1 e2 -> Just e0 _ -> Nothing , set = \e0 e -> case e of IfThenElse _ e1 e2 -> IfThenElse e0 e1 e2 _ -> e } if1 : Context if1 = { getOption = \e -> case e of IfThenElse e0 e1 e2 -> Just e1 _ -> Nothing , set = \e1 e -> case e of IfThenElse e0 _ e2 -> IfThenElse e0 e1 e2 _ -> e } if2 : Context if2 = { getOption = \e -> case e of IfThenElse e0 e1 e2 -> Just e2 _ -> Nothing , set = \e2 e -> case e of IfThenElse e0 e1 _ -> IfThenElse e0 e1 e2 _ -> e }
22367
{- Evaluation contexts for Haskelite expressions <NAME>, 2021 -} module Context exposing (..) import AST exposing (Expr(..)) import Monocle.Common as Monocle import Monocle.Optional exposing (Optional) -- * evaluation contexts type alias Context = Optional Expr Expr -- empty context hole : Context hole = { getOption = \expr -> Just expr , set = \new _ -> new } -- contexts for list construtor cons0 : Context cons0 = { getOption= \e -> case e of App (Var ":") [e0, _] -> Just e0 _ -> Nothing , set= \e0 e -> case e of App (Var ":") [_, e1] -> App (Var ":") [e0,e1] _ -> e } cons1 : Context cons1 = { getOption= \e -> case e of App (Var ":") [_, e1] -> Just e1 _ -> Nothing , set= \e1 e -> case e of App (Var ":") [e0, _] -> App (Var ":") [e0, e1] _ -> e } -- contexts for looking into infix operators infixOp0 : Context infixOp0 = { getOption= \e -> case e of InfixOp _ e0 _ -> Just e0 _ -> Nothing , set= \e0 e -> case e of InfixOp op _ e1 -> InfixOp op e0 e1 _ -> e } infixOp1 : Context infixOp1 = { getOption = \e -> case e of InfixOp _ _ e1 -> Just e1 _ -> Nothing , set = \e1 e -> case e of InfixOp op e0 _ -> InfixOp op e0 e1 _ -> e } -- contexts for looking into applications app0 : Context app0 = { getOption = \e -> case e of App e0 _ -> Just e0 _ -> Nothing , set = \e0 e -> case e of App _ args -> App e0 args _ -> e } appArg : Int -> Context appArg i = { getOption = \e -> case e of App _ args -> .getOption (Monocle.list i) args _ -> Nothing , set = \n e -> case e of App e0 args -> App e0 (.set (Monocle.list i) n args) _ -> e } -- contexts for literal lists and tuples listItem : Int -> Context listItem i = { getOption = \e -> case e of ListLit items -> .getOption (Monocle.list i) items _ -> Nothing , set = \n e -> case e of ListLit items -> ListLit (.set (Monocle.list i) n items) _ -> e } tupleItem : Int -> Context tupleItem i = { getOption = \e -> case e of TupleLit items -> .getOption (Monocle.list i) items _ -> Nothing , set = \n e -> case e of TupleLit items -> TupleLit (.set (Monocle.list i) n items) _ -> e } --- contexts for if expressions if0 : Context if0 = { getOption = \e -> case e of IfThenElse e0 e1 e2 -> Just e0 _ -> Nothing , set = \e0 e -> case e of IfThenElse _ e1 e2 -> IfThenElse e0 e1 e2 _ -> e } if1 : Context if1 = { getOption = \e -> case e of IfThenElse e0 e1 e2 -> Just e1 _ -> Nothing , set = \e1 e -> case e of IfThenElse e0 _ e2 -> IfThenElse e0 e1 e2 _ -> e } if2 : Context if2 = { getOption = \e -> case e of IfThenElse e0 e1 e2 -> Just e2 _ -> Nothing , set = \e2 e -> case e of IfThenElse e0 e1 _ -> IfThenElse e0 e1 e2 _ -> e }
true
{- Evaluation contexts for Haskelite expressions PI:NAME:<NAME>END_PI, 2021 -} module Context exposing (..) import AST exposing (Expr(..)) import Monocle.Common as Monocle import Monocle.Optional exposing (Optional) -- * evaluation contexts type alias Context = Optional Expr Expr -- empty context hole : Context hole = { getOption = \expr -> Just expr , set = \new _ -> new } -- contexts for list construtor cons0 : Context cons0 = { getOption= \e -> case e of App (Var ":") [e0, _] -> Just e0 _ -> Nothing , set= \e0 e -> case e of App (Var ":") [_, e1] -> App (Var ":") [e0,e1] _ -> e } cons1 : Context cons1 = { getOption= \e -> case e of App (Var ":") [_, e1] -> Just e1 _ -> Nothing , set= \e1 e -> case e of App (Var ":") [e0, _] -> App (Var ":") [e0, e1] _ -> e } -- contexts for looking into infix operators infixOp0 : Context infixOp0 = { getOption= \e -> case e of InfixOp _ e0 _ -> Just e0 _ -> Nothing , set= \e0 e -> case e of InfixOp op _ e1 -> InfixOp op e0 e1 _ -> e } infixOp1 : Context infixOp1 = { getOption = \e -> case e of InfixOp _ _ e1 -> Just e1 _ -> Nothing , set = \e1 e -> case e of InfixOp op e0 _ -> InfixOp op e0 e1 _ -> e } -- contexts for looking into applications app0 : Context app0 = { getOption = \e -> case e of App e0 _ -> Just e0 _ -> Nothing , set = \e0 e -> case e of App _ args -> App e0 args _ -> e } appArg : Int -> Context appArg i = { getOption = \e -> case e of App _ args -> .getOption (Monocle.list i) args _ -> Nothing , set = \n e -> case e of App e0 args -> App e0 (.set (Monocle.list i) n args) _ -> e } -- contexts for literal lists and tuples listItem : Int -> Context listItem i = { getOption = \e -> case e of ListLit items -> .getOption (Monocle.list i) items _ -> Nothing , set = \n e -> case e of ListLit items -> ListLit (.set (Monocle.list i) n items) _ -> e } tupleItem : Int -> Context tupleItem i = { getOption = \e -> case e of TupleLit items -> .getOption (Monocle.list i) items _ -> Nothing , set = \n e -> case e of TupleLit items -> TupleLit (.set (Monocle.list i) n items) _ -> e } --- contexts for if expressions if0 : Context if0 = { getOption = \e -> case e of IfThenElse e0 e1 e2 -> Just e0 _ -> Nothing , set = \e0 e -> case e of IfThenElse _ e1 e2 -> IfThenElse e0 e1 e2 _ -> e } if1 : Context if1 = { getOption = \e -> case e of IfThenElse e0 e1 e2 -> Just e1 _ -> Nothing , set = \e1 e -> case e of IfThenElse e0 _ e2 -> IfThenElse e0 e1 e2 _ -> e } if2 : Context if2 = { getOption = \e -> case e of IfThenElse e0 e1 e2 -> Just e2 _ -> Nothing , set = \e2 e -> case e of IfThenElse e0 e1 _ -> IfThenElse e0 e1 e2 _ -> e }
elm
[ { "context": "\"Test\"\n , email = \"test@test.com\"\n , photoURL = \"te", "end": 647, "score": 0.9999265671, "start": 634, "tag": "EMAIL", "value": "test@test.com" }, { "context": "\n { displayName = \"Test\"\n , email = \"test@", "end": 1302, "score": 0.5582540035, "start": 1298, "tag": "NAME", "value": "Test" }, { "context": "\"Test\"\n , email = \"test@test.com\"\n , photoURL = \"te", "end": 1360, "score": 0.9999238849, "start": 1347, "tag": "EMAIL", "value": "test@test.com" }, { "context": "\n { displayName = \"Test\"\n , email = \"test@", "end": 2039, "score": 0.7827138901, "start": 2035, "tag": "NAME", "value": "Test" }, { "context": "\"Test\"\n , email = \"test@test.com\"\n , photoURL = \"te", "end": 2097, "score": 0.9999257922, "start": 2084, "tag": "EMAIL", "value": "test@test.com" } ]
web/tests/TestSession.elm
MULXCODE/textusm
0
module TestSession exposing (all) import Data.IdToken as IdToken import Data.Session as Session import Expect import Test exposing (Test, describe, test) all : Test all = describe "Session test" [ describe "isGuest test" [ test "guest" <| \() -> Expect.equal (Session.isGuest Session.guest) True , test "not guest" <| \() -> Expect.equal (Session.isGuest <| Session.signIn { displayName = "Test" , email = "test@test.com" , photoURL = "test" , idToken = "test" , id = "test" } ) False ] , describe "isSignedIn test" [ test "signedIn" <| \() -> Expect.equal (Session.isSignedIn Session.guest) False , test "not guest" <| \() -> Expect.equal (Session.isSignedIn <| Session.signIn { displayName = "Test" , email = "test@test.com" , photoURL = "test" , idToken = "test" , id = "test" } ) True ] , describe "getIdToken test" [ test "guest idtoken is empty" <| \() -> Expect.equal (Session.getIdToken Session.guest) Nothing , test "signed in idtoken " <| \() -> Expect.equal (Session.getIdToken <| Session.signIn { displayName = "Test" , email = "test@test.com" , photoURL = "test" , idToken = "idToken" , id = "test" } ) (Just <| IdToken.fromString "idToken") ] ]
45217
module TestSession exposing (all) import Data.IdToken as IdToken import Data.Session as Session import Expect import Test exposing (Test, describe, test) all : Test all = describe "Session test" [ describe "isGuest test" [ test "guest" <| \() -> Expect.equal (Session.isGuest Session.guest) True , test "not guest" <| \() -> Expect.equal (Session.isGuest <| Session.signIn { displayName = "Test" , email = "<EMAIL>" , photoURL = "test" , idToken = "test" , id = "test" } ) False ] , describe "isSignedIn test" [ test "signedIn" <| \() -> Expect.equal (Session.isSignedIn Session.guest) False , test "not guest" <| \() -> Expect.equal (Session.isSignedIn <| Session.signIn { displayName = "<NAME>" , email = "<EMAIL>" , photoURL = "test" , idToken = "test" , id = "test" } ) True ] , describe "getIdToken test" [ test "guest idtoken is empty" <| \() -> Expect.equal (Session.getIdToken Session.guest) Nothing , test "signed in idtoken " <| \() -> Expect.equal (Session.getIdToken <| Session.signIn { displayName = "<NAME>" , email = "<EMAIL>" , photoURL = "test" , idToken = "idToken" , id = "test" } ) (Just <| IdToken.fromString "idToken") ] ]
true
module TestSession exposing (all) import Data.IdToken as IdToken import Data.Session as Session import Expect import Test exposing (Test, describe, test) all : Test all = describe "Session test" [ describe "isGuest test" [ test "guest" <| \() -> Expect.equal (Session.isGuest Session.guest) True , test "not guest" <| \() -> Expect.equal (Session.isGuest <| Session.signIn { displayName = "Test" , email = "PI:EMAIL:<EMAIL>END_PI" , photoURL = "test" , idToken = "test" , id = "test" } ) False ] , describe "isSignedIn test" [ test "signedIn" <| \() -> Expect.equal (Session.isSignedIn Session.guest) False , test "not guest" <| \() -> Expect.equal (Session.isSignedIn <| Session.signIn { displayName = "PI:NAME:<NAME>END_PI" , email = "PI:EMAIL:<EMAIL>END_PI" , photoURL = "test" , idToken = "test" , id = "test" } ) True ] , describe "getIdToken test" [ test "guest idtoken is empty" <| \() -> Expect.equal (Session.getIdToken Session.guest) Nothing , test "signed in idtoken " <| \() -> Expect.equal (Session.getIdToken <| Session.signIn { displayName = "PI:NAME:<NAME>END_PI" , email = "PI:EMAIL:<EMAIL>END_PI" , photoURL = "test" , idToken = "idToken" , id = "test" } ) (Just <| IdToken.fromString "idToken") ] ]
elm
[ { "context": " ticksADay\r\n@docs ticksAWeek\r\n\r\nCopyright (c) 2016 Robin Luiten\r\n-}\r\n\r\nimport Date exposing (Date, Day (..), Mont", "end": 1268, "score": 0.9998613596, "start": 1256, "tag": "NAME", "value": "Robin Luiten" } ]
src/Date/Core.elm
altworx/elm-date-extra
0
module Date.Core ( monthToInt , daysInMonth , monthList , daysInNextMonth , daysInPrevMonth , daysInMonthDate , isLeapYear , isLeapYearDate , yearToDayLength , isoDayOfWeek , toFirstOfMonth , firstOfNextMonthDate , lastOfMonthDate , lastOfPrevMonthDate , daysBackToStartOfWeek , fromTime , toTime , nextDay , prevDay , nextMonth , prevMonth , epochDateStr , ticksAMillisecond , ticksASecond , ticksAMinute , ticksAnHour , ticksADay , ticksAWeek ) where {-| Date core. ## Info @docs monthToInt @docs daysInMonth @docs monthList @docs daysInNextMonth @docs daysInPrevMonth @docs daysInMonthDate @docs isLeapYear @docs isLeapYearDate @docs yearToDayLength @docs isoDayOfWeek ## Utility @docs toFirstOfMonth @docs firstOfNextMonthDate @docs lastOfMonthDate @docs lastOfPrevMonthDate @docs daysBackToStartOfWeek ## Conversion @docs fromTime @docs toTime ## Iteration Utility @docs nextDay @docs prevDay @docs nextMonth @docs prevMonth ## Date constants @docs epochDateStr ## Date constants @docs ticksAMillisecond @docs ticksASecond @docs ticksAMinute @docs ticksAnHour @docs ticksADay @docs ticksAWeek Copyright (c) 2016 Robin Luiten -} import Date exposing (Date, Day (..), Month (..)) import Time -- _ = Debug.log("Date Const ticks") (ticksASecond, ticksAMinute, ticksAnHour, ticksADay, ticksAWeek) {-| Epoch starting point for tick 0. -} epochDateStr : String epochDateStr = "1970-01-01T00:00:00Z" {-| Ticks in a millisecond. (this is 1 on Win 7 in Chrome) -} ticksAMillisecond : Int ticksAMillisecond = floor Time.millisecond {-| Ticks in a second. -} ticksASecond : Int ticksASecond = ticksAMillisecond * 1000 {-| Ticks in a minute. -} ticksAMinute : Int ticksAMinute = ticksASecond * 60 {-| Ticks in an hour. -} ticksAnHour : Int ticksAnHour = ticksAMinute * 60 {-| Ticks in a day. -} ticksADay : Int ticksADay = ticksAnHour * 24 {-| Ticks in a week. -} ticksAWeek : Int ticksAWeek = ticksADay * 7 {-| Return the Iso DayOfWeek Monday 1, to Sunday 7. -} isoDayOfWeek : Date.Day -> Int isoDayOfWeek day = case day of Mon -> 1 Tue -> 2 Wed -> 3 Thu -> 4 Fri -> 5 Sat -> 6 Sun -> 7 {-| Return next day in calendar sequence. -} nextDay : Day -> Day nextDay day = case day of Mon -> Tue Tue -> Wed Wed -> Thu Thu -> Fri Fri -> Sat Sat -> Sun Sun -> Mon {-| Return previous day in calendar sequence. -} prevDay : Day -> Day prevDay day = case day of Mon -> Sun Tue -> Mon Wed -> Tue Thu -> Wed Fri -> Thu Sat -> Fri Sun -> Sat {-| Convenience fromTime as time ticks are Elm Ints in this library. -} fromTime : Int -> Date fromTime = Date.fromTime << toFloat {-| Convenience toTime as time ticks are Elm Ints in this library. -} toTime : Date -> Int toTime = floor << Date.toTime {-| List of months in order from Jan to Dec. -} monthList : List Month monthList = [ Jan , Feb , Mar , Apr , May , Jun , Jul , Aug , Sep , Oct , Nov , Dec ] {-| Return days in month for year month. -} daysInMonth : Int -> Month -> Int daysInMonth year month = case month of Jan -> 31 Feb -> if isLeapYear year then 29 else 28 Mar -> 31 Apr -> 30 May -> 31 Jun -> 30 Jul -> 31 Aug -> 31 Sep -> 30 Oct -> 31 Nov -> 30 Dec -> 31 {-| Days in month for given date. -} daysInMonthDate : Date -> Int daysInMonthDate date = daysInMonth (Date.year date) (Date.month date) -- go to Calendar {-| Return True if Year is a leap year. -} isLeapYear : Int -> Bool isLeapYear year = ((year % 4 == 0) && (year % 100 /= 0)) || ((year % 400) == 0) {-| Return True if Year of Date is a leap year. -} isLeapYearDate : Date -> Bool isLeapYearDate date = isLeapYear (Date.year date) {-| Return number of days in a year. -} yearToDayLength : Int -> Int yearToDayLength year = if isLeapYear year then 366 else 365 {-| Return days in next calendar month. -} daysInNextMonth : Date -> Int daysInNextMonth date = daysInMonthDate (firstOfNextMonthDate date) {-| Return days in previous calendar month. -} daysInPrevMonth : Date -> Int daysInPrevMonth date = daysInMonthDate (lastOfPrevMonthDate date) {-| Return month as integer. Jan = 1 to Dec = 12. -} monthToInt : Month -> Int monthToInt month = case month of Jan -> 1 Feb -> 2 Mar -> 3 Apr -> 4 May -> 5 Jun -> 6 Jul -> 7 Aug -> 8 Sep -> 9 Oct -> 10 Nov -> 11 Dec -> 12 {-| Return next month in calendar sequence. -} nextMonth : Month -> Month nextMonth month = case month of Jan -> Feb Feb -> Mar Mar -> Apr Apr -> May May -> Jun Jun -> Jul Jul -> Aug Aug -> Sep Sep -> Oct Oct -> Nov Nov -> Dec Dec -> Jan {-| Return previous month in calendar sequence. -} prevMonth : Month -> Month prevMonth month = case month of Jan -> Dec Feb -> Jan Mar -> Feb Apr -> Mar May -> Apr Jun -> May Jul -> Jun Aug -> Jul Sep -> Aug Oct -> Sep Nov -> Oct Dec -> Nov {-| Return first of next month date. -} firstOfNextMonthDate : Date -> Date firstOfNextMonthDate date = fromTime ((lastOfMonthTicks date) + ticksADay) {-| Return last of previous month date. -} lastOfPrevMonthDate : Date -> Date lastOfPrevMonthDate date = fromTime ((firstOfMonthTicks date) - ticksADay) {-| Return date of first of month. -} toFirstOfMonth : Date -> Date toFirstOfMonth date = fromTime (firstOfMonthTicks date) {- Return ticks to modify date to first of month. -} firstOfMonthTicks : Date -> Int firstOfMonthTicks date = let day = Date.day date dateTicks = toTime date -- _ = Debug.log("firstOfMonthTicks") (day, dateTicks) in dateTicks + ((1 - day) * ticksADay) {-| Resturn date of last day of month. -} lastOfMonthDate : Date -> Date lastOfMonthDate date = fromTime (lastOfMonthTicks date) {- Return ticks to modify date to last day of month. -} lastOfMonthTicks : Date -> Int lastOfMonthTicks date = let year = Date.year date month = Date.month date day = Date.day date dateTicks = toTime date -- _ = Debug.log("lastOfMonthTicks") (day, dateTicks) daysInMonthVal = daysInMonth year month addDays = daysInMonthVal - day in dateTicks + (addDays * ticksADay) {-| Days back to start of week day. -} daysBackToStartOfWeek : Date.Day -> Date.Day -> Int daysBackToStartOfWeek dateDay startOfWeekDay = let dateDayIndex = isoDayOfWeek dateDay startOfWeekDayIndex = isoDayOfWeek startOfWeekDay in if dateDayIndex < startOfWeekDayIndex then (7 + dateDayIndex) - startOfWeekDayIndex else dateDayIndex - startOfWeekDayIndex
38798
module Date.Core ( monthToInt , daysInMonth , monthList , daysInNextMonth , daysInPrevMonth , daysInMonthDate , isLeapYear , isLeapYearDate , yearToDayLength , isoDayOfWeek , toFirstOfMonth , firstOfNextMonthDate , lastOfMonthDate , lastOfPrevMonthDate , daysBackToStartOfWeek , fromTime , toTime , nextDay , prevDay , nextMonth , prevMonth , epochDateStr , ticksAMillisecond , ticksASecond , ticksAMinute , ticksAnHour , ticksADay , ticksAWeek ) where {-| Date core. ## Info @docs monthToInt @docs daysInMonth @docs monthList @docs daysInNextMonth @docs daysInPrevMonth @docs daysInMonthDate @docs isLeapYear @docs isLeapYearDate @docs yearToDayLength @docs isoDayOfWeek ## Utility @docs toFirstOfMonth @docs firstOfNextMonthDate @docs lastOfMonthDate @docs lastOfPrevMonthDate @docs daysBackToStartOfWeek ## Conversion @docs fromTime @docs toTime ## Iteration Utility @docs nextDay @docs prevDay @docs nextMonth @docs prevMonth ## Date constants @docs epochDateStr ## Date constants @docs ticksAMillisecond @docs ticksASecond @docs ticksAMinute @docs ticksAnHour @docs ticksADay @docs ticksAWeek Copyright (c) 2016 <NAME> -} import Date exposing (Date, Day (..), Month (..)) import Time -- _ = Debug.log("Date Const ticks") (ticksASecond, ticksAMinute, ticksAnHour, ticksADay, ticksAWeek) {-| Epoch starting point for tick 0. -} epochDateStr : String epochDateStr = "1970-01-01T00:00:00Z" {-| Ticks in a millisecond. (this is 1 on Win 7 in Chrome) -} ticksAMillisecond : Int ticksAMillisecond = floor Time.millisecond {-| Ticks in a second. -} ticksASecond : Int ticksASecond = ticksAMillisecond * 1000 {-| Ticks in a minute. -} ticksAMinute : Int ticksAMinute = ticksASecond * 60 {-| Ticks in an hour. -} ticksAnHour : Int ticksAnHour = ticksAMinute * 60 {-| Ticks in a day. -} ticksADay : Int ticksADay = ticksAnHour * 24 {-| Ticks in a week. -} ticksAWeek : Int ticksAWeek = ticksADay * 7 {-| Return the Iso DayOfWeek Monday 1, to Sunday 7. -} isoDayOfWeek : Date.Day -> Int isoDayOfWeek day = case day of Mon -> 1 Tue -> 2 Wed -> 3 Thu -> 4 Fri -> 5 Sat -> 6 Sun -> 7 {-| Return next day in calendar sequence. -} nextDay : Day -> Day nextDay day = case day of Mon -> Tue Tue -> Wed Wed -> Thu Thu -> Fri Fri -> Sat Sat -> Sun Sun -> Mon {-| Return previous day in calendar sequence. -} prevDay : Day -> Day prevDay day = case day of Mon -> Sun Tue -> Mon Wed -> Tue Thu -> Wed Fri -> Thu Sat -> Fri Sun -> Sat {-| Convenience fromTime as time ticks are Elm Ints in this library. -} fromTime : Int -> Date fromTime = Date.fromTime << toFloat {-| Convenience toTime as time ticks are Elm Ints in this library. -} toTime : Date -> Int toTime = floor << Date.toTime {-| List of months in order from Jan to Dec. -} monthList : List Month monthList = [ Jan , Feb , Mar , Apr , May , Jun , Jul , Aug , Sep , Oct , Nov , Dec ] {-| Return days in month for year month. -} daysInMonth : Int -> Month -> Int daysInMonth year month = case month of Jan -> 31 Feb -> if isLeapYear year then 29 else 28 Mar -> 31 Apr -> 30 May -> 31 Jun -> 30 Jul -> 31 Aug -> 31 Sep -> 30 Oct -> 31 Nov -> 30 Dec -> 31 {-| Days in month for given date. -} daysInMonthDate : Date -> Int daysInMonthDate date = daysInMonth (Date.year date) (Date.month date) -- go to Calendar {-| Return True if Year is a leap year. -} isLeapYear : Int -> Bool isLeapYear year = ((year % 4 == 0) && (year % 100 /= 0)) || ((year % 400) == 0) {-| Return True if Year of Date is a leap year. -} isLeapYearDate : Date -> Bool isLeapYearDate date = isLeapYear (Date.year date) {-| Return number of days in a year. -} yearToDayLength : Int -> Int yearToDayLength year = if isLeapYear year then 366 else 365 {-| Return days in next calendar month. -} daysInNextMonth : Date -> Int daysInNextMonth date = daysInMonthDate (firstOfNextMonthDate date) {-| Return days in previous calendar month. -} daysInPrevMonth : Date -> Int daysInPrevMonth date = daysInMonthDate (lastOfPrevMonthDate date) {-| Return month as integer. Jan = 1 to Dec = 12. -} monthToInt : Month -> Int monthToInt month = case month of Jan -> 1 Feb -> 2 Mar -> 3 Apr -> 4 May -> 5 Jun -> 6 Jul -> 7 Aug -> 8 Sep -> 9 Oct -> 10 Nov -> 11 Dec -> 12 {-| Return next month in calendar sequence. -} nextMonth : Month -> Month nextMonth month = case month of Jan -> Feb Feb -> Mar Mar -> Apr Apr -> May May -> Jun Jun -> Jul Jul -> Aug Aug -> Sep Sep -> Oct Oct -> Nov Nov -> Dec Dec -> Jan {-| Return previous month in calendar sequence. -} prevMonth : Month -> Month prevMonth month = case month of Jan -> Dec Feb -> Jan Mar -> Feb Apr -> Mar May -> Apr Jun -> May Jul -> Jun Aug -> Jul Sep -> Aug Oct -> Sep Nov -> Oct Dec -> Nov {-| Return first of next month date. -} firstOfNextMonthDate : Date -> Date firstOfNextMonthDate date = fromTime ((lastOfMonthTicks date) + ticksADay) {-| Return last of previous month date. -} lastOfPrevMonthDate : Date -> Date lastOfPrevMonthDate date = fromTime ((firstOfMonthTicks date) - ticksADay) {-| Return date of first of month. -} toFirstOfMonth : Date -> Date toFirstOfMonth date = fromTime (firstOfMonthTicks date) {- Return ticks to modify date to first of month. -} firstOfMonthTicks : Date -> Int firstOfMonthTicks date = let day = Date.day date dateTicks = toTime date -- _ = Debug.log("firstOfMonthTicks") (day, dateTicks) in dateTicks + ((1 - day) * ticksADay) {-| Resturn date of last day of month. -} lastOfMonthDate : Date -> Date lastOfMonthDate date = fromTime (lastOfMonthTicks date) {- Return ticks to modify date to last day of month. -} lastOfMonthTicks : Date -> Int lastOfMonthTicks date = let year = Date.year date month = Date.month date day = Date.day date dateTicks = toTime date -- _ = Debug.log("lastOfMonthTicks") (day, dateTicks) daysInMonthVal = daysInMonth year month addDays = daysInMonthVal - day in dateTicks + (addDays * ticksADay) {-| Days back to start of week day. -} daysBackToStartOfWeek : Date.Day -> Date.Day -> Int daysBackToStartOfWeek dateDay startOfWeekDay = let dateDayIndex = isoDayOfWeek dateDay startOfWeekDayIndex = isoDayOfWeek startOfWeekDay in if dateDayIndex < startOfWeekDayIndex then (7 + dateDayIndex) - startOfWeekDayIndex else dateDayIndex - startOfWeekDayIndex
true
module Date.Core ( monthToInt , daysInMonth , monthList , daysInNextMonth , daysInPrevMonth , daysInMonthDate , isLeapYear , isLeapYearDate , yearToDayLength , isoDayOfWeek , toFirstOfMonth , firstOfNextMonthDate , lastOfMonthDate , lastOfPrevMonthDate , daysBackToStartOfWeek , fromTime , toTime , nextDay , prevDay , nextMonth , prevMonth , epochDateStr , ticksAMillisecond , ticksASecond , ticksAMinute , ticksAnHour , ticksADay , ticksAWeek ) where {-| Date core. ## Info @docs monthToInt @docs daysInMonth @docs monthList @docs daysInNextMonth @docs daysInPrevMonth @docs daysInMonthDate @docs isLeapYear @docs isLeapYearDate @docs yearToDayLength @docs isoDayOfWeek ## Utility @docs toFirstOfMonth @docs firstOfNextMonthDate @docs lastOfMonthDate @docs lastOfPrevMonthDate @docs daysBackToStartOfWeek ## Conversion @docs fromTime @docs toTime ## Iteration Utility @docs nextDay @docs prevDay @docs nextMonth @docs prevMonth ## Date constants @docs epochDateStr ## Date constants @docs ticksAMillisecond @docs ticksASecond @docs ticksAMinute @docs ticksAnHour @docs ticksADay @docs ticksAWeek Copyright (c) 2016 PI:NAME:<NAME>END_PI -} import Date exposing (Date, Day (..), Month (..)) import Time -- _ = Debug.log("Date Const ticks") (ticksASecond, ticksAMinute, ticksAnHour, ticksADay, ticksAWeek) {-| Epoch starting point for tick 0. -} epochDateStr : String epochDateStr = "1970-01-01T00:00:00Z" {-| Ticks in a millisecond. (this is 1 on Win 7 in Chrome) -} ticksAMillisecond : Int ticksAMillisecond = floor Time.millisecond {-| Ticks in a second. -} ticksASecond : Int ticksASecond = ticksAMillisecond * 1000 {-| Ticks in a minute. -} ticksAMinute : Int ticksAMinute = ticksASecond * 60 {-| Ticks in an hour. -} ticksAnHour : Int ticksAnHour = ticksAMinute * 60 {-| Ticks in a day. -} ticksADay : Int ticksADay = ticksAnHour * 24 {-| Ticks in a week. -} ticksAWeek : Int ticksAWeek = ticksADay * 7 {-| Return the Iso DayOfWeek Monday 1, to Sunday 7. -} isoDayOfWeek : Date.Day -> Int isoDayOfWeek day = case day of Mon -> 1 Tue -> 2 Wed -> 3 Thu -> 4 Fri -> 5 Sat -> 6 Sun -> 7 {-| Return next day in calendar sequence. -} nextDay : Day -> Day nextDay day = case day of Mon -> Tue Tue -> Wed Wed -> Thu Thu -> Fri Fri -> Sat Sat -> Sun Sun -> Mon {-| Return previous day in calendar sequence. -} prevDay : Day -> Day prevDay day = case day of Mon -> Sun Tue -> Mon Wed -> Tue Thu -> Wed Fri -> Thu Sat -> Fri Sun -> Sat {-| Convenience fromTime as time ticks are Elm Ints in this library. -} fromTime : Int -> Date fromTime = Date.fromTime << toFloat {-| Convenience toTime as time ticks are Elm Ints in this library. -} toTime : Date -> Int toTime = floor << Date.toTime {-| List of months in order from Jan to Dec. -} monthList : List Month monthList = [ Jan , Feb , Mar , Apr , May , Jun , Jul , Aug , Sep , Oct , Nov , Dec ] {-| Return days in month for year month. -} daysInMonth : Int -> Month -> Int daysInMonth year month = case month of Jan -> 31 Feb -> if isLeapYear year then 29 else 28 Mar -> 31 Apr -> 30 May -> 31 Jun -> 30 Jul -> 31 Aug -> 31 Sep -> 30 Oct -> 31 Nov -> 30 Dec -> 31 {-| Days in month for given date. -} daysInMonthDate : Date -> Int daysInMonthDate date = daysInMonth (Date.year date) (Date.month date) -- go to Calendar {-| Return True if Year is a leap year. -} isLeapYear : Int -> Bool isLeapYear year = ((year % 4 == 0) && (year % 100 /= 0)) || ((year % 400) == 0) {-| Return True if Year of Date is a leap year. -} isLeapYearDate : Date -> Bool isLeapYearDate date = isLeapYear (Date.year date) {-| Return number of days in a year. -} yearToDayLength : Int -> Int yearToDayLength year = if isLeapYear year then 366 else 365 {-| Return days in next calendar month. -} daysInNextMonth : Date -> Int daysInNextMonth date = daysInMonthDate (firstOfNextMonthDate date) {-| Return days in previous calendar month. -} daysInPrevMonth : Date -> Int daysInPrevMonth date = daysInMonthDate (lastOfPrevMonthDate date) {-| Return month as integer. Jan = 1 to Dec = 12. -} monthToInt : Month -> Int monthToInt month = case month of Jan -> 1 Feb -> 2 Mar -> 3 Apr -> 4 May -> 5 Jun -> 6 Jul -> 7 Aug -> 8 Sep -> 9 Oct -> 10 Nov -> 11 Dec -> 12 {-| Return next month in calendar sequence. -} nextMonth : Month -> Month nextMonth month = case month of Jan -> Feb Feb -> Mar Mar -> Apr Apr -> May May -> Jun Jun -> Jul Jul -> Aug Aug -> Sep Sep -> Oct Oct -> Nov Nov -> Dec Dec -> Jan {-| Return previous month in calendar sequence. -} prevMonth : Month -> Month prevMonth month = case month of Jan -> Dec Feb -> Jan Mar -> Feb Apr -> Mar May -> Apr Jun -> May Jul -> Jun Aug -> Jul Sep -> Aug Oct -> Sep Nov -> Oct Dec -> Nov {-| Return first of next month date. -} firstOfNextMonthDate : Date -> Date firstOfNextMonthDate date = fromTime ((lastOfMonthTicks date) + ticksADay) {-| Return last of previous month date. -} lastOfPrevMonthDate : Date -> Date lastOfPrevMonthDate date = fromTime ((firstOfMonthTicks date) - ticksADay) {-| Return date of first of month. -} toFirstOfMonth : Date -> Date toFirstOfMonth date = fromTime (firstOfMonthTicks date) {- Return ticks to modify date to first of month. -} firstOfMonthTicks : Date -> Int firstOfMonthTicks date = let day = Date.day date dateTicks = toTime date -- _ = Debug.log("firstOfMonthTicks") (day, dateTicks) in dateTicks + ((1 - day) * ticksADay) {-| Resturn date of last day of month. -} lastOfMonthDate : Date -> Date lastOfMonthDate date = fromTime (lastOfMonthTicks date) {- Return ticks to modify date to last day of month. -} lastOfMonthTicks : Date -> Int lastOfMonthTicks date = let year = Date.year date month = Date.month date day = Date.day date dateTicks = toTime date -- _ = Debug.log("lastOfMonthTicks") (day, dateTicks) daysInMonthVal = daysInMonth year month addDays = daysInMonthVal - day in dateTicks + (addDays * ticksADay) {-| Days back to start of week day. -} daysBackToStartOfWeek : Date.Day -> Date.Day -> Int daysBackToStartOfWeek dateDay startOfWeekDay = let dateDayIndex = isoDayOfWeek dateDay startOfWeekDayIndex = isoDayOfWeek startOfWeekDay in if dateDayIndex < startOfWeekDayIndex then (7 + dateDayIndex) - startOfWeekDayIndex else dateDayIndex - startOfWeekDayIndex
elm
[ { "context": "pdown\n\n dropdownModel =\n { labelText = \"Hello world\"\n , dropDownValue = \"Some value you determ", "end": 839, "score": 0.7514370084, "start": 828, "tag": "NAME", "value": "Hello world" }, { "context": " usage\n dropdownModel =\n { labelText = \"Hello world\"\n , dropDownValue = \"Some value you determ", "end": 1847, "score": 0.6759240031, "start": 1836, "tag": "NAME", "value": "Hello world" } ]
src/Isdc/Ui/Dropdown.elm
InsideSalesOfficial/isdc-elm-ui
5
module Isdc.Ui.Dropdown exposing (multiCheckDropdown, DropDownProperties, multiCheckDropdownItem) {-| Dropdown contains dropdown functions which return HTML # Multi Check Dropdown @docs multiCheckDropdown, DropDownProperties, multiCheckDropdownItem -} import Css exposing (..) import Html.Styled exposing (..) import Html.Styled.Attributes exposing (css, placeholder, value) import Html.Styled.Events exposing (onClick, onInput) import Isdc.Ui.Button as Button import Isdc.Ui.Checkbox exposing (..) import Isdc.Ui.Color.Css as Color import Isdc.Ui.Color.Hex as Hex import Isdc.Ui.Icons exposing (..) import Isdc.Ui.Theme as Theme exposing (Theme) import Isdc.Ui.Typography exposing (..) {-| DropDownProperties contains all needed data and msg types for the multiCheckDropdown dropdownModel = { labelText = "Hello world" , dropDownValue = "Some value you determine" , options = [ { label = "Foo" , value = "foo" , checked = False } , { label = "Bar" , value = "bar" , checked = False } ] , open = False , openMessage = Open , toggleMessage = Toggle , searchMessage = Search , saveMessage = Save , cancelMessage = Cancel , search = "" } -} type alias DropDownProperties msg = { labelText : String , dropDownValue : String , options : List Option , open : Bool , openMessage : msg , toggleMessage : String -> msg , searchMessage : String -> msg , saveMessage : msg , cancelMessage : msg , search : String , theme : Theme } {-| multiCheckDropdown is a dropdown with checkboxes and confirmation buttons. -- Example usage dropdownModel = { labelText = "Hello world" , dropDownValue = "Some value you determine" , options = [ { label = "Foo" , value = "foo" , checked = False } , { label = "Bar" , value = "bar" , checked = False } ] , open = False , openMessage = Open , toggleMessage = Toggle , searchMessage = Search , saveMessage = Save , cancelMessage = Cancel , search = "" } multiCheckDropdown dropdownModel -} multiCheckDropdown : DropDownProperties msg -> Html msg multiCheckDropdown dropDownArgs = let { theme, labelText, dropDownValue, options, open, openMessage, toggleMessage, searchMessage, search, saveMessage, cancelMessage } = dropDownArgs labelColor = case theme of Theme.New -> Color.white40 _ -> Color.black inputColor = case theme of Theme.New -> Color.white60 _ -> Color.black60 inputBorderColor = case theme of Theme.New -> Color.white40 _ -> Color.black40 modalBackgroundColor = case theme of Theme.New -> Color.primary03 _ -> Color.white searchTextColor = case theme of Theme.New -> Color.white60 _ -> Color.black40 searchIconColor = Hex.grayC borderBottomColor = case theme of Theme.New -> Color.white60 _ -> Color.black60 caretColor = case theme of Theme.New -> Color.white90 _ -> Color.black60 cancelButton = case theme of Theme.New -> Button.secondaryDark _ -> Button.white saveButton = case theme of Theme.New -> Button.brand _ -> Button.green in div [ css [ position relative ] ] [ label [ css [ Isdc.Ui.Typography.caption, color labelColor ] ] [ text labelText ] , button [ css [ color inputColor , backgroundColor <| rgba 0 0 0 0 , fontSize (px 16) , border zero , borderBottom3 (px 1) solid borderBottomColor , width (pct 100) , textAlign left , outline zero , cursor pointer , padding2 (px 10) zero ] , onClick openMessage ] [ text dropDownValue , span [ css [ width zero , height zero , borderLeft3 (px 5) solid transparent , borderRight3 (px 5) solid transparent , borderTop3 (px 5) solid caretColor , position absolute , top (pct 50) , right (px 10) , transform (translateY (pct -50)) ] ] [] ] , if open then div [] [ div [ css [ position fixed , top zero , left zero , bottom zero , right zero , zIndex (int 100) ] , onClick openMessage ] [] , div [ css [ position absolute , top zero , boxShadow4 (px 2) (px 4) (px 10) Color.black40 , backgroundColor modalBackgroundColor , padding (px 15) , zIndex (int 101) , width (pct 100) , boxSizing borderBox , borderRadius (px 3) ] ] [ div [ css [ border3 (px 1) solid inputBorderColor , borderRadius (px 3) , alignItems center , displayFlex ] ] [ span [ css [ displayFlex , margin2 zero (px 6) , alignItems center ] ] [ fromUnstyled <| searchIcon "24px" "24px" searchIconColor ] , input [ css [ border zero , body1 , outline zero , height (px 36) , backgroundColor <| rgba 0 0 0 0 , color searchTextColor ] , onInput searchMessage , value search , placeholder "Search" ] [] ] , div [ css [ paddingTop (px 10) ] ] [ div [ css [ maxHeight (px 200) , overflow auto ] ] (List.map (\option -> multiCheckDropdownItem theme option toggleMessage) options) , div [ css [ displayFlex , justifyContent flexEnd ] ] [ cancelButton [ css [ minWidth (px 88) ], onClick cancelMessage ] [ text "Cancel" ] , saveButton [ css [ minWidth (px 88) ], onClick saveMessage ] [ text "Save" ] ] ] ] , div [] [] ] else div [] [] ] type alias Option = { label : String , value : String , checked : Bool } {-| multiCheckDropdownItem is a single checkbox and label which can send a message to toggle the checkbox -} multiCheckDropdownItem : Theme -> Option -> (String -> msg) -> Html msg multiCheckDropdownItem theme option toggleMessage = div [ css [ margin2 (px 10) (px 0) ] ] [ checkBox theme { checked = option.checked , disabled = False , onValueChange = toggleMessage option.value , label = option.label } ]
44613
module Isdc.Ui.Dropdown exposing (multiCheckDropdown, DropDownProperties, multiCheckDropdownItem) {-| Dropdown contains dropdown functions which return HTML # Multi Check Dropdown @docs multiCheckDropdown, DropDownProperties, multiCheckDropdownItem -} import Css exposing (..) import Html.Styled exposing (..) import Html.Styled.Attributes exposing (css, placeholder, value) import Html.Styled.Events exposing (onClick, onInput) import Isdc.Ui.Button as Button import Isdc.Ui.Checkbox exposing (..) import Isdc.Ui.Color.Css as Color import Isdc.Ui.Color.Hex as Hex import Isdc.Ui.Icons exposing (..) import Isdc.Ui.Theme as Theme exposing (Theme) import Isdc.Ui.Typography exposing (..) {-| DropDownProperties contains all needed data and msg types for the multiCheckDropdown dropdownModel = { labelText = "<NAME>" , dropDownValue = "Some value you determine" , options = [ { label = "Foo" , value = "foo" , checked = False } , { label = "Bar" , value = "bar" , checked = False } ] , open = False , openMessage = Open , toggleMessage = Toggle , searchMessage = Search , saveMessage = Save , cancelMessage = Cancel , search = "" } -} type alias DropDownProperties msg = { labelText : String , dropDownValue : String , options : List Option , open : Bool , openMessage : msg , toggleMessage : String -> msg , searchMessage : String -> msg , saveMessage : msg , cancelMessage : msg , search : String , theme : Theme } {-| multiCheckDropdown is a dropdown with checkboxes and confirmation buttons. -- Example usage dropdownModel = { labelText = "<NAME>" , dropDownValue = "Some value you determine" , options = [ { label = "Foo" , value = "foo" , checked = False } , { label = "Bar" , value = "bar" , checked = False } ] , open = False , openMessage = Open , toggleMessage = Toggle , searchMessage = Search , saveMessage = Save , cancelMessage = Cancel , search = "" } multiCheckDropdown dropdownModel -} multiCheckDropdown : DropDownProperties msg -> Html msg multiCheckDropdown dropDownArgs = let { theme, labelText, dropDownValue, options, open, openMessage, toggleMessage, searchMessage, search, saveMessage, cancelMessage } = dropDownArgs labelColor = case theme of Theme.New -> Color.white40 _ -> Color.black inputColor = case theme of Theme.New -> Color.white60 _ -> Color.black60 inputBorderColor = case theme of Theme.New -> Color.white40 _ -> Color.black40 modalBackgroundColor = case theme of Theme.New -> Color.primary03 _ -> Color.white searchTextColor = case theme of Theme.New -> Color.white60 _ -> Color.black40 searchIconColor = Hex.grayC borderBottomColor = case theme of Theme.New -> Color.white60 _ -> Color.black60 caretColor = case theme of Theme.New -> Color.white90 _ -> Color.black60 cancelButton = case theme of Theme.New -> Button.secondaryDark _ -> Button.white saveButton = case theme of Theme.New -> Button.brand _ -> Button.green in div [ css [ position relative ] ] [ label [ css [ Isdc.Ui.Typography.caption, color labelColor ] ] [ text labelText ] , button [ css [ color inputColor , backgroundColor <| rgba 0 0 0 0 , fontSize (px 16) , border zero , borderBottom3 (px 1) solid borderBottomColor , width (pct 100) , textAlign left , outline zero , cursor pointer , padding2 (px 10) zero ] , onClick openMessage ] [ text dropDownValue , span [ css [ width zero , height zero , borderLeft3 (px 5) solid transparent , borderRight3 (px 5) solid transparent , borderTop3 (px 5) solid caretColor , position absolute , top (pct 50) , right (px 10) , transform (translateY (pct -50)) ] ] [] ] , if open then div [] [ div [ css [ position fixed , top zero , left zero , bottom zero , right zero , zIndex (int 100) ] , onClick openMessage ] [] , div [ css [ position absolute , top zero , boxShadow4 (px 2) (px 4) (px 10) Color.black40 , backgroundColor modalBackgroundColor , padding (px 15) , zIndex (int 101) , width (pct 100) , boxSizing borderBox , borderRadius (px 3) ] ] [ div [ css [ border3 (px 1) solid inputBorderColor , borderRadius (px 3) , alignItems center , displayFlex ] ] [ span [ css [ displayFlex , margin2 zero (px 6) , alignItems center ] ] [ fromUnstyled <| searchIcon "24px" "24px" searchIconColor ] , input [ css [ border zero , body1 , outline zero , height (px 36) , backgroundColor <| rgba 0 0 0 0 , color searchTextColor ] , onInput searchMessage , value search , placeholder "Search" ] [] ] , div [ css [ paddingTop (px 10) ] ] [ div [ css [ maxHeight (px 200) , overflow auto ] ] (List.map (\option -> multiCheckDropdownItem theme option toggleMessage) options) , div [ css [ displayFlex , justifyContent flexEnd ] ] [ cancelButton [ css [ minWidth (px 88) ], onClick cancelMessage ] [ text "Cancel" ] , saveButton [ css [ minWidth (px 88) ], onClick saveMessage ] [ text "Save" ] ] ] ] , div [] [] ] else div [] [] ] type alias Option = { label : String , value : String , checked : Bool } {-| multiCheckDropdownItem is a single checkbox and label which can send a message to toggle the checkbox -} multiCheckDropdownItem : Theme -> Option -> (String -> msg) -> Html msg multiCheckDropdownItem theme option toggleMessage = div [ css [ margin2 (px 10) (px 0) ] ] [ checkBox theme { checked = option.checked , disabled = False , onValueChange = toggleMessage option.value , label = option.label } ]
true
module Isdc.Ui.Dropdown exposing (multiCheckDropdown, DropDownProperties, multiCheckDropdownItem) {-| Dropdown contains dropdown functions which return HTML # Multi Check Dropdown @docs multiCheckDropdown, DropDownProperties, multiCheckDropdownItem -} import Css exposing (..) import Html.Styled exposing (..) import Html.Styled.Attributes exposing (css, placeholder, value) import Html.Styled.Events exposing (onClick, onInput) import Isdc.Ui.Button as Button import Isdc.Ui.Checkbox exposing (..) import Isdc.Ui.Color.Css as Color import Isdc.Ui.Color.Hex as Hex import Isdc.Ui.Icons exposing (..) import Isdc.Ui.Theme as Theme exposing (Theme) import Isdc.Ui.Typography exposing (..) {-| DropDownProperties contains all needed data and msg types for the multiCheckDropdown dropdownModel = { labelText = "PI:NAME:<NAME>END_PI" , dropDownValue = "Some value you determine" , options = [ { label = "Foo" , value = "foo" , checked = False } , { label = "Bar" , value = "bar" , checked = False } ] , open = False , openMessage = Open , toggleMessage = Toggle , searchMessage = Search , saveMessage = Save , cancelMessage = Cancel , search = "" } -} type alias DropDownProperties msg = { labelText : String , dropDownValue : String , options : List Option , open : Bool , openMessage : msg , toggleMessage : String -> msg , searchMessage : String -> msg , saveMessage : msg , cancelMessage : msg , search : String , theme : Theme } {-| multiCheckDropdown is a dropdown with checkboxes and confirmation buttons. -- Example usage dropdownModel = { labelText = "PI:NAME:<NAME>END_PI" , dropDownValue = "Some value you determine" , options = [ { label = "Foo" , value = "foo" , checked = False } , { label = "Bar" , value = "bar" , checked = False } ] , open = False , openMessage = Open , toggleMessage = Toggle , searchMessage = Search , saveMessage = Save , cancelMessage = Cancel , search = "" } multiCheckDropdown dropdownModel -} multiCheckDropdown : DropDownProperties msg -> Html msg multiCheckDropdown dropDownArgs = let { theme, labelText, dropDownValue, options, open, openMessage, toggleMessage, searchMessage, search, saveMessage, cancelMessage } = dropDownArgs labelColor = case theme of Theme.New -> Color.white40 _ -> Color.black inputColor = case theme of Theme.New -> Color.white60 _ -> Color.black60 inputBorderColor = case theme of Theme.New -> Color.white40 _ -> Color.black40 modalBackgroundColor = case theme of Theme.New -> Color.primary03 _ -> Color.white searchTextColor = case theme of Theme.New -> Color.white60 _ -> Color.black40 searchIconColor = Hex.grayC borderBottomColor = case theme of Theme.New -> Color.white60 _ -> Color.black60 caretColor = case theme of Theme.New -> Color.white90 _ -> Color.black60 cancelButton = case theme of Theme.New -> Button.secondaryDark _ -> Button.white saveButton = case theme of Theme.New -> Button.brand _ -> Button.green in div [ css [ position relative ] ] [ label [ css [ Isdc.Ui.Typography.caption, color labelColor ] ] [ text labelText ] , button [ css [ color inputColor , backgroundColor <| rgba 0 0 0 0 , fontSize (px 16) , border zero , borderBottom3 (px 1) solid borderBottomColor , width (pct 100) , textAlign left , outline zero , cursor pointer , padding2 (px 10) zero ] , onClick openMessage ] [ text dropDownValue , span [ css [ width zero , height zero , borderLeft3 (px 5) solid transparent , borderRight3 (px 5) solid transparent , borderTop3 (px 5) solid caretColor , position absolute , top (pct 50) , right (px 10) , transform (translateY (pct -50)) ] ] [] ] , if open then div [] [ div [ css [ position fixed , top zero , left zero , bottom zero , right zero , zIndex (int 100) ] , onClick openMessage ] [] , div [ css [ position absolute , top zero , boxShadow4 (px 2) (px 4) (px 10) Color.black40 , backgroundColor modalBackgroundColor , padding (px 15) , zIndex (int 101) , width (pct 100) , boxSizing borderBox , borderRadius (px 3) ] ] [ div [ css [ border3 (px 1) solid inputBorderColor , borderRadius (px 3) , alignItems center , displayFlex ] ] [ span [ css [ displayFlex , margin2 zero (px 6) , alignItems center ] ] [ fromUnstyled <| searchIcon "24px" "24px" searchIconColor ] , input [ css [ border zero , body1 , outline zero , height (px 36) , backgroundColor <| rgba 0 0 0 0 , color searchTextColor ] , onInput searchMessage , value search , placeholder "Search" ] [] ] , div [ css [ paddingTop (px 10) ] ] [ div [ css [ maxHeight (px 200) , overflow auto ] ] (List.map (\option -> multiCheckDropdownItem theme option toggleMessage) options) , div [ css [ displayFlex , justifyContent flexEnd ] ] [ cancelButton [ css [ minWidth (px 88) ], onClick cancelMessage ] [ text "Cancel" ] , saveButton [ css [ minWidth (px 88) ], onClick saveMessage ] [ text "Save" ] ] ] ] , div [] [] ] else div [] [] ] type alias Option = { label : String , value : String , checked : Bool } {-| multiCheckDropdownItem is a single checkbox and label which can send a message to toggle the checkbox -} multiCheckDropdownItem : Theme -> Option -> (String -> msg) -> Html msg multiCheckDropdownItem theme option toggleMessage = div [ css [ margin2 (px 10) (px 0) ] ] [ checkBox theme { checked = option.checked , disabled = False , onValueChange = toggleMessage option.value , label = option.label } ]
elm
[ { "context": " Nothing ->\n nothing\n\n\nsearchId =\n \"diffuse__alfred\"\n\n\n\n-- 🖼\n\n\nactiveItemIndicatorStyles : List Css.S", "end": 8606, "score": 0.6555015445, "start": 8591, "tag": "PASSWORD", "value": "diffuse__alfred" } ]
src/Applications/UI/Alfred.elm
Borewit/diffuse
1
module UI.Alfred exposing (Model, Msg(..), initialModel, subscriptions, update, view) import Alfred exposing (Alfred) import Browser.Dom as Dom import Chunky exposing (..) import Classes as C import Conditional exposing (ifThenElse) import Css import Html.Styled as Html exposing (Html, fromUnstyled, text) import Html.Styled.Attributes exposing (autofocus, css, id, placeholder, type_) import Html.Styled.Events exposing (onInput) import Html.Styled.Ext exposing (onTapPreventDefault) import Json.Decode import Keyboard import List.Extra as List import Material.Icons exposing (Coloring(..)) import Material.Icons.Hardware as Icons import Return3 as Return exposing (..) import Tachyons.Classes as T import Task import UI.Kit import UI.Reply exposing (Reply) -- 🌳 type alias Model = { instance : Maybe (Alfred Reply) } initialModel : Model initialModel = { instance = Nothing } -- 📣 type Msg = Assign (Alfred Reply) | Bypass | DetermineResults String | Hide | RunAction Int ----------------------------------------- -- Keyboard ----------------------------------------- | KeyDown (Maybe Keyboard.Key) update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of Assign instance -> returnCommandWithModel { model | instance = Just instance } (Task.attempt (always Bypass) (Dom.focus searchId)) Bypass -> return model DetermineResults searchTerm -> model.instance |> Maybe.map (determineResults searchTerm) |> (\a -> return { model | instance = a }) Hide -> return { model | instance = Nothing } RunAction index -> case model.instance of Just instance -> { result = List.getAt index instance.results , searchTerm = instance.searchTerm } |> instance.action |> returnRepliesWithModel model |> andThen (update Hide) Nothing -> update Hide model ----------------------------------------- -- Keyboard ----------------------------------------- KeyDown (Just Keyboard.ArrowDown) -> case model.instance of Just instance -> instance |> (\i -> { i | focus = min (i.focus + 1) (List.length i.results - 1) }) |> (\i -> { model | instance = Just i }) |> return Nothing -> return model KeyDown (Just Keyboard.ArrowUp) -> case model.instance of Just instance -> instance |> (\i -> { i | focus = max (i.focus - 1) 0 }) |> (\i -> { model | instance = Just i }) |> return Nothing -> return model KeyDown (Just Keyboard.Enter) -> case model.instance of Just instance -> update (RunAction instance.focus) model Nothing -> return model KeyDown _ -> return model determineResults : String -> Alfred Reply -> Alfred Reply determineResults searchTerm alfred = let lowerSearchTerm = searchTerm |> String.toLower |> String.trim in if String.length lowerSearchTerm > 0 then { alfred | searchTerm = Just searchTerm , results = alfred.index |> List.filter (String.toLower >> String.contains lowerSearchTerm) |> List.sort } else { alfred | searchTerm = Nothing , results = alfred.index } -- 📰 subscriptions : Model -> Sub Msg subscriptions _ = Keyboard.downs (Keyboard.anyKeyUpper >> KeyDown) -- 🗺 view : Model -> Html Msg view model = case model.instance of Just instance -> chunk [ T.absolute__fill , T.flex , T.flex_column , T.fixed , T.items_center , T.ph3 , T.pointer , T.z_9999 ] [ ----------------------------------------- -- Message ----------------------------------------- chunk [ T.i, T.lh_copy, T.mt4, T.pt3, T.tc, T.white ] [ text instance.message ] ----------------------------------------- -- Search ----------------------------------------- , brick [ Html.Styled.Events.custom "tap" (Json.Decode.succeed { message = Bypass , stopPropagation = True , preventDefault = True } ) ] [ T.f6 , T.measure_wide , T.mt4 , T.w_100 ] [ slab Html.input [ autofocus True , css shadowStyles , id searchId , onInput DetermineResults , placeholder "Type to search or create" , type_ "text" ] [ T.bn , T.bg_white , T.br2 , T.db , T.f3 , T.lh_copy , T.outline_0 , T.pa3 , T.w_100 ] [] ] ----------------------------------------- -- Results ----------------------------------------- , brick [ css shadowStyles ] [ T.bg_white , T.br2 , T.f6 , T.lh_solid , T.measure_wide , T.mid_gray , T.mt4 , T.overflow_hidden , T.w_100 ] (List.indexedMap (\idx result -> brick [ onTapPreventDefault (RunAction idx) ] [ T.pa3 , T.relative , T.truncate -- , if idx == instance.focus then T.white else T.color_inherit -- , if idx == instance.focus then C.bg_base_0D else if modBy 2 idx == 0 then T.bg_transparent else T.bg_near_white ] [ text result -- , if idx == instance.focus then brick [ css activeItemIndicatorStyles ] [ T.absolute , C.lh_0 , T.mr3 , T.right_0 ] [ fromUnstyled (Icons.keyboard_return 13 Inherit) ] else nothing ] ) instance.results ) ] Nothing -> nothing searchId = "diffuse__alfred" -- 🖼 activeItemIndicatorStyles : List Css.Style activeItemIndicatorStyles = [ Css.top (Css.pct 50) , Css.transform (Css.translateY <| Css.pct -50) ] shadowStyles : List Css.Style shadowStyles = [ UI.Kit.onOverlayShadow ]
59662
module UI.Alfred exposing (Model, Msg(..), initialModel, subscriptions, update, view) import Alfred exposing (Alfred) import Browser.Dom as Dom import Chunky exposing (..) import Classes as C import Conditional exposing (ifThenElse) import Css import Html.Styled as Html exposing (Html, fromUnstyled, text) import Html.Styled.Attributes exposing (autofocus, css, id, placeholder, type_) import Html.Styled.Events exposing (onInput) import Html.Styled.Ext exposing (onTapPreventDefault) import Json.Decode import Keyboard import List.Extra as List import Material.Icons exposing (Coloring(..)) import Material.Icons.Hardware as Icons import Return3 as Return exposing (..) import Tachyons.Classes as T import Task import UI.Kit import UI.Reply exposing (Reply) -- 🌳 type alias Model = { instance : Maybe (Alfred Reply) } initialModel : Model initialModel = { instance = Nothing } -- 📣 type Msg = Assign (Alfred Reply) | Bypass | DetermineResults String | Hide | RunAction Int ----------------------------------------- -- Keyboard ----------------------------------------- | KeyDown (Maybe Keyboard.Key) update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of Assign instance -> returnCommandWithModel { model | instance = Just instance } (Task.attempt (always Bypass) (Dom.focus searchId)) Bypass -> return model DetermineResults searchTerm -> model.instance |> Maybe.map (determineResults searchTerm) |> (\a -> return { model | instance = a }) Hide -> return { model | instance = Nothing } RunAction index -> case model.instance of Just instance -> { result = List.getAt index instance.results , searchTerm = instance.searchTerm } |> instance.action |> returnRepliesWithModel model |> andThen (update Hide) Nothing -> update Hide model ----------------------------------------- -- Keyboard ----------------------------------------- KeyDown (Just Keyboard.ArrowDown) -> case model.instance of Just instance -> instance |> (\i -> { i | focus = min (i.focus + 1) (List.length i.results - 1) }) |> (\i -> { model | instance = Just i }) |> return Nothing -> return model KeyDown (Just Keyboard.ArrowUp) -> case model.instance of Just instance -> instance |> (\i -> { i | focus = max (i.focus - 1) 0 }) |> (\i -> { model | instance = Just i }) |> return Nothing -> return model KeyDown (Just Keyboard.Enter) -> case model.instance of Just instance -> update (RunAction instance.focus) model Nothing -> return model KeyDown _ -> return model determineResults : String -> Alfred Reply -> Alfred Reply determineResults searchTerm alfred = let lowerSearchTerm = searchTerm |> String.toLower |> String.trim in if String.length lowerSearchTerm > 0 then { alfred | searchTerm = Just searchTerm , results = alfred.index |> List.filter (String.toLower >> String.contains lowerSearchTerm) |> List.sort } else { alfred | searchTerm = Nothing , results = alfred.index } -- 📰 subscriptions : Model -> Sub Msg subscriptions _ = Keyboard.downs (Keyboard.anyKeyUpper >> KeyDown) -- 🗺 view : Model -> Html Msg view model = case model.instance of Just instance -> chunk [ T.absolute__fill , T.flex , T.flex_column , T.fixed , T.items_center , T.ph3 , T.pointer , T.z_9999 ] [ ----------------------------------------- -- Message ----------------------------------------- chunk [ T.i, T.lh_copy, T.mt4, T.pt3, T.tc, T.white ] [ text instance.message ] ----------------------------------------- -- Search ----------------------------------------- , brick [ Html.Styled.Events.custom "tap" (Json.Decode.succeed { message = Bypass , stopPropagation = True , preventDefault = True } ) ] [ T.f6 , T.measure_wide , T.mt4 , T.w_100 ] [ slab Html.input [ autofocus True , css shadowStyles , id searchId , onInput DetermineResults , placeholder "Type to search or create" , type_ "text" ] [ T.bn , T.bg_white , T.br2 , T.db , T.f3 , T.lh_copy , T.outline_0 , T.pa3 , T.w_100 ] [] ] ----------------------------------------- -- Results ----------------------------------------- , brick [ css shadowStyles ] [ T.bg_white , T.br2 , T.f6 , T.lh_solid , T.measure_wide , T.mid_gray , T.mt4 , T.overflow_hidden , T.w_100 ] (List.indexedMap (\idx result -> brick [ onTapPreventDefault (RunAction idx) ] [ T.pa3 , T.relative , T.truncate -- , if idx == instance.focus then T.white else T.color_inherit -- , if idx == instance.focus then C.bg_base_0D else if modBy 2 idx == 0 then T.bg_transparent else T.bg_near_white ] [ text result -- , if idx == instance.focus then brick [ css activeItemIndicatorStyles ] [ T.absolute , C.lh_0 , T.mr3 , T.right_0 ] [ fromUnstyled (Icons.keyboard_return 13 Inherit) ] else nothing ] ) instance.results ) ] Nothing -> nothing searchId = "<PASSWORD>" -- 🖼 activeItemIndicatorStyles : List Css.Style activeItemIndicatorStyles = [ Css.top (Css.pct 50) , Css.transform (Css.translateY <| Css.pct -50) ] shadowStyles : List Css.Style shadowStyles = [ UI.Kit.onOverlayShadow ]
true
module UI.Alfred exposing (Model, Msg(..), initialModel, subscriptions, update, view) import Alfred exposing (Alfred) import Browser.Dom as Dom import Chunky exposing (..) import Classes as C import Conditional exposing (ifThenElse) import Css import Html.Styled as Html exposing (Html, fromUnstyled, text) import Html.Styled.Attributes exposing (autofocus, css, id, placeholder, type_) import Html.Styled.Events exposing (onInput) import Html.Styled.Ext exposing (onTapPreventDefault) import Json.Decode import Keyboard import List.Extra as List import Material.Icons exposing (Coloring(..)) import Material.Icons.Hardware as Icons import Return3 as Return exposing (..) import Tachyons.Classes as T import Task import UI.Kit import UI.Reply exposing (Reply) -- 🌳 type alias Model = { instance : Maybe (Alfred Reply) } initialModel : Model initialModel = { instance = Nothing } -- 📣 type Msg = Assign (Alfred Reply) | Bypass | DetermineResults String | Hide | RunAction Int ----------------------------------------- -- Keyboard ----------------------------------------- | KeyDown (Maybe Keyboard.Key) update : Msg -> Model -> Return Model Msg Reply update msg model = case msg of Assign instance -> returnCommandWithModel { model | instance = Just instance } (Task.attempt (always Bypass) (Dom.focus searchId)) Bypass -> return model DetermineResults searchTerm -> model.instance |> Maybe.map (determineResults searchTerm) |> (\a -> return { model | instance = a }) Hide -> return { model | instance = Nothing } RunAction index -> case model.instance of Just instance -> { result = List.getAt index instance.results , searchTerm = instance.searchTerm } |> instance.action |> returnRepliesWithModel model |> andThen (update Hide) Nothing -> update Hide model ----------------------------------------- -- Keyboard ----------------------------------------- KeyDown (Just Keyboard.ArrowDown) -> case model.instance of Just instance -> instance |> (\i -> { i | focus = min (i.focus + 1) (List.length i.results - 1) }) |> (\i -> { model | instance = Just i }) |> return Nothing -> return model KeyDown (Just Keyboard.ArrowUp) -> case model.instance of Just instance -> instance |> (\i -> { i | focus = max (i.focus - 1) 0 }) |> (\i -> { model | instance = Just i }) |> return Nothing -> return model KeyDown (Just Keyboard.Enter) -> case model.instance of Just instance -> update (RunAction instance.focus) model Nothing -> return model KeyDown _ -> return model determineResults : String -> Alfred Reply -> Alfred Reply determineResults searchTerm alfred = let lowerSearchTerm = searchTerm |> String.toLower |> String.trim in if String.length lowerSearchTerm > 0 then { alfred | searchTerm = Just searchTerm , results = alfred.index |> List.filter (String.toLower >> String.contains lowerSearchTerm) |> List.sort } else { alfred | searchTerm = Nothing , results = alfred.index } -- 📰 subscriptions : Model -> Sub Msg subscriptions _ = Keyboard.downs (Keyboard.anyKeyUpper >> KeyDown) -- 🗺 view : Model -> Html Msg view model = case model.instance of Just instance -> chunk [ T.absolute__fill , T.flex , T.flex_column , T.fixed , T.items_center , T.ph3 , T.pointer , T.z_9999 ] [ ----------------------------------------- -- Message ----------------------------------------- chunk [ T.i, T.lh_copy, T.mt4, T.pt3, T.tc, T.white ] [ text instance.message ] ----------------------------------------- -- Search ----------------------------------------- , brick [ Html.Styled.Events.custom "tap" (Json.Decode.succeed { message = Bypass , stopPropagation = True , preventDefault = True } ) ] [ T.f6 , T.measure_wide , T.mt4 , T.w_100 ] [ slab Html.input [ autofocus True , css shadowStyles , id searchId , onInput DetermineResults , placeholder "Type to search or create" , type_ "text" ] [ T.bn , T.bg_white , T.br2 , T.db , T.f3 , T.lh_copy , T.outline_0 , T.pa3 , T.w_100 ] [] ] ----------------------------------------- -- Results ----------------------------------------- , brick [ css shadowStyles ] [ T.bg_white , T.br2 , T.f6 , T.lh_solid , T.measure_wide , T.mid_gray , T.mt4 , T.overflow_hidden , T.w_100 ] (List.indexedMap (\idx result -> brick [ onTapPreventDefault (RunAction idx) ] [ T.pa3 , T.relative , T.truncate -- , if idx == instance.focus then T.white else T.color_inherit -- , if idx == instance.focus then C.bg_base_0D else if modBy 2 idx == 0 then T.bg_transparent else T.bg_near_white ] [ text result -- , if idx == instance.focus then brick [ css activeItemIndicatorStyles ] [ T.absolute , C.lh_0 , T.mr3 , T.right_0 ] [ fromUnstyled (Icons.keyboard_return 13 Inherit) ] else nothing ] ) instance.results ) ] Nothing -> nothing searchId = "PI:PASSWORD:<PASSWORD>END_PI" -- 🖼 activeItemIndicatorStyles : List Css.Style activeItemIndicatorStyles = [ Css.top (Css.pct 50) , Css.transform (Css.translateY <| Css.pct -50) ] shadowStyles : List Css.Style shadowStyles = [ UI.Kit.onOverlayShadow ]
elm
[ { "context": "{-\nCopyright 2020 Morgan Stanley\n\nLicensed under the Apache License, Version 2.0 (", "end": 32, "score": 0.999797225, "start": 18, "tag": "NAME", "value": "Morgan Stanley" } ]
src/Morphir/Sample/LCR/Basics.elm
maoo/morphir-examples
0
{- 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 Morphir.Sample.LCR.Basics exposing ( AssetCategoryCodes(..) , InsuranceType(..) , Entity , Currency , Fed5GCode ) import Date exposing (Date, Unit(..)) import Time exposing (Month(..)) {-| Asset categories apply to the flows and are specified in the spec. There are a bunch of them, but we're only concerned with these three in this example . -} type AssetCategoryCodes = Level1Assets | Level2aAssets | Level2bAssets {-| Insurance type as specified in the spec. There are a bunch of them, but we're only concerned with FDIC in this example . -} type InsuranceType = FDIC | Uninsured type alias Entity = String type alias Currency = String type alias Fed5GCode = String {-| A currency isn't always itself in 5G. -} fed5GCurrency : Currency -> Currency fed5GCurrency currency = if List.member currency ["USD", "EUR", "GBP", "CHF", "JPY", "AUD", "CAD"] then currency else "USD"
48399
{- 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 Morphir.Sample.LCR.Basics exposing ( AssetCategoryCodes(..) , InsuranceType(..) , Entity , Currency , Fed5GCode ) import Date exposing (Date, Unit(..)) import Time exposing (Month(..)) {-| Asset categories apply to the flows and are specified in the spec. There are a bunch of them, but we're only concerned with these three in this example . -} type AssetCategoryCodes = Level1Assets | Level2aAssets | Level2bAssets {-| Insurance type as specified in the spec. There are a bunch of them, but we're only concerned with FDIC in this example . -} type InsuranceType = FDIC | Uninsured type alias Entity = String type alias Currency = String type alias Fed5GCode = String {-| A currency isn't always itself in 5G. -} fed5GCurrency : Currency -> Currency fed5GCurrency currency = if List.member currency ["USD", "EUR", "GBP", "CHF", "JPY", "AUD", "CAD"] then currency else "USD"
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 Morphir.Sample.LCR.Basics exposing ( AssetCategoryCodes(..) , InsuranceType(..) , Entity , Currency , Fed5GCode ) import Date exposing (Date, Unit(..)) import Time exposing (Month(..)) {-| Asset categories apply to the flows and are specified in the spec. There are a bunch of them, but we're only concerned with these three in this example . -} type AssetCategoryCodes = Level1Assets | Level2aAssets | Level2bAssets {-| Insurance type as specified in the spec. There are a bunch of them, but we're only concerned with FDIC in this example . -} type InsuranceType = FDIC | Uninsured type alias Entity = String type alias Currency = String type alias Fed5GCode = String {-| A currency isn't always itself in 5G. -} fed5GCurrency : Currency -> Currency fed5GCurrency currency = if List.member currency ["USD", "EUR", "GBP", "CHF", "JPY", "AUD", "CAD"] then currency else "USD"
elm
[ { "context": "{- Copyright (C) 2020 Mark D. Blackwell.\n All rights reserved.\n This program is distr", "end": 39, "score": 0.9998523593, "start": 22, "tag": "NAME", "value": "Mark D. Blackwell" } ]
src/front-end/update/UserIdentifierUpdate.elm
MarkDBlackwell/qplaylist-remember
0
{- Copyright (C) 2020 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 UserIdentifierUpdate exposing (userIdentifierEstablish) import ElmCycle import FocusUpdate import ModelType exposing ( Model ) import UserIdentifier import UserIdentifierType exposing ( UserIdentifierNumberSpaceInt ) import Utilities exposing ( idRefreshString ) -- UPDATE userIdentifierEstablish : Model -> UserIdentifierNumberSpaceInt -> ElmCycle.ElmCycle userIdentifierEstablish model randomInt = ( { model | userIdentifier = randomInt |> UserIdentifier.userIdentifierCalc } , Cmd.batch [ FocusUpdate.cmdFocusSetId idRefreshString , FocusUpdate.cmdFocusInputPossibly model ] )
55100
{- Copyright (C) 2020 <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 UserIdentifierUpdate exposing (userIdentifierEstablish) import ElmCycle import FocusUpdate import ModelType exposing ( Model ) import UserIdentifier import UserIdentifierType exposing ( UserIdentifierNumberSpaceInt ) import Utilities exposing ( idRefreshString ) -- UPDATE userIdentifierEstablish : Model -> UserIdentifierNumberSpaceInt -> ElmCycle.ElmCycle userIdentifierEstablish model randomInt = ( { model | userIdentifier = randomInt |> UserIdentifier.userIdentifierCalc } , Cmd.batch [ FocusUpdate.cmdFocusSetId idRefreshString , FocusUpdate.cmdFocusInputPossibly model ] )
true
{- Copyright (C) 2020 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 UserIdentifierUpdate exposing (userIdentifierEstablish) import ElmCycle import FocusUpdate import ModelType exposing ( Model ) import UserIdentifier import UserIdentifierType exposing ( UserIdentifierNumberSpaceInt ) import Utilities exposing ( idRefreshString ) -- UPDATE userIdentifierEstablish : Model -> UserIdentifierNumberSpaceInt -> ElmCycle.ElmCycle userIdentifierEstablish model randomInt = ( { model | userIdentifier = randomInt |> UserIdentifier.userIdentifierCalc } , Cmd.batch [ FocusUpdate.cmdFocusSetId idRefreshString , FocusUpdate.cmdFocusInputPossibly model ] )
elm
[ { "context": " }\n warAndPeace\n\n\nresult =\n [ \"“Well, Prince, so Genoa and Lucca are now just\"\n , \"family e", "end": 252, "score": 0.9925941229, "start": 246, "tag": "NAME", "value": "Prince" }, { "context": " warAndPeace\n\n\nresult =\n [ \"“Well, Prince, so Genoa and Lucca are now just\"\n , \"family estates of ", "end": 262, "score": 0.9997039437, "start": 257, "tag": "NAME", "value": "Genoa" }, { "context": "eace\n\n\nresult =\n [ \"“Well, Prince, so Genoa and Lucca are now just\"\n , \"family estates of the Buonap", "end": 272, "score": 0.994923234, "start": 267, "tag": "NAME", "value": "Lucca" }, { "context": " of \"War and Peace\"\n-}\nwarAndPeace =\n \"\"\"“Well, Prince, so Genoa and Lucca are now just family\n estat", "end": 866, "score": 0.9929261208, "start": 860, "tag": "NAME", "value": "Prince" }, { "context": "d Peace\"\n-}\nwarAndPeace =\n \"\"\"“Well, Prince, so Genoa and Lucca are now just family\n estates of the ", "end": 876, "score": 0.9996543527, "start": 871, "tag": "NAME", "value": "Genoa" }, { "context": "}\nwarAndPeace =\n \"\"\"“Well, Prince, so Genoa and Lucca are now just family\n estates of the Buonaparte", "end": 886, "score": 0.9959598184, "start": 881, "tag": "NAME", "value": "Lucca" } ]
src/Example.elm
folkertdev/elm-paragraph
7
module Example exposing (result) import Dict import Paragraph formatted = Paragraph.lines { maximumWidth = 50 , optimalWidth = 45 , stringWidth = String.length } warAndPeace result = [ "“Well, Prince, so Genoa and Lucca are now just" , "family estates of the Buonapartes. But I warn" , "you, if you don’t tell me that this means war," , "if you still try to defend the infamies and" , "horrors perpetrated by that Antichrist—I really" , "believe he is Antichrist—I will have nothing" , "more to do with you and you are no longer my" , "friend, no longer my ‘faithful slave,’ as you" , "call yourself! But how do you do? I see I have" , "frightened you—sit down and tell me all the news.”" ] {-| The first paragraph of "War and Peace" -} warAndPeace = """“Well, Prince, so Genoa and Lucca are now just family estates of the Buonapartes. But I warn you, if you don’t tell me that this means war, if you still try to defend the infamies and horrors perpetrated by that Antichrist— I really believe he is Antichrist—I will have nothing more to do with you and you are no longer my friend, no longer my ‘faithful slave,’ as you call yourself! But how do you do? I see I have frightened you— sit down and tell me all the news.”"""
38337
module Example exposing (result) import Dict import Paragraph formatted = Paragraph.lines { maximumWidth = 50 , optimalWidth = 45 , stringWidth = String.length } warAndPeace result = [ "“Well, <NAME>, so <NAME> and <NAME> are now just" , "family estates of the Buonapartes. But I warn" , "you, if you don’t tell me that this means war," , "if you still try to defend the infamies and" , "horrors perpetrated by that Antichrist—I really" , "believe he is Antichrist—I will have nothing" , "more to do with you and you are no longer my" , "friend, no longer my ‘faithful slave,’ as you" , "call yourself! But how do you do? I see I have" , "frightened you—sit down and tell me all the news.”" ] {-| The first paragraph of "War and Peace" -} warAndPeace = """“Well, <NAME>, so <NAME> and <NAME> are now just family estates of the Buonapartes. But I warn you, if you don’t tell me that this means war, if you still try to defend the infamies and horrors perpetrated by that Antichrist— I really believe he is Antichrist—I will have nothing more to do with you and you are no longer my friend, no longer my ‘faithful slave,’ as you call yourself! But how do you do? I see I have frightened you— sit down and tell me all the news.”"""
true
module Example exposing (result) import Dict import Paragraph formatted = Paragraph.lines { maximumWidth = 50 , optimalWidth = 45 , stringWidth = String.length } warAndPeace result = [ "“Well, PI:NAME:<NAME>END_PI, so PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI are now just" , "family estates of the Buonapartes. But I warn" , "you, if you don’t tell me that this means war," , "if you still try to defend the infamies and" , "horrors perpetrated by that Antichrist—I really" , "believe he is Antichrist—I will have nothing" , "more to do with you and you are no longer my" , "friend, no longer my ‘faithful slave,’ as you" , "call yourself! But how do you do? I see I have" , "frightened you—sit down and tell me all the news.”" ] {-| The first paragraph of "War and Peace" -} warAndPeace = """“Well, PI:NAME:<NAME>END_PI, so PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI are now just family estates of the Buonapartes. But I warn you, if you don’t tell me that this means war, if you still try to defend the infamies and horrors perpetrated by that Antichrist— I really believe he is Antichrist—I will have nothing more to do with you and you are no longer my friend, no longer my ‘faithful slave,’ as you call yourself! But how do you do? I see I have frightened you— sit down and tell me all the news.”"""
elm
[ { "context": "nd\"\n , \"Embellissement\"\n , \"Lac Chambon\"\n , \"Création du SIVU\"\n , \"", "end": 3414, "score": 0.9998874664, "start": 3403, "tag": "NAME", "value": "Lac Chambon" }, { "context": " , \"Ecoles\"\n , \"Sivom de la Vallée Verte\"\n , \"Maison médicale\"\n ", "end": 4284, "score": 0.6700748205, "start": 4279, "tag": "NAME", "value": "allée" }, { "context": " , \"Ecoles\"\n , \"Sivom de la Vallée Verte\"\n , \"Maison médicale\"\n , \"C", "end": 4290, "score": 0.6977357268, "start": 4288, "tag": "NAME", "value": "te" }, { "context": " , \"Eléments budgétaires\"\n , \"Rue George Sand\"\n , \"Circulation bourg\"\n ", "end": 6010, "score": 0.9954687953, "start": 5995, "tag": "NAME", "value": "Rue George Sand" }, { "context": " , \"Jeunesse et sports\"\n , \"Lac Chambon\"\n , \"CCAS Social\"\n , \"Ate", "end": 6535, "score": 0.9988552928, "start": 6524, "tag": "NAME", "value": "Lac Chambon" }, { "context": "abitat)\"\n , \"Personnel\"\n , \"Chantier de jeunesse\"\n , \"Travaux 2014\"\n ", "end": 7184, "score": 0.8287317753, "start": 7173, "tag": "NAME", "value": "Chantier de" }, { "context": " , \"Musée des peintres\"\n , \"Lac Chambon\"\n , \"Autres projets en cours\"\n ", "end": 7736, "score": 0.9983876944, "start": 7725, "tag": "NAME", "value": "Lac Chambon" }, { "context": "e communes du massif du Sancy\"\n , \"SIVU Couze Chambon\"\n , \"Pavillon Bleu\"\n , \"Env", "end": 10893, "score": 0.9970887303, "start": 10880, "tag": "NAME", "value": "Couze Chambon" }, { "context": " , \"SIVU Couze Chambon\"\n , \"Pavillon Bleu\"\n , \"Environnement\"\n , \"Eco", "end": 10923, "score": 0.9998649955, "start": 10910, "tag": "NAME", "value": "Pavillon Bleu" } ]
src/BulletinsMunicipaux.elm
eniac314/mairieMurol
0
module BulletinsMunicipaux where import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import StartApp.Simple as StartApp import List exposing (..) import String exposing (words, join, cons, uncons) import Char import Dict exposing (..) import Utils exposing (mainMenu, renderMainMenu, pageFooter, capitalize, renderListImg, logos, Action (..), renderSubMenu, mail, site, link) -- Model subMenu = [] initialModel = { mainMenu = mainMenu , subMenu = subMenu , mainContent = initialContent } type alias Bulletin = { cover : String , date : String , index : List String , addr : String } type alias Entry = (String,String) -- View view address model = div [ id "container"] [ renderMainMenu ["Documentation", "Bulletins municipaux"] (.mainMenu model) , div [ id "subContainer"] [ .mainContent model ] , pageFooter ] renderBulletin {cover, date, index, addr} = div [class "bulletin"] [ figure [ class "cover"] [ figcaption [] [text date] , img [src ("/images/bulletin/" ++ cover)] [] ] , ul [] ((h6 [] [text "Dans ce numéro:"] :: List.map (\e -> li [] [text e]) index) ++ [link "Téléchargez ici" addr]) ] contentMap = fromList [] update action model = case action of NoOp -> model Entry s -> changeMain model s changeMain model s = let newContent = get s contentMap in case newContent of Nothing -> model Just c -> { model | mainContent = c } --Main main = StartApp.start { model = initialModel , view = view , update = update } initialContent = bulletin -- Data bulletin = div [class "subContainerData noSubmenu", id "bullPubli"] ( (h2 [] [text "Le bulletin municipal"]) :: (List.map renderBulletin bulls) ) bulls = List.reverse [ Bulletin "cover0.png" "Janvier 2009" [ "La maison médicale" , "La sécurité : Pompiers et Maîtres Nageurs Sauveteurs" , "Murol en chiffres: Les employés communaux" , "Le château : travail des archéologues" , "Les écoles maternelles et élémentaires" , "Murol en images" , "Le tri des déchets" , "L’animation estivale" , "L’embellissement" , "Les commissions" , "Les opérations 2008" , "L’intercommunalité" , "L’état civil" , "Le site internet" ] "/baseDocumentaire/bulletin/1janvier2009.pdf" , Bulletin "cover1.png" "Janvier 2011" [ "Etat civil 2010" , "Horaires des services" , "Recensement 2011" , "Travaux en cours" , "Urbanisme" , "Budget et fiscalité" , "Archéologie" , "Ecoles" , "SIVOM de la Vallée Verte" , "Animation estivale" , "Musée" , "Ski de fond" , "Embellissement" , "Lac Chambon" , "Création du SIVU" , "Employés communaux" , "Propreté" , "SIVOM de Besse" , "Sécurité: pompiers MNS, gendarmerie" , "CCAS services sociaux" , "Relais bibliothèque" , "TNT" , "Murol en images" , "Associations" , "Calendrier des diverses manifestations du 1er semestre 2011" ] "/baseDocumentaire/bulletin/2janvier2011.pdf" , Bulletin "cover2.png" "Février 2012" [ "Etat civil 2011" , "Horaires des services" , "Urbanisme" , "SIVU assainissement" , "Travaux et investissements" , "Chantier de jeunesse" , "Archéologie" , "Musée des peintres" , "Ecoles" , "Sivom de la Vallée Verte" , "Maison médicale" , "Communauté de Communes du Massif du Sancy" , "Animation estivale" , "Sécurité : pompiers, gendarmerie et MNS" , "CCAS et services sociaux" , "SIVOM de Besse" , "Exposition: « la mairie de Murol a 100 ans »" , "Elections 2012" , "Murol en images" , "Associations" , "Calendrier des manifestations du 1er semestre 2012" ] "/baseDocumentaire/bulletin/3fevrier2012.pdf" , Bulletin "cover3.png" "Mars 2013" [ "Etat civil" , "Urbanisme" , "Transports" , "Services" , "Recyclage" , "Sports" , "Parcours sportif" , "Activités jeunesse" , "Eléments budgétaires" , "Travaux" , "Projets en cours" , "SIVU" , "Personnel" , "Embellissement" , "Archéologie" , "Musée" , "Pompiers" , "Plage" , "DICRIM cahier détachable" , "Murol en images" , "Station de tourisme" , "ONF" , "Animation" , "Ecoles" , "CCAS" , "SIVOM de Besse" , "Services sociaux" , "Associations" , "Calendrier" ] "/baseDocumentaire/bulletin/4mars2013.pdf" , Bulletin "cover4.png" "Janvier 2014" [ "Etat civil" , "Elections" , "Services" , "Chiens et chats" , "Personnel" , "Eléments budgétaires" , "Rue George Sand" , "Circulation bourg" , "Travaux" , "Maison médicale" , "Sécurité / Pompiers" , "Urbanisme" , "Agriculture - Forêts" , "Embellissement" , "Musée des peintres" , "Tourisme" , "Murol en images" , "Station de tourisme" , "Archéologie" , "Ecoles" , "Réforme des rythmes scolaires" , "Jeunesse et sports" , "Lac Chambon" , "CCAS Social" , "Atelier couture" , "Balades du journal" , "Informatique et sites" , "Associations" , "Calendrier" ] "/baseDocumentaire/bulletin/5janvier2014.pdf" , Bulletin "cover5.png" "Mars 2015" [ "Equipe municipale" , "Intercommunalité" , "Réforme territoriale" , "Elections régionales" , "Etat civil" , "Conseil des jeunes" , "Services" , "Ordures ménagères" , "ADIL (énergie, habitat)" , "Personnel" , "Chantier de jeunesse" , "Travaux 2014" , "Maison de santé" , "Pompiers" , "Eclairage public" , "Tourisme" , "Festival d'art" , "Embellissement" , "Archéologie" , "Mutuelle" , "CCAS" , "Ecoles" , "SIVOM de la Vallée Verte" , "Activités jeunesse" , "Eléments budgétaires" , "Accessibilité" , "Abords du chateau" , "Musée des peintres" , "Lac Chambon" , "Autres projets en cours" , "Murol en images" , "Associations" , "Calendrier" ] "/baseDocumentaire/bulletin/26mars2015.pdf" , Bulletin "cover6.jpg" "Mars 2016" [ "Conseil régional" , "Communauté de communes" , "Sapeurs pompiers" , "SIVOM de besse" , "CCAS" , "Organicité ®" , "Tri des déchets " , "Travaux realisés" , "Embellissement et fleurissement" , "Château et archeologie" , "Prélong" , "Congres national des maires ruraux" , "Murol en images" , "Plan local d’urbanisme" , "Pavillon bleu" , "Ecoles" , "SIVOM de la vallée verte" , "Activités jeunesse" , "Animation estivale" , "Grandes manifestations" , "Associations" , "Musée des peintres" , "Investissements" , "Etat civil" , "Services" , "Site municipal" , "Maison de sante" , "Calendrier" ] "/baseDocumentaire/bulletin/mars2016.pdf" , Bulletin "cover7.jpg" "Mars 2017" [ "La communauté de communes du Sancy" , "Le Pôle Lecture Publique" , "La charte de développement durable" , "Les actions du SIVU" , "Les sapeurs-pompiers volontaires" , "Les surveillants de baignade" , "L'état civil" , "Le SIVOM de Besse" , "Les actions du CCAS" , "Les écoles" , "Le SIVOM de la vallée verte" , "Salage et déneigement" , "Les travaux de l'équipe technique" , "Le château et la DSP" , "Les travaux de la plage et le pavillon bleu" , "Gros travaux et investissements" , "Embellissement et fleurissement" , "La journée des Murolais et le compostage" , "Le tri des déchets" , "Les animations" , "Le musée" , "L'archéologie" , "Les associations" , "SOS Animaux" , "Les éléctions 2017" , "Le site internet" , "L'annuaire de la maison de santé" , "Les services" , "Le calendrier" ] "/baseDocumentaire/bulletin/mars2017.pdf" , Bulletin "cover8.jpg" "Mars 2018" [ "Etat civil 2017" , "Urbanisme" , "Personnel communal" , "Sapeurs pompiers" , "Eléments budgétaires" , "Locations communales" , "Travaux équipe technique" , "Circulation stationnement" , "Travaux des entreprises" , "Investissements 2017" , "Archéologie" , "Château" , "Musée des peintres" , "Article IGN magazine" , "Murol en images" , "Animation estivale" , "Grandes manifestations" , "Communauté de communes du massif du Sancy" , "SIVU Couze Chambon" , "Pavillon Bleu" , "Environnement" , "Ecoles" , "SIVOM vallée verte" , "CCAS" , "Attention aux arnaques !" , "CLIC et SIVOM de Besse" , "Associations" , "Services" , "Maison de santé" , "Calendrier" ] "/baseDocumentaire/bulletin/mars2018.pdf" ]
33984
module BulletinsMunicipaux where import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import StartApp.Simple as StartApp import List exposing (..) import String exposing (words, join, cons, uncons) import Char import Dict exposing (..) import Utils exposing (mainMenu, renderMainMenu, pageFooter, capitalize, renderListImg, logos, Action (..), renderSubMenu, mail, site, link) -- Model subMenu = [] initialModel = { mainMenu = mainMenu , subMenu = subMenu , mainContent = initialContent } type alias Bulletin = { cover : String , date : String , index : List String , addr : String } type alias Entry = (String,String) -- View view address model = div [ id "container"] [ renderMainMenu ["Documentation", "Bulletins municipaux"] (.mainMenu model) , div [ id "subContainer"] [ .mainContent model ] , pageFooter ] renderBulletin {cover, date, index, addr} = div [class "bulletin"] [ figure [ class "cover"] [ figcaption [] [text date] , img [src ("/images/bulletin/" ++ cover)] [] ] , ul [] ((h6 [] [text "Dans ce numéro:"] :: List.map (\e -> li [] [text e]) index) ++ [link "Téléchargez ici" addr]) ] contentMap = fromList [] update action model = case action of NoOp -> model Entry s -> changeMain model s changeMain model s = let newContent = get s contentMap in case newContent of Nothing -> model Just c -> { model | mainContent = c } --Main main = StartApp.start { model = initialModel , view = view , update = update } initialContent = bulletin -- Data bulletin = div [class "subContainerData noSubmenu", id "bullPubli"] ( (h2 [] [text "Le bulletin municipal"]) :: (List.map renderBulletin bulls) ) bulls = List.reverse [ Bulletin "cover0.png" "Janvier 2009" [ "La maison médicale" , "La sécurité : Pompiers et Maîtres Nageurs Sauveteurs" , "Murol en chiffres: Les employés communaux" , "Le château : travail des archéologues" , "Les écoles maternelles et élémentaires" , "Murol en images" , "Le tri des déchets" , "L’animation estivale" , "L’embellissement" , "Les commissions" , "Les opérations 2008" , "L’intercommunalité" , "L’état civil" , "Le site internet" ] "/baseDocumentaire/bulletin/1janvier2009.pdf" , Bulletin "cover1.png" "Janvier 2011" [ "Etat civil 2010" , "Horaires des services" , "Recensement 2011" , "Travaux en cours" , "Urbanisme" , "Budget et fiscalité" , "Archéologie" , "Ecoles" , "SIVOM de la Vallée Verte" , "Animation estivale" , "Musée" , "Ski de fond" , "Embellissement" , "<NAME>" , "Création du SIVU" , "Employés communaux" , "Propreté" , "SIVOM de Besse" , "Sécurité: pompiers MNS, gendarmerie" , "CCAS services sociaux" , "Relais bibliothèque" , "TNT" , "Murol en images" , "Associations" , "Calendrier des diverses manifestations du 1er semestre 2011" ] "/baseDocumentaire/bulletin/2janvier2011.pdf" , Bulletin "cover2.png" "Février 2012" [ "Etat civil 2011" , "Horaires des services" , "Urbanisme" , "SIVU assainissement" , "Travaux et investissements" , "Chantier de jeunesse" , "Archéologie" , "Musée des peintres" , "Ecoles" , "Sivom de la V<NAME> Ver<NAME>" , "Maison médicale" , "Communauté de Communes du Massif du Sancy" , "Animation estivale" , "Sécurité : pompiers, gendarmerie et MNS" , "CCAS et services sociaux" , "SIVOM de Besse" , "Exposition: « la mairie de Murol a 100 ans »" , "Elections 2012" , "Murol en images" , "Associations" , "Calendrier des manifestations du 1er semestre 2012" ] "/baseDocumentaire/bulletin/3fevrier2012.pdf" , Bulletin "cover3.png" "Mars 2013" [ "Etat civil" , "Urbanisme" , "Transports" , "Services" , "Recyclage" , "Sports" , "Parcours sportif" , "Activités jeunesse" , "Eléments budgétaires" , "Travaux" , "Projets en cours" , "SIVU" , "Personnel" , "Embellissement" , "Archéologie" , "Musée" , "Pompiers" , "Plage" , "DICRIM cahier détachable" , "Murol en images" , "Station de tourisme" , "ONF" , "Animation" , "Ecoles" , "CCAS" , "SIVOM de Besse" , "Services sociaux" , "Associations" , "Calendrier" ] "/baseDocumentaire/bulletin/4mars2013.pdf" , Bulletin "cover4.png" "Janvier 2014" [ "Etat civil" , "Elections" , "Services" , "Chiens et chats" , "Personnel" , "Eléments budgétaires" , "<NAME>" , "Circulation bourg" , "Travaux" , "Maison médicale" , "Sécurité / Pompiers" , "Urbanisme" , "Agriculture - Forêts" , "Embellissement" , "Musée des peintres" , "Tourisme" , "Murol en images" , "Station de tourisme" , "Archéologie" , "Ecoles" , "Réforme des rythmes scolaires" , "Jeunesse et sports" , "<NAME>" , "CCAS Social" , "Atelier couture" , "Balades du journal" , "Informatique et sites" , "Associations" , "Calendrier" ] "/baseDocumentaire/bulletin/5janvier2014.pdf" , Bulletin "cover5.png" "Mars 2015" [ "Equipe municipale" , "Intercommunalité" , "Réforme territoriale" , "Elections régionales" , "Etat civil" , "Conseil des jeunes" , "Services" , "Ordures ménagères" , "ADIL (énergie, habitat)" , "Personnel" , "<NAME> jeunesse" , "Travaux 2014" , "Maison de santé" , "Pompiers" , "Eclairage public" , "Tourisme" , "Festival d'art" , "Embellissement" , "Archéologie" , "Mutuelle" , "CCAS" , "Ecoles" , "SIVOM de la Vallée Verte" , "Activités jeunesse" , "Eléments budgétaires" , "Accessibilité" , "Abords du chateau" , "Musée des peintres" , "<NAME>" , "Autres projets en cours" , "Murol en images" , "Associations" , "Calendrier" ] "/baseDocumentaire/bulletin/26mars2015.pdf" , Bulletin "cover6.jpg" "Mars 2016" [ "Conseil régional" , "Communauté de communes" , "Sapeurs pompiers" , "SIVOM de besse" , "CCAS" , "Organicité ®" , "Tri des déchets " , "Travaux realisés" , "Embellissement et fleurissement" , "Château et archeologie" , "Prélong" , "Congres national des maires ruraux" , "Murol en images" , "Plan local d’urbanisme" , "Pavillon bleu" , "Ecoles" , "SIVOM de la vallée verte" , "Activités jeunesse" , "Animation estivale" , "Grandes manifestations" , "Associations" , "Musée des peintres" , "Investissements" , "Etat civil" , "Services" , "Site municipal" , "Maison de sante" , "Calendrier" ] "/baseDocumentaire/bulletin/mars2016.pdf" , Bulletin "cover7.jpg" "Mars 2017" [ "La communauté de communes du Sancy" , "Le Pôle Lecture Publique" , "La charte de développement durable" , "Les actions du SIVU" , "Les sapeurs-pompiers volontaires" , "Les surveillants de baignade" , "L'état civil" , "Le SIVOM de Besse" , "Les actions du CCAS" , "Les écoles" , "Le SIVOM de la vallée verte" , "Salage et déneigement" , "Les travaux de l'équipe technique" , "Le château et la DSP" , "Les travaux de la plage et le pavillon bleu" , "Gros travaux et investissements" , "Embellissement et fleurissement" , "La journée des Murolais et le compostage" , "Le tri des déchets" , "Les animations" , "Le musée" , "L'archéologie" , "Les associations" , "SOS Animaux" , "Les éléctions 2017" , "Le site internet" , "L'annuaire de la maison de santé" , "Les services" , "Le calendrier" ] "/baseDocumentaire/bulletin/mars2017.pdf" , Bulletin "cover8.jpg" "Mars 2018" [ "Etat civil 2017" , "Urbanisme" , "Personnel communal" , "Sapeurs pompiers" , "Eléments budgétaires" , "Locations communales" , "Travaux équipe technique" , "Circulation stationnement" , "Travaux des entreprises" , "Investissements 2017" , "Archéologie" , "Château" , "Musée des peintres" , "Article IGN magazine" , "Murol en images" , "Animation estivale" , "Grandes manifestations" , "Communauté de communes du massif du Sancy" , "SIVU <NAME>" , "<NAME>" , "Environnement" , "Ecoles" , "SIVOM vallée verte" , "CCAS" , "Attention aux arnaques !" , "CLIC et SIVOM de Besse" , "Associations" , "Services" , "Maison de santé" , "Calendrier" ] "/baseDocumentaire/bulletin/mars2018.pdf" ]
true
module BulletinsMunicipaux where import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import StartApp.Simple as StartApp import List exposing (..) import String exposing (words, join, cons, uncons) import Char import Dict exposing (..) import Utils exposing (mainMenu, renderMainMenu, pageFooter, capitalize, renderListImg, logos, Action (..), renderSubMenu, mail, site, link) -- Model subMenu = [] initialModel = { mainMenu = mainMenu , subMenu = subMenu , mainContent = initialContent } type alias Bulletin = { cover : String , date : String , index : List String , addr : String } type alias Entry = (String,String) -- View view address model = div [ id "container"] [ renderMainMenu ["Documentation", "Bulletins municipaux"] (.mainMenu model) , div [ id "subContainer"] [ .mainContent model ] , pageFooter ] renderBulletin {cover, date, index, addr} = div [class "bulletin"] [ figure [ class "cover"] [ figcaption [] [text date] , img [src ("/images/bulletin/" ++ cover)] [] ] , ul [] ((h6 [] [text "Dans ce numéro:"] :: List.map (\e -> li [] [text e]) index) ++ [link "Téléchargez ici" addr]) ] contentMap = fromList [] update action model = case action of NoOp -> model Entry s -> changeMain model s changeMain model s = let newContent = get s contentMap in case newContent of Nothing -> model Just c -> { model | mainContent = c } --Main main = StartApp.start { model = initialModel , view = view , update = update } initialContent = bulletin -- Data bulletin = div [class "subContainerData noSubmenu", id "bullPubli"] ( (h2 [] [text "Le bulletin municipal"]) :: (List.map renderBulletin bulls) ) bulls = List.reverse [ Bulletin "cover0.png" "Janvier 2009" [ "La maison médicale" , "La sécurité : Pompiers et Maîtres Nageurs Sauveteurs" , "Murol en chiffres: Les employés communaux" , "Le château : travail des archéologues" , "Les écoles maternelles et élémentaires" , "Murol en images" , "Le tri des déchets" , "L’animation estivale" , "L’embellissement" , "Les commissions" , "Les opérations 2008" , "L’intercommunalité" , "L’état civil" , "Le site internet" ] "/baseDocumentaire/bulletin/1janvier2009.pdf" , Bulletin "cover1.png" "Janvier 2011" [ "Etat civil 2010" , "Horaires des services" , "Recensement 2011" , "Travaux en cours" , "Urbanisme" , "Budget et fiscalité" , "Archéologie" , "Ecoles" , "SIVOM de la Vallée Verte" , "Animation estivale" , "Musée" , "Ski de fond" , "Embellissement" , "PI:NAME:<NAME>END_PI" , "Création du SIVU" , "Employés communaux" , "Propreté" , "SIVOM de Besse" , "Sécurité: pompiers MNS, gendarmerie" , "CCAS services sociaux" , "Relais bibliothèque" , "TNT" , "Murol en images" , "Associations" , "Calendrier des diverses manifestations du 1er semestre 2011" ] "/baseDocumentaire/bulletin/2janvier2011.pdf" , Bulletin "cover2.png" "Février 2012" [ "Etat civil 2011" , "Horaires des services" , "Urbanisme" , "SIVU assainissement" , "Travaux et investissements" , "Chantier de jeunesse" , "Archéologie" , "Musée des peintres" , "Ecoles" , "Sivom de la VPI:NAME:<NAME>END_PI VerPI:NAME:<NAME>END_PI" , "Maison médicale" , "Communauté de Communes du Massif du Sancy" , "Animation estivale" , "Sécurité : pompiers, gendarmerie et MNS" , "CCAS et services sociaux" , "SIVOM de Besse" , "Exposition: « la mairie de Murol a 100 ans »" , "Elections 2012" , "Murol en images" , "Associations" , "Calendrier des manifestations du 1er semestre 2012" ] "/baseDocumentaire/bulletin/3fevrier2012.pdf" , Bulletin "cover3.png" "Mars 2013" [ "Etat civil" , "Urbanisme" , "Transports" , "Services" , "Recyclage" , "Sports" , "Parcours sportif" , "Activités jeunesse" , "Eléments budgétaires" , "Travaux" , "Projets en cours" , "SIVU" , "Personnel" , "Embellissement" , "Archéologie" , "Musée" , "Pompiers" , "Plage" , "DICRIM cahier détachable" , "Murol en images" , "Station de tourisme" , "ONF" , "Animation" , "Ecoles" , "CCAS" , "SIVOM de Besse" , "Services sociaux" , "Associations" , "Calendrier" ] "/baseDocumentaire/bulletin/4mars2013.pdf" , Bulletin "cover4.png" "Janvier 2014" [ "Etat civil" , "Elections" , "Services" , "Chiens et chats" , "Personnel" , "Eléments budgétaires" , "PI:NAME:<NAME>END_PI" , "Circulation bourg" , "Travaux" , "Maison médicale" , "Sécurité / Pompiers" , "Urbanisme" , "Agriculture - Forêts" , "Embellissement" , "Musée des peintres" , "Tourisme" , "Murol en images" , "Station de tourisme" , "Archéologie" , "Ecoles" , "Réforme des rythmes scolaires" , "Jeunesse et sports" , "PI:NAME:<NAME>END_PI" , "CCAS Social" , "Atelier couture" , "Balades du journal" , "Informatique et sites" , "Associations" , "Calendrier" ] "/baseDocumentaire/bulletin/5janvier2014.pdf" , Bulletin "cover5.png" "Mars 2015" [ "Equipe municipale" , "Intercommunalité" , "Réforme territoriale" , "Elections régionales" , "Etat civil" , "Conseil des jeunes" , "Services" , "Ordures ménagères" , "ADIL (énergie, habitat)" , "Personnel" , "PI:NAME:<NAME>END_PI jeunesse" , "Travaux 2014" , "Maison de santé" , "Pompiers" , "Eclairage public" , "Tourisme" , "Festival d'art" , "Embellissement" , "Archéologie" , "Mutuelle" , "CCAS" , "Ecoles" , "SIVOM de la Vallée Verte" , "Activités jeunesse" , "Eléments budgétaires" , "Accessibilité" , "Abords du chateau" , "Musée des peintres" , "PI:NAME:<NAME>END_PI" , "Autres projets en cours" , "Murol en images" , "Associations" , "Calendrier" ] "/baseDocumentaire/bulletin/26mars2015.pdf" , Bulletin "cover6.jpg" "Mars 2016" [ "Conseil régional" , "Communauté de communes" , "Sapeurs pompiers" , "SIVOM de besse" , "CCAS" , "Organicité ®" , "Tri des déchets " , "Travaux realisés" , "Embellissement et fleurissement" , "Château et archeologie" , "Prélong" , "Congres national des maires ruraux" , "Murol en images" , "Plan local d’urbanisme" , "Pavillon bleu" , "Ecoles" , "SIVOM de la vallée verte" , "Activités jeunesse" , "Animation estivale" , "Grandes manifestations" , "Associations" , "Musée des peintres" , "Investissements" , "Etat civil" , "Services" , "Site municipal" , "Maison de sante" , "Calendrier" ] "/baseDocumentaire/bulletin/mars2016.pdf" , Bulletin "cover7.jpg" "Mars 2017" [ "La communauté de communes du Sancy" , "Le Pôle Lecture Publique" , "La charte de développement durable" , "Les actions du SIVU" , "Les sapeurs-pompiers volontaires" , "Les surveillants de baignade" , "L'état civil" , "Le SIVOM de Besse" , "Les actions du CCAS" , "Les écoles" , "Le SIVOM de la vallée verte" , "Salage et déneigement" , "Les travaux de l'équipe technique" , "Le château et la DSP" , "Les travaux de la plage et le pavillon bleu" , "Gros travaux et investissements" , "Embellissement et fleurissement" , "La journée des Murolais et le compostage" , "Le tri des déchets" , "Les animations" , "Le musée" , "L'archéologie" , "Les associations" , "SOS Animaux" , "Les éléctions 2017" , "Le site internet" , "L'annuaire de la maison de santé" , "Les services" , "Le calendrier" ] "/baseDocumentaire/bulletin/mars2017.pdf" , Bulletin "cover8.jpg" "Mars 2018" [ "Etat civil 2017" , "Urbanisme" , "Personnel communal" , "Sapeurs pompiers" , "Eléments budgétaires" , "Locations communales" , "Travaux équipe technique" , "Circulation stationnement" , "Travaux des entreprises" , "Investissements 2017" , "Archéologie" , "Château" , "Musée des peintres" , "Article IGN magazine" , "Murol en images" , "Animation estivale" , "Grandes manifestations" , "Communauté de communes du massif du Sancy" , "SIVU PI:NAME:<NAME>END_PI" , "PI:NAME:<NAME>END_PI" , "Environnement" , "Ecoles" , "SIVOM vallée verte" , "CCAS" , "Attention aux arnaques !" , "CLIC et SIVOM de Besse" , "Associations" , "Services" , "Maison de santé" , "Calendrier" ] "/baseDocumentaire/bulletin/mars2018.pdf" ]
elm
[ { "context": ": Inline\n textNode1 =\n plainText \"sample1\"\n\n nodeWithTextLeafToSplit : Block\n nodeWit", "end": 42577, "score": 0.823620677, "start": 42576, "tag": "NAME", "value": "1" }, { "context": "en <|\n Array.fromList [ plainText \"sam\" ]\n )\n\n nodeAfterTextLeafSplit : Bl", "end": 42995, "score": 0.9218155146, "start": 42992, "tag": "NAME", "value": "sam" } ]
src/RichText/Node.elm
matsjoyce/elm-rte-toolkit
0
module RichText.Node exposing ( insertAfter, insertBefore, replace, replaceWithFragment , removeInRange, removeNodeAndEmptyParents , allRange, anyRange, isEmptyTextBlock, selectionIsBeginningOfTextBlock, selectionIsEndOfTextBlock , concatMap, indexedMap, joinBlocks, map , Iterator, last, next, nodeAt, previous, findAncestor, findBackwardFrom, findBackwardFromExclusive, findClosestBlockPath, findForwardFrom, findForwardFromExclusive, findTextBlockNodeAncestor , foldl, foldlRange, foldr, foldrRange, indexedFoldl, indexedFoldr , splitBlockAtPathAndOffset, splitTextLeaf , toggleMark , Fragment(..), Node(..) ) {-| This module contains convenience functions for working with Block and Inline nodes. # Insert / Replace @docs insertAfter, insertBefore, replace, replaceWithFragment # Remove @docs removeInRange, removeNodeAndEmptyParents # Predicates @docs allRange, anyRange, isEmptyTextBlock, selectionIsBeginningOfTextBlock, selectionIsEndOfTextBlock # Transform @docs concatMap, indexedMap, joinBlocks, map # Searching @docs Iterator, last, next, nodeAt, previous, findAncestor, findBackwardFrom, findBackwardFromExclusive, findClosestBlockPath, findForwardFrom, findForwardFromExclusive, findTextBlockNodeAncestor # Folds @docs foldl, foldlRange, foldr, foldrRange, indexedFoldl, indexedFoldr # Split @docs splitBlockAtPathAndOffset, splitTextLeaf # Marks @docs toggleMark # Types These are convenience types to wrap around inline and block node and arrays @docs Fragment, Node -} import Array exposing (Array) import Array.Extra import List.Extra import RichText.Model.InlineElement as InlineElement import RichText.Model.Mark exposing (Mark, MarkOrder, ToggleAction, toggle) import RichText.Model.Node exposing ( Block , Children(..) , Inline(..) , Path , blockChildren , childNodes , inlineChildren , parent , toBlockArray , toInlineArray , withChildNodes ) import RichText.Model.Selection exposing (Selection, anchorNode, anchorOffset, isCollapsed) import RichText.Model.Text as Text exposing (Text, text, withText) {-| Node represents either a `Block` or `Inline`. It's a convenience type that wraps an argument or return value of a function that can use either block or inline, like `nodeAt` or `replace`. -} type Node = Block Block | Inline Inline {-| A `Fragment` represents an array of `Block` or `Inline` nodes. It's a convenience type used for things like insertion or deserialization. -} type Fragment = BlockFragment (Array Block) | InlineFragment (Array Inline) {-| Returns the last path and node in the block. ( lastPath, lastNode ) = last node -} last : Block -> ( Path, Node ) last node = case childNodes node of BlockChildren a -> let arr = toBlockArray a lastIndex = Array.length arr - 1 in case Array.get lastIndex arr of Nothing -> ( [], Block node ) Just b -> let ( p, n ) = last b in ( lastIndex :: p, n ) InlineChildren a -> let array = toInlineArray a lastIndex = Array.length array - 1 in case Array.get lastIndex array of Nothing -> ( [], Block node ) Just l -> ( [ lastIndex ], Inline l ) Leaf -> ( [], Block node ) {-| Type alias for a function that takes a path and a root block and returns a path and node. Useful for generalizing functions like previous and next that can iterate through a Block. -} type alias Iterator = Path -> Block -> Maybe ( Path, Node ) {-| Returns the previous path and node, if one exists, relative to the given path. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" previous [0, 1] rootNode == Just ([0, 0], Inline textNode1) -} previous : Iterator previous path node = case path of [] -> Nothing [ x ] -> let prevIndex = x - 1 in case childNodes node of BlockChildren a -> case Array.get prevIndex (toBlockArray a) of Nothing -> Just ( [], Block node ) Just b -> let ( p, n ) = last b in Just ( prevIndex :: p, n ) InlineChildren a -> case Array.get prevIndex (toInlineArray a) of Nothing -> Just ( [], Block node ) Just l -> Just ( [ prevIndex ], Inline l ) Leaf -> Just ( [], Block node ) x :: xs -> case childNodes node of BlockChildren a -> case Array.get x (toBlockArray a) of Nothing -> Nothing Just b -> case previous xs b of Nothing -> Just ( [ x ], Block b ) Just ( p, n ) -> Just ( x :: p, n ) InlineChildren a -> case Array.get (x - 1) (toInlineArray a) of Nothing -> Just ( [], Block node ) Just l -> Just ( [ x - 1 ], Inline l ) Leaf -> Nothing {-| Returns the next path and node, if one exists, relative to the given path. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" next [0, 0] rootNode == Just ([0, 1], Inline textNode2) -} next : Iterator next path node = case path of [] -> case childNodes node of BlockChildren a -> case Array.get 0 (toBlockArray a) of Nothing -> Nothing Just b -> Just ( [ 0 ], Block b ) InlineChildren a -> case Array.get 0 (toInlineArray a) of Nothing -> Nothing Just b -> Just ( [ 0 ], Inline b ) Leaf -> Nothing x :: xs -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> Nothing Just b -> case next xs b of Nothing -> case Array.get (x + 1) arr of Nothing -> Nothing Just bNext -> Just ( [ x + 1 ], Block bNext ) Just ( p, n ) -> Just ( x :: p, n ) InlineChildren a -> case Array.get (x + 1) (toInlineArray a) of Nothing -> Nothing Just b -> Just ( [ x + 1 ], Inline b ) Leaf -> Nothing {-| Starting from the given path, scans the node forward until the predicate has been met or it reaches the last node. -} findForwardFrom : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findForwardFrom = findNodeFrom next {-| Starting from but excluding the given path, scans the node forward until the predicate has been met or it reaches the last node. -} findForwardFromExclusive : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findForwardFromExclusive = findNodeFromExclusive next {-| Starting from the given path, scans the node backward until the predicate has been met or it reaches the last node. -} findBackwardFrom : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findBackwardFrom = findNodeFrom previous {-| Starting from but excluding the given path, scans the node backward until the predicate has been met or it reaches the last node. -} findBackwardFromExclusive : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findBackwardFromExclusive = findNodeFromExclusive previous findNodeFromExclusive : Iterator -> (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findNodeFromExclusive iterator pred path node = case iterator path node of Nothing -> Nothing Just ( nextPath, _ ) -> findNodeFrom iterator pred nextPath node findNodeFrom : Iterator -> (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findNodeFrom iterator pred path node = case nodeAt path node of Just n -> if pred path n then Just ( path, n ) else findNodeFromExclusive iterator pred path node Nothing -> Nothing {-| Map a given function onto a block's children recursively and flatten the resulting list. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" doubleRoot : Block doubleRoot = block (Element.element doc []) (blockChildren <| Array.fromList [ doublePNode, doublePNode ] ) doublePNode : Block doublePNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode1, textNode2, textNode2 ] ) concatMap (\node -> [ node, node ]) rootNode == doubleRoot --> True -} concatMap : (Node -> List Node) -> Block -> Block concatMap func node = let newChildren = case childNodes node of Leaf -> Leaf BlockChildren a -> let c = List.concatMap (\x -> case x of Block v -> [ v ] Inline _ -> [] ) <| List.concatMap func (List.map Block (Array.toList (toBlockArray a))) in blockChildren <| Array.fromList (List.map (concatMap func) c) InlineChildren a -> inlineChildren <| Array.fromList (List.concatMap (\x -> case x of Block _ -> [] Inline v -> [ v ] ) <| List.concatMap func (List.map Inline (Array.toList (toInlineArray a))) ) in node |> withChildNodes newChildren {-| Apply a function to this node and all child nodes. setAnnotations : String -> Node -> Node setAnnotations mark node = let annotations = Set.fromList [ mark ] in case node of Block bn -> let params = Node.element bn in Block (bn |> withElement (params |> Element.withAnnotations annotations)) Inline il -> case il of Text tl -> Inline (Text (tl |> Text.withAnnotations annotations)) InlineElement l -> let params = InlineElement.element l in Inline (InlineElement (l |> InlineElement.withElement (params |> Element.withAnnotations annotations))) setDummyAnnotation : Node -> Node setDummyAnnotation node = setAnnotations dummyAnnotation node map setDummyAnnotation (Block rootNode) --> Recursively adds a dummy annotation to rootNode and all its children -} map : (Node -> Node) -> Node -> Node map func node = let applied = func node in case applied of Block blockNode -> Block <| (blockNode |> withChildNodes (case childNodes blockNode of BlockChildren a -> blockChildren <| Array.map (\v -> case map func (Block v) of Block b -> b _ -> v ) (toBlockArray a) InlineChildren a -> inlineChildren <| Array.map (\v -> case map func (Inline v) of Inline b -> b _ -> v ) (toInlineArray a) Leaf -> Leaf ) ) Inline inlineLeaf -> Inline inlineLeaf {-| Same as map but the function is also applied with the path of each element (starting at []). indexedMap (\path node -> if path == [ 0, 0 ] then text2 else node ) (Block rootNode) --> replaces the node at [0, 0] with the text2 node -} indexedMap : (Path -> Node -> Node) -> Node -> Node indexedMap = indexedMapRec [] indexedMapRec : Path -> (Path -> Node -> Node) -> Node -> Node indexedMapRec path func node = let applied = func path node in case applied of Block blockNode -> let cn = case childNodes blockNode of BlockChildren a -> blockChildren <| Array.indexedMap (\i v -> case indexedMapRec (path ++ [ i ]) func (Block v) of Block b -> b _ -> v ) (toBlockArray a) InlineChildren a -> inlineChildren <| Array.indexedMap (\i v -> case indexedMapRec (path ++ [ i ]) func (Inline v) of Inline b -> b _ -> v ) (toInlineArray a) Leaf -> Leaf in Block (blockNode |> withChildNodes cn) Inline inlineLeaf -> Inline inlineLeaf {-| Reduce a node from the bottom right (e.g. from last to first). nodeNameOrTextValue : Node -> List String -> List String nodeNameOrTextValue node list = (case node of Block bn -> Element.name (Node.element bn) Inline il -> case il of Text tl -> text tl InlineElement p -> Element.name (InlineElement.element p) ) :: list foldr nodeNameOrTextValue [] (Block rootNode) --> [ "doc", "paragraph", "sample1", "sample2" ] -} foldr : (Node -> b -> b) -> b -> Node -> b foldr func acc node = func node (case node of Block blockNode -> let children = case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldr (\childNode agg -> foldr func agg childNode ) acc children Inline _ -> acc ) {-| Reduce a node from the top left (e.g. from first to last). rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" nodeNameOrTextValue : Node -> List String -> List String nodeNameOrTextValue node list = (case node of Block bn -> Element.name (Node.element bn) Inline il -> case il of Text tl -> text tl InlineElement p -> Element.name (InlineElement.element p) ) :: list foldl nodeNameOrTextValue [] (Block rootNode) --> [ "sample2", "sample1", "paragraph", "doc" ] -} foldl : (Node -> b -> b) -> b -> Node -> b foldl func acc node = case node of Block blockNode -> let children = case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldl (\childNode agg -> foldl func agg childNode ) (func node acc) children Inline _ -> func node acc {-| Same as `foldr` but the reduce function also has the current node's path. pathList : Path -> Node -> List Path -> List Path pathList path _ list = path :: list (indexedFoldr pathList [] (Block rootNode)) == [ [], [ 0 ], [ 0, 0 ], [ 0, 1 ] ] -} indexedFoldr : (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldr = indexedFoldrRec [] indexedFoldrRec : Path -> (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldrRec path func acc node = func path node (case node of Block blockNode -> let children = Array.indexedMap Tuple.pair <| case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldr (\( index, childNode ) agg -> indexedFoldrRec (path ++ [ index ]) func agg childNode ) acc children Inline _ -> acc ) {-| Same as `foldl` but the reduce function also has the current node's path. pathList : Path -> Node -> List Path -> List Path pathList path _ list = path :: list (indexedFoldl pathList [] (Block rootNode)) == [ [ 0, 1 ], [ 0, 0 ], [ 0 ], [] ] -} indexedFoldl : (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldl = indexedFoldlRec [] indexedFoldlRec : Path -> (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldlRec path func acc node = case node of Block blockNode -> let children = Array.indexedMap Tuple.pair <| case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldl (\( index, childNode ) agg -> indexedFoldlRec (path ++ [ index ]) func agg childNode ) (func path node acc) children Inline _ -> func path node acc {-| Same as `foldl` but only applied the nodes between the given paths, inclusive. foldlRange [] [ 1 ] nodeNameOrTextValue [] (Block rootNode) --> [ "sample2", "sample1", "paragraph" ] -} foldlRange : Path -> Path -> (Node -> b -> b) -> b -> Block -> b foldlRange start end func acc root = case nodeAt start root of Nothing -> acc Just node -> foldlRangeRec start end func acc root node foldlRangeRec : Path -> Path -> (Node -> b -> b) -> b -> Block -> Node -> b foldlRangeRec start end func acc root node = if start > end then acc else let result = func node acc in case next start root of Nothing -> result Just ( p, n ) -> foldlRangeRec p end func result root n {-| Same as `foldr` but only applied the nodes between the given paths, inclusive. foldlRange [ 0 ] [ 0, 1 ] nodeNameOrTextValue [] (Block rootNode) --> [ "paragraph", "sample1", "sample2" ] -} foldrRange : Path -> Path -> (Node -> b -> b) -> b -> Block -> b foldrRange start end func acc root = case nodeAt end root of Nothing -> acc Just node -> foldrRangeRec start end func acc root node foldrRangeRec : Path -> Path -> (Node -> b -> b) -> b -> Block -> Node -> b foldrRangeRec start end func acc root node = if start > end then acc else let result = func node acc in case previous end root of Nothing -> result Just ( p, n ) -> foldrRangeRec start p func result root n {-| Returns a Ok Block that replaces the node at the node path with the given fragment. If it is unable to replace it do to an invalid path or the wrong type of node, a Err string describing the error is returned. -- replaces the node at [0, 0] with the given inline fragment replaceWithFragment [ 0, 0 ] (InlineFragment <| Array.fromList [ textNode ]) rootNode -} replaceWithFragment : Path -> Fragment -> Block -> Result String Block replaceWithFragment path fragment root = case path of [] -> Err "Invalid path" [ x ] -> case childNodes root of BlockChildren a -> case fragment of BlockFragment blocks -> let arr = toBlockArray a in Ok <| (root |> withChildNodes (blockChildren (Array.append (Array.append (Array.Extra.sliceUntil x arr) blocks ) (Array.Extra.sliceFrom (x + 1) arr) ) ) ) InlineFragment _ -> Err "I cannot replace a block fragment with an inline leaf fragment" InlineChildren a -> case fragment of InlineFragment leaves -> let arr = toInlineArray a in Ok <| (root |> withChildNodes (inlineChildren (Array.append (Array.append (Array.Extra.sliceUntil x arr) leaves ) (Array.Extra.sliceFrom (x + 1) arr) ) ) ) BlockFragment _ -> Err "I cannot replace an inline fragment with a block fragment" Leaf -> Err "Not implemented" x :: xs -> case childNodes root of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> Err "I received an invalid path, I can't find a block node at the given index." Just node -> case replaceWithFragment xs fragment node of Ok n -> Ok <| (root |> withChildNodes (blockChildren (Array.set x n arr))) Err v -> Err v InlineChildren _ -> Err "I received an invalid path, I reached an inline leaf array but I still have more path left." Leaf -> Err "I received an invalid path, I am on a leaf node, but I still have more path left." {-| Replaces the node at the path with the given editor node. -- replaces the node at [0, 0] with the inline text replace [ 0, 0 ] (Inline textNode) rootNode -} replace : Path -> Node -> Block -> Result String Block replace path node root = case path of [] -> case node of Block n -> Ok n Inline _ -> Err "I cannot replace a block node with an inline leaf." _ -> let fragment = case node of Block n -> BlockFragment <| Array.fromList [ n ] Inline n -> InlineFragment <| Array.fromList [ n ] in replaceWithFragment path fragment root {-| Returns Just the parent of the given path if the path refers to an inline node, otherwise inline content, otherwisereturn Nothing. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" findTextBlockNodeAncestor [ 0, 0 ] rootNode --> Just ( [ 0 ], pNode ) findTextBlockNodeAncestor [ 0 ] rootNode --> Nothing == -} findTextBlockNodeAncestor : Path -> Block -> Maybe ( Path, Block ) findTextBlockNodeAncestor = findAncestor (\n -> case childNodes n of InlineChildren _ -> True _ -> False ) {-| Find ancestor from path finds the closest ancestor from the given NodePath that matches the predicate. -- Finds the closest list item ancestor if it exists findAncestor (\n -> Element.name (Node.element n) == "list_item") -} findAncestor : (Block -> Bool) -> Path -> Block -> Maybe ( Path, Block ) findAncestor pred path node = case path of [] -> Nothing x :: xs -> case childNodes node of BlockChildren a -> case Array.get x (toBlockArray a) of Nothing -> Nothing Just childNode -> case findAncestor pred xs childNode of Nothing -> if pred node then Just ( [], node ) else Nothing Just ( p, result ) -> Just ( x :: p, result ) _ -> if pred node then Just ( [], node ) else Nothing {-| Returns the node at the specified path if it exists. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) nodeAt [0] rootNode == Just (Block pNode) -} nodeAt : Path -> Block -> Maybe Node nodeAt path node = case path of [] -> Just <| Block node x :: xs -> case childNodes node of BlockChildren arr -> case Array.get x (toBlockArray arr) of Nothing -> Nothing Just childNode -> nodeAt xs childNode InlineChildren a -> case Array.get x (toInlineArray a) of Nothing -> Nothing Just childLeafNode -> if List.isEmpty xs then Just <| Inline childLeafNode else Nothing Leaf -> Nothing {-| This method removes all the nodes inclusive to both the start and end path. Note that an ancestor is not removed if the start path or end path is a child node. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) emptyRoot : Block emptyRoot = block (Element.element doc []) (blockChildren <| Array.empty) removeInRange [0] [0] root == emptyRoot --> True -} removeInRange : Path -> Path -> Block -> Block removeInRange start end node = let startIndex = Maybe.withDefault 0 (List.head start) startRest = Maybe.withDefault [] (List.tail start) endIndex = Maybe.withDefault (case childNodes node of BlockChildren a -> Array.length (toBlockArray a) InlineChildren a -> Array.length (toInlineArray a) Leaf -> 0 ) (List.head end) endRest = Maybe.withDefault [] (List.tail end) in if startIndex > endIndex then node else if startIndex == endIndex then case childNodes node of BlockChildren a -> let array = toBlockArray a in if List.isEmpty startRest && List.isEmpty endRest then node |> withChildNodes (blockChildren <| Array.Extra.removeAt startIndex array) else case Array.get startIndex array of Nothing -> node Just b -> node |> withChildNodes (blockChildren <| Array.set startIndex (removeInRange startRest endRest b) array) InlineChildren a -> if List.isEmpty startRest && List.isEmpty endRest then node |> withChildNodes (inlineChildren <| Array.Extra.removeAt startIndex (toInlineArray a)) else node Leaf -> node else case childNodes node of BlockChildren a -> let arr = toBlockArray a left = Array.Extra.sliceUntil startIndex arr right = Array.Extra.sliceFrom (endIndex + 1) arr leftRest = if List.isEmpty startRest then Array.empty else case Array.get startIndex arr of Nothing -> Array.empty Just b -> Array.fromList [ removeInRange startRest endRest b ] rightRest = if List.isEmpty endRest then Array.empty else case Array.get endIndex arr of Nothing -> Array.empty Just b -> Array.fromList [ removeInRange startRest endRest b ] in node |> withChildNodes (blockChildren <| List.foldr Array.append Array.empty [ left, leftRest, rightRest, right ]) InlineChildren a -> let arr = toInlineArray a left = Array.Extra.sliceUntil (if List.isEmpty startRest then startIndex else startIndex + 1 ) arr right = Array.Extra.sliceFrom (if List.isEmpty endRest then endIndex + 1 else endIndex ) arr in node |> withChildNodes (inlineChildren <| Array.append left right) Leaf -> node {-| Removes the node at the given path, and recursively removes parent blocks that have no remaining child nodes, excluding the root. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ removedPHtmlNode ] ) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode ] ) textNode : Inline textNode = plainText "sample1" removedRoot : Block removedRoot = block (Element.element doc []) (blockChildren Array.empty) removeNodeAndEmptyParents [0, 0] root == removedRoot --> True -} removeNodeAndEmptyParents : Path -> Block -> Block removeNodeAndEmptyParents path node = case path of [] -> node [ x ] -> case childNodes node of BlockChildren a -> node |> withChildNodes (blockChildren <| Array.Extra.removeAt x (toBlockArray a)) InlineChildren a -> node |> withChildNodes (inlineChildren <| Array.Extra.removeAt x (toInlineArray a)) Leaf -> node x :: xs -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> node Just n -> let newNode = removeNodeAndEmptyParents xs n in case childNodes newNode of BlockChildren newNodeChildren -> let newChildNodes = toBlockArray newNodeChildren in if Array.isEmpty newChildNodes then node |> withChildNodes (blockChildren <| Array.Extra.removeAt x arr) else node |> withChildNodes (blockChildren <| Array.set x newNode arr) InlineChildren newNodeChildren -> let newChildNodes = toInlineArray newNodeChildren in if Array.isEmpty newChildNodes then node |> withChildNodes (blockChildren <| Array.Extra.removeAt x arr) else node |> withChildNodes (blockChildren <| Array.set x newNode arr) _ -> node |> withChildNodes (blockChildren <| Array.set x newNode arr) InlineChildren _ -> node Leaf -> node {-| Splits a text leaf into two based on the given offset. splitTextLeaf 1 (emptyText <| withText "test") --> (Text "t", Text "est") -} splitTextLeaf : Int -> Text -> ( Text, Text ) splitTextLeaf offset leaf = let leafText = text leaf in ( leaf |> withText (String.left offset leafText), leaf |> withText (String.dropLeft offset leafText) ) {-| Splits a block at the given path and offset and returns Just the split nodes. If the path is invalid or the node cannot be split, Nothing is returned. textNode1 : Inline textNode1 = plainText "sample1" nodeWithTextLeafToSplit : Block nodeWithTextLeafToSplit = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1 ] ) nodeBeforeTextLeafSplit : Block nodeBeforeTextLeafSplit = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ plainText "sam" ] ) nodeAfterTextLeafSplit : Block nodeAfterTextLeafSplit = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ plainText "ple1" ] ) Just (nodeBeforeTextLeafSplit, nodeAfterTextLeafSplit) == splitBlockAtPathAndOffset [ 0 ] 3 nodeWithTextLeafToSplit -} splitBlockAtPathAndOffset : Path -> Int -> Block -> Maybe ( Block, Block ) splitBlockAtPathAndOffset path offset node = case path of [] -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in Just ( node |> withChildNodes (blockChildren (Array.Extra.sliceUntil offset arr)) , node |> withChildNodes (blockChildren (Array.Extra.sliceFrom offset arr)) ) InlineChildren a -> let arr = toInlineArray a in Just ( node |> withChildNodes (inlineChildren (Array.Extra.sliceUntil offset arr)) , node |> withChildNodes (inlineChildren (Array.Extra.sliceFrom offset arr)) ) Leaf -> Just ( node, node ) x :: xs -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> Nothing Just n -> case splitBlockAtPathAndOffset xs offset n of Nothing -> Nothing Just ( before, after ) -> Just ( node |> withChildNodes (blockChildren (Array.append (Array.Extra.sliceUntil x arr) (Array.fromList [ before ]))) , node |> withChildNodes (blockChildren (Array.append (Array.fromList [ after ]) (Array.Extra.sliceFrom (x + 1) arr))) ) InlineChildren a -> let arr = toInlineArray a in case Array.get x arr of Nothing -> Nothing Just n -> case n of Text tl -> let ( before, after ) = splitTextLeaf offset tl in Just ( node |> withChildNodes (inlineChildren (Array.set x (Text before) (Array.Extra.sliceUntil (x + 1) arr))) , node |> withChildNodes (inlineChildren (Array.set 0 (Text after) (Array.Extra.sliceFrom x arr))) ) InlineElement _ -> Just ( node |> withChildNodes (inlineChildren (Array.Extra.sliceUntil x arr)) , node |> withChildNodes (inlineChildren (Array.Extra.sliceFrom x arr)) ) Leaf -> Nothing {-| Determine if all elements in range satisfy some test. -- Query to determine if all the elements in range are selectable allRange isSelectable [ 0, 0 ] [ 0, 2 ] root -} allRange : (Node -> Bool) -> Path -> Path -> Block -> Bool allRange pred start end root = if start > end then True else case nodeAt start root of Nothing -> -- In the case of an invalid path, just return true. True Just node -> if pred node then case next start root of Nothing -> True Just ( nextPath, _ ) -> allRange pred nextPath end root else False {-| Determine if any elements in range satisfy some test. -- Query to determine if any elements in range are selectable allRange isSelectable [ 0, 0 ] [ 0, 2 ] root -} anyRange : (Node -> Bool) -> Path -> Path -> Block -> Bool anyRange pred start end root = not <| allRange (\x -> not <| pred x) start end root {-| If the node specified by the path is an inline node, returns the parent. If the node at the path is a block, then returns the same path. Otherwise if the path is invalid, returns the root path. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" findClosestBlockPath [0, 0] rootNode --> [0] findClosestBlockPath [0] rootNode --> [0] -} findClosestBlockPath : Path -> Block -> Path findClosestBlockPath path node = case nodeAt path node of Nothing -> [] Just n -> case n of Block _ -> path Inline _ -> parent path {-| If the two blocks have the same type of children, returns the joined block. Otherwise, if the blocks have different children or one or more is a leaf node, then Nothing is return. pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) pNodeReverse : Block pNodeReverse = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode2, textNode1 ] ) pNodeExpectedJoin : Block pNodeExpectedJoin = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2, textNode2, textNode1 ] ) pNodeExpectedJoin == joinBlocks pNode pNodeReverse -} joinBlocks : Block -> Block -> Maybe Block joinBlocks b1 b2 = case childNodes b1 of BlockChildren a1 -> case childNodes b2 of BlockChildren a2 -> Just <| (b1 |> withChildNodes (blockChildren (Array.append (toBlockArray a1) (toBlockArray a2)))) _ -> Nothing InlineChildren a1 -> case childNodes b2 of InlineChildren a2 -> Just <| (b1 |> withChildNodes (inlineChildren (Array.append (toInlineArray a1) (toInlineArray a2)))) _ -> Nothing Leaf -> Nothing {-| Inserts the fragments after the node at the given path and returns the result. Returns an error if the path is invalid or the fragment cannot be inserted. insertAfter [ 0, 0 ] fragment root --> Inserts the fragment after the node at path [0, 0] -} insertAfter : Path -> Fragment -> Block -> Result String Block insertAfter path fragment root = case nodeAt path root of Nothing -> Err "There is no node at this path" Just node -> case node of Inline il -> case fragment of InlineFragment a -> let newFragment = InlineFragment <| Array.fromList (il :: Array.toList a) in replaceWithFragment path newFragment root BlockFragment _ -> Err "I cannot insert a block node fragment into an inline leaf fragment" Block bn -> case fragment of BlockFragment a -> let newFragment = BlockFragment <| Array.fromList (bn :: Array.toList a) in replaceWithFragment path newFragment root InlineFragment _ -> Err "I cannot insert an inline leaf fragment fragment into a block node fragment" {-| Inserts the fragments before the node at the given path and returns the result. Returns an error if the path is invalid or the fragment cannot be inserted. insertBefore [ 0, 0 ] fragment root --> Inserts the fragment before the node at path [0, 0] -} insertBefore : Path -> Fragment -> Block -> Result String Block insertBefore path fragment root = case nodeAt path root of Nothing -> Err "There is no node at this path" Just node -> case node of Inline il -> case fragment of InlineFragment a -> let newFragment = InlineFragment <| Array.push il a in replaceWithFragment path newFragment root BlockFragment _ -> Err "I cannot insert a block node fragment into an inline leaf fragment" Block bn -> case fragment of BlockFragment a -> let newFragment = BlockFragment <| Array.push bn a in replaceWithFragment path newFragment root InlineFragment _ -> Err "I cannot insert an inline leaf fragment fragment into a block node fragment" {-| Runs the toggle action on the node for the given mark. toggleMark Add markOrder bold node --> Adds bold to the given node -} toggleMark : ToggleAction -> MarkOrder -> Mark -> Node -> Node toggleMark action markOrder mark node = case node of Block _ -> node Inline il -> Inline <| case il of Text leaf -> Text <| (leaf |> Text.withMarks (toggle action markOrder mark (Text.marks leaf)) ) InlineElement leaf -> InlineElement <| (leaf |> InlineElement.withMarks (toggle action markOrder mark (InlineElement.marks leaf)) ) {-| True if this block has inline content with no children or a single empty text node, false otherwise pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ emptyText ] ) isEmptyTextBlock pNode --> True -} isEmptyTextBlock : Node -> Bool isEmptyTextBlock node = case node of Block bn -> case childNodes bn of InlineChildren a -> let array = toInlineArray a in case Array.get 0 array of Nothing -> Array.isEmpty array Just n -> Array.length array == 1 && (case n of Text t -> String.isEmpty (Text.text t) _ -> False ) _ -> False Inline _ -> False {-| True if the selection is collapsed at the beginning of a text block, false otherwise. -- selectionIsBeginningOfTextBlock is used for things like lift and join backward if selectionIsBeginningOfTextBlock selection (State.root editorState) then -- Do join backward logic else -- Do something else -} selectionIsBeginningOfTextBlock : Selection -> Block -> Bool selectionIsBeginningOfTextBlock selection root = if not <| isCollapsed selection then False else case findTextBlockNodeAncestor (anchorNode selection) root of Nothing -> False Just ( _, n ) -> case childNodes n of InlineChildren a -> case List.Extra.last (anchorNode selection) of Nothing -> False Just i -> if i /= 0 || Array.isEmpty (toInlineArray a) then False else anchorOffset selection == 0 _ -> False {-| True if the selection is collapsed at the end of a text block, false otherwise. -- selectionIsEndOfTextBlock is used for things like join forward if selectionIsEndOfTextBlock selection (State.root editorState) then -- Do join forward logic else -- Do something else -} selectionIsEndOfTextBlock : Selection -> Block -> Bool selectionIsEndOfTextBlock selection root = if not <| isCollapsed selection then False else case findTextBlockNodeAncestor (anchorNode selection) root of Nothing -> False Just ( _, n ) -> case childNodes n of InlineChildren a -> case List.Extra.last (anchorNode selection) of Nothing -> False Just i -> if i /= Array.length (toInlineArray a) - 1 then False else case Array.get i (toInlineArray a) of Nothing -> False Just leaf -> case leaf of Text tl -> String.length (Text.text tl) == anchorOffset selection InlineElement _ -> True _ -> False
992
module RichText.Node exposing ( insertAfter, insertBefore, replace, replaceWithFragment , removeInRange, removeNodeAndEmptyParents , allRange, anyRange, isEmptyTextBlock, selectionIsBeginningOfTextBlock, selectionIsEndOfTextBlock , concatMap, indexedMap, joinBlocks, map , Iterator, last, next, nodeAt, previous, findAncestor, findBackwardFrom, findBackwardFromExclusive, findClosestBlockPath, findForwardFrom, findForwardFromExclusive, findTextBlockNodeAncestor , foldl, foldlRange, foldr, foldrRange, indexedFoldl, indexedFoldr , splitBlockAtPathAndOffset, splitTextLeaf , toggleMark , Fragment(..), Node(..) ) {-| This module contains convenience functions for working with Block and Inline nodes. # Insert / Replace @docs insertAfter, insertBefore, replace, replaceWithFragment # Remove @docs removeInRange, removeNodeAndEmptyParents # Predicates @docs allRange, anyRange, isEmptyTextBlock, selectionIsBeginningOfTextBlock, selectionIsEndOfTextBlock # Transform @docs concatMap, indexedMap, joinBlocks, map # Searching @docs Iterator, last, next, nodeAt, previous, findAncestor, findBackwardFrom, findBackwardFromExclusive, findClosestBlockPath, findForwardFrom, findForwardFromExclusive, findTextBlockNodeAncestor # Folds @docs foldl, foldlRange, foldr, foldrRange, indexedFoldl, indexedFoldr # Split @docs splitBlockAtPathAndOffset, splitTextLeaf # Marks @docs toggleMark # Types These are convenience types to wrap around inline and block node and arrays @docs Fragment, Node -} import Array exposing (Array) import Array.Extra import List.Extra import RichText.Model.InlineElement as InlineElement import RichText.Model.Mark exposing (Mark, MarkOrder, ToggleAction, toggle) import RichText.Model.Node exposing ( Block , Children(..) , Inline(..) , Path , blockChildren , childNodes , inlineChildren , parent , toBlockArray , toInlineArray , withChildNodes ) import RichText.Model.Selection exposing (Selection, anchorNode, anchorOffset, isCollapsed) import RichText.Model.Text as Text exposing (Text, text, withText) {-| Node represents either a `Block` or `Inline`. It's a convenience type that wraps an argument or return value of a function that can use either block or inline, like `nodeAt` or `replace`. -} type Node = Block Block | Inline Inline {-| A `Fragment` represents an array of `Block` or `Inline` nodes. It's a convenience type used for things like insertion or deserialization. -} type Fragment = BlockFragment (Array Block) | InlineFragment (Array Inline) {-| Returns the last path and node in the block. ( lastPath, lastNode ) = last node -} last : Block -> ( Path, Node ) last node = case childNodes node of BlockChildren a -> let arr = toBlockArray a lastIndex = Array.length arr - 1 in case Array.get lastIndex arr of Nothing -> ( [], Block node ) Just b -> let ( p, n ) = last b in ( lastIndex :: p, n ) InlineChildren a -> let array = toInlineArray a lastIndex = Array.length array - 1 in case Array.get lastIndex array of Nothing -> ( [], Block node ) Just l -> ( [ lastIndex ], Inline l ) Leaf -> ( [], Block node ) {-| Type alias for a function that takes a path and a root block and returns a path and node. Useful for generalizing functions like previous and next that can iterate through a Block. -} type alias Iterator = Path -> Block -> Maybe ( Path, Node ) {-| Returns the previous path and node, if one exists, relative to the given path. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" previous [0, 1] rootNode == Just ([0, 0], Inline textNode1) -} previous : Iterator previous path node = case path of [] -> Nothing [ x ] -> let prevIndex = x - 1 in case childNodes node of BlockChildren a -> case Array.get prevIndex (toBlockArray a) of Nothing -> Just ( [], Block node ) Just b -> let ( p, n ) = last b in Just ( prevIndex :: p, n ) InlineChildren a -> case Array.get prevIndex (toInlineArray a) of Nothing -> Just ( [], Block node ) Just l -> Just ( [ prevIndex ], Inline l ) Leaf -> Just ( [], Block node ) x :: xs -> case childNodes node of BlockChildren a -> case Array.get x (toBlockArray a) of Nothing -> Nothing Just b -> case previous xs b of Nothing -> Just ( [ x ], Block b ) Just ( p, n ) -> Just ( x :: p, n ) InlineChildren a -> case Array.get (x - 1) (toInlineArray a) of Nothing -> Just ( [], Block node ) Just l -> Just ( [ x - 1 ], Inline l ) Leaf -> Nothing {-| Returns the next path and node, if one exists, relative to the given path. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" next [0, 0] rootNode == Just ([0, 1], Inline textNode2) -} next : Iterator next path node = case path of [] -> case childNodes node of BlockChildren a -> case Array.get 0 (toBlockArray a) of Nothing -> Nothing Just b -> Just ( [ 0 ], Block b ) InlineChildren a -> case Array.get 0 (toInlineArray a) of Nothing -> Nothing Just b -> Just ( [ 0 ], Inline b ) Leaf -> Nothing x :: xs -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> Nothing Just b -> case next xs b of Nothing -> case Array.get (x + 1) arr of Nothing -> Nothing Just bNext -> Just ( [ x + 1 ], Block bNext ) Just ( p, n ) -> Just ( x :: p, n ) InlineChildren a -> case Array.get (x + 1) (toInlineArray a) of Nothing -> Nothing Just b -> Just ( [ x + 1 ], Inline b ) Leaf -> Nothing {-| Starting from the given path, scans the node forward until the predicate has been met or it reaches the last node. -} findForwardFrom : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findForwardFrom = findNodeFrom next {-| Starting from but excluding the given path, scans the node forward until the predicate has been met or it reaches the last node. -} findForwardFromExclusive : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findForwardFromExclusive = findNodeFromExclusive next {-| Starting from the given path, scans the node backward until the predicate has been met or it reaches the last node. -} findBackwardFrom : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findBackwardFrom = findNodeFrom previous {-| Starting from but excluding the given path, scans the node backward until the predicate has been met or it reaches the last node. -} findBackwardFromExclusive : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findBackwardFromExclusive = findNodeFromExclusive previous findNodeFromExclusive : Iterator -> (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findNodeFromExclusive iterator pred path node = case iterator path node of Nothing -> Nothing Just ( nextPath, _ ) -> findNodeFrom iterator pred nextPath node findNodeFrom : Iterator -> (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findNodeFrom iterator pred path node = case nodeAt path node of Just n -> if pred path n then Just ( path, n ) else findNodeFromExclusive iterator pred path node Nothing -> Nothing {-| Map a given function onto a block's children recursively and flatten the resulting list. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" doubleRoot : Block doubleRoot = block (Element.element doc []) (blockChildren <| Array.fromList [ doublePNode, doublePNode ] ) doublePNode : Block doublePNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode1, textNode2, textNode2 ] ) concatMap (\node -> [ node, node ]) rootNode == doubleRoot --> True -} concatMap : (Node -> List Node) -> Block -> Block concatMap func node = let newChildren = case childNodes node of Leaf -> Leaf BlockChildren a -> let c = List.concatMap (\x -> case x of Block v -> [ v ] Inline _ -> [] ) <| List.concatMap func (List.map Block (Array.toList (toBlockArray a))) in blockChildren <| Array.fromList (List.map (concatMap func) c) InlineChildren a -> inlineChildren <| Array.fromList (List.concatMap (\x -> case x of Block _ -> [] Inline v -> [ v ] ) <| List.concatMap func (List.map Inline (Array.toList (toInlineArray a))) ) in node |> withChildNodes newChildren {-| Apply a function to this node and all child nodes. setAnnotations : String -> Node -> Node setAnnotations mark node = let annotations = Set.fromList [ mark ] in case node of Block bn -> let params = Node.element bn in Block (bn |> withElement (params |> Element.withAnnotations annotations)) Inline il -> case il of Text tl -> Inline (Text (tl |> Text.withAnnotations annotations)) InlineElement l -> let params = InlineElement.element l in Inline (InlineElement (l |> InlineElement.withElement (params |> Element.withAnnotations annotations))) setDummyAnnotation : Node -> Node setDummyAnnotation node = setAnnotations dummyAnnotation node map setDummyAnnotation (Block rootNode) --> Recursively adds a dummy annotation to rootNode and all its children -} map : (Node -> Node) -> Node -> Node map func node = let applied = func node in case applied of Block blockNode -> Block <| (blockNode |> withChildNodes (case childNodes blockNode of BlockChildren a -> blockChildren <| Array.map (\v -> case map func (Block v) of Block b -> b _ -> v ) (toBlockArray a) InlineChildren a -> inlineChildren <| Array.map (\v -> case map func (Inline v) of Inline b -> b _ -> v ) (toInlineArray a) Leaf -> Leaf ) ) Inline inlineLeaf -> Inline inlineLeaf {-| Same as map but the function is also applied with the path of each element (starting at []). indexedMap (\path node -> if path == [ 0, 0 ] then text2 else node ) (Block rootNode) --> replaces the node at [0, 0] with the text2 node -} indexedMap : (Path -> Node -> Node) -> Node -> Node indexedMap = indexedMapRec [] indexedMapRec : Path -> (Path -> Node -> Node) -> Node -> Node indexedMapRec path func node = let applied = func path node in case applied of Block blockNode -> let cn = case childNodes blockNode of BlockChildren a -> blockChildren <| Array.indexedMap (\i v -> case indexedMapRec (path ++ [ i ]) func (Block v) of Block b -> b _ -> v ) (toBlockArray a) InlineChildren a -> inlineChildren <| Array.indexedMap (\i v -> case indexedMapRec (path ++ [ i ]) func (Inline v) of Inline b -> b _ -> v ) (toInlineArray a) Leaf -> Leaf in Block (blockNode |> withChildNodes cn) Inline inlineLeaf -> Inline inlineLeaf {-| Reduce a node from the bottom right (e.g. from last to first). nodeNameOrTextValue : Node -> List String -> List String nodeNameOrTextValue node list = (case node of Block bn -> Element.name (Node.element bn) Inline il -> case il of Text tl -> text tl InlineElement p -> Element.name (InlineElement.element p) ) :: list foldr nodeNameOrTextValue [] (Block rootNode) --> [ "doc", "paragraph", "sample1", "sample2" ] -} foldr : (Node -> b -> b) -> b -> Node -> b foldr func acc node = func node (case node of Block blockNode -> let children = case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldr (\childNode agg -> foldr func agg childNode ) acc children Inline _ -> acc ) {-| Reduce a node from the top left (e.g. from first to last). rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" nodeNameOrTextValue : Node -> List String -> List String nodeNameOrTextValue node list = (case node of Block bn -> Element.name (Node.element bn) Inline il -> case il of Text tl -> text tl InlineElement p -> Element.name (InlineElement.element p) ) :: list foldl nodeNameOrTextValue [] (Block rootNode) --> [ "sample2", "sample1", "paragraph", "doc" ] -} foldl : (Node -> b -> b) -> b -> Node -> b foldl func acc node = case node of Block blockNode -> let children = case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldl (\childNode agg -> foldl func agg childNode ) (func node acc) children Inline _ -> func node acc {-| Same as `foldr` but the reduce function also has the current node's path. pathList : Path -> Node -> List Path -> List Path pathList path _ list = path :: list (indexedFoldr pathList [] (Block rootNode)) == [ [], [ 0 ], [ 0, 0 ], [ 0, 1 ] ] -} indexedFoldr : (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldr = indexedFoldrRec [] indexedFoldrRec : Path -> (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldrRec path func acc node = func path node (case node of Block blockNode -> let children = Array.indexedMap Tuple.pair <| case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldr (\( index, childNode ) agg -> indexedFoldrRec (path ++ [ index ]) func agg childNode ) acc children Inline _ -> acc ) {-| Same as `foldl` but the reduce function also has the current node's path. pathList : Path -> Node -> List Path -> List Path pathList path _ list = path :: list (indexedFoldl pathList [] (Block rootNode)) == [ [ 0, 1 ], [ 0, 0 ], [ 0 ], [] ] -} indexedFoldl : (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldl = indexedFoldlRec [] indexedFoldlRec : Path -> (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldlRec path func acc node = case node of Block blockNode -> let children = Array.indexedMap Tuple.pair <| case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldl (\( index, childNode ) agg -> indexedFoldlRec (path ++ [ index ]) func agg childNode ) (func path node acc) children Inline _ -> func path node acc {-| Same as `foldl` but only applied the nodes between the given paths, inclusive. foldlRange [] [ 1 ] nodeNameOrTextValue [] (Block rootNode) --> [ "sample2", "sample1", "paragraph" ] -} foldlRange : Path -> Path -> (Node -> b -> b) -> b -> Block -> b foldlRange start end func acc root = case nodeAt start root of Nothing -> acc Just node -> foldlRangeRec start end func acc root node foldlRangeRec : Path -> Path -> (Node -> b -> b) -> b -> Block -> Node -> b foldlRangeRec start end func acc root node = if start > end then acc else let result = func node acc in case next start root of Nothing -> result Just ( p, n ) -> foldlRangeRec p end func result root n {-| Same as `foldr` but only applied the nodes between the given paths, inclusive. foldlRange [ 0 ] [ 0, 1 ] nodeNameOrTextValue [] (Block rootNode) --> [ "paragraph", "sample1", "sample2" ] -} foldrRange : Path -> Path -> (Node -> b -> b) -> b -> Block -> b foldrRange start end func acc root = case nodeAt end root of Nothing -> acc Just node -> foldrRangeRec start end func acc root node foldrRangeRec : Path -> Path -> (Node -> b -> b) -> b -> Block -> Node -> b foldrRangeRec start end func acc root node = if start > end then acc else let result = func node acc in case previous end root of Nothing -> result Just ( p, n ) -> foldrRangeRec start p func result root n {-| Returns a Ok Block that replaces the node at the node path with the given fragment. If it is unable to replace it do to an invalid path or the wrong type of node, a Err string describing the error is returned. -- replaces the node at [0, 0] with the given inline fragment replaceWithFragment [ 0, 0 ] (InlineFragment <| Array.fromList [ textNode ]) rootNode -} replaceWithFragment : Path -> Fragment -> Block -> Result String Block replaceWithFragment path fragment root = case path of [] -> Err "Invalid path" [ x ] -> case childNodes root of BlockChildren a -> case fragment of BlockFragment blocks -> let arr = toBlockArray a in Ok <| (root |> withChildNodes (blockChildren (Array.append (Array.append (Array.Extra.sliceUntil x arr) blocks ) (Array.Extra.sliceFrom (x + 1) arr) ) ) ) InlineFragment _ -> Err "I cannot replace a block fragment with an inline leaf fragment" InlineChildren a -> case fragment of InlineFragment leaves -> let arr = toInlineArray a in Ok <| (root |> withChildNodes (inlineChildren (Array.append (Array.append (Array.Extra.sliceUntil x arr) leaves ) (Array.Extra.sliceFrom (x + 1) arr) ) ) ) BlockFragment _ -> Err "I cannot replace an inline fragment with a block fragment" Leaf -> Err "Not implemented" x :: xs -> case childNodes root of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> Err "I received an invalid path, I can't find a block node at the given index." Just node -> case replaceWithFragment xs fragment node of Ok n -> Ok <| (root |> withChildNodes (blockChildren (Array.set x n arr))) Err v -> Err v InlineChildren _ -> Err "I received an invalid path, I reached an inline leaf array but I still have more path left." Leaf -> Err "I received an invalid path, I am on a leaf node, but I still have more path left." {-| Replaces the node at the path with the given editor node. -- replaces the node at [0, 0] with the inline text replace [ 0, 0 ] (Inline textNode) rootNode -} replace : Path -> Node -> Block -> Result String Block replace path node root = case path of [] -> case node of Block n -> Ok n Inline _ -> Err "I cannot replace a block node with an inline leaf." _ -> let fragment = case node of Block n -> BlockFragment <| Array.fromList [ n ] Inline n -> InlineFragment <| Array.fromList [ n ] in replaceWithFragment path fragment root {-| Returns Just the parent of the given path if the path refers to an inline node, otherwise inline content, otherwisereturn Nothing. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" findTextBlockNodeAncestor [ 0, 0 ] rootNode --> Just ( [ 0 ], pNode ) findTextBlockNodeAncestor [ 0 ] rootNode --> Nothing == -} findTextBlockNodeAncestor : Path -> Block -> Maybe ( Path, Block ) findTextBlockNodeAncestor = findAncestor (\n -> case childNodes n of InlineChildren _ -> True _ -> False ) {-| Find ancestor from path finds the closest ancestor from the given NodePath that matches the predicate. -- Finds the closest list item ancestor if it exists findAncestor (\n -> Element.name (Node.element n) == "list_item") -} findAncestor : (Block -> Bool) -> Path -> Block -> Maybe ( Path, Block ) findAncestor pred path node = case path of [] -> Nothing x :: xs -> case childNodes node of BlockChildren a -> case Array.get x (toBlockArray a) of Nothing -> Nothing Just childNode -> case findAncestor pred xs childNode of Nothing -> if pred node then Just ( [], node ) else Nothing Just ( p, result ) -> Just ( x :: p, result ) _ -> if pred node then Just ( [], node ) else Nothing {-| Returns the node at the specified path if it exists. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) nodeAt [0] rootNode == Just (Block pNode) -} nodeAt : Path -> Block -> Maybe Node nodeAt path node = case path of [] -> Just <| Block node x :: xs -> case childNodes node of BlockChildren arr -> case Array.get x (toBlockArray arr) of Nothing -> Nothing Just childNode -> nodeAt xs childNode InlineChildren a -> case Array.get x (toInlineArray a) of Nothing -> Nothing Just childLeafNode -> if List.isEmpty xs then Just <| Inline childLeafNode else Nothing Leaf -> Nothing {-| This method removes all the nodes inclusive to both the start and end path. Note that an ancestor is not removed if the start path or end path is a child node. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) emptyRoot : Block emptyRoot = block (Element.element doc []) (blockChildren <| Array.empty) removeInRange [0] [0] root == emptyRoot --> True -} removeInRange : Path -> Path -> Block -> Block removeInRange start end node = let startIndex = Maybe.withDefault 0 (List.head start) startRest = Maybe.withDefault [] (List.tail start) endIndex = Maybe.withDefault (case childNodes node of BlockChildren a -> Array.length (toBlockArray a) InlineChildren a -> Array.length (toInlineArray a) Leaf -> 0 ) (List.head end) endRest = Maybe.withDefault [] (List.tail end) in if startIndex > endIndex then node else if startIndex == endIndex then case childNodes node of BlockChildren a -> let array = toBlockArray a in if List.isEmpty startRest && List.isEmpty endRest then node |> withChildNodes (blockChildren <| Array.Extra.removeAt startIndex array) else case Array.get startIndex array of Nothing -> node Just b -> node |> withChildNodes (blockChildren <| Array.set startIndex (removeInRange startRest endRest b) array) InlineChildren a -> if List.isEmpty startRest && List.isEmpty endRest then node |> withChildNodes (inlineChildren <| Array.Extra.removeAt startIndex (toInlineArray a)) else node Leaf -> node else case childNodes node of BlockChildren a -> let arr = toBlockArray a left = Array.Extra.sliceUntil startIndex arr right = Array.Extra.sliceFrom (endIndex + 1) arr leftRest = if List.isEmpty startRest then Array.empty else case Array.get startIndex arr of Nothing -> Array.empty Just b -> Array.fromList [ removeInRange startRest endRest b ] rightRest = if List.isEmpty endRest then Array.empty else case Array.get endIndex arr of Nothing -> Array.empty Just b -> Array.fromList [ removeInRange startRest endRest b ] in node |> withChildNodes (blockChildren <| List.foldr Array.append Array.empty [ left, leftRest, rightRest, right ]) InlineChildren a -> let arr = toInlineArray a left = Array.Extra.sliceUntil (if List.isEmpty startRest then startIndex else startIndex + 1 ) arr right = Array.Extra.sliceFrom (if List.isEmpty endRest then endIndex + 1 else endIndex ) arr in node |> withChildNodes (inlineChildren <| Array.append left right) Leaf -> node {-| Removes the node at the given path, and recursively removes parent blocks that have no remaining child nodes, excluding the root. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ removedPHtmlNode ] ) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode ] ) textNode : Inline textNode = plainText "sample1" removedRoot : Block removedRoot = block (Element.element doc []) (blockChildren Array.empty) removeNodeAndEmptyParents [0, 0] root == removedRoot --> True -} removeNodeAndEmptyParents : Path -> Block -> Block removeNodeAndEmptyParents path node = case path of [] -> node [ x ] -> case childNodes node of BlockChildren a -> node |> withChildNodes (blockChildren <| Array.Extra.removeAt x (toBlockArray a)) InlineChildren a -> node |> withChildNodes (inlineChildren <| Array.Extra.removeAt x (toInlineArray a)) Leaf -> node x :: xs -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> node Just n -> let newNode = removeNodeAndEmptyParents xs n in case childNodes newNode of BlockChildren newNodeChildren -> let newChildNodes = toBlockArray newNodeChildren in if Array.isEmpty newChildNodes then node |> withChildNodes (blockChildren <| Array.Extra.removeAt x arr) else node |> withChildNodes (blockChildren <| Array.set x newNode arr) InlineChildren newNodeChildren -> let newChildNodes = toInlineArray newNodeChildren in if Array.isEmpty newChildNodes then node |> withChildNodes (blockChildren <| Array.Extra.removeAt x arr) else node |> withChildNodes (blockChildren <| Array.set x newNode arr) _ -> node |> withChildNodes (blockChildren <| Array.set x newNode arr) InlineChildren _ -> node Leaf -> node {-| Splits a text leaf into two based on the given offset. splitTextLeaf 1 (emptyText <| withText "test") --> (Text "t", Text "est") -} splitTextLeaf : Int -> Text -> ( Text, Text ) splitTextLeaf offset leaf = let leafText = text leaf in ( leaf |> withText (String.left offset leafText), leaf |> withText (String.dropLeft offset leafText) ) {-| Splits a block at the given path and offset and returns Just the split nodes. If the path is invalid or the node cannot be split, Nothing is returned. textNode1 : Inline textNode1 = plainText "sample<NAME>" nodeWithTextLeafToSplit : Block nodeWithTextLeafToSplit = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1 ] ) nodeBeforeTextLeafSplit : Block nodeBeforeTextLeafSplit = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ plainText "<NAME>" ] ) nodeAfterTextLeafSplit : Block nodeAfterTextLeafSplit = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ plainText "ple1" ] ) Just (nodeBeforeTextLeafSplit, nodeAfterTextLeafSplit) == splitBlockAtPathAndOffset [ 0 ] 3 nodeWithTextLeafToSplit -} splitBlockAtPathAndOffset : Path -> Int -> Block -> Maybe ( Block, Block ) splitBlockAtPathAndOffset path offset node = case path of [] -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in Just ( node |> withChildNodes (blockChildren (Array.Extra.sliceUntil offset arr)) , node |> withChildNodes (blockChildren (Array.Extra.sliceFrom offset arr)) ) InlineChildren a -> let arr = toInlineArray a in Just ( node |> withChildNodes (inlineChildren (Array.Extra.sliceUntil offset arr)) , node |> withChildNodes (inlineChildren (Array.Extra.sliceFrom offset arr)) ) Leaf -> Just ( node, node ) x :: xs -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> Nothing Just n -> case splitBlockAtPathAndOffset xs offset n of Nothing -> Nothing Just ( before, after ) -> Just ( node |> withChildNodes (blockChildren (Array.append (Array.Extra.sliceUntil x arr) (Array.fromList [ before ]))) , node |> withChildNodes (blockChildren (Array.append (Array.fromList [ after ]) (Array.Extra.sliceFrom (x + 1) arr))) ) InlineChildren a -> let arr = toInlineArray a in case Array.get x arr of Nothing -> Nothing Just n -> case n of Text tl -> let ( before, after ) = splitTextLeaf offset tl in Just ( node |> withChildNodes (inlineChildren (Array.set x (Text before) (Array.Extra.sliceUntil (x + 1) arr))) , node |> withChildNodes (inlineChildren (Array.set 0 (Text after) (Array.Extra.sliceFrom x arr))) ) InlineElement _ -> Just ( node |> withChildNodes (inlineChildren (Array.Extra.sliceUntil x arr)) , node |> withChildNodes (inlineChildren (Array.Extra.sliceFrom x arr)) ) Leaf -> Nothing {-| Determine if all elements in range satisfy some test. -- Query to determine if all the elements in range are selectable allRange isSelectable [ 0, 0 ] [ 0, 2 ] root -} allRange : (Node -> Bool) -> Path -> Path -> Block -> Bool allRange pred start end root = if start > end then True else case nodeAt start root of Nothing -> -- In the case of an invalid path, just return true. True Just node -> if pred node then case next start root of Nothing -> True Just ( nextPath, _ ) -> allRange pred nextPath end root else False {-| Determine if any elements in range satisfy some test. -- Query to determine if any elements in range are selectable allRange isSelectable [ 0, 0 ] [ 0, 2 ] root -} anyRange : (Node -> Bool) -> Path -> Path -> Block -> Bool anyRange pred start end root = not <| allRange (\x -> not <| pred x) start end root {-| If the node specified by the path is an inline node, returns the parent. If the node at the path is a block, then returns the same path. Otherwise if the path is invalid, returns the root path. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" findClosestBlockPath [0, 0] rootNode --> [0] findClosestBlockPath [0] rootNode --> [0] -} findClosestBlockPath : Path -> Block -> Path findClosestBlockPath path node = case nodeAt path node of Nothing -> [] Just n -> case n of Block _ -> path Inline _ -> parent path {-| If the two blocks have the same type of children, returns the joined block. Otherwise, if the blocks have different children or one or more is a leaf node, then Nothing is return. pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) pNodeReverse : Block pNodeReverse = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode2, textNode1 ] ) pNodeExpectedJoin : Block pNodeExpectedJoin = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2, textNode2, textNode1 ] ) pNodeExpectedJoin == joinBlocks pNode pNodeReverse -} joinBlocks : Block -> Block -> Maybe Block joinBlocks b1 b2 = case childNodes b1 of BlockChildren a1 -> case childNodes b2 of BlockChildren a2 -> Just <| (b1 |> withChildNodes (blockChildren (Array.append (toBlockArray a1) (toBlockArray a2)))) _ -> Nothing InlineChildren a1 -> case childNodes b2 of InlineChildren a2 -> Just <| (b1 |> withChildNodes (inlineChildren (Array.append (toInlineArray a1) (toInlineArray a2)))) _ -> Nothing Leaf -> Nothing {-| Inserts the fragments after the node at the given path and returns the result. Returns an error if the path is invalid or the fragment cannot be inserted. insertAfter [ 0, 0 ] fragment root --> Inserts the fragment after the node at path [0, 0] -} insertAfter : Path -> Fragment -> Block -> Result String Block insertAfter path fragment root = case nodeAt path root of Nothing -> Err "There is no node at this path" Just node -> case node of Inline il -> case fragment of InlineFragment a -> let newFragment = InlineFragment <| Array.fromList (il :: Array.toList a) in replaceWithFragment path newFragment root BlockFragment _ -> Err "I cannot insert a block node fragment into an inline leaf fragment" Block bn -> case fragment of BlockFragment a -> let newFragment = BlockFragment <| Array.fromList (bn :: Array.toList a) in replaceWithFragment path newFragment root InlineFragment _ -> Err "I cannot insert an inline leaf fragment fragment into a block node fragment" {-| Inserts the fragments before the node at the given path and returns the result. Returns an error if the path is invalid or the fragment cannot be inserted. insertBefore [ 0, 0 ] fragment root --> Inserts the fragment before the node at path [0, 0] -} insertBefore : Path -> Fragment -> Block -> Result String Block insertBefore path fragment root = case nodeAt path root of Nothing -> Err "There is no node at this path" Just node -> case node of Inline il -> case fragment of InlineFragment a -> let newFragment = InlineFragment <| Array.push il a in replaceWithFragment path newFragment root BlockFragment _ -> Err "I cannot insert a block node fragment into an inline leaf fragment" Block bn -> case fragment of BlockFragment a -> let newFragment = BlockFragment <| Array.push bn a in replaceWithFragment path newFragment root InlineFragment _ -> Err "I cannot insert an inline leaf fragment fragment into a block node fragment" {-| Runs the toggle action on the node for the given mark. toggleMark Add markOrder bold node --> Adds bold to the given node -} toggleMark : ToggleAction -> MarkOrder -> Mark -> Node -> Node toggleMark action markOrder mark node = case node of Block _ -> node Inline il -> Inline <| case il of Text leaf -> Text <| (leaf |> Text.withMarks (toggle action markOrder mark (Text.marks leaf)) ) InlineElement leaf -> InlineElement <| (leaf |> InlineElement.withMarks (toggle action markOrder mark (InlineElement.marks leaf)) ) {-| True if this block has inline content with no children or a single empty text node, false otherwise pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ emptyText ] ) isEmptyTextBlock pNode --> True -} isEmptyTextBlock : Node -> Bool isEmptyTextBlock node = case node of Block bn -> case childNodes bn of InlineChildren a -> let array = toInlineArray a in case Array.get 0 array of Nothing -> Array.isEmpty array Just n -> Array.length array == 1 && (case n of Text t -> String.isEmpty (Text.text t) _ -> False ) _ -> False Inline _ -> False {-| True if the selection is collapsed at the beginning of a text block, false otherwise. -- selectionIsBeginningOfTextBlock is used for things like lift and join backward if selectionIsBeginningOfTextBlock selection (State.root editorState) then -- Do join backward logic else -- Do something else -} selectionIsBeginningOfTextBlock : Selection -> Block -> Bool selectionIsBeginningOfTextBlock selection root = if not <| isCollapsed selection then False else case findTextBlockNodeAncestor (anchorNode selection) root of Nothing -> False Just ( _, n ) -> case childNodes n of InlineChildren a -> case List.Extra.last (anchorNode selection) of Nothing -> False Just i -> if i /= 0 || Array.isEmpty (toInlineArray a) then False else anchorOffset selection == 0 _ -> False {-| True if the selection is collapsed at the end of a text block, false otherwise. -- selectionIsEndOfTextBlock is used for things like join forward if selectionIsEndOfTextBlock selection (State.root editorState) then -- Do join forward logic else -- Do something else -} selectionIsEndOfTextBlock : Selection -> Block -> Bool selectionIsEndOfTextBlock selection root = if not <| isCollapsed selection then False else case findTextBlockNodeAncestor (anchorNode selection) root of Nothing -> False Just ( _, n ) -> case childNodes n of InlineChildren a -> case List.Extra.last (anchorNode selection) of Nothing -> False Just i -> if i /= Array.length (toInlineArray a) - 1 then False else case Array.get i (toInlineArray a) of Nothing -> False Just leaf -> case leaf of Text tl -> String.length (Text.text tl) == anchorOffset selection InlineElement _ -> True _ -> False
true
module RichText.Node exposing ( insertAfter, insertBefore, replace, replaceWithFragment , removeInRange, removeNodeAndEmptyParents , allRange, anyRange, isEmptyTextBlock, selectionIsBeginningOfTextBlock, selectionIsEndOfTextBlock , concatMap, indexedMap, joinBlocks, map , Iterator, last, next, nodeAt, previous, findAncestor, findBackwardFrom, findBackwardFromExclusive, findClosestBlockPath, findForwardFrom, findForwardFromExclusive, findTextBlockNodeAncestor , foldl, foldlRange, foldr, foldrRange, indexedFoldl, indexedFoldr , splitBlockAtPathAndOffset, splitTextLeaf , toggleMark , Fragment(..), Node(..) ) {-| This module contains convenience functions for working with Block and Inline nodes. # Insert / Replace @docs insertAfter, insertBefore, replace, replaceWithFragment # Remove @docs removeInRange, removeNodeAndEmptyParents # Predicates @docs allRange, anyRange, isEmptyTextBlock, selectionIsBeginningOfTextBlock, selectionIsEndOfTextBlock # Transform @docs concatMap, indexedMap, joinBlocks, map # Searching @docs Iterator, last, next, nodeAt, previous, findAncestor, findBackwardFrom, findBackwardFromExclusive, findClosestBlockPath, findForwardFrom, findForwardFromExclusive, findTextBlockNodeAncestor # Folds @docs foldl, foldlRange, foldr, foldrRange, indexedFoldl, indexedFoldr # Split @docs splitBlockAtPathAndOffset, splitTextLeaf # Marks @docs toggleMark # Types These are convenience types to wrap around inline and block node and arrays @docs Fragment, Node -} import Array exposing (Array) import Array.Extra import List.Extra import RichText.Model.InlineElement as InlineElement import RichText.Model.Mark exposing (Mark, MarkOrder, ToggleAction, toggle) import RichText.Model.Node exposing ( Block , Children(..) , Inline(..) , Path , blockChildren , childNodes , inlineChildren , parent , toBlockArray , toInlineArray , withChildNodes ) import RichText.Model.Selection exposing (Selection, anchorNode, anchorOffset, isCollapsed) import RichText.Model.Text as Text exposing (Text, text, withText) {-| Node represents either a `Block` or `Inline`. It's a convenience type that wraps an argument or return value of a function that can use either block or inline, like `nodeAt` or `replace`. -} type Node = Block Block | Inline Inline {-| A `Fragment` represents an array of `Block` or `Inline` nodes. It's a convenience type used for things like insertion or deserialization. -} type Fragment = BlockFragment (Array Block) | InlineFragment (Array Inline) {-| Returns the last path and node in the block. ( lastPath, lastNode ) = last node -} last : Block -> ( Path, Node ) last node = case childNodes node of BlockChildren a -> let arr = toBlockArray a lastIndex = Array.length arr - 1 in case Array.get lastIndex arr of Nothing -> ( [], Block node ) Just b -> let ( p, n ) = last b in ( lastIndex :: p, n ) InlineChildren a -> let array = toInlineArray a lastIndex = Array.length array - 1 in case Array.get lastIndex array of Nothing -> ( [], Block node ) Just l -> ( [ lastIndex ], Inline l ) Leaf -> ( [], Block node ) {-| Type alias for a function that takes a path and a root block and returns a path and node. Useful for generalizing functions like previous and next that can iterate through a Block. -} type alias Iterator = Path -> Block -> Maybe ( Path, Node ) {-| Returns the previous path and node, if one exists, relative to the given path. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" previous [0, 1] rootNode == Just ([0, 0], Inline textNode1) -} previous : Iterator previous path node = case path of [] -> Nothing [ x ] -> let prevIndex = x - 1 in case childNodes node of BlockChildren a -> case Array.get prevIndex (toBlockArray a) of Nothing -> Just ( [], Block node ) Just b -> let ( p, n ) = last b in Just ( prevIndex :: p, n ) InlineChildren a -> case Array.get prevIndex (toInlineArray a) of Nothing -> Just ( [], Block node ) Just l -> Just ( [ prevIndex ], Inline l ) Leaf -> Just ( [], Block node ) x :: xs -> case childNodes node of BlockChildren a -> case Array.get x (toBlockArray a) of Nothing -> Nothing Just b -> case previous xs b of Nothing -> Just ( [ x ], Block b ) Just ( p, n ) -> Just ( x :: p, n ) InlineChildren a -> case Array.get (x - 1) (toInlineArray a) of Nothing -> Just ( [], Block node ) Just l -> Just ( [ x - 1 ], Inline l ) Leaf -> Nothing {-| Returns the next path and node, if one exists, relative to the given path. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" next [0, 0] rootNode == Just ([0, 1], Inline textNode2) -} next : Iterator next path node = case path of [] -> case childNodes node of BlockChildren a -> case Array.get 0 (toBlockArray a) of Nothing -> Nothing Just b -> Just ( [ 0 ], Block b ) InlineChildren a -> case Array.get 0 (toInlineArray a) of Nothing -> Nothing Just b -> Just ( [ 0 ], Inline b ) Leaf -> Nothing x :: xs -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> Nothing Just b -> case next xs b of Nothing -> case Array.get (x + 1) arr of Nothing -> Nothing Just bNext -> Just ( [ x + 1 ], Block bNext ) Just ( p, n ) -> Just ( x :: p, n ) InlineChildren a -> case Array.get (x + 1) (toInlineArray a) of Nothing -> Nothing Just b -> Just ( [ x + 1 ], Inline b ) Leaf -> Nothing {-| Starting from the given path, scans the node forward until the predicate has been met or it reaches the last node. -} findForwardFrom : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findForwardFrom = findNodeFrom next {-| Starting from but excluding the given path, scans the node forward until the predicate has been met or it reaches the last node. -} findForwardFromExclusive : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findForwardFromExclusive = findNodeFromExclusive next {-| Starting from the given path, scans the node backward until the predicate has been met or it reaches the last node. -} findBackwardFrom : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findBackwardFrom = findNodeFrom previous {-| Starting from but excluding the given path, scans the node backward until the predicate has been met or it reaches the last node. -} findBackwardFromExclusive : (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findBackwardFromExclusive = findNodeFromExclusive previous findNodeFromExclusive : Iterator -> (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findNodeFromExclusive iterator pred path node = case iterator path node of Nothing -> Nothing Just ( nextPath, _ ) -> findNodeFrom iterator pred nextPath node findNodeFrom : Iterator -> (Path -> Node -> Bool) -> Path -> Block -> Maybe ( Path, Node ) findNodeFrom iterator pred path node = case nodeAt path node of Just n -> if pred path n then Just ( path, n ) else findNodeFromExclusive iterator pred path node Nothing -> Nothing {-| Map a given function onto a block's children recursively and flatten the resulting list. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" doubleRoot : Block doubleRoot = block (Element.element doc []) (blockChildren <| Array.fromList [ doublePNode, doublePNode ] ) doublePNode : Block doublePNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode1, textNode2, textNode2 ] ) concatMap (\node -> [ node, node ]) rootNode == doubleRoot --> True -} concatMap : (Node -> List Node) -> Block -> Block concatMap func node = let newChildren = case childNodes node of Leaf -> Leaf BlockChildren a -> let c = List.concatMap (\x -> case x of Block v -> [ v ] Inline _ -> [] ) <| List.concatMap func (List.map Block (Array.toList (toBlockArray a))) in blockChildren <| Array.fromList (List.map (concatMap func) c) InlineChildren a -> inlineChildren <| Array.fromList (List.concatMap (\x -> case x of Block _ -> [] Inline v -> [ v ] ) <| List.concatMap func (List.map Inline (Array.toList (toInlineArray a))) ) in node |> withChildNodes newChildren {-| Apply a function to this node and all child nodes. setAnnotations : String -> Node -> Node setAnnotations mark node = let annotations = Set.fromList [ mark ] in case node of Block bn -> let params = Node.element bn in Block (bn |> withElement (params |> Element.withAnnotations annotations)) Inline il -> case il of Text tl -> Inline (Text (tl |> Text.withAnnotations annotations)) InlineElement l -> let params = InlineElement.element l in Inline (InlineElement (l |> InlineElement.withElement (params |> Element.withAnnotations annotations))) setDummyAnnotation : Node -> Node setDummyAnnotation node = setAnnotations dummyAnnotation node map setDummyAnnotation (Block rootNode) --> Recursively adds a dummy annotation to rootNode and all its children -} map : (Node -> Node) -> Node -> Node map func node = let applied = func node in case applied of Block blockNode -> Block <| (blockNode |> withChildNodes (case childNodes blockNode of BlockChildren a -> blockChildren <| Array.map (\v -> case map func (Block v) of Block b -> b _ -> v ) (toBlockArray a) InlineChildren a -> inlineChildren <| Array.map (\v -> case map func (Inline v) of Inline b -> b _ -> v ) (toInlineArray a) Leaf -> Leaf ) ) Inline inlineLeaf -> Inline inlineLeaf {-| Same as map but the function is also applied with the path of each element (starting at []). indexedMap (\path node -> if path == [ 0, 0 ] then text2 else node ) (Block rootNode) --> replaces the node at [0, 0] with the text2 node -} indexedMap : (Path -> Node -> Node) -> Node -> Node indexedMap = indexedMapRec [] indexedMapRec : Path -> (Path -> Node -> Node) -> Node -> Node indexedMapRec path func node = let applied = func path node in case applied of Block blockNode -> let cn = case childNodes blockNode of BlockChildren a -> blockChildren <| Array.indexedMap (\i v -> case indexedMapRec (path ++ [ i ]) func (Block v) of Block b -> b _ -> v ) (toBlockArray a) InlineChildren a -> inlineChildren <| Array.indexedMap (\i v -> case indexedMapRec (path ++ [ i ]) func (Inline v) of Inline b -> b _ -> v ) (toInlineArray a) Leaf -> Leaf in Block (blockNode |> withChildNodes cn) Inline inlineLeaf -> Inline inlineLeaf {-| Reduce a node from the bottom right (e.g. from last to first). nodeNameOrTextValue : Node -> List String -> List String nodeNameOrTextValue node list = (case node of Block bn -> Element.name (Node.element bn) Inline il -> case il of Text tl -> text tl InlineElement p -> Element.name (InlineElement.element p) ) :: list foldr nodeNameOrTextValue [] (Block rootNode) --> [ "doc", "paragraph", "sample1", "sample2" ] -} foldr : (Node -> b -> b) -> b -> Node -> b foldr func acc node = func node (case node of Block blockNode -> let children = case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldr (\childNode agg -> foldr func agg childNode ) acc children Inline _ -> acc ) {-| Reduce a node from the top left (e.g. from first to last). rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" nodeNameOrTextValue : Node -> List String -> List String nodeNameOrTextValue node list = (case node of Block bn -> Element.name (Node.element bn) Inline il -> case il of Text tl -> text tl InlineElement p -> Element.name (InlineElement.element p) ) :: list foldl nodeNameOrTextValue [] (Block rootNode) --> [ "sample2", "sample1", "paragraph", "doc" ] -} foldl : (Node -> b -> b) -> b -> Node -> b foldl func acc node = case node of Block blockNode -> let children = case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldl (\childNode agg -> foldl func agg childNode ) (func node acc) children Inline _ -> func node acc {-| Same as `foldr` but the reduce function also has the current node's path. pathList : Path -> Node -> List Path -> List Path pathList path _ list = path :: list (indexedFoldr pathList [] (Block rootNode)) == [ [], [ 0 ], [ 0, 0 ], [ 0, 1 ] ] -} indexedFoldr : (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldr = indexedFoldrRec [] indexedFoldrRec : Path -> (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldrRec path func acc node = func path node (case node of Block blockNode -> let children = Array.indexedMap Tuple.pair <| case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldr (\( index, childNode ) agg -> indexedFoldrRec (path ++ [ index ]) func agg childNode ) acc children Inline _ -> acc ) {-| Same as `foldl` but the reduce function also has the current node's path. pathList : Path -> Node -> List Path -> List Path pathList path _ list = path :: list (indexedFoldl pathList [] (Block rootNode)) == [ [ 0, 1 ], [ 0, 0 ], [ 0 ], [] ] -} indexedFoldl : (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldl = indexedFoldlRec [] indexedFoldlRec : Path -> (Path -> Node -> b -> b) -> b -> Node -> b indexedFoldlRec path func acc node = case node of Block blockNode -> let children = Array.indexedMap Tuple.pair <| case childNodes blockNode of Leaf -> Array.empty InlineChildren a -> Array.map Inline (toInlineArray a) BlockChildren a -> Array.map Block (toBlockArray a) in Array.foldl (\( index, childNode ) agg -> indexedFoldlRec (path ++ [ index ]) func agg childNode ) (func path node acc) children Inline _ -> func path node acc {-| Same as `foldl` but only applied the nodes between the given paths, inclusive. foldlRange [] [ 1 ] nodeNameOrTextValue [] (Block rootNode) --> [ "sample2", "sample1", "paragraph" ] -} foldlRange : Path -> Path -> (Node -> b -> b) -> b -> Block -> b foldlRange start end func acc root = case nodeAt start root of Nothing -> acc Just node -> foldlRangeRec start end func acc root node foldlRangeRec : Path -> Path -> (Node -> b -> b) -> b -> Block -> Node -> b foldlRangeRec start end func acc root node = if start > end then acc else let result = func node acc in case next start root of Nothing -> result Just ( p, n ) -> foldlRangeRec p end func result root n {-| Same as `foldr` but only applied the nodes between the given paths, inclusive. foldlRange [ 0 ] [ 0, 1 ] nodeNameOrTextValue [] (Block rootNode) --> [ "paragraph", "sample1", "sample2" ] -} foldrRange : Path -> Path -> (Node -> b -> b) -> b -> Block -> b foldrRange start end func acc root = case nodeAt end root of Nothing -> acc Just node -> foldrRangeRec start end func acc root node foldrRangeRec : Path -> Path -> (Node -> b -> b) -> b -> Block -> Node -> b foldrRangeRec start end func acc root node = if start > end then acc else let result = func node acc in case previous end root of Nothing -> result Just ( p, n ) -> foldrRangeRec start p func result root n {-| Returns a Ok Block that replaces the node at the node path with the given fragment. If it is unable to replace it do to an invalid path or the wrong type of node, a Err string describing the error is returned. -- replaces the node at [0, 0] with the given inline fragment replaceWithFragment [ 0, 0 ] (InlineFragment <| Array.fromList [ textNode ]) rootNode -} replaceWithFragment : Path -> Fragment -> Block -> Result String Block replaceWithFragment path fragment root = case path of [] -> Err "Invalid path" [ x ] -> case childNodes root of BlockChildren a -> case fragment of BlockFragment blocks -> let arr = toBlockArray a in Ok <| (root |> withChildNodes (blockChildren (Array.append (Array.append (Array.Extra.sliceUntil x arr) blocks ) (Array.Extra.sliceFrom (x + 1) arr) ) ) ) InlineFragment _ -> Err "I cannot replace a block fragment with an inline leaf fragment" InlineChildren a -> case fragment of InlineFragment leaves -> let arr = toInlineArray a in Ok <| (root |> withChildNodes (inlineChildren (Array.append (Array.append (Array.Extra.sliceUntil x arr) leaves ) (Array.Extra.sliceFrom (x + 1) arr) ) ) ) BlockFragment _ -> Err "I cannot replace an inline fragment with a block fragment" Leaf -> Err "Not implemented" x :: xs -> case childNodes root of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> Err "I received an invalid path, I can't find a block node at the given index." Just node -> case replaceWithFragment xs fragment node of Ok n -> Ok <| (root |> withChildNodes (blockChildren (Array.set x n arr))) Err v -> Err v InlineChildren _ -> Err "I received an invalid path, I reached an inline leaf array but I still have more path left." Leaf -> Err "I received an invalid path, I am on a leaf node, but I still have more path left." {-| Replaces the node at the path with the given editor node. -- replaces the node at [0, 0] with the inline text replace [ 0, 0 ] (Inline textNode) rootNode -} replace : Path -> Node -> Block -> Result String Block replace path node root = case path of [] -> case node of Block n -> Ok n Inline _ -> Err "I cannot replace a block node with an inline leaf." _ -> let fragment = case node of Block n -> BlockFragment <| Array.fromList [ n ] Inline n -> InlineFragment <| Array.fromList [ n ] in replaceWithFragment path fragment root {-| Returns Just the parent of the given path if the path refers to an inline node, otherwise inline content, otherwisereturn Nothing. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" findTextBlockNodeAncestor [ 0, 0 ] rootNode --> Just ( [ 0 ], pNode ) findTextBlockNodeAncestor [ 0 ] rootNode --> Nothing == -} findTextBlockNodeAncestor : Path -> Block -> Maybe ( Path, Block ) findTextBlockNodeAncestor = findAncestor (\n -> case childNodes n of InlineChildren _ -> True _ -> False ) {-| Find ancestor from path finds the closest ancestor from the given NodePath that matches the predicate. -- Finds the closest list item ancestor if it exists findAncestor (\n -> Element.name (Node.element n) == "list_item") -} findAncestor : (Block -> Bool) -> Path -> Block -> Maybe ( Path, Block ) findAncestor pred path node = case path of [] -> Nothing x :: xs -> case childNodes node of BlockChildren a -> case Array.get x (toBlockArray a) of Nothing -> Nothing Just childNode -> case findAncestor pred xs childNode of Nothing -> if pred node then Just ( [], node ) else Nothing Just ( p, result ) -> Just ( x :: p, result ) _ -> if pred node then Just ( [], node ) else Nothing {-| Returns the node at the specified path if it exists. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) nodeAt [0] rootNode == Just (Block pNode) -} nodeAt : Path -> Block -> Maybe Node nodeAt path node = case path of [] -> Just <| Block node x :: xs -> case childNodes node of BlockChildren arr -> case Array.get x (toBlockArray arr) of Nothing -> Nothing Just childNode -> nodeAt xs childNode InlineChildren a -> case Array.get x (toInlineArray a) of Nothing -> Nothing Just childLeafNode -> if List.isEmpty xs then Just <| Inline childLeafNode else Nothing Leaf -> Nothing {-| This method removes all the nodes inclusive to both the start and end path. Note that an ancestor is not removed if the start path or end path is a child node. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) emptyRoot : Block emptyRoot = block (Element.element doc []) (blockChildren <| Array.empty) removeInRange [0] [0] root == emptyRoot --> True -} removeInRange : Path -> Path -> Block -> Block removeInRange start end node = let startIndex = Maybe.withDefault 0 (List.head start) startRest = Maybe.withDefault [] (List.tail start) endIndex = Maybe.withDefault (case childNodes node of BlockChildren a -> Array.length (toBlockArray a) InlineChildren a -> Array.length (toInlineArray a) Leaf -> 0 ) (List.head end) endRest = Maybe.withDefault [] (List.tail end) in if startIndex > endIndex then node else if startIndex == endIndex then case childNodes node of BlockChildren a -> let array = toBlockArray a in if List.isEmpty startRest && List.isEmpty endRest then node |> withChildNodes (blockChildren <| Array.Extra.removeAt startIndex array) else case Array.get startIndex array of Nothing -> node Just b -> node |> withChildNodes (blockChildren <| Array.set startIndex (removeInRange startRest endRest b) array) InlineChildren a -> if List.isEmpty startRest && List.isEmpty endRest then node |> withChildNodes (inlineChildren <| Array.Extra.removeAt startIndex (toInlineArray a)) else node Leaf -> node else case childNodes node of BlockChildren a -> let arr = toBlockArray a left = Array.Extra.sliceUntil startIndex arr right = Array.Extra.sliceFrom (endIndex + 1) arr leftRest = if List.isEmpty startRest then Array.empty else case Array.get startIndex arr of Nothing -> Array.empty Just b -> Array.fromList [ removeInRange startRest endRest b ] rightRest = if List.isEmpty endRest then Array.empty else case Array.get endIndex arr of Nothing -> Array.empty Just b -> Array.fromList [ removeInRange startRest endRest b ] in node |> withChildNodes (blockChildren <| List.foldr Array.append Array.empty [ left, leftRest, rightRest, right ]) InlineChildren a -> let arr = toInlineArray a left = Array.Extra.sliceUntil (if List.isEmpty startRest then startIndex else startIndex + 1 ) arr right = Array.Extra.sliceFrom (if List.isEmpty endRest then endIndex + 1 else endIndex ) arr in node |> withChildNodes (inlineChildren <| Array.append left right) Leaf -> node {-| Removes the node at the given path, and recursively removes parent blocks that have no remaining child nodes, excluding the root. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ removedPHtmlNode ] ) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode ] ) textNode : Inline textNode = plainText "sample1" removedRoot : Block removedRoot = block (Element.element doc []) (blockChildren Array.empty) removeNodeAndEmptyParents [0, 0] root == removedRoot --> True -} removeNodeAndEmptyParents : Path -> Block -> Block removeNodeAndEmptyParents path node = case path of [] -> node [ x ] -> case childNodes node of BlockChildren a -> node |> withChildNodes (blockChildren <| Array.Extra.removeAt x (toBlockArray a)) InlineChildren a -> node |> withChildNodes (inlineChildren <| Array.Extra.removeAt x (toInlineArray a)) Leaf -> node x :: xs -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> node Just n -> let newNode = removeNodeAndEmptyParents xs n in case childNodes newNode of BlockChildren newNodeChildren -> let newChildNodes = toBlockArray newNodeChildren in if Array.isEmpty newChildNodes then node |> withChildNodes (blockChildren <| Array.Extra.removeAt x arr) else node |> withChildNodes (blockChildren <| Array.set x newNode arr) InlineChildren newNodeChildren -> let newChildNodes = toInlineArray newNodeChildren in if Array.isEmpty newChildNodes then node |> withChildNodes (blockChildren <| Array.Extra.removeAt x arr) else node |> withChildNodes (blockChildren <| Array.set x newNode arr) _ -> node |> withChildNodes (blockChildren <| Array.set x newNode arr) InlineChildren _ -> node Leaf -> node {-| Splits a text leaf into two based on the given offset. splitTextLeaf 1 (emptyText <| withText "test") --> (Text "t", Text "est") -} splitTextLeaf : Int -> Text -> ( Text, Text ) splitTextLeaf offset leaf = let leafText = text leaf in ( leaf |> withText (String.left offset leafText), leaf |> withText (String.dropLeft offset leafText) ) {-| Splits a block at the given path and offset and returns Just the split nodes. If the path is invalid or the node cannot be split, Nothing is returned. textNode1 : Inline textNode1 = plainText "samplePI:NAME:<NAME>END_PI" nodeWithTextLeafToSplit : Block nodeWithTextLeafToSplit = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1 ] ) nodeBeforeTextLeafSplit : Block nodeBeforeTextLeafSplit = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ plainText "PI:NAME:<NAME>END_PI" ] ) nodeAfterTextLeafSplit : Block nodeAfterTextLeafSplit = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ plainText "ple1" ] ) Just (nodeBeforeTextLeafSplit, nodeAfterTextLeafSplit) == splitBlockAtPathAndOffset [ 0 ] 3 nodeWithTextLeafToSplit -} splitBlockAtPathAndOffset : Path -> Int -> Block -> Maybe ( Block, Block ) splitBlockAtPathAndOffset path offset node = case path of [] -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in Just ( node |> withChildNodes (blockChildren (Array.Extra.sliceUntil offset arr)) , node |> withChildNodes (blockChildren (Array.Extra.sliceFrom offset arr)) ) InlineChildren a -> let arr = toInlineArray a in Just ( node |> withChildNodes (inlineChildren (Array.Extra.sliceUntil offset arr)) , node |> withChildNodes (inlineChildren (Array.Extra.sliceFrom offset arr)) ) Leaf -> Just ( node, node ) x :: xs -> case childNodes node of BlockChildren a -> let arr = toBlockArray a in case Array.get x arr of Nothing -> Nothing Just n -> case splitBlockAtPathAndOffset xs offset n of Nothing -> Nothing Just ( before, after ) -> Just ( node |> withChildNodes (blockChildren (Array.append (Array.Extra.sliceUntil x arr) (Array.fromList [ before ]))) , node |> withChildNodes (blockChildren (Array.append (Array.fromList [ after ]) (Array.Extra.sliceFrom (x + 1) arr))) ) InlineChildren a -> let arr = toInlineArray a in case Array.get x arr of Nothing -> Nothing Just n -> case n of Text tl -> let ( before, after ) = splitTextLeaf offset tl in Just ( node |> withChildNodes (inlineChildren (Array.set x (Text before) (Array.Extra.sliceUntil (x + 1) arr))) , node |> withChildNodes (inlineChildren (Array.set 0 (Text after) (Array.Extra.sliceFrom x arr))) ) InlineElement _ -> Just ( node |> withChildNodes (inlineChildren (Array.Extra.sliceUntil x arr)) , node |> withChildNodes (inlineChildren (Array.Extra.sliceFrom x arr)) ) Leaf -> Nothing {-| Determine if all elements in range satisfy some test. -- Query to determine if all the elements in range are selectable allRange isSelectable [ 0, 0 ] [ 0, 2 ] root -} allRange : (Node -> Bool) -> Path -> Path -> Block -> Bool allRange pred start end root = if start > end then True else case nodeAt start root of Nothing -> -- In the case of an invalid path, just return true. True Just node -> if pred node then case next start root of Nothing -> True Just ( nextPath, _ ) -> allRange pred nextPath end root else False {-| Determine if any elements in range satisfy some test. -- Query to determine if any elements in range are selectable allRange isSelectable [ 0, 0 ] [ 0, 2 ] root -} anyRange : (Node -> Bool) -> Path -> Path -> Block -> Bool anyRange pred start end root = not <| allRange (\x -> not <| pred x) start end root {-| If the node specified by the path is an inline node, returns the parent. If the node at the path is a block, then returns the same path. Otherwise if the path is invalid, returns the root path. rootNode : Block rootNode = block (Element.element doc []) (blockChildren <| Array.fromList [ pNode ]) pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) textNode1 : Inline textNode1 = plainText "sample1" textNode2 : Inline textNode2 = plainText "sample2" findClosestBlockPath [0, 0] rootNode --> [0] findClosestBlockPath [0] rootNode --> [0] -} findClosestBlockPath : Path -> Block -> Path findClosestBlockPath path node = case nodeAt path node of Nothing -> [] Just n -> case n of Block _ -> path Inline _ -> parent path {-| If the two blocks have the same type of children, returns the joined block. Otherwise, if the blocks have different children or one or more is a leaf node, then Nothing is return. pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2 ] ) pNodeReverse : Block pNodeReverse = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode2, textNode1 ] ) pNodeExpectedJoin : Block pNodeExpectedJoin = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ textNode1, textNode2, textNode2, textNode1 ] ) pNodeExpectedJoin == joinBlocks pNode pNodeReverse -} joinBlocks : Block -> Block -> Maybe Block joinBlocks b1 b2 = case childNodes b1 of BlockChildren a1 -> case childNodes b2 of BlockChildren a2 -> Just <| (b1 |> withChildNodes (blockChildren (Array.append (toBlockArray a1) (toBlockArray a2)))) _ -> Nothing InlineChildren a1 -> case childNodes b2 of InlineChildren a2 -> Just <| (b1 |> withChildNodes (inlineChildren (Array.append (toInlineArray a1) (toInlineArray a2)))) _ -> Nothing Leaf -> Nothing {-| Inserts the fragments after the node at the given path and returns the result. Returns an error if the path is invalid or the fragment cannot be inserted. insertAfter [ 0, 0 ] fragment root --> Inserts the fragment after the node at path [0, 0] -} insertAfter : Path -> Fragment -> Block -> Result String Block insertAfter path fragment root = case nodeAt path root of Nothing -> Err "There is no node at this path" Just node -> case node of Inline il -> case fragment of InlineFragment a -> let newFragment = InlineFragment <| Array.fromList (il :: Array.toList a) in replaceWithFragment path newFragment root BlockFragment _ -> Err "I cannot insert a block node fragment into an inline leaf fragment" Block bn -> case fragment of BlockFragment a -> let newFragment = BlockFragment <| Array.fromList (bn :: Array.toList a) in replaceWithFragment path newFragment root InlineFragment _ -> Err "I cannot insert an inline leaf fragment fragment into a block node fragment" {-| Inserts the fragments before the node at the given path and returns the result. Returns an error if the path is invalid or the fragment cannot be inserted. insertBefore [ 0, 0 ] fragment root --> Inserts the fragment before the node at path [0, 0] -} insertBefore : Path -> Fragment -> Block -> Result String Block insertBefore path fragment root = case nodeAt path root of Nothing -> Err "There is no node at this path" Just node -> case node of Inline il -> case fragment of InlineFragment a -> let newFragment = InlineFragment <| Array.push il a in replaceWithFragment path newFragment root BlockFragment _ -> Err "I cannot insert a block node fragment into an inline leaf fragment" Block bn -> case fragment of BlockFragment a -> let newFragment = BlockFragment <| Array.push bn a in replaceWithFragment path newFragment root InlineFragment _ -> Err "I cannot insert an inline leaf fragment fragment into a block node fragment" {-| Runs the toggle action on the node for the given mark. toggleMark Add markOrder bold node --> Adds bold to the given node -} toggleMark : ToggleAction -> MarkOrder -> Mark -> Node -> Node toggleMark action markOrder mark node = case node of Block _ -> node Inline il -> Inline <| case il of Text leaf -> Text <| (leaf |> Text.withMarks (toggle action markOrder mark (Text.marks leaf)) ) InlineElement leaf -> InlineElement <| (leaf |> InlineElement.withMarks (toggle action markOrder mark (InlineElement.marks leaf)) ) {-| True if this block has inline content with no children or a single empty text node, false otherwise pNode : Block pNode = block (Element.element paragraph []) (inlineChildren <| Array.fromList [ emptyText ] ) isEmptyTextBlock pNode --> True -} isEmptyTextBlock : Node -> Bool isEmptyTextBlock node = case node of Block bn -> case childNodes bn of InlineChildren a -> let array = toInlineArray a in case Array.get 0 array of Nothing -> Array.isEmpty array Just n -> Array.length array == 1 && (case n of Text t -> String.isEmpty (Text.text t) _ -> False ) _ -> False Inline _ -> False {-| True if the selection is collapsed at the beginning of a text block, false otherwise. -- selectionIsBeginningOfTextBlock is used for things like lift and join backward if selectionIsBeginningOfTextBlock selection (State.root editorState) then -- Do join backward logic else -- Do something else -} selectionIsBeginningOfTextBlock : Selection -> Block -> Bool selectionIsBeginningOfTextBlock selection root = if not <| isCollapsed selection then False else case findTextBlockNodeAncestor (anchorNode selection) root of Nothing -> False Just ( _, n ) -> case childNodes n of InlineChildren a -> case List.Extra.last (anchorNode selection) of Nothing -> False Just i -> if i /= 0 || Array.isEmpty (toInlineArray a) then False else anchorOffset selection == 0 _ -> False {-| True if the selection is collapsed at the end of a text block, false otherwise. -- selectionIsEndOfTextBlock is used for things like join forward if selectionIsEndOfTextBlock selection (State.root editorState) then -- Do join forward logic else -- Do something else -} selectionIsEndOfTextBlock : Selection -> Block -> Bool selectionIsEndOfTextBlock selection root = if not <| isCollapsed selection then False else case findTextBlockNodeAncestor (anchorNode selection) root of Nothing -> False Just ( _, n ) -> case childNodes n of InlineChildren a -> case List.Extra.last (anchorNode selection) of Nothing -> False Just i -> if i /= Array.length (toInlineArray a) - 1 then False else case Array.get i (toInlineArray a) of Nothing -> False Just leaf -> case leaf of Text tl -> String.length (Text.text tl) == anchorOffset selection InlineElement _ -> True _ -> False
elm
[ { "context": " { url = \"http://package.elm-lang.org/packages/mdgriffith/stylish-elephants/latest\"\n , l", "end": 1198, "score": 0.9989671707, "start": 1188, "tag": "USERNAME", "value": "mdgriffith" }, { "context": " { url = \"http://package.elm-lang.org/packages/mdgriffith/stylish-elephants/latest\"\n , label = E", "end": 1906, "score": 0.999237299, "start": 1896, "tag": "USERNAME", "value": "mdgriffith" }, { "context": "kOrange ]\n { url = \"https://github.com/jbrgfx\"\n , label = Element.text \"jbrgfx's git", "end": 2226, "score": 0.9995501637, "start": 2220, "tag": "USERNAME", "value": "jbrgfx" }, { "context": "b.com/jbrgfx\"\n , label = Element.text \"jbrgfx's github repos\"\n }\n ]\n\n\nsidebar", "end": 2270, "score": 0.9919931293, "start": 2264, "tag": "USERNAME", "value": "jbrgfx" }, { "context": " []\n { url = \"https://github.com/billperegoy/elm-page-layout\"\n , label = Element.te", "end": 3343, "score": 0.9997116923, "start": 3332, "tag": "USERNAME", "value": "billperegoy" }, { "context": " []\n { url = \"https://github.com/lucamug/elm-spa-boilerplate\"\n , label = Elemen", "end": 3832, "score": 0.9997009635, "start": 3825, "tag": "USERNAME", "value": "lucamug" }, { "context": "]\n { url = \"https://github.com/billperegoy/elm-page-layout\"\n , label = El", "end": 5115, "score": 0.9995309711, "start": 5104, "tag": "USERNAME", "value": "billperegoy" }, { "context": "]\n { url = \"https://github.com/lucamug/elm-spa-boilerplate\"\n , label ", "end": 5566, "score": 0.9991148114, "start": 5559, "tag": "USERNAME", "value": "lucamug" }, { "context": "sons : List Person\npersons =\n [ { firstName = \"David\"\n , middleName = \"Robert\"\n , lastName =", "end": 6380, "score": 0.9998545647, "start": 6375, "tag": "NAME", "value": "David" }, { "context": " [ { firstName = \"David\"\n , middleName = \"Robert\"\n , lastName = \"Bowie\"\n }\n , { first", "end": 6410, "score": 0.9997857809, "start": 6404, "tag": "NAME", "value": "Robert" }, { "context": " , middleName = \"Robert\"\n , lastName = \"Bowie\"\n }\n , { firstName = \"Florence\"\n , m", "end": 6437, "score": 0.9976043105, "start": 6432, "tag": "NAME", "value": "Bowie" }, { "context": ", lastName = \"Bowie\"\n }\n , { firstName = \"Florence\"\n , middleName = \"Leontine Mary\"\n , las", "end": 6476, "score": 0.9998100996, "start": 6468, "tag": "NAME", "value": "Florence" }, { "context": " , { firstName = \"Florence\"\n , middleName = \"Leontine Mary\"\n , lastName = \"Welch\"\n }\n ]\n\n\nmainC", "end": 6513, "score": 0.9997660518, "start": 6500, "tag": "NAME", "value": "Leontine Mary" }, { "context": " middleName = \"Leontine Mary\"\n , lastName = \"Welch\"\n }\n ]\n\n\nmainContentArea model =\n {- C", "end": 6540, "score": 0.998690784, "start": 6535, "tag": "NAME", "value": "Welch" }, { "context": ": attrA) <|\n Element.text \"First Name\"\n , view =\n \\inde", "end": 6855, "score": 0.8310664892, "start": 6845, "tag": "NAME", "value": "First Name" }, { "context": ": attrA) <|\n Element.text \"Middle Name\"\n , view =\n \\inde", "end": 7179, "score": 0.6515083313, "start": 7168, "tag": "NAME", "value": "Middle Name" }, { "context": ": attrA) <|\n Element.text \"Last Name\"\n , view =\n \\inde", "end": 7502, "score": 0.8743078709, "start": 7493, "tag": "NAME", "value": "Last Name" }, { "context": "e\n Element.width fill :: attrB\n\n\n\n{- Credit lucamug for the code above (shared via elm-lang-slack ) -", "end": 8560, "score": 0.9989466071, "start": 8553, "tag": "USERNAME", "value": "lucamug" }, { "context": "ment.text \"This refactoring of https://github.com/billperegoy/elm-page-layout is an experiment in converting a ", "end": 8780, "score": 0.9981328845, "start": 8769, "tag": "USERNAME", "value": "billperegoy" }, { "context": ".2 (the next version of style-elements). Thanks to lucamug for adding an example of alterate row colors usin", "end": 8962, "score": 0.9996755123, "start": 8955, "tag": "USERNAME", "value": "lucamug" }, { "context": "ng indexedTable in his source: https://github.com/lucamug/elm-spa-boilerplate/blob/master/src/Pages/Example", "end": 9068, "score": 0.9997200966, "start": 9061, "tag": "USERNAME", "value": "lucamug" }, { "context": "\ngutter =\n 20\n\n\n\n{- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -}\n\n\nbor", "end": 9193, "score": 0.9995632172, "start": 9189, "tag": "USERNAME", "value": "opsb" }, { "context": " 0, bottom = n }\n\n\n\n{- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -}\n\n\npad", "end": 9444, "score": 0.9995042682, "start": 9440, "tag": "USERNAME", "value": "opsb" }, { "context": "= 0, right = 0 }\n\n\n\n{- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -}\n\n\npad", "end": 9684, "score": 0.9995331764, "start": 9680, "tag": "USERNAME", "value": "opsb" }, { "context": "= 0, right = 0 }\n\n\n\n{- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -}\n\n\npad", "end": 9847, "score": 0.9995319843, "start": 9843, "tag": "USERNAME", "value": "opsb" } ]
src/View.elm
jbrgfx/responsive-stylish-elephants
1
module View exposing (view) import Color exposing (..) import Element exposing (..) import Element.Background as Background exposing (..) import Element.Border as Border exposing (..) import Element.Font as Font exposing (..) import Html exposing (..) import Model exposing (..) blockAttributes screenSize = case screenSize of Phone -> [ Element.width (px 800) ] Tablet -> [ Element.width (px 1000) ] Desktop -> [ Element.width (px 1200) ] wrapper : Model -> Element Msg wrapper model = Element.column [] [ pageArea model ] pageArea : Model -> Element Msg pageArea model = if model.screenSize == Phone then Element.column [ padding 10 , spacing 10 ] [ phoneLinkOne , phoneLinkTwo , phoneLinkThree , contentArea model , aboutExperiment , footerArea , row [ Font.size 14 ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "http://package.elm-lang.org/packages/mdgriffith/stylish-elephants/latest" , label = Element.text "stylish-elephants latest: package docs" } ] ] else Element.column [ Element.alignTop , paddingRight gutter , spaceEvenly ] [ headerArea , contentArea model , aboutExperiment , footerArea ] headerArea : Element Msg headerArea = row [ Element.alignLeft ] [ newTabLink [ Element.alignLeft , Font.mouseOverColor Color.darkOrange ] { url = "http://package.elm-lang.org/packages/mdgriffith/stylish-elephants/latest" , label = Element.text "stylish-elephants latest: package docs" } ] footerArea : Element msg footerArea = row [ Font.size 14 ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://github.com/jbrgfx" , label = Element.text "jbrgfx's github repos" } ] sidebarTitle : Element msg sidebarTitle = row [ padding 8 ] [ Element.text "Sidebar Links" ] phoneLinkOne = row [ spacing 20 , Element.height (px 60) , Background.color darkBlue , Font.size 20 , Font.color Color.white , Background.mouseOverColor Color.lightOrange , Font.mouseOverColor Color.darkBlue ] [ newTabLink [] { url = "https://becoming-functional.com/responsive-design-with-elm-style-elements-9d0eca8eb9ed" , label = Element.text "Test-drive Article" } ] phoneLinkTwo = row [ spacing 20 , Element.height (px 60) , Element.width fill , Background.color darkBlue , Font.size 20 , Font.color Color.white , Background.mouseOverColor Color.lightOrange , Font.mouseOverColor Color.darkBlue ] [ newTabLink [] { url = "https://github.com/billperegoy/elm-page-layout" , label = Element.text "Elm-page-layout" } ] phoneLinkThree = row [ spacing 20 , Element.height (px 60) , Element.width fill , Background.color darkBlue , Font.size 20 , Font.color Color.white , Background.mouseOverColor Color.lightOrange , Font.mouseOverColor Color.darkBlue ] [ newTabLink [] { url = "https://github.com/lucamug/elm-spa-boilerplate" , label = Element.text "Elm-spa-boilerplate" } ] sidebarArea : Model -> Element Msg sidebarArea model = if model.screenSize == Phone then Element.empty else column [ Element.alignLeft , Element.width (px 180) , Element.height (px 110) , Font.size 16 , paddingRight 10 ] [ sidebarTitle , row [ Element.width (px 110) , Element.alignRight , Font.underline , Font.color Color.blue ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://becoming-functional.com/responsive-design-with-elm-style-elements-9d0eca8eb9ed" , label = Element.text "Test-drive Article" } ] , row [ Element.width (px 110) , Element.alignRight , Font.underline , Font.color Color.blue ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://github.com/billperegoy/elm-page-layout" , label = Element.text "elm-page-layout" } ] , row [ Element.width (px 110) , Element.alignRight , Font.underline , Font.color Color.blue ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://github.com/lucamug/elm-spa-boilerplate" , label = Element.text "elm-spa-boilerplate" } ] ] contentArea : Model -> Element Msg contentArea model = row [ padding gutter ] [ sidebarArea model , column [ Element.padding 8 , Element.alignLeft , Element.width (px 450) ] [ mainContentArea model ] ] bodyWidth screenSize = if screenSize == Phone then Element.width (px 600) else if screenSize == Tablet then Element.width (px 800) else Element.width (px 1000) type alias Person = { firstName : String , middleName : String , lastName : String } persons : List Person persons = [ { firstName = "David" , middleName = "Robert" , lastName = "Bowie" } , { firstName = "Florence" , middleName = "Leontine Mary" , lastName = "Welch" } ] mainContentArea model = {- Credit lucamug for the code below (shared via elm-lang-slack ) -} indexedTable attrCont { data = persons , columns = [ { header = el (Element.width fill :: attrA) <| Element.text "First Name" , view = \index persons -> el (alternateCellAttr index) <| Element.text persons.firstName } , { header = el (Element.width fill :: attrA) <| Element.text "Middle Name" , view = \index persons -> el (alternateCellAttr index) <| Element.text persons.middleName } , { header = el (Element.width fill :: attrA) <| Element.text "Last Name" , view = \index persons -> el (alternateCellAttr index) <| Element.text persons.lastName } ] } attrBackground : List (Element.Attribute msg) attrBackground = [ Background.color darkCharcoal , Font.color white ] attrCont : List (Element.Attribute msg) attrCont = [ padding 1 , spacing 1 ] ++ attrBackground attrA : List (Element.Attribute msg) attrA = [ Background.color <| rgb 0xD1 0xE5 0xFA , Font.color black , padding 1 ] attrB : List (Element.Attribute msg) attrB = [ Background.color white , Font.color black , padding 1 ] attrC : List (Element.Attribute msg) attrC = [ Background.color darkBlue , Font.color white , padding 1 ] alternateCellAttr : Int -> List (Element.Attribute msg) alternateCellAttr index = if index % 2 == 0 then Element.width fill :: attrC else Element.width fill :: attrB {- Credit lucamug for the code above (shared via elm-lang-slack ) -} aboutExperiment = paragraph [ paddingBottom 20 , Font.size 14 ] [ Element.text "This refactoring of https://github.com/billperegoy/elm-page-layout is an experiment in converting a style-elements 4.2.1. project into one that uses the stylish-elephants 6.0.2 (the next version of style-elements). Thanks to lucamug for adding an example of alterate row colors using indexedTable in his source: https://github.com/lucamug/elm-spa-boilerplate/blob/master/src/Pages/Examples.elm#L314,L319." ] gutter = 20 {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} borderRight n = Border.widthEach { right = n, left = 0, top = 0, bottom = 0 } borderBottom n = Border.widthEach { right = 0, left = 0, top = 0, bottom = n } {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} paddingRight n = paddingEach { right = n, left = 0, top = 0, bottom = 0 } paddingTop n = paddingEach { bottom = 0, top = n, left = 0, right = 0 } {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} paddingBottom n = paddingEach { bottom = n, top = 0, left = 0, right = 0 } {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} paddingLeft n = paddingEach { right = 0, left = n, top = 0, bottom = 0 } view : Model -> Html Msg view model = Element.layout [ Background.color white , padding gutter , spacing gutter ] <| wrapper model
45937
module View exposing (view) import Color exposing (..) import Element exposing (..) import Element.Background as Background exposing (..) import Element.Border as Border exposing (..) import Element.Font as Font exposing (..) import Html exposing (..) import Model exposing (..) blockAttributes screenSize = case screenSize of Phone -> [ Element.width (px 800) ] Tablet -> [ Element.width (px 1000) ] Desktop -> [ Element.width (px 1200) ] wrapper : Model -> Element Msg wrapper model = Element.column [] [ pageArea model ] pageArea : Model -> Element Msg pageArea model = if model.screenSize == Phone then Element.column [ padding 10 , spacing 10 ] [ phoneLinkOne , phoneLinkTwo , phoneLinkThree , contentArea model , aboutExperiment , footerArea , row [ Font.size 14 ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "http://package.elm-lang.org/packages/mdgriffith/stylish-elephants/latest" , label = Element.text "stylish-elephants latest: package docs" } ] ] else Element.column [ Element.alignTop , paddingRight gutter , spaceEvenly ] [ headerArea , contentArea model , aboutExperiment , footerArea ] headerArea : Element Msg headerArea = row [ Element.alignLeft ] [ newTabLink [ Element.alignLeft , Font.mouseOverColor Color.darkOrange ] { url = "http://package.elm-lang.org/packages/mdgriffith/stylish-elephants/latest" , label = Element.text "stylish-elephants latest: package docs" } ] footerArea : Element msg footerArea = row [ Font.size 14 ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://github.com/jbrgfx" , label = Element.text "jbrgfx's github repos" } ] sidebarTitle : Element msg sidebarTitle = row [ padding 8 ] [ Element.text "Sidebar Links" ] phoneLinkOne = row [ spacing 20 , Element.height (px 60) , Background.color darkBlue , Font.size 20 , Font.color Color.white , Background.mouseOverColor Color.lightOrange , Font.mouseOverColor Color.darkBlue ] [ newTabLink [] { url = "https://becoming-functional.com/responsive-design-with-elm-style-elements-9d0eca8eb9ed" , label = Element.text "Test-drive Article" } ] phoneLinkTwo = row [ spacing 20 , Element.height (px 60) , Element.width fill , Background.color darkBlue , Font.size 20 , Font.color Color.white , Background.mouseOverColor Color.lightOrange , Font.mouseOverColor Color.darkBlue ] [ newTabLink [] { url = "https://github.com/billperegoy/elm-page-layout" , label = Element.text "Elm-page-layout" } ] phoneLinkThree = row [ spacing 20 , Element.height (px 60) , Element.width fill , Background.color darkBlue , Font.size 20 , Font.color Color.white , Background.mouseOverColor Color.lightOrange , Font.mouseOverColor Color.darkBlue ] [ newTabLink [] { url = "https://github.com/lucamug/elm-spa-boilerplate" , label = Element.text "Elm-spa-boilerplate" } ] sidebarArea : Model -> Element Msg sidebarArea model = if model.screenSize == Phone then Element.empty else column [ Element.alignLeft , Element.width (px 180) , Element.height (px 110) , Font.size 16 , paddingRight 10 ] [ sidebarTitle , row [ Element.width (px 110) , Element.alignRight , Font.underline , Font.color Color.blue ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://becoming-functional.com/responsive-design-with-elm-style-elements-9d0eca8eb9ed" , label = Element.text "Test-drive Article" } ] , row [ Element.width (px 110) , Element.alignRight , Font.underline , Font.color Color.blue ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://github.com/billperegoy/elm-page-layout" , label = Element.text "elm-page-layout" } ] , row [ Element.width (px 110) , Element.alignRight , Font.underline , Font.color Color.blue ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://github.com/lucamug/elm-spa-boilerplate" , label = Element.text "elm-spa-boilerplate" } ] ] contentArea : Model -> Element Msg contentArea model = row [ padding gutter ] [ sidebarArea model , column [ Element.padding 8 , Element.alignLeft , Element.width (px 450) ] [ mainContentArea model ] ] bodyWidth screenSize = if screenSize == Phone then Element.width (px 600) else if screenSize == Tablet then Element.width (px 800) else Element.width (px 1000) type alias Person = { firstName : String , middleName : String , lastName : String } persons : List Person persons = [ { firstName = "<NAME>" , middleName = "<NAME>" , lastName = "<NAME>" } , { firstName = "<NAME>" , middleName = "<NAME>" , lastName = "<NAME>" } ] mainContentArea model = {- Credit lucamug for the code below (shared via elm-lang-slack ) -} indexedTable attrCont { data = persons , columns = [ { header = el (Element.width fill :: attrA) <| Element.text "<NAME>" , view = \index persons -> el (alternateCellAttr index) <| Element.text persons.firstName } , { header = el (Element.width fill :: attrA) <| Element.text "<NAME>" , view = \index persons -> el (alternateCellAttr index) <| Element.text persons.middleName } , { header = el (Element.width fill :: attrA) <| Element.text "<NAME>" , view = \index persons -> el (alternateCellAttr index) <| Element.text persons.lastName } ] } attrBackground : List (Element.Attribute msg) attrBackground = [ Background.color darkCharcoal , Font.color white ] attrCont : List (Element.Attribute msg) attrCont = [ padding 1 , spacing 1 ] ++ attrBackground attrA : List (Element.Attribute msg) attrA = [ Background.color <| rgb 0xD1 0xE5 0xFA , Font.color black , padding 1 ] attrB : List (Element.Attribute msg) attrB = [ Background.color white , Font.color black , padding 1 ] attrC : List (Element.Attribute msg) attrC = [ Background.color darkBlue , Font.color white , padding 1 ] alternateCellAttr : Int -> List (Element.Attribute msg) alternateCellAttr index = if index % 2 == 0 then Element.width fill :: attrC else Element.width fill :: attrB {- Credit lucamug for the code above (shared via elm-lang-slack ) -} aboutExperiment = paragraph [ paddingBottom 20 , Font.size 14 ] [ Element.text "This refactoring of https://github.com/billperegoy/elm-page-layout is an experiment in converting a style-elements 4.2.1. project into one that uses the stylish-elephants 6.0.2 (the next version of style-elements). Thanks to lucamug for adding an example of alterate row colors using indexedTable in his source: https://github.com/lucamug/elm-spa-boilerplate/blob/master/src/Pages/Examples.elm#L314,L319." ] gutter = 20 {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} borderRight n = Border.widthEach { right = n, left = 0, top = 0, bottom = 0 } borderBottom n = Border.widthEach { right = 0, left = 0, top = 0, bottom = n } {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} paddingRight n = paddingEach { right = n, left = 0, top = 0, bottom = 0 } paddingTop n = paddingEach { bottom = 0, top = n, left = 0, right = 0 } {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} paddingBottom n = paddingEach { bottom = n, top = 0, left = 0, right = 0 } {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} paddingLeft n = paddingEach { right = 0, left = n, top = 0, bottom = 0 } view : Model -> Html Msg view model = Element.layout [ Background.color white , padding gutter , spacing gutter ] <| wrapper model
true
module View exposing (view) import Color exposing (..) import Element exposing (..) import Element.Background as Background exposing (..) import Element.Border as Border exposing (..) import Element.Font as Font exposing (..) import Html exposing (..) import Model exposing (..) blockAttributes screenSize = case screenSize of Phone -> [ Element.width (px 800) ] Tablet -> [ Element.width (px 1000) ] Desktop -> [ Element.width (px 1200) ] wrapper : Model -> Element Msg wrapper model = Element.column [] [ pageArea model ] pageArea : Model -> Element Msg pageArea model = if model.screenSize == Phone then Element.column [ padding 10 , spacing 10 ] [ phoneLinkOne , phoneLinkTwo , phoneLinkThree , contentArea model , aboutExperiment , footerArea , row [ Font.size 14 ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "http://package.elm-lang.org/packages/mdgriffith/stylish-elephants/latest" , label = Element.text "stylish-elephants latest: package docs" } ] ] else Element.column [ Element.alignTop , paddingRight gutter , spaceEvenly ] [ headerArea , contentArea model , aboutExperiment , footerArea ] headerArea : Element Msg headerArea = row [ Element.alignLeft ] [ newTabLink [ Element.alignLeft , Font.mouseOverColor Color.darkOrange ] { url = "http://package.elm-lang.org/packages/mdgriffith/stylish-elephants/latest" , label = Element.text "stylish-elephants latest: package docs" } ] footerArea : Element msg footerArea = row [ Font.size 14 ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://github.com/jbrgfx" , label = Element.text "jbrgfx's github repos" } ] sidebarTitle : Element msg sidebarTitle = row [ padding 8 ] [ Element.text "Sidebar Links" ] phoneLinkOne = row [ spacing 20 , Element.height (px 60) , Background.color darkBlue , Font.size 20 , Font.color Color.white , Background.mouseOverColor Color.lightOrange , Font.mouseOverColor Color.darkBlue ] [ newTabLink [] { url = "https://becoming-functional.com/responsive-design-with-elm-style-elements-9d0eca8eb9ed" , label = Element.text "Test-drive Article" } ] phoneLinkTwo = row [ spacing 20 , Element.height (px 60) , Element.width fill , Background.color darkBlue , Font.size 20 , Font.color Color.white , Background.mouseOverColor Color.lightOrange , Font.mouseOverColor Color.darkBlue ] [ newTabLink [] { url = "https://github.com/billperegoy/elm-page-layout" , label = Element.text "Elm-page-layout" } ] phoneLinkThree = row [ spacing 20 , Element.height (px 60) , Element.width fill , Background.color darkBlue , Font.size 20 , Font.color Color.white , Background.mouseOverColor Color.lightOrange , Font.mouseOverColor Color.darkBlue ] [ newTabLink [] { url = "https://github.com/lucamug/elm-spa-boilerplate" , label = Element.text "Elm-spa-boilerplate" } ] sidebarArea : Model -> Element Msg sidebarArea model = if model.screenSize == Phone then Element.empty else column [ Element.alignLeft , Element.width (px 180) , Element.height (px 110) , Font.size 16 , paddingRight 10 ] [ sidebarTitle , row [ Element.width (px 110) , Element.alignRight , Font.underline , Font.color Color.blue ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://becoming-functional.com/responsive-design-with-elm-style-elements-9d0eca8eb9ed" , label = Element.text "Test-drive Article" } ] , row [ Element.width (px 110) , Element.alignRight , Font.underline , Font.color Color.blue ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://github.com/billperegoy/elm-page-layout" , label = Element.text "elm-page-layout" } ] , row [ Element.width (px 110) , Element.alignRight , Font.underline , Font.color Color.blue ] [ newTabLink [ Font.mouseOverColor Color.darkOrange ] { url = "https://github.com/lucamug/elm-spa-boilerplate" , label = Element.text "elm-spa-boilerplate" } ] ] contentArea : Model -> Element Msg contentArea model = row [ padding gutter ] [ sidebarArea model , column [ Element.padding 8 , Element.alignLeft , Element.width (px 450) ] [ mainContentArea model ] ] bodyWidth screenSize = if screenSize == Phone then Element.width (px 600) else if screenSize == Tablet then Element.width (px 800) else Element.width (px 1000) type alias Person = { firstName : String , middleName : String , lastName : String } persons : List Person persons = [ { firstName = "PI:NAME:<NAME>END_PI" , middleName = "PI:NAME:<NAME>END_PI" , lastName = "PI:NAME:<NAME>END_PI" } , { firstName = "PI:NAME:<NAME>END_PI" , middleName = "PI:NAME:<NAME>END_PI" , lastName = "PI:NAME:<NAME>END_PI" } ] mainContentArea model = {- Credit lucamug for the code below (shared via elm-lang-slack ) -} indexedTable attrCont { data = persons , columns = [ { header = el (Element.width fill :: attrA) <| Element.text "PI:NAME:<NAME>END_PI" , view = \index persons -> el (alternateCellAttr index) <| Element.text persons.firstName } , { header = el (Element.width fill :: attrA) <| Element.text "PI:NAME:<NAME>END_PI" , view = \index persons -> el (alternateCellAttr index) <| Element.text persons.middleName } , { header = el (Element.width fill :: attrA) <| Element.text "PI:NAME:<NAME>END_PI" , view = \index persons -> el (alternateCellAttr index) <| Element.text persons.lastName } ] } attrBackground : List (Element.Attribute msg) attrBackground = [ Background.color darkCharcoal , Font.color white ] attrCont : List (Element.Attribute msg) attrCont = [ padding 1 , spacing 1 ] ++ attrBackground attrA : List (Element.Attribute msg) attrA = [ Background.color <| rgb 0xD1 0xE5 0xFA , Font.color black , padding 1 ] attrB : List (Element.Attribute msg) attrB = [ Background.color white , Font.color black , padding 1 ] attrC : List (Element.Attribute msg) attrC = [ Background.color darkBlue , Font.color white , padding 1 ] alternateCellAttr : Int -> List (Element.Attribute msg) alternateCellAttr index = if index % 2 == 0 then Element.width fill :: attrC else Element.width fill :: attrB {- Credit lucamug for the code above (shared via elm-lang-slack ) -} aboutExperiment = paragraph [ paddingBottom 20 , Font.size 14 ] [ Element.text "This refactoring of https://github.com/billperegoy/elm-page-layout is an experiment in converting a style-elements 4.2.1. project into one that uses the stylish-elephants 6.0.2 (the next version of style-elements). Thanks to lucamug for adding an example of alterate row colors using indexedTable in his source: https://github.com/lucamug/elm-spa-boilerplate/blob/master/src/Pages/Examples.elm#L314,L319." ] gutter = 20 {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} borderRight n = Border.widthEach { right = n, left = 0, top = 0, bottom = 0 } borderBottom n = Border.widthEach { right = 0, left = 0, top = 0, bottom = n } {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} paddingRight n = paddingEach { right = n, left = 0, top = 0, bottom = 0 } paddingTop n = paddingEach { bottom = 0, top = n, left = 0, right = 0 } {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} paddingBottom n = paddingEach { bottom = n, top = 0, left = 0, right = 0 } {- credit: https://github.com/opsb/cv-elm/blob/master/src/Extra/Element.elm -} paddingLeft n = paddingEach { right = 0, left = n, top = 0, bottom = 0 } view : Model -> Html Msg view model = Element.layout [ Background.color white , padding gutter , spacing gutter ] <| wrapper model
elm
[ { "context": "String, age:Int }\nport students =\n [ { name = \"Tom\", age = 42 } ]", "end": 314, "score": 0.9997766018, "start": 311, "tag": "NAME", "value": "Tom" } ]
parser/tests/test-files/good/Ports.elm
turboMaCk/elm-format
1,432
-- incoming port userID : String port number : Int port tuple : (Float,Bool) port array : List Int port record : { x:Float, y:Float } -- outgoing port fortyTwo : Int port fortyTwo = 42 port time : Float port time = 3.14 port students : List { name:String, age:Int } port students = [ { name = "Tom", age = 42 } ]
35177
-- incoming port userID : String port number : Int port tuple : (Float,Bool) port array : List Int port record : { x:Float, y:Float } -- outgoing port fortyTwo : Int port fortyTwo = 42 port time : Float port time = 3.14 port students : List { name:String, age:Int } port students = [ { name = "<NAME>", age = 42 } ]
true
-- incoming port userID : String port number : Int port tuple : (Float,Bool) port array : List Int port record : { x:Float, y:Float } -- outgoing port fortyTwo : Int port fortyTwo = 42 port time : Float port time = 3.14 port students : List { name:String, age:Int } port students = [ { name = "PI:NAME:<NAME>END_PI", age = 42 } ]
elm
[ { "context": "{-\n Copyright 2020 Morgan Stanley\n\n Licensed under the Apache License, Version 2.", "end": 35, "score": 0.9998205304, "start": 21, "tag": "NAME", "value": "Morgan Stanley" } ]
src/Morphir/IR/Package/Codec.elm
aszenz/morphir-elm
0
{- 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 Morphir.IR.Package.Codec exposing (..) import Dict import Json.Decode as Decode import Json.Encode as Encode import Morphir.IR.AccessControlled.Codec exposing (decodeAccessControlled, encodeAccessControlled) import Morphir.IR.Module.Codec as ModuleCodec import Morphir.IR.Name.Codec exposing (encodeName) import Morphir.IR.Package exposing (Definition, Distribution(..), Specification) import Morphir.IR.Path.Codec exposing (decodePath, encodePath) encodeSpecification : (a -> Encode.Value) -> Specification a -> Encode.Value encodeSpecification encodeAttributes spec = Encode.object [ ( "modules" , spec.modules |> Dict.toList |> Encode.list (\( moduleName, moduleSpec ) -> Encode.object [ ( "name", encodePath moduleName ) , ( "spec", ModuleCodec.encodeSpecification encodeAttributes moduleSpec ) ] ) ) ] encodeDefinition : (a -> Encode.Value) -> Definition a -> Encode.Value encodeDefinition encodeAttributes def = Encode.object [ ( "dependencies" , def.dependencies |> Dict.toList |> Encode.list (\( packageName, packageSpec ) -> Encode.object [ ( "name", encodePath packageName ) , ( "spec", encodeSpecification encodeAttributes packageSpec ) ] ) ) , ( "modules" , def.modules |> Dict.toList |> Encode.list (\( moduleName, moduleDef ) -> Encode.object [ ( "name", encodePath moduleName ) , ( "def", encodeAccessControlled (ModuleCodec.encodeDefinition encodeAttributes) moduleDef ) ] ) ) ] decodeDefinition : Decode.Decoder a -> Decode.Decoder (Definition a) decodeDefinition decodeAttributes = Decode.map2 Definition (Decode.field "dependencies" (Decode.succeed Dict.empty) ) (Decode.field "modules" (Decode.map Dict.fromList (Decode.list (Decode.map2 Tuple.pair (Decode.field "name" decodePath) (Decode.field "def" (decodeAccessControlled (ModuleCodec.decodeDefinition decodeAttributes))) ) ) ) ) encodeDistribution : Distribution -> Encode.Value encodeDistribution distro = case distro of Library packagePath def -> Encode.list identity [ Encode.string "library" , encodePath packagePath , encodeDefinition (\_ -> Encode.object []) def ] decodeDistribution : Decode.Decoder Distribution decodeDistribution = Decode.index 0 Decode.string |> Decode.andThen (\kind -> case kind of "library" -> Decode.map2 Library (Decode.index 1 decodePath) (Decode.index 2 (decodeDefinition (Decode.succeed ()))) other -> Decode.fail <| "Unknown value type: " ++ other )
19383
{- 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 Morphir.IR.Package.Codec exposing (..) import Dict import Json.Decode as Decode import Json.Encode as Encode import Morphir.IR.AccessControlled.Codec exposing (decodeAccessControlled, encodeAccessControlled) import Morphir.IR.Module.Codec as ModuleCodec import Morphir.IR.Name.Codec exposing (encodeName) import Morphir.IR.Package exposing (Definition, Distribution(..), Specification) import Morphir.IR.Path.Codec exposing (decodePath, encodePath) encodeSpecification : (a -> Encode.Value) -> Specification a -> Encode.Value encodeSpecification encodeAttributes spec = Encode.object [ ( "modules" , spec.modules |> Dict.toList |> Encode.list (\( moduleName, moduleSpec ) -> Encode.object [ ( "name", encodePath moduleName ) , ( "spec", ModuleCodec.encodeSpecification encodeAttributes moduleSpec ) ] ) ) ] encodeDefinition : (a -> Encode.Value) -> Definition a -> Encode.Value encodeDefinition encodeAttributes def = Encode.object [ ( "dependencies" , def.dependencies |> Dict.toList |> Encode.list (\( packageName, packageSpec ) -> Encode.object [ ( "name", encodePath packageName ) , ( "spec", encodeSpecification encodeAttributes packageSpec ) ] ) ) , ( "modules" , def.modules |> Dict.toList |> Encode.list (\( moduleName, moduleDef ) -> Encode.object [ ( "name", encodePath moduleName ) , ( "def", encodeAccessControlled (ModuleCodec.encodeDefinition encodeAttributes) moduleDef ) ] ) ) ] decodeDefinition : Decode.Decoder a -> Decode.Decoder (Definition a) decodeDefinition decodeAttributes = Decode.map2 Definition (Decode.field "dependencies" (Decode.succeed Dict.empty) ) (Decode.field "modules" (Decode.map Dict.fromList (Decode.list (Decode.map2 Tuple.pair (Decode.field "name" decodePath) (Decode.field "def" (decodeAccessControlled (ModuleCodec.decodeDefinition decodeAttributes))) ) ) ) ) encodeDistribution : Distribution -> Encode.Value encodeDistribution distro = case distro of Library packagePath def -> Encode.list identity [ Encode.string "library" , encodePath packagePath , encodeDefinition (\_ -> Encode.object []) def ] decodeDistribution : Decode.Decoder Distribution decodeDistribution = Decode.index 0 Decode.string |> Decode.andThen (\kind -> case kind of "library" -> Decode.map2 Library (Decode.index 1 decodePath) (Decode.index 2 (decodeDefinition (Decode.succeed ()))) other -> Decode.fail <| "Unknown value type: " ++ other )
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 Morphir.IR.Package.Codec exposing (..) import Dict import Json.Decode as Decode import Json.Encode as Encode import Morphir.IR.AccessControlled.Codec exposing (decodeAccessControlled, encodeAccessControlled) import Morphir.IR.Module.Codec as ModuleCodec import Morphir.IR.Name.Codec exposing (encodeName) import Morphir.IR.Package exposing (Definition, Distribution(..), Specification) import Morphir.IR.Path.Codec exposing (decodePath, encodePath) encodeSpecification : (a -> Encode.Value) -> Specification a -> Encode.Value encodeSpecification encodeAttributes spec = Encode.object [ ( "modules" , spec.modules |> Dict.toList |> Encode.list (\( moduleName, moduleSpec ) -> Encode.object [ ( "name", encodePath moduleName ) , ( "spec", ModuleCodec.encodeSpecification encodeAttributes moduleSpec ) ] ) ) ] encodeDefinition : (a -> Encode.Value) -> Definition a -> Encode.Value encodeDefinition encodeAttributes def = Encode.object [ ( "dependencies" , def.dependencies |> Dict.toList |> Encode.list (\( packageName, packageSpec ) -> Encode.object [ ( "name", encodePath packageName ) , ( "spec", encodeSpecification encodeAttributes packageSpec ) ] ) ) , ( "modules" , def.modules |> Dict.toList |> Encode.list (\( moduleName, moduleDef ) -> Encode.object [ ( "name", encodePath moduleName ) , ( "def", encodeAccessControlled (ModuleCodec.encodeDefinition encodeAttributes) moduleDef ) ] ) ) ] decodeDefinition : Decode.Decoder a -> Decode.Decoder (Definition a) decodeDefinition decodeAttributes = Decode.map2 Definition (Decode.field "dependencies" (Decode.succeed Dict.empty) ) (Decode.field "modules" (Decode.map Dict.fromList (Decode.list (Decode.map2 Tuple.pair (Decode.field "name" decodePath) (Decode.field "def" (decodeAccessControlled (ModuleCodec.decodeDefinition decodeAttributes))) ) ) ) ) encodeDistribution : Distribution -> Encode.Value encodeDistribution distro = case distro of Library packagePath def -> Encode.list identity [ Encode.string "library" , encodePath packagePath , encodeDefinition (\_ -> Encode.object []) def ] decodeDistribution : Decode.Decoder Distribution decodeDistribution = Decode.index 0 Decode.string |> Decode.andThen (\kind -> case kind of "library" -> Decode.map2 Library (Decode.index 1 decodePath) (Decode.index 2 (decodeDefinition (Decode.succeed ()))) other -> Decode.fail <| "Unknown value type: " ++ other )
elm
[ { "context": "fee is in my bag\"\n }\n , { latin = \"qahwa siith\"\n , kana = \"かハワ スィース\"\n , arabic = \"قَ", "end": 17279, "score": 0.9060000181, "start": 17274, "tag": "NAME", "value": "siith" }, { "context": "rabic = \"إسمه بشير\"\n , meaning = \"HIs name is Bashir.\"\n } \n , { latin = \"ismhaa Tawiil\"\n ", "end": 20127, "score": 0.9861999154, "start": 20121, "tag": "NAME", "value": "Bashir" }, { "context": "ا بوب قريب من بيتها\"\n , meaning = \"Her friend Bob is close to her house.\"\n } \n , { latin = ", "end": 20459, "score": 0.999612987, "start": 20456, "tag": "NAME", "value": "Bob" }, { "context": "arabic = \"إسمه بوب\"\n , meaning = \"His name is Bob.\"\n }\n , { latin = \"baythu qariib min bayt", "end": 20611, "score": 0.9978110194, "start": 20608, "tag": "NAME", "value": "Bob" }, { "context": " تامِر غَنِيّ جِدّاً\"\n , meaning = \"My friend Tamer is very rich\"\n }\n , { latin = \"laa 2a3rif", "end": 38327, "score": 0.9687978625, "start": 38322, "tag": "NAME", "value": "Tamer" }, { "context": "مْية لابِسة تّنّورة\"\n , meaning = \"His friend Samia is wearing a skirt.\"\n }\n , { latin = \"wa-", "end": 39203, "score": 0.9984054565, "start": 39198, "tag": "NAME", "value": "Samia" }, { "context": "\"أَخي بَشير مَشْغول\"\n , meaning = \"My brother Bashir is busy.\"\n }\n , { latin = \"fii haadhihi a", "end": 39948, "score": 0.9988242388, "start": 39942, "tag": "NAME", "value": "Bashir" }, { "context": "ً اِسْمي بوب\"\n , meaning = \"Hello, my name is Bob.\"\n }\n , { latin = \"mariiD\"\n , kana =", "end": 50642, "score": 0.9996179342, "start": 50639, "tag": "NAME", "value": "Bob" }, { "context": "أُسْتاذة\"\n , meaning = \"What is your name ma'am?\"\n }\n , { latin = \"qiTTatak malika\"\n ", "end": 54345, "score": 0.5379536152, "start": 54343, "tag": "NAME", "value": "am" }, { "context": " \"أَنا إِسمي فاطِمة\"\n , meaning = \"My name is Fatima (female name).\"\n }\n , { latin = \"2a3iish", "end": 58388, "score": 0.9991941452, "start": 58382, "tag": "NAME", "value": "Fatima" }, { "context": "جورْج\"\n , meaning = \"my sister and her friend George\"\n }\n , { latin = \"3amalii\"\n , kana =", "end": 58849, "score": 0.8910580873, "start": 58843, "tag": "NAME", "value": "George" }, { "context": "ُ سامية\"\n , meaning = \"This is his girlfriend Samia.\"\n }\n , { latin = \"shitaa2\"\n , kana ", "end": 59143, "score": 0.9799274206, "start": 59138, "tag": "NAME", "value": "Samia" }, { "context": "ِنْدهُ عَمَل مُمْتاز\"\n , meaning = \"My friend George has excellent job.\"\n }\n , { latin = \"", "end": 71020, "score": 0.6230959892, "start": 71018, "tag": "NAME", "value": "Ge" }, { "context": "زا قَريبة مِن بَيته\"\n , meaning = \"His friend Rosa is close to his house.\"\n }\n , { latin = \"", "end": 96377, "score": 0.9984395504, "start": 96373, "tag": "NAME", "value": "Rosa" }, { "context": "ー\"\n , arabic = \"باب كَري\"\n , meaning = \"Carrie’s door\"\n }\n , { latin = \"kalb al-bint\"\n ", "end": 101440, "score": 0.9926139116, "start": 101434, "tag": "NAME", "value": "Carrie" }, { "context": " }\n , { latin = \"li2anna 2ukhtii tadhrus kathiiraan\"\n , kana = \"リアンナ ウクフティー タずるス カしーラン\"\n , ", "end": 127715, "score": 0.7908785343, "start": 127706, "tag": "NAME", "value": "athiiraan" } ]
src/Arabic004.elm
kalz2q/elm-examples
0
module Arabic001 exposing (main) -- backup 2020-06-07 16:51:47 import Browser import Html exposing (..) import Html.Attributes as HA import Html.Events as HE import Random main : Program () Model Msg main = Browser.element { init = init , update = update , subscriptions = subscriptions , view = view } type alias Model = { latin : String , kana : String , arabic : String , meaning : String , showanswer : Bool , list : List Arabicdata } type alias Arabicdata = { latin : String , kana : String , arabic : String , meaning : String } init : () -> ( Model, Cmd Msg ) init _ = ( Model "" "" "" "" False dict , Random.generate NewList (shuffle dict) ) type Msg = Delete | Next | NewRandom Int | Shuffle | NewList (List Arabicdata) | ShowAnswer Int update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of Delete -> ( model , Cmd.none ) Next -> ( model , Cmd.none ) NewRandom n -> case List.drop n dict of x :: _ -> ( { model | latin = x.latin , kana = x.kana , arabic = x.arabic , meaning = x.meaning } , Cmd.none ) [] -> ( model , Cmd.none ) Shuffle -> ( model , Random.generate NewList (shuffle dict) ) NewList newList -> ( { model | list = newList } , Cmd.none ) ShowAnswer index -> case List.drop index model.list of x :: _ -> ( { model | latin = x.latin , kana = x.kana , arabic = x.arabic , meaning = x.meaning , showanswer = True } , Cmd.none ) [] -> ( model , Cmd.none ) subscriptions : Model -> Sub Msg subscriptions model = Sub.none view : Model -> Html Msg view model = div [] [ text "Convert latin to arabic" , p [] [ text "SabaaH" ] , button [] [ text "Show Answer" ] , button [] [ text "Delete" ] , button [] [ text "Next" ] ] shuffle : List a -> Random.Generator (List a) shuffle list = let randomNumbers : Random.Generator (List Int) randomNumbers = Random.list (List.length list) <| Random.int Random.minInt Random.maxInt zipWithList : List Int -> List ( a, Int ) zipWithList intList = List.map2 Tuple.pair list intList listWithRandomNumbers : Random.Generator (List ( a, Int )) listWithRandomNumbers = Random.map zipWithList randomNumbers sortedGenerator : Random.Generator (List ( a, Int )) sortedGenerator = Random.map (List.sortBy Tuple.second) listWithRandomNumbers in Random.map (List.map Tuple.first) sortedGenerator dict = [ { latin = "a-s-salaamu" , kana = "アッサラーム" , arabic = "اَلسَّلَامُ" , meaning = "peace" } , { latin = "2alaykum" , kana = "アライクム" , arabic = "عَلَيْكُمْ" , meaning = "on you" } , { latin = "SabaaH" , kana = "サバーフ" , arabic = "صَبَاح" , meaning = "morning" } , { latin = "marHaban" , kana = "マルハバン" , arabic = "مَرْحَبًا" , meaning = "Hello" } , { latin = "2anaa bikhayr" , kana = "アナー ビクハイル" , arabic = "أَنا بِخَيْر" , meaning = "I'm fine" } , { latin = "kabir" , kana = "カビール" , arabic = "كَبير" , meaning = "large, big" } , { latin = "kabiira" , kana = "カビーラ" , arabic = "كبيرة" , meaning = "large, big" } , { latin = "siith" , kana = "スィース" , arabic = "سيث" , meaning = "Seth (male name)" } , { latin = "baluuza" , kana = "バルーザ" , arabic = "بَلوزة" , meaning = "blouse" } , { latin = "tii shiirt" , kana = "ティー シイールト" , arabic = "تي شيرْت" , meaning = "T-shirt" } , { latin = "ma3Taf" , kana = "マアタフ" , arabic = "معْطَف" , meaning = "a coat" } , { latin = "riim" , kana = "リーム" , arabic = "ريم" , meaning = "Reem (male name)" } , { latin = "tan-nuura" , kana = "タンヌーラ" , arabic = "تَنّورة" , meaning = "a skirt" } , { latin = "jadiid" , kana = "ジャディード" , arabic = "جَديد" , meaning = "new" } , { latin = "wishshaaH" , kana = "ウィシャーハ" , arabic = "وِشَاح" , meaning = "a scarf" } , { latin = "juudii" , kana = "ジューディー" , arabic = "جودي" , meaning = "Judy(name)" } , { latin = "jamiil" , kana = "ジャミール" , arabic = "جَميل" , meaning = "good, nice, pretty, beautiful" } , { latin = "kalb" , kana = "キャルブ" , arabic = "كَلْب" , meaning = "a dog" } , { latin = "2abyaD" , kana = "アビヤッド" , arabic = "أَبْيَض" , meaning = "white" } , { latin = "qub-b3a" , kana = "クッバ" , arabic = "قُبَّعة" , meaning = "a hat" } , { latin = "mruu2a" , kana = "ムルーア" , arabic = "مْروءة" , meaning = "chivalry" } , { latin = "Taawila" , kana = "ターウィラ" , arabic = "طاوِلة" , meaning = "a table" } , { latin = "haadhihi madiina qadiima" , kana = "ハージヒ マディーナ カディーマ" , arabic = "هَذِهِ مَدينة قَديمة" , meaning = "This is an ancient city" } , { latin = "haadhihi binaaya jamiila" , kana = "ハージヒ ビナーヤ ジャミーラ" , arabic = "هَذِهِ بِناية جَميلة" , meaning = "This is a beautiful building" } , { latin = "hadhaa muhammad" , kana = "ハーザー ムハンマド" , arabic = "هَذا مُحَمَّد" , meaning = "This is Mohammed" } , { latin = "haadhihi Hadiiqa jamiila" , kana = "ハージヒ ハディーカ ジャミーラ" , arabic = "هَذِهِ حَديقة جَميلة" , meaning = "This is a pretty garden" } , { latin = "haadhihi Hadiiqa qadiima" , kana = "ハージヒ ハディーカ カディーマ" , arabic = "هَذِهِ حَديقة قَديمة" , meaning = "This is an old garden" } , { latin = "al-Haa2iT" , kana = "アルハーイト" , arabic = "الْحائط" , meaning = "the wall" } , { latin = "Haa2iT" , kana = "ハーイト" , arabic = "حائِط" , meaning = "wall" } , { latin = "hadhaa al-Haa2iT kabiir" , kana = "ハーザ ル ハーイト カビール" , arabic = "هَذا الْحائِط كَبير" , meaning = "this wall is big" } , { latin = "al-kalb" , kana = "アル カルブ" , arabic = "الْكَلْب" , meaning = "the dog" } , { latin = "haadhihi al-binaaya" , kana = "ハージヒ アル ビナーヤ" , arabic = "هذِهِ الْبِناية" , meaning = "this building" } , { latin = "al-ghurfa" , kana = "アル グルファ" , arabic = "اَلْغُرفة" , meaning = "the room" } , { latin = "al-ghurfa kabiira" , kana = "アルグルファ カビーラ" , arabic = "اَلْغرْفة كَبيرة" , meaning = "Theroom is big" } , { latin = "haadhihi alghurfa kabiira" , kana = "ハージヒ アルグルファ カビーラ" , arabic = "هَذِهِ الْغُرْفة كَبيرة" , meaning = "this room is big" } , { latin = "hadhaa alkalb kalbii" , kana = "ハーザー アルカルブ カルビー" , arabic = "هَذا الْكَلْب كَْلبي" , meaning = "this dog is my dog" } , { latin = "hadhaa alkalb jaw3aan" , kana = "ハーザー アルカルブ ジャウあーン" , arabic = "هَذا الْكَلْب جَوْعان" , meaning = "this dog is hungry" } , { latin = "haadhihi al-binaaya waasi3a" , kana = "ハージヒ アルビナーヤ ワースィア" , arabic = "هَذِهِ الْبناية واسِعة" , meaning = "this building is spacious" } , { latin = "al-kalb ghariib" , kana = "アルカルブ ガリーブ" , arabic = "اَلْكَلْب غَريب" , meaning = "The dog is weird" } , { latin = "alkalb kalbii" , kana = "アルカルブ カルビー" , arabic = "اَلْكَلْب كَلْبي" , meaning = "The dog is my dog" } , { latin = "hunaak" , kana = "フゥナーク" , arabic = "هُناك" , meaning = "there" } , { latin = "hunaak bayt" , kana = "フゥナーク バイト" , arabic = "هُناك بَيْت" , meaning = "There is a house" } , { latin = "al-bayt hunaak" , kana = "アル バイト フゥナーク" , arabic = "اَلْبَيْت هُناك" , meaning = "The house is there" } , { latin = "hunaak wishaaH 2abyaD" , kana = "フゥナーク ウィシャーハ アビヤド" , arabic = "هُناك وِشاح أبْيَض" , meaning = "There is a white scarf" } , { latin = "alkalb munaak" , kana = "アルカルブ ムナーク" , arabic = "اَلْكَلْب مُناك" , meaning = "The dog is there" } , { latin = "fii shanTatii" , kana = "フィー シャンタティー" , arabic = "في شَنْطَتي" , meaning = "in my bag" } , { latin = "hal 3indak maHfaDha yaa juurj" , kana = "ハル アインダク マハファザ ヤー ジュールジュ" , arabic = "هَل عِنْدَك مَحْفَظة يا جورْج" , meaning = "do you have a wallet , george" } , { latin = "3indii shanTa ghaalya" , kana = "アインディー シャンタ ガーリヤ" , arabic = "عِنْدي شَنْطة غالْية" , meaning = "I have an expensive bag" } , { latin = "shanTatii fii shanTatik ya raanyaa" , kana = "シャンタティー フィー シャンタティク ヤー ラーニヤー" , arabic = "شِنْطَتي في شَنْطتِك يا رانْيا" , meaning = "my bag is in your bag rania" } , { latin = "huunak maHfaDha Saghiira" , kana = "フゥナーク マハファザ サギーラ" , arabic = "هُناك مَحْفَظة صَغيرة" , meaning = "There is a small wallet" } , { latin = "hunaak kitaab jadiid" , kana = "フゥナーク キターブ ジャディード" , arabic = "هَناك كِتاب جَديد" , meaning = "There is a new book" } , { latin = "hunaak kitaab Saghiir" , kana = "フゥナーク キターブ サギール" , arabic = "هُناك كِتاب صَغير" , meaning = "There is a small book" } , { latin = "hunaak qubb3a fii shanTatak yaa buub" , kana = "フゥナーク クッバア フィー シャンタタク ヤー ブーブ" , arabic = "هُناك قُبَّعة في شَنْطَتَك يا بوب" , meaning = "There is a hat in your bag bob" } , { latin = "hunaak shanTa Saghiira" , kana = "フゥナーク シャンタ サギーラ" , arabic = "هُناك شَنْطة صَغيرة" , meaning = "There is a small bag" } , { latin = "shanTatii hunaak" , kana = "シャンタティー フゥナーク" , arabic = "شَنْطَتي هُناك" , meaning = "my bag is over there" } , { latin = "hunaak kitaab Saghiir wa-wishaaH kabiir fii ShanTatii" , kana = "フゥナーク キターブ サギール ワ ウィシャーハ カビール フィー シャンタティー" , arabic = "هُناك كِتاب صَغير وَوِشاح كَبير في شَنْطَتي" , meaning = "There is a small book and a big scarf in my bag" } , { latin = "hunaak maHfaDha Saghiir fii shanTatii" , kana = "フゥナーク マハファザ サギール フィー シャンタティー" , arabic = "هُناك مَحْفَظة صَغيرة في شَنْطَتي" , meaning = "There is a small wallet in my bag" } , { latin = "aljaami3a hunaak" , kana = "アルジャーミア フゥナーク" , arabic = "اَلْجامِعة هُناك" , meaning = "The university is there" } , { latin = "hunaak kitaab" , kana = "フゥナーク キターブ" , arabic = "هُناك كِتاب" , meaning = "There is a book" } , { latin = "al-madiina hunaak" , kana = "アルマディーナ フゥナーク" , arabic = "اَلْمَدينة هُناك" , meaning = "Thecity is there" } , { latin = "hal 3indik shanTa ghaaliya yaa Riim" , kana = "ハル アインディク シャンタ ガーリヤ ヤー リーム" , arabic = "هَل عِندِك شَنْطة غالْية يا ريم" , meaning = "do you have an expensive bag Reem" } , { latin = "hal 3indik mashruub yaa saamya" , kana = "ハル アインディク マシュルーブ ヤー サーミヤ" , arabic = "هَل عِنْدِك مَشْروب يا سامْية" , meaning = "do you have a drink samia" } , { latin = "hunaak daftar rakhiiS" , kana = "フゥナーク ダフタル ラクヒース" , arabic = "هُناك دَفْتَر رَخيص" , meaning = "There is a cheep notebook" } , { latin = "laysa 3indii daftar" , kana = "ライサ アインディー ダフタル" , arabic = "لَيْسَ عِنْدي دَفْتَر" , meaning = "I do not have a notebook" } , { latin = "laysa hunaak masharuub fii shanTatii" , kana = "ライサ フゥナーク マシャルーブ フィー シャンタティー" , arabic = "لَيْسَ هُناك مَشْروب في شَنْطَتي" , meaning = "There is no drink in my bag" } , { latin = "laysa hunaak kitaab qaSiir fii baytii" , kana = "ライサ フゥナーク キターブ カスィール フィー バイティ" , arabic = "لَيْسَ هُناك كِتاب قَصير في بَيْتي" , meaning = "There is no short book in my house" } , { latin = "laysa hunaak daftar rakhiiS" , kana = "ライサ フゥナーク ダフタル ラクヒース" , arabic = "لَيْسَ هُناك دَفْتَر رَخيص" , meaning = "There is no cheap notebook" } , { latin = "laysa 3indii sii dii" , kana = "ライサ アインディー スィー ヂー" , arabic = "لَيْسَ عَنْدي سي دي" , meaning = "I do not have a CD" } , { latin = "laysa hunaak qalam fii shanTatii" , kana = "ライサ フゥナーク カラム フィー シャンタティー" , arabic = "لَيْسَ هُناك قَلَم في شَنْطَتي" , meaning = "There is no pen in my bag" } , { latin = "laysa hunaak kitaab qaSiir fii shanTatii" , kana = "ライサ フゥナーク キターブ カスィール フィー シャンタティー" , arabic = "لَيْسَ هُناك كِتاب قَصير في شَنْطَتي" , meaning = "There is no short book in my bag" } , { latin = "laysa hunaak daftar 2abyaD" , kana = "ライサ フゥナーク ダフタル アビヤド" , arabic = "لَيْسَ هُناك دَفْتَر أَبْيَض" , meaning = "There is no white notebook." } , { latin = "maTbakh" , kana = "マタバクフ" , arabic = "مَطْبَخ" , meaning = "a kitchen" } , { latin = "3ilka" , kana = "アイルカ" , arabic = "عِلْكة" , meaning = "chewing gum" } , { latin = "miftaaH" , kana = "ミフターフ" , arabic = "مفْتاح" , meaning = "a key" } , { latin = "tuub" , kana = "トゥーブ" , arabic = "توب" , meaning = "top" } , { latin = "nuquud" , kana = "ヌクード" , arabic = "نُقود" , meaning = "money, cash" } , { latin = "aljazeera" , kana = "アルジャズィーラ" , arabic = "الجزيرة" , meaning = "Al Jazeera" } , { latin = "kursii" , kana = "クルスィー" , arabic = "كَرْسي" , meaning = "a chair" } , { latin = "sari3" , kana = "サリア" , arabic = "سَريع" , meaning = "fast" } , { latin = "Haasuub" , kana = "ハースーブ" , arabic = "حاسوب" , meaning = "a computer" } , { latin = "maktab" , kana = "マクタブ" , arabic = "مَكْتَب" , meaning = "office, desk" } , { latin = "hadhaa maktab kabiir" , kana = "ハーザー マクタブ カビール" , arabic = "هَذا مَِكْتَب كَبير" , meaning = "This is a big office" } , { latin = "kursii alqiTTa" , kana = "クルスィー アルキッタ" , arabic = "كُرْسي الْقِطّة" , meaning = "the cat's chair" } , { latin = "Haasuub al-2ustaadha" , kana = "ハースーブ アル ウスターザ" , arabic = "حاسوب اَلْأُسْتاذة" , meaning = "professor's computer" } , { latin = "kursii jadiid" , kana = "クルスィー ジャディード" , arabic = "كُرْسي جَديد" , meaning = "a new chair" } , { latin = "SaHiifa" , kana = "サヒーファ" , arabic = "صَحيفة" , meaning = "newspaper" } , { latin = "haatif" , kana = "ハーティフ" , arabic = "هاتِف" , meaning = "phone" } , { latin = "2amriikiyy" , kana = "アムりーキーイ" , arabic = "أمْريكِي" , meaning = "American" } , { latin = "2amriikaa wa-a-S-Siin" , kana = "アムりーカー ワ アッスィーン" , arabic = "أَمْريكا وَالْصّين" , meaning = "America and China" } , { latin = "qahwa" , kana = "かハワ" , arabic = "قَهْوة" , meaning = "coffee" } , { latin = "Haliib" , kana = "ハリーブ" , arabic = "حَليب" , meaning = "milk" } , { latin = "muuza" , kana = "ムーザ" , arabic = "موزة" , meaning = "a banana" } , { latin = "2akl" , kana = "アクル" , arabic = "أَكْل" , meaning = "food" } , { latin = "2akl 3arabiyy wa-qahwa 3arabiyy" , kana = "アクル アラビーイ ワ かハワ アラビーイ" , arabic = "أَكْل عَرَبيّ وَقَهْوة عَرَبيّة" , meaning = "Arabic food and Arabic coffee" } , { latin = "ruzz" , kana = "ルッズ" , arabic = "رُزّ" , meaning = "rice" } , { latin = "ruzzii wa-qahwatii" , kana = "ルッズイー ワ かハワティー" , arabic = "رُزّي وَقَهْوَتي" , meaning = "my rice and my coffee" } , { latin = "qahwatii fii shanTatii" , kana = "かハワティー フィー シャンタティー" , arabic = "قَهْوَتي في شَنْطَتي" , meaning = "My coffee is in my bag" } , { latin = "qahwa siith" , kana = "かハワ スィース" , arabic = "قَهْوَة سيث" , meaning = "Seth's coffee" } , { latin = "Sadiiqat-haa" , kana = "すぁディーかトハー" , arabic = "صَديقَتها" , meaning = "her friend" } , { latin = "jaarat-haa" , kana = "ジャーラト ハー" , arabic = "جارَتها" , meaning = "her neighbor" } , { latin = "2ukhtii" , kana = "ウクフティ" , arabic = "أُخْتي" , meaning = "my sister" } , { latin = "Sadiiqa jayyida" , kana = "サディーカ ジャイイダ" , arabic = "صَديقة جَيِّدة" , meaning = "a good friend" }أ , { latin = "2a3rif" , arabic = "أَعْرِف" , meaning = "I know" } , { latin = "2anaa 2a3rifhu" , kana = "アナー アーリフフゥ" , arabic = "أَنا أَعْرِفه" , meaning = "I know him" } , { latin = "Taawila Tawiila" , kana = "ターウィラ タウィーラ" , arabic = "طاوِلة طَويلة" , meaning = "a long table" } , { latin = "baytik wa-bayt-haa" , kana = "バイティク ワ バイトハー" , arabic = "بَيْتِك وَبَيْتها" , meaning = "your house and her house" } , { latin = "ism Tawiil" , kana = "イスム タウィール" , arabic = "اِسْم طَويل" , meaning = "long name" } , { latin = "baytii wa-baythaa" , kana = "バイティー ワ バイトハー" , arabic = "بَيْتي وَبَيْتها" , meaning = "my house and her house" } , { latin = "laysa hunaak lugha Sa3ba" , kana = "ライサ フゥナーク ルガ サアバ" , arabic = "لَيْسَ هُناك لُغة صَعْبة" , meaning = "There is no diffcult language." } , { latin = "hadhaa shay2 Sa3b" , kana = "ハーザー シャイ サアバ" , arabic = "هَذا شَيْء صَعْب" , meaning = "This is a difficult thing." } , { latin = "ismhu taamir" , kana = "イスムフゥ ターミル" , arabic = "اِسْمهُ تامِر" , meaning = "His name is Tamer." } , { latin = "laa 2a3rif 2ayn bayt-hu" , kana = "ラー アーリフ アイン バイトフゥ" , arabic = "لا أَعْرِف أَيْن بَيْته" , meaning = "I don't know where his house is" } , { latin = "laa 2a3rif 2ayn 2anaa" , kana = "ラー アーリフ アイン アナー" , arabic = "لا أعرف أين أنا." , meaning = "I don't know where I am." } , { latin = "bayt-hu qariib min al-jaami3a" , kana = "バイトフゥ カリーブ ミン アル ジャーミア" , arabic = "بيته قريب من الجامعة" , meaning = "His house is close to the university" } , { latin = "ismhaa arabiyy" , kana = "イスムハー アラビーイ" , arabic = "إسمها عربي" , meaning = "Her name is arabic." } , { latin = "riim Sadiiqa Sa3ba" , kana = "リーム サディーカ サアバ" , arabic = "ريم صديقة صعبة" , meaning = "Reem is a difficult friend." } , { latin = "ismhu bashiir" , kana = "イスムフゥ バシール" , arabic = "إسمه بشير" , meaning = "HIs name is Bashir." } , { latin = "ismhaa Tawiil" , kana = "イスムハー タウィール" , arabic = "إسمها طويل" , meaning = "Her name is long." } , { latin = "Sadiiqhaa buub qariib min baythaa" , kana = "サディークハー ブーブ カリーブ ミン バイトハー" , arabic = "صديقها بوب قريب من بيتها" , meaning = "Her friend Bob is close to her house." } , { latin = "ismhu buub" , kana = "イスムフゥ ブーブ" , arabic = "إسمه بوب" , meaning = "His name is Bob." } , { latin = "baythu qariib min baythaa" , kana = "バイトフゥ カリーブ ミン バイトハー" , arabic = "بيته قريب من بيتها" , meaning = "His house is close to her house." } , { latin = "hadhaa shay2 Sa3b" , kana = "ハーザー シャイ サアブ" , arabic = "هذا شيء صعب" , meaning = "This is a difficult thing." } , { latin = "3alaaqa" , kana = "アラーカ" , arabic = "عَلاقَة" , meaning = "relationship" } , { latin = "al-qiTTa" , kana = "アルキッタ" , arabic = "اَلْقِطّة" , meaning = "the cat" } , { latin = "laa 2uhib" , kana = "ラー ウひッブ" , arabic = "لا أُحِب" , meaning = "I do not like" } , { latin = "al-2akl mumti3" , kana = "アルアクル ムムティア" , arabic = "اَلْأَكْل مُمْتع" , meaning = "Eating is fun." } , { latin = "al-qiraa2a" , kana = "アルキラーエ" , arabic = "اَلْقِراءة" , meaning = "reading" } , { latin = "alkitaaba" , kana = "アルキターバ" , arabic = "الْكِتابة" , meaning = "writing" } , { latin = "alkiraa2a wa-alkitaaba" , kana = "アルキラーエ ワ アルキターバ" , arabic = "اَلْقِراءة وَالْكِتابة" , meaning = "reading and writing" } , { latin = "muhimm" , kana = "ムヒンム" , arabic = "مُهِمّ" , meaning = "important" } , { latin = "alkiaaba shay2 muhimm" , kana = "アルキターバ シャイ ムヒンム" , arabic = "اَلْكِتابة شَيْء مُهِمّ" , meaning = "Writing is an important thing." } , { latin = "al-jaara wa-al-qiTTa" , kana = "アル ジャーラ ワ アル キッタ" , arabic = "اَلْجارة وَالْقِطّة" , meaning = "the neighbor and the cat" } , { latin = "qiTTa wa-alqiTTa" , kana = "キッタ ワ アルキッタ" , arabic = "قِطّة وَالْقِطّة" , meaning = "a cat and the cat" } , { latin = "2ayDan" , kana = "アイだン" , arabic = "أَيْضاً" , meaning = "also" } , { latin = "almaT3m" , kana = "アル マたあム" , arabic = "الْمَطْعْم" , meaning = "the restaurant" } , { latin = "maa2" , kana = "マー" , arabic = "ماء" , meaning = "water" } , { latin = "maT3am" , kana = "マタム" , arabic = "مَطْعَم" , meaning = "a restaurant" } , { latin = "a-t-taSwiir" , kana = "アッタスウィール" , arabic = "اَلْتَّصْوير" , meaning = "photography" } , { latin = "a-n-nawm" , kana = "アンナウム" , arabic = "اَلْنَّوْم" , meaning = "sleeping, sleep" } , { latin = "a-s-sibaaha" , kana = "アッスィバーハ" , arabic = "اَلْسِّباحة" , meaning = "swimming" } , { latin = "Sabaahan 2uhibb al-2akl hunaa" , kana = "サバーハン ウひッブ アルアクル フゥナー" , arabic = "صَباحاً أُحِبّ اَلْأَكْل هُنا" , meaning = "In the morning, I like eating here." } , { latin = "kathiiraan" , kana = "カシーラン" , arabic = "كَثيراً" , meaning = "much" } , { latin = "hunaa" , kana = "フゥナー" , arabic = "هُنا" , meaning = "here" } , { latin = "jiddan" , kana = "ジッダン" , arabic = "جِدَّاً" , meaning = "very" } , { latin = "3an" , kana = "アン" , arabic = "عَن" , meaning = "about" } , { latin = "2uhibb a-s-safar 2ilaa 2iiTaaliyaa" , kana = "ウひッブ アッサファル いらー イーターリヤー" , arabic = "أُحِبّ اَلْسَّفَر إِلى إيطالْيا" , meaning = "I like traveling to Italy." } , { latin = "al-kalaam ma3a 2abii" , kana = "アルカラーム マア アビー" , arabic = "اَلْكَلام مَعَ أَبي" , meaning = "talking with my father" } , { latin = "2uHibb aljarii bi-l-layl" , kana = "ウひッブ アルジャリー ビッライル" , arabic = "أُحِبّ اَلْجَري بِالْلَّيْل" , meaning = "I like running at night." } , { latin = "2uriidu" , kana = "ウりード" , arabic = "أُريدُ" , meaning = "I want" } , { latin = "2uHibb 2iiTaaliyaa 2ayDan" , kana = "ウひッブ イーターリヤー アイダン" , arabic = "أُحِبّ إيطاليا أَيْضاً" , meaning = "I like Italy also." } , { latin = "2uHibb alqiraa2a 3an kuubaa bi-l-layl" , kana = "ウひッブ アルキラーア アン クーバー ビッライル" , arabic = "أُحِبّ اَلْقِراءة عَن كوبا بِالْلَّيْل" , meaning = "I like reading about Cuba at night." } , { latin = "2uHibb al-kalaam 3an il-kitaaba" , kana = "ウひッブ アル カラーム アニル キターバ" , arabic = "أحِبّ اَلْكَلام عَن اَلْكِتابة" , meaning = "I like talking about writing." } , { latin = "alqur2aan" , kana = "アルクルアーン" , arabic = "اَلْقُرْآن" , meaning = "Koran" } , { latin = "bayt jamiil" , kana = "バイト ジャミール" , arabic = "بَيْت جَميل" , meaning = "a pretty house" } , { latin = "mutarjim mumtaaz" , kana = "ムタるジム ムムターズ" , arabic = "مُتَرْجِم مُمْتاز" , meaning = "an amazing translator" } , { latin = "jaami3a mash-huura" , kana = "ジャーミア マシュフーラ" , arabic = "جامِعة مَشْهورة" , meaning = "a famous university" } , { latin = "al-bayt al-jamiil" , kana = "アルバイト アルジャミール" , arabic = "اَلْبَيْت اَلْجَميل" , meaning = "the pretty house" } , { latin = "al-bint a-s-suuriyya" , kana = "アル ビンタ ッスーリヤ" , arabic = "اَلْبِنْت اَلْسّورِيّة" , meaning = "a Syrian girl" } , { latin = "al-mutarjim al-mumtaaz" , kana = "アルムタルジム アルムムターズ" , arabic = "اَلْمُتَرْجِم اَلْمُمْتاز" , meaning = "the amazing translator" } , { latin = "al-jaami3a al-mash-huura" , kana = "アルジャーミア アルマシュフーラ" , arabic = "اَلْجامِعة اَلْمَشْهورة" , meaning = "the famous university" } , { latin = "al-bayt jamiil" , kana = "アルバイト ジャミール" , arabic = "اَلْبَيْت جَميل" , meaning = "The house is pretty." } , { latin = "al-bint suuriyya" , kana = "アルビント スーリーヤ" , arabic = "البنت سورِيّة" , meaning = "The girl is Syrian." } , { latin = "al-mutarjim mumtaaz" , kana = "アルムタルジム ムムターズ" , arabic = "اَلْمُتَرْجِم مُمْتاز" , meaning = "The translator is amazing." } , { latin = "al-jaami3a mash-huura" , kana = "アルジャーミア マシュフーラ" , arabic = "اَلْجامِعة مَشْهورة" , meaning = "The university is famous." } , { latin = "maTar" , kana = "マタル" , arabic = "مَطَر" , meaning = "rain" } , { latin = "yawm Tawiil" , kana = "ヤウム タウィール" , arabic = "يَوْم طَويل" , meaning = "a long day" } , { latin = "haadhaa yawm Tawiil" , kana = "ハーザー ヤウム タウィール" , arabic = "هَذا يَوْم طَويل" , meaning = "This is a long day." } , { latin = "shanTa fafiifa" , kana = "シャンタ ファフィーファ" , arabic = "شَنْطة خَفيفة" , meaning = "a light bag" } , { latin = "al-maTar a-th-thaqiil mumtaaz" , kana = "アルマタル アッサキール ムムターズ" , arabic = "اَلْمَطَر اَلْثَّقيل مُمْتاز" , meaning = "The heavy rain is amazing." } , { latin = "Taqs ghariib" , kana = "タクス ガリーブ" , arabic = "طَقْس غَريب" , meaning = "a weird weather" } , { latin = "yawm Haarr" , kana = "ヤウム ハール" , arabic = "يَوْم حارّ" , meaning = "a hot day" } , { latin = "Taawila khafiifa" , kana = "ターウィラ クハフィーファ" , arabic = "طاوِلة خَفيفة" , meaning = "a light table" } , { latin = "Taqs jamiil" , kana = "タクス ジャミール" , arabic = "طَقْس جَميل" , meaning = "a pretty weather" } , { latin = "al-maTar a-th-thaqiil mumtaaz" , kana = "アルマタル アッサキール ムムターズ" , arabic = "اَلْمَطَر اَلْثَّقيل مُمْتاز" , meaning = "The heavy rain is amazing." } , { latin = "haadhaa yawm Haarr" , kana = "ハーザー ヤウム ハール" , arabic = "هَذا يَوْم حارّ" , meaning = "This is a hot day." } , { latin = "shanTa khafiifa" , kana = "シャンタ クハフィーファ" , arabic = "شَنْطة خَفيفة" , meaning = "a light bag" } , { latin = "hunaak maTar baarid jiddan" , kana = "フゥナーク マタル バーリド ジッダン" , arabic = "هُناك مَطَر بارِد جِدّاً" , meaning = "There is a very cold rain." } , { latin = "Sayf" , kana = "サイフ" , arabic = "صّيْف" , meaning = "summer" } , { latin = "shitaa2" , kana = "シター" , arabic = "شِتاء" , meaning = "winter" } , { latin = "shitaa2 baarid" , kana = "シター バーリド" , arabic = "شِتاء بارِد" , meaning = "cold winter" } , { latin = "binaaya 3aalya" , kana = "ビナーヤ アーリヤ" , arabic = "بِناية عالْية" , meaning = "a high building" } , { latin = "yawm baarid" , kana = "ヤウム バーリド" , arabic = "يَوْم بارِد" , meaning = "a cold day" } , { latin = "ruTuuba 3aalya" , kana = "ルトゥーバ アーリヤ" , arabic = "رُطوبة عالْية" , meaning = "high humidity" } , { latin = "Sayf mumTir" , kana = "サイフ ムムティル" , arabic = "صَيْف مُمْطِر" , meaning = "a rainy summer" } , { latin = "a-r-ruTuubat al3aalya" , kana = "アッルルトゥーバト アラーリヤ" , arabic = "اَلْرُّطوبة الْعالْية" , meaning = "the high humidity" } , { latin = "a-T-Taqs al-mushmis" , kana = "アッタクス アルムシュミス" , arabic = "اّلْطَّقْس الّْمُشْمِس" , meaning = "the sunny weather" } , { latin = "shitaa2 mumTir" , kana = "シター ムムティル" , arabic = "شِتاء مُمْطِر" , meaning = "a rainy winter" } , { latin = "Sayf Haarr" , kana = "サイフ ハール" , arabic = "صَيْف حارّ" , meaning = "a hot summer" } , { latin = "al-yawm yawm Tawiil" , kana = "アルヤウム ヤウム タウィール" , arabic = "اَلْيَوْم يَوْم طَويل" , meaning = "Today is a long day." } , { latin = "laa 2uhibb a-T-Taqs al-mushmis" , kana = "ラー ウひッブ アッタクス アルムシュミス" , arabic = "لا أُحِبّ اَلْطَقْس اَلْمُشْمِس" , meaning = "I do not like sunny weather." } , { latin = "a-T-Taqs mumTir jiddan al-yawm" , kana = "アッタクス ムムティル ジッダン アルヤウム" , arabic = "اَلْطَقْس مُمْطِر جِدّاً اَلْيَوْم" , meaning = "The weather is very rainy today." } , { latin = "laa 2uhibb a-T-Taqs al-mumTir" , kana = "ラー ウひッブ アッタクス アルムティル" , arabic = "لا أحِبّ اَلْطَّقْس اَلْمُمْطِر" , meaning = "I do not like the rainy weather." } , { latin = "a-T-Taqs mushmis al-yawm" , kana = "アッタクス ムシュミス アルヤウム" , arabic = "اَلْطَّقْس مُشْمِس اَلْيَوْم" , meaning = "The weather is sunny today." } , { latin = "khariif" , kana = "ハリーフ" , arabic = "خَريف" , meaning = "fall, autumn" } , { latin = "qamar" , kana = "カマル" , arabic = "قَمَر" , meaning = "moon" } , { latin = "rabii3" , kana = "ラビーア" , arabic = "رَبيع" , meaning = "spring" } , { latin = "a-sh-shitaa2 mumTir" , kana = "アッシター ムムティル" , arabic = "اَلْشِّتاء مُمْطِر" , meaning = "The winter is rainy." } , { latin = "a-S-Sayf al-baarid" , kana = "アッサイフ アルバーリド" , arabic = "اَلْصَّيْف اَلْبارِد" , meaning = "the cold summer" } , { latin = "al-qamar al-2abyaD" , kana = "アルカマル アルアビヤド" , arabic = "اَلْقَمَر اَلْأَبْيَض" , meaning = "the white moon" } , { latin = "a-sh-shitaa2 Tawiil wa-baarid" , kana = "アッシター タウィール ワ バーリド" , arabic = "اَلْشِّتاء طَويل وَبارِد" , meaning = "The winter is long and cold." } , { latin = "a-r-rabii3 mumTir al-2aan" , kana = "アッラビーア ムムティル アルアーン" , arabic = "اَلْرَّبيع مُمْطِر اَلآن" , meaning = "The spring is rainy now" } , { latin = "Saghiir" , kana = "サギール" , arabic = "صَغير" , meaning = "small" } , { latin = "kashiiran" , kana = "カシーラン" , arabic = "كَثيراً" , meaning = "a lot, much" } , { latin = "a-S-Siin" , kana = "アッスィーン" , arabic = "اَلْصّين" , meaning = "China" } , { latin = "al-qaahira" , kana = "アル カーヒラ" , arabic = "اَلْقاهِرة" , meaning = "Cairo" } , { latin = "al-bunduqiyya" , kana = "アル ブンドゥキーヤ" , arabic = "اَلْبُنْدُقِية" , meaning = "Venice" } , { latin = "filasTiin" , kana = "フィラスティーン" , arabic = "فِلَسْطين" , meaning = "Palestine" } , { latin = "huulandaa" , kana = "フーランダー" , arabic = "هولَنْدا" , meaning = "Netherlands, Holland" } , { latin = "baghdaad" , kana = "バグダード" , arabic = "بَغْداد" , meaning = "Bagdad" } , { latin = "Tuukyuu" , kana = "トーキョー" , arabic = "طوكْيو" , meaning = "Tokyo" } , { latin = "al-yaman" , kana = "アル ヤマン" , arabic = "اَلْيَمَن" , meaning = "Yemen" } , { latin = "SaaHil Tawiil" , kana = "サーヒル タウィール" , arabic = "ساحَل طَويل" , meaning = "a long coast" } , { latin = "al-2urdun" , kana = "アル ウルドゥン" , arabic = "اَلْأُرْدُن" , meaning = "Jordan" } , { latin = "haadha l-balad" , kana = "ハーザ ル バラド" , arabic = "هَذا الْبَلَد" , meaning = "this country" } , { latin = "2ayn baladik yaa riim" , kana = "アイン バラディク ヤー リーム" , arabic = "أَيْن بَلَدِك يا ريم" , meaning = "Where is your country, Reem?" } , { latin = "baladii mumtaaz" , kana = "バラディー ムムターズ" , arabic = "بَلَدي مُمْتاز" , meaning = "My country is amazing." } , { latin = "haadhaa balad-haa" , kana = "ハーザー バラドハー" , arabic = "هَذا بَلَدها" , meaning = "This is her country." } , { latin = "hal baladak jamiil yaa juurj?" , kana = "ハル バラダク ジャミール ヤー ジュールジュ" , arabic = "هَل بَلَدَك جَميل يا جورْج" , meaning = "Is your country pretty, George" } , { latin = "al-yaman balad Saghiir" , kana = "アルヤマン バラド サギール" , arabic = "اَلْيَمَن بَلَد صَغير" , meaning = "Yemen is a small country." } , { latin = "qaari2" , kana = "カーリー" , arabic = "قارِئ" , meaning = "reader" } , { latin = "ghaa2ib" , kana = "ガーイブ" , arabic = "غائِب" , meaning = "absent" } , { latin = "mas2uul" , kana = "マスウール" , arabic = "مَسْؤول" , meaning = "responsoble, administrator" } , { latin = "jaa2at" , kana = "ジャーアト" , arabic = "جاءَت" , meaning = "she came" } , { latin = "3indii" , kana = "アインディー" , arabic = "عِنْدي" , meaning = "I have" } , { latin = "3indik" , kana = "アインディク" , arabic = "عِنْدِك" , meaning = "you have" } , { latin = "ladii kitaab" , kana = "ラディー キターブ" , arabic = "لَدي كِتاب" , meaning = "I have a book." } , { latin = "3indhaa" , kana = "アインドハー" , arabic = "عِنْدها" , meaning = "she has" } , { latin = "3indhu" , kana = "アインドフゥ" , arabic = "عِنْدهُ" , meaning = "he has" } , { latin = "laysa 3indhu" , kana = "ライサ アインドフゥ" , arabic = "لَيْسَ عِنْدهُ" , meaning = "he does not have" } , { latin = "laysa 3indhaa" , kana = "ライサ アインドハー" , arabic = "لَيْسَ عِنْدها" , meaning = "she does not have" } , { latin = "hunaak maTar thaqiil" , kana = "フゥナーク マタル サキール" , arabic = "هُناك مَطَر ثَقيل" , meaning = "There is a heavy rain." } , { latin = "hunaak wishaaH fii shanTatii" , kana = "フゥナーク ウィシャーハ フィー シャンタティー" , arabic = "هُناك وِشاح في شَنْطتي" , meaning = "There is a scarf in my bag." } , { latin = "2amaamii rajul ghariib" , kana = "アマーマミー ラジュル ガリーブ" , arabic = "أَمامي رَجُل غَريب" , meaning = "There is a weird man in front of me." } , { latin = "fi l-khalfiyya bayt" , kana = "フィル クハルフィーヤ バイト" , arabic = "في الْخَلفِيْة بَيْت" , meaning = "There is a house in the background." } , { latin = "fii shanTatii wishaaH" , kana = "フィー シャンタティー ウィシャーハ" , arabic = "في شَنْطَتي وِشاح" , meaning = "There is a scarf in my bag." } , { latin = "2asad" , kana = "アサド" , arabic = "أَسَد" , meaning = "a lion" } , { latin = "2uHibb 2asadii laakinn laa 2uHibb 2asadhaa" , kana = "ウひッブ アサディ ラキン ラー ウひッブ アサドハー" , arabic = "أحِبَ أَسَدي لَكِنّ لا أُحِبّ أَسَدها" , meaning = "I like my lion but I do not like her lion." } , { latin = "laysa 3indhu" , kana = "ライサ アインドフゥ" , arabic = "لَيْسَ عِنْدهُ" , meaning = "he does not have" } , { latin = "3indhaa kalb wa-qiTTa" , kana = "アインドハー カルブ ワ キッタ" , arabic = "عِنْدها كَلْب وَقِطّة" , meaning = "She has a doc and a cat." } , { latin = "Sadiiqat-hu saamia ghaniyya" , kana = "すぁディーかトフゥ サーミヤ ガニーヤ" , arabic = "صَديقَتهُ سامْية غَنِيّة" , meaning = "His friend Samia is rich." } , { latin = "taariikhiyya" , kana = "ターリークヒーヤ" , arabic = "تاريخِيّة" , meaning = "historical" } , { latin = "juurj 3indhu 3amal mumtaaz" , kana = "ジュールジュ アインドフゥ アアマル ムムターズ" , arabic = "جورْج عِنْدهُ عَمَل مُمْتاز" , meaning = "George has an amazing work." } , { latin = "Sadiiqii taamir ghaniyy jiddan" , kana = "サディーキー ターミル ガニーイ ジッダン" , arabic = "صَديقي تامِر غَنِيّ جِدّاً" , meaning = "My friend Tamer is very rich" } , { latin = "laa 2a3rif haadha l-2asad" , kana = "ラー アーリフ ハーザ ル アサド" , arabic = "لا أَعْرِف هَذا الْأَسّد" , meaning = "I do not know this lion." } , { latin = "laysa 3indhu ma3Taf" , kana = "ライサ アインドフゥ マアタフ" , arabic = "لَيْسَ عِنْدهُ معْطَف" , meaning = "He does not have a coat." } , { latin = "fi l-khalfiyya zawjatak yaa siith" , kana = "フィ ル クハルフィーヤ ザウジャタク ヤー スィース" , arabic = "في الْخَلْفِيّة زَوْجَتَك يا سيث" , meaning = "There is your wife in background, Seth" } , { latin = "su2uaal" , kana = "スウアール" , arabic = "سُؤال" , meaning = "a question" } , { latin = "Sadiiqat-hu saamya laabisa tannuura" , kana = "すぁディーかトフゥ サーミヤ ラービサ タンヌーラ" , arabic = "صدَيقَتهُ سامْية لابِسة تّنّورة" , meaning = "His friend Samia is wearing a skirt." } , { latin = "wa-hunaa fi l-khalfiyya rajul muD-Hik" , kana = "ワ フゥナー フィル クハルフィーヤ ラジュル ムドヒク" , arabic = "وَهُنا في الْخَلْفِتّة رَجُل مُضْحِك" , meaning = "And here in the background there is a funny man." } , { latin = "man haadhaa" , kana = "マン ハーザー" , arabic = "مَن هَذا" , meaning = "Who is this?" } , { latin = "hal 2anti labisa wishaaH yaa lamaa" , kana = "ハル アンティ ラビサ ウィシャーハ ヤー ラマー" , arabic = "هَل أَنْتِ لابِسة وِشاح يا لَمى" , meaning = "Are you wering a scarf, Lama?" } , { latin = "2akhii bashiir mashghuul" , kana = "アクヒー バシール マシュグール" , arabic = "أَخي بَشير مَشْغول" , meaning = "My brother Bashir is busy." } , { latin = "fii haadhihi a-S-Suura imraa muD-Hika" , kana = "フィー ハージヒ アッスーラ イムラア ムドヒカ" , arabic = "في هَذِهِ الْصّورة اِمْرأة مُضْحِكة" , meaning = "Thre is a funny woman in this picture." } , { latin = "hal 2anta laabis qubb3a yaa siith" , kana = "ハル アンタ ラービス クッバ ヤー スィース" , arabic = "هَل أَنْتَ لابِس قُبَّعة يا سيث" , meaning = "Are you wearing a hat, Seth?" } , { latin = "fi l-khalfiyya rajul muD-Hik" , kana = "フィル クハルフィーヤ ラジュル ムドヒク" , arabic = "في الْخَلْفِيّة رَجُل مُضْحِك" , meaning = "There is a funny man in the background." } , { latin = "shub-baak" , kana = "シュッバーク" , arabic = "شُبّاك" , meaning = "a window" } , { latin = "sariir" , kana = "サリール" , arabic = "سَرير" , meaning = "a bed" } , { latin = "saadii 2ustaadhii" , kana = "サーディー ウスタージー" , arabic = "شادي أُسْتاذي" , meaning = "Sadie is my teacher." } , { latin = "2ummhu" , kana = "ウンムフゥ" , arabic = "أُمّهُ" , meaning = "his mother" } , { latin = "maa haadhaa a-S-Sawt" , kana = "マー ハーザー アッサウト" , arabic = "ما هَذا الْصَّوْت" , meaning = "What is this noise" } , { latin = "2adkhul al-Hammaam" , kana = "アドクフル アルハンマーム" , arabic = "أَدْخُل اَلْحَمّام" , meaning = "I enter the bathroom." } , { latin = "2uHibb a-s-sariir al-kabiir" , kana = "ウひッブ アッサリール アルカビール" , arabic = "أُحِبّ اَلْسَّرير اَلْكَبير" , meaning = "I love the big bed." } , { latin = "hunaak Sawt ghariib fi l-maTbakh" , kana = "フゥナーク サウト ガリーブ フィル マトバクフ" , arabic = "هُناك صَوْت غَريب في الْمَطْبَخ" , meaning = "There is a weird nose in the kitchen." } , { latin = "2anaam fi l-ghurfa" , kana = "アナーム フィル グルファ" , arabic = "أَنام في الْغُرْفة" , meaning = "I sleep in the room." } , { latin = "tilfaaz Saghiir fii Saaluun kabiir" , kana = "ティルファーズ サギール フィー サールーン カビール" , arabic = "تِلْفاز صَغير في صالون كَبير" , meaning = "a small television in a big living room" } , { latin = "2anaam fii sariir maksuur" , kana = "アナーム フィー サリール マクスール" , arabic = "أَنام في سَرير مَكْسور" , meaning = "I sleep in a broken bed." } , { latin = "a-s-sariir al-kabiir" , kana = "アッサリール アルカビール" , arabic = "اَلْسَّرير اَلْكَبير" , meaning = "the big bed" } , { latin = "maa haadhaa a-S-Swut" , kana = "マー ハーザー アッスウト" , arabic = "ما هَذا الصّوُت" , meaning = "What is this noise?" } , { latin = "sariirii mumtaaz al-Hamdu li-l-laa" , kana = "サリーリー ムムターズ アルハムド リッラー" , arabic = "سَريري مُمتاز اَلْحَمْدُ لِله" , meaning = "My bed is amazing, praise be to God" } , { latin = "2anaam kathiiran" , kana = "アナーム カシーラン" , arabic = "أَنام كَشيراً" , meaning = "I sleep a lot" } , { latin = "hunaak Sawt ghariib" , kana = "フゥナーク サウト ガリーブ" , arabic = "هُناك صَوْت غَريب" , meaning = "There is a weird noise." } , { latin = "shub-baak" , kana = "シュッバーク" , arabic = "شُبّاك" , meaning = "a window" } , { latin = "2anaam fii sariir Saghiir" , kana = "アナーム フィー サリール サギール" , arabic = "أَنام في سَرير صَغير" , meaning = "I sleep in a small bed." } , { latin = "muHammad 2ustaadhii" , kana = "ムハンマド ウスタージー" , arabic = "مُحَمَّد أُسْتاذي" , meaning = "Mohammed is my teacher." } , { latin = "mahaa 2ummhu" , kana = "マハー ウンムフゥ" , arabic = "مَها أُمّهُ" , meaning = "Maha is his mother." } , { latin = "fii haadhaa sh-shaari3 Sawt ghariib" , kana = "フィー ハーザー ッシャーリア サウト ガリーブ" , arabic = "في هٰذا ٱلْشّارِع صَوْت غَريب" , meaning = "There is a weird noise on this street" } , { latin = "2askun fii a-s-saaluun" , kana = "アスクン フィー アッサルーン" , arabic = "أَسْكُن في الْصّالون" , meaning = "I live in the living room." } , { latin = "haadhaa sh-shaari3" , kana = "ハーザー ッシャーリア" , arabic = "هَذا الْشّارِع" , meaning = "this street" } , { latin = "3ind-hu ghurfa nawm Saghiira" , kana = "アインドフゥ グルファ ナウム サギーラ" , arabic = "عِندهُ غُرْفة نَوْم صَغيرة" , meaning = "He has a small bedroom." } , { latin = "laa 2aftaH albaab bisabab l-T-Taqs" , kana = "ラー アフタフ アルバーブ ビサバブ ルッタクス" , arabic = "لا أَفْتَح اَلْباب بِسَبَب اّلْطَّقْس" , meaning = "I do not open the door because of the weather." } , { latin = "Sifr" , kana = "スィフル" , arabic = "صِفْر" , meaning = "zero" } , { latin = "3ashara" , kana = "アシャラ" , arabic = "عَشَرَة" , meaning = "ten" } , { latin = "waaHid" , kana = "ワーヒド" , arabic = "وَاحِد" , meaning = "one" } , { latin = "2ithnaan" , kana = "イスナーン" , arabic = "اِثْنان" , meaning = "two" } , { latin = "kayf ta3uddiin min waaHid 2ilaa sitta" , kana = "カイフ タアウッディーン ミン ワーヒド イラー スィッタ" , arabic = "كَيْف تَعُدّين مِن ١ إِلى ٦" , meaning = "How do you count from one to six?" } , { latin = "bil-lugha" , kana = "ビッルガ" , arabic = "بِالْلُّغة" , meaning = "in language" } , { latin = "bil-lugha l-3arabiya" , kana = "ビッルガルアラビーヤ" , arabic = "بِالْلُّغة الْعَرَبِيّة" , meaning = "in the arabic language" } , { latin = "ta3rifiin" , kana = "ターリフィーン" , arabic = "تَعْرِفين" , meaning = "you know" } , { latin = "hal ta3rifiin kull shay2 yaa mahaa" , kana = "ハル ターリフィーン クル シャイ ヤー マハー" , arabic = "هَل تَعْرِفين كُلّ شَيء يا مَها" , meaning = "Do you know everything Maha?" } , { latin = "kayf ta3udd yaa 3umar" , kana = "カイフ タアウッド ヤ ウマル" , arabic = "كَيْف تَعُدّ يا عُمَر" , meaning = "How do you count Omar?" } , { latin = "Kayf ta3udd min Sifr 2ilaa 2ashara yaa muHammad" , kana = "カイフ タアウッド ミン スィフル イラー アシャラ ヤー ムハンマド" , arabic = "كَيْف تَعُدّ مِن٠ إِلى ١٠ يا مُحَمَّد" , meaning = "How do you count from 0 to 10 , Mohammed?" } , { latin = "hal ta3rif yaa siith" , kana = "ハル ターリフ ヤー スィース" , arabic = "هَل تَعْرِف يا سيث" , meaning = "Do you know Seth?" } , { latin = "bayt buub" , kana = "バイト ブーブ" , arabic = "بَيْت بوب" , meaning = "Bob's house" } , { latin = "maT3am muHammad" , kana = "マタム ムハンマド" , arabic = "مَطْعَم مُحَمَّد" , meaning = "Mohammed's restaurant" } , { latin = "SaHiifat al-muhandis" , kana = "サヒーファト アル ムハンディス" , arabic = "صَحيفة اَلْمُهَنْدِس" , meaning = "the enginner's newspaper" } , { latin = "madiinat diitruuyt" , kana = "マディーナト ディートルーイト" , arabic = "مَدينة ديتْرويْت" , meaning = "the city of Detroit" } , { latin = "jaami3a juurj waashinTun" , kana = "ジャーミア ジュールジュ ワーシントン" , arabic = "جامِعة جورْج واشِنْطُن" , meaning = "George Washinton University" } , { latin = "SabaaHan" , kana = "サバーハン" , arabic = "صَباحاً" , meaning = "in the morning" } , { latin = "masaa2an" , kana = "マサーアン" , arabic = "مَساءً" , meaning = "in the evening" } , { latin = "wilaayatak" , kana = "ウィラーヤタク" , arabic = "وِلايَتَك" , meaning = "your state" } , { latin = "madiina saaHiliyya" , kana = "マディーナ サーヒリーヤ" , arabic = "مَدينة ساحِلِيّة" , meaning = "a coastal city" } , { latin = "muzdaHima" , kana = "ムズダヒマ" , arabic = "مُزْدَحِمة" , meaning = "crowded" } , { latin = "wilaaya kaaliifuurniyaa" , kana = "ウィラーヤ カーリーフールニヤー" , arabic = "وِلاية كاليفورْنْيا" , meaning = "the state of California" } , { latin = "baHr" , kana = "バハル" , arabic = "بَحْر" , meaning = "sea" } , { latin = "DawaaHii" , kana = "ダワーヒー" , arabic = "ضَواحي" , meaning = "suburbs" } , { latin = "taskuniin" , kana = "タスクニーン" , arabic = "تَسْكُنين" , meaning = "you live" } , { latin = "nyuuyuurk" , kana = "ニューユールク" , arabic = "نْيويورْك" , meaning = "New York" } , { latin = "qar-yatik" , kana = "かるヤティク" , arabic = "قَرْيَتِك" , meaning = "your (to female) village" } , { latin = "shubbaak" , kana = "シュッバーク" , arabic = "شُبّاك" , meaning = "a window" } , { latin = "jaziira" , kana = "ジャズィーラ" , arabic = "جَزيرة" , meaning = "an island" } , { latin = "Tabii3a" , kana = "タビーア" , arabic = "طَبيعة" , meaning = "nature" } , { latin = "al-2iskandariyya" , kana = "アル イスカンダリーヤ" , arabic = "اَلْإِسْكَندَرِيّة" , meaning = "Alexandria" } , { latin = "miSr" , kana = "ミスル" , arabic = "مِصْر" , meaning = "Egypt" } , { latin = "na3am" , kana = "ナアム" , arabic = "نَعَم" , meaning = "yes" } , { latin = "SabaaH l-khayr" , kana = "サバーフ ル クハイル" , arabic = "صَباح اَلْخَيْر" , meaning = "Good morning." } , { latin = "SabaaH an-nuur" , kana = "サバーフ アン ヌール" , arabic = "صَباح اَلْنّور" , meaning = "Good morning." } , { latin = "masaa2 al-khayr" , kana = "マサー アル クハイル" , arabic = "مَساء اَلْخَيْر" , meaning = "Good evening" } , { latin = "masaa2 an-nuur" , kana = "マサー アンヌール" , arabic = "مَساء اَلْنّور" , meaning = "Good evening." } , { latin = "tasharrafnaa" , kana = "タシャッラフゥナー" , arabic = "تَشَرَّفْنا" , meaning = "It's a pleasure to meet you." } , { latin = "hal 2anta bi-khyr" , kana = "ハル アンタ ビ クハイル" , arabic = "هَل أَنْتَ بِخَيْر" , meaning = "Are you well?" } , { latin = "kayfak" , kana = "カイファク" , arabic = "كَيْفَك" , meaning = "How are you?" } , { latin = "al-yawm" , kana = "アル ヤウム" , arabic = "اَلْيَوْم" , meaning = "today" } , { latin = "kayfik al-yawm" , kana = "カイフィク アル ヤウム" , arabic = "كَيْفِك اَلْيَوْم" , meaning = "How are you today?" } , { latin = "marHaban ismii buub" , kana = "マルハバン イスミー ブーブ" , arabic = "مَرْحَباً اِسْمي بوب" , meaning = "Hello, my name is Bob." } , { latin = "mariiD" , kana = "マリード" , arabic = "مَريض" , meaning = "sick" } , { latin = "yawm sa3iid" , kana = "ヤウム サアイード" , arabic = "يَوْم سَعيد" , meaning = "Have a nice day." } , { latin = "sa3iid" , kana = "サアイード" , arabic = "سَعيد" , meaning = "happy" } , { latin = "2anaa Haziinat l-yawm" , kana = "アナー ハズィーナト ル ヤウム" , arabic = "أَنا حَزينة الْيَوْم" , meaning = "I am sad today." } , { latin = "2anaa Haziin jiddan" , kana = "アナー ハズィーン ジッダン" , arabic = "أَنا حَزين جِدّاً" , meaning = "I am very sad." } , { latin = "2anaa mariiDa lil2asaf" , kana = "アナー マリーダ リルアサフ" , arabic = "أَنا مَريضة لِلْأَسَف" , meaning = "I am sick unfortunately." } , { latin = "2ilaa l-liqaa2 yaa Sadiiqii" , kana = "イラー ッリカー ヤー サディーキイ" , arabic = "إِلى الْلِّقاء يا صَديقي" , meaning = "Until next time, my friend." } , { latin = "na3saana" , kana = "ナアサーナ" , arabic = "نَعْسانة" , meaning = "sleepy" } , { latin = "mutaHammis" , kana = "ムタハムミス" , arabic = "مُتَحَمِّس" , meaning = "excited" } , { latin = "maa smak" , kana = "マー スマク" , arabic = "ما إسْمَك" , meaning = "What is your name?" } , { latin = "2anaa na3saan" , kana = "アナー ナアサーン" , arabic = "أَنا نَعْسان" , meaning = "I am sleepy." } , { latin = "yal-laa 2ilaa l-liqaa2" , kana = "ヤッラー イラー ッリカー" , arabic = "يَلّإِ إِلى الْلَّقاء" , meaning = "Alright, until next time." } , { latin = "ma3a as-salaama" , kana = "マア アッサラーマ" , arabic = "مَعَ الْسَّلامة" , meaning = "Goodbye." } , { latin = "tamaam" , kana = "タマーム" , arabic = "تَمام" , meaning = "OK" } , { latin = "2anaatamaam al-Hamdu li-l-laa" , kana = "アナ タマーム アル ハムドゥ リッラー" , arabic = "أَنا تَمام اَلْحَمْدُ لِله" , meaning = "I am OK , praise be to God." } , { latin = "maa al2akhbaar" , arabic = "ما الْأَخْبار" , meaning = "What is new?" } , { latin = "al-bathu alhii" , kana = "アル バス アルヒー" , arabic = "اَلْبَثُ اَلْحي" , meaning = "live broadcast" } , { latin = "2ikhtar" , kana = "イクフタル" , arabic = "إِخْتَر" , meaning = "choose" } , { latin = "sayyaara" , kana = "サイヤーラ" , arabic = "سَيّارة" , meaning = "a car" } , { latin = "2akh ghariib" , kana = "アクフ ガリーブ" , arabic = "أَخ غَريب" , meaning = "a weird brother" } , { latin = "2ukht muhimma" , kana = "ウクフト ムヒムマ" , arabic = "أُخْت مُهِمّة" , meaning = "an important sister" } , { latin = "ibn kariim wa-mumtaaz" , kana = "イブン カリーム ワ ムムターズ" , arabic = "اِبْن كَريم وَمُمْتاز" , meaning = "a generous and amazing son" } , { latin = "2ab" , kana = "アブ" , arabic = "أَب" , meaning = "a father" } , { latin = "2umm" , kana = "ウンム" , arabic = "أُمّ" , meaning = "a mother" } , { latin = "ibn" , kana = "イブン" , arabic = "اِبْن" , meaning = "a son" } , { latin = "mumti3" , kana = "ムムティア" , arabic = "مُمْتِع" , meaning = "fun" } , { latin = "muHaasib" , kana = "ムハースィブ" , arabic = "مُحاسِب" , meaning = "an accountant" } , { latin = "ma-smika ya 2ustaadha" , kana = "マスミカ ヤー ウスターザ" , arabic = "ما اسْمِك يا أُسْتاذة" , meaning = "What is your name ma'am?" } , { latin = "qiTTatak malika" , kana = "キッタタク マリカ" , arabic = "قِطَّتَك مَلِكة" , meaning = "Your cat is a queen." } , { latin = "jadda laTiifa wa-jadd laTiif" , kana = "ジャッダ ラティーファ ワ ジャッド ラティーフ" , arabic = "جَدّة لَطيفة وَجَدّ لَطيف" , meaning = "a kind grandmother and a kind grandfather" } , { latin = "qiTTa jadiida" , kana = "キッタ ジャディーダ" , arabic = "قِطّة جَديدة" , meaning = "a new cat" } , { latin = "hal jaddatak 2ustaadha" , kana = "ハル ジャーダタック ウスターザ" , arabic = "هَل جَدَّتَك أُسْتاذة" , meaning = "Is your grandmother a professor?" } , { latin = "hal zawjatak 2urduniyya" , arabic = "هَل زَوْجَتَك أُرْدُنِتّة" , meaning = "Is your wife a Jordanian?" } , { latin = "mu3allim" , kana = "ムアッリム" , arabic = "مُعَلِّم" , meaning = "a teacher" } , { latin = "dhakiyya" , kana = "ザキーヤ" , arabic = "ذَكِيّة" , meaning = "smart" } , { latin = "ma3Taf" , kana = "マアタフ" , arabic = "مَعْطَف" , meaning = "a coat" } , { latin = "qubba3a zarqaa2 wa-bunniyya" , kana = "くッバ ザルかー ワ ブンニーヤ" , arabic = "قُبَّعة زَرْقاء وَبُنّية" , meaning = "a blue ad brown hat" } , { latin = "bayDaa2" , kana = "バイダー" , arabic = "بَيْضاء" , meaning = "white" } , { latin = "al-2iijaar jayyid al-Hamdu li-l-laa" , kana = "アル イージャール ジャイイド アル ハムドゥ リッラー" , arabic = "اَلْإِيجار جَيِّد اَلْحَمْدُ لِله" , meaning = "The rent is good, praise be to God." } , { latin = "jaami3a ghaalya" , kana = "ジャーミア ガーリヤ" , arabic = "جامِعة غالْية" , meaning = "an expensive university" } , { latin = "haadhaa Saaluun qadiim" , kana = "ハーザー サルーン カディーム" , arabic = "هَذا صالون قَديم" , meaning = "This is an old living room." } , { latin = "haadhihi Hadiiqa 3arabiyya" , kana = "ハーディヒ ハディーカ アラビーヤ" , arabic = "هَذِهِ حَديقة عَرَبِيّة" , meaning = "This is an Arabian guarden." } , { latin = "al-HaaiT" , kana = "アル ハーイト" , arabic = "اَلْحائِط" , meaning = "the wall" } , { latin = "hunaak shanTa Saghiira" , kana = "フゥナーク シャンタ サギーラ" , arabic = "هُناك شَنطة صَغيرة" , meaning = "There is a small bag." } , { latin = "2abii hunaak" , kana = "アビー フゥナーク" , arabic = "أَبي هُناك" , meaning = "My father is there." } , { latin = "haatifak hunaak yaa buub" , kana = "ハーティファク フゥナーク ヤー ブーブ" , arabic = "هاتِفَك هُناك يا بوب" , meaning = "Your telephone is there, Bob." } , { latin = "haatifii hunaak" , kana = "ハーティフィー フゥナーク" , arabic = "هاتِفي هُناك" , meaning = "My telephone is there." } , { latin = "hunaak 3ilka wa-laab tuub fii shanTatik" , kana = "フゥナーク アイルカ ワ ラーブトゥーブ フィー シャンタティク" , arabic = "هُناك عِلكة وَلاب توب في شَنطَتِك" , meaning = "There is a chewing gum and a laptop in your bag." } , { latin = "raSaaS" , kana = "ラサース" , arabic = "رَصاص" , meaning = "lead" } , { latin = "qalam raSaaS" , kana = "カラム ラサース" , arabic = "قَلَم رَصاص" , meaning = "a pencil" } , { latin = "mu2al-lif" , kana = "ムアッリフ" , arabic = "مُؤَلِّف" , meaning = "an author" } , { latin = "shaahid al-bath-t il-Hayy" , kana = "シャーヒド アル バスト アル ハイイ" , arabic = "شاهد البث الحي" , meaning = "Watch the live braodcast" } , { latin = "2a3iish" , kana = "アーイーシュ" , arabic = "أَعيش" , meaning = "I live" } , { latin = "2a3iish fi l-yaabaan" , kana = "アーイーシュ フィ ル ヤーバーン" , arabic = "أَعيش في لايابان" , meaning = "I live in Japan." } , { latin = "2anaa 2ismii faaTima" , kana = "アナー イスミー ファーティマ" , arabic = "أَنا إِسمي فاطِمة" , meaning = "My name is Fatima (female name)." } , { latin = "2a3iish fii miSr" , kana = "アーイーシュ フィー ミスル" , arabic = "أَعيش في مِصر" , meaning = "I live in Egypt." } , { latin = "al3mr" , kana = "アラームル" , arabic = "العمر" , meaning = "age" } , { latin = "2ukhtii wa-Sadiiqhaa juurj" , kana = "ウクフティー ワ サディークハー ジュールジュ" , arabic = "أُخْتي وَصَديقهل جورْج" , meaning = "my sister and her friend George" } , { latin = "3amalii" , kana = "アアマリー" , arabic = "عَمَلي" , meaning = "my work" } , { latin = "haadhihi Sadiiqat-hu saamiya" , kana = "ハージヒ すぁディーかトフゥ サーミア" , arabic = "هَذِهِ صَديقَتهُ سامية" , meaning = "This is his girlfriend Samia." } , { latin = "shitaa2" , kana = "シター" , arabic = "شِتاء" , meaning = "winter" } , { latin = "Sayf mumTil" , kana = "サイフ ムムティル" , arabic = "صَيْف مُمْطِر" , meaning = "a rainy summer" } , { latin = "3aalya" , kana = "アーリヤ" , arabic = "عالْية" , meaning = "high" } , { latin = "laa 2uHibb a-T-Taqs al mumTil" , kana = "ラー ウひッブ アッタクス アル ムムティル" , arabic = "لا أُحِبّ اَلْطَّقْس اَلْمُمْطِر" , meaning = "I do not like rainy weather." } , { latin = "Sayf Haarr Tawiil" , kana = "サイフ ハール タウィール" , arabic = "صَيْف حارّ طَويل" , meaning = "a long hot summer" } , { latin = "ruTuuba 3aalya" , kana = "ルトゥーバ アーリヤ" , arabic = "رُطوبة عالية" , meaning = "high humidity" } , { latin = "a-r-rTuubat l-3aalya" , kana = "アルトゥーバト ルアーリヤ" , arabic = "اَلْرُّطوبة الْعالْية" , meaning = "the high humidity" } , { latin = "al-yawm" , kana = "アルヤウム" , arabic = "اَلْيَوْم" , meaning = "today" } , { latin = "alyawm yawm baarid" , kana = "アルヤウム ヤウム バーリド" , arabic = "اَلْيَوْم يَوْم بارِد" , meaning = "Today is a cold day." } , { latin = "tashar-rfnaa" , kana = "タシャッラフゥナー" , arabic = "تشرفنا" , meaning = "Pleased to meet you." } , { latin = "a-S-Sayf l-baarid" , kana = "アッサイフ ル バーリド" , arabic = "اَلْصَّيْف اَلْبارِد" , meaning = "the cold summer" } , { latin = "a-r-rabii3" , kana = "アッラビーア" , arabic = "اَلْرَّبيع" , meaning = "the spring" } , { latin = "al-khariif mushmis" , kana = "アル ハリーフ ムシュミス" , arabic = "اَلْخَريف مُشْمِس" , meaning = "The fall is sunny." } , { latin = "rabii3 jamiil" , kana = "ラビーア ジャミール" , arabic = "رَبيع جَميل" , meaning = "a pretty spring" } , { latin = "rabii3 baarid fii 2iskutlandan" , kana = "ラビーア バアリド フィー スクトランダン" , arabic = "رَبيع بارِد في إِسْكُتْلَنْدا" , meaning = "a cold spring in Scotland" } , { latin = "kayfa" , kana = "カイファ" , arabic = "كَيْفَ" , meaning = "how" } , { latin = "kaifa Haalka" , kana = "カイファ ハールカ" , arabic = "كَيْفَ حالكَ" , meaning = "How are you?" } , { latin = "Hammaam" , kana = "ハンマーム" , arabic = "حَمّام" , meaning = "bathroom" } , { latin = "haadhaa balad-haa" , kana = "ハーザー バラドハー" , arabic = "هَذا بَلَدها" , meaning = "This is her country." } , { latin = "al-2urdun" , kana = "アル ウルドゥン" , arabic = "اَلْأُرْدُن" , meaning = "Jordan" } , { latin = "a-s-saaHil" , kana = "アッサーヒル" , arabic = "اَلْسّاحِل" , meaning = "the coast" } , { latin = "2uhibb a-s-safar 2ilaa 2almaaniiaa" , kana = "ウひッブ アッサファル イラ アルマニア" , arabic = "أُحِب اَلْسَّفَر إِلى أَلْمانيا" , meaning = "I like travelling to Germany" } , { latin = "hiyya" , kana = "ヒヤ" , arabic = "هِيَّ" , meaning = "she" } , { latin = "huwwa" , kana = "フワ" , arabic = "هُوَّ" , meaning = "he" } , { latin = "2anti" , kana = "アンティ" , arabic = "أَنْتِ" , meaning = "you (female)" } , { latin = "2anta" , kana = "アンタ" , arabic = "أَنْتَ" , meaning = "you (male)" } , { latin = "mutarjim dhakiyy" , kana = "ムタルジム ザキーイ" , arabic = "مُتَرْجِم ذَكِيّ" , meaning = "a smart translator (male)" } , { latin = "mutarjima dhakiyya" , kana = "ムタルジマ ザキーヤ" , arabic = "مُتَرْجِمة ذَكِيّة" , meaning = "a smart translator (female)" } , { latin = "2ustaadh 2amriikiyy" , kana = "ウスターズ アマリキーイ" , arabic = "أُسْتاذ أَمْريكِيّ" , meaning = "an American professor (male)" } , { latin = "2ustaadha 2amriikiyya" , kana = "ウスターザ アマリキーヤ" , arabic = "أُسْتاذة أَمْريكِيّة" , meaning = "an American professor (female)" } , { latin = "3alaa" , kana = "アラー" , arabic = "عَلى" , meaning = "on, on top of" } , { latin = "al-3arabiyya l-fuSHaa" , kana = "アルアラビーヤ ル フスハー" , arabic = "اَلْعَرَبِيّة الْفُصْحى" , meaning = "Standard Arabic" } , { latin = "bariiTaanyaa l-kubraa" , kana = "ブリターニヤー ル クブラー" , arabic = "بَريطانْيا الْكُبْرى" , meaning = "Great Britain" } , { latin = "balad 3arabiyy" , kana = "バラド アラビーイ" , arabic = "بَلَد عَرَبِيّ" , meaning = "an Arab country" } , { latin = "madiina 3arabiyya" , kana = "マディーナ アラビーヤ" , arabic = "مَدينة عَرَبِيّة" , meaning = "an Arab city" } , { latin = "bint jadiid" , kana = "ビント ジャディード" , arabic = "بَيْت جَديد" , meaning = "a new house" } , { latin = "jaami3a jadiida" , kana = "ジャーミア ジャディーダ" , arabic = "جامِعة جَديدة" , meaning = "a new university" } , { latin = "hadhaa Saaluun ghaalii" , kana = "ハーザー サールーン ガーリー" , arabic = "هَذا صالون غالي" , meaning = "This is an expensive living room" } , { latin = "ghaalii" , kana = "ガーリー" , arabic = "غالي" , meaning = "expensive, dear" } , { latin = "khaalii" , kana = "クハーリー" , arabic = "خالي" , meaning = "my mother’s brother, uncle" } , { latin = "taab" , kana = "ターブ" , arabic = "تاب" , meaning = "to repent" } , { latin = "Taab" , kana = "ターブ" , arabic = "طاب" , meaning = "to be good, pleasant" } , { latin = "2umm" , kana = "ウンム" , arabic = "أُمّ" , meaning = "mother" } , { latin = "2ukht" , kana = "ウフト" , arabic = "أُخْت" , meaning = "siter" } , { latin = "bint" , kana = "ビント" , arabic = "بِنْت" , meaning = "daughter, girl" } , { latin = "2ummii" , kana = "ウンミー" , arabic = "أُمّي" , meaning = "my mother" } , { latin = "ibnak" , kana = "イブナク" , arabic = "اِبْنَك" , meaning = "your son (to a man)" } , { latin = "ibnik" , kana = "イブニク" , arabic = "اِبْنِك" , meaning = "your son (to a woman)" } , { latin = "al-3iraaq" , kana = "アライラーク" , arabic = "اَلْعِراق" , meaning = "iraq" } , { latin = "nadhiir" , kana = "ナディール" , arabic = "نَذير" , meaning = "warner, herald" } , { latin = "naDhiir" , kana = "ナディール" , arabic = "نَظير" , meaning = "equal" } , { latin = "madiinatii" , kana = "マディーナティ" , arabic = "مَدينَتي" , meaning = "my city" } , { latin = "madiinatak" , kana = "マディーナタク" , arabic = "مَدينَتَك" , meaning = "your city (to a male)" } , { latin = "madiinatik" , kana = "マディーナティク" , arabic = "مَدينَتِك" , meaning = "your city (to a female)" } , { latin = "jaara" , kana = "ジャーラ" , arabic = "جارة" , meaning = "a neighbor (female)" } , { latin = "jaaratii" , kana = "ジャーラティ" , arabic = "جارَتي" , meaning = "my neighbor (female)" } , { latin = "jaaratak" , kana = "ジャーラタク" , arabic = "جارَتَك" , meaning = "your (female) neighbor (to a male)" } , { latin = "jaaratik" , kana = "ジャーラティク" , arabic = "جارَتِك" , meaning = "your (female) neighbor (to a female)" } , { latin = "al-bayt jamiil" , kana = "アルバイト ジャミール" , arabic = "اَلْبَيْت جَميل" , meaning = "The house is pretty" } , { latin = "al-madiina jamiila" , kana = "アルマディーナ ジャミーラ" , arabic = "اَلْمَدينة جَميلة" , meaning = "The city is pretty" } , { latin = "baytak jamiil" , kana = "バイタク ジャミール" , arabic = "بَيْتَك جَميل" , meaning = "Your house is pretty (to a male)" } , { latin = "madiinatak jamiila" , kana = "マディーナタク ジャミーラ" , arabic = "مَدينَتَك جَميلة" , meaning = "Your city is pretty (to a male)" } , { latin = "baytik jamiil" , kana = "バイティク ジャミール" , arabic = "بَيْتِك جَميل" , meaning = "Your house is pretty (to a female)" } , { latin = "madiinatik jamiila" , kana = "マディーナティク ジャミーラ" , arabic = "مَدينَتِك جَميلة" , meaning = "Your city is pretty (to a female)" } , { latin = "dall" , kana = "ダル" , arabic = "دَلّ" , meaning = "to show, guide" } , { latin = "Dall" , kana = "ダル" , arabic = "ضَلّ" , meaning = "to stray" } , { latin = "3ind juudii bayt" , kana = "アインド ジューディー バイト" , arabic = "عِنْد جودي بَيْت" , meaning = "Judy has a house." } , { latin = "3indii baitii" , kana = "アインディー バイティー" , arabic = "عِنْدي بَيْت" , meaning = "I have a house." } , { latin = "3indaka bayt" , kana = "アインダカ バイト" , arabic = "عِنْدَك بَيْت" , meaning = "You (to a man) have a house." } , { latin = "3indika bayt" , kana = "アインディカ バイト" , arabic = "عِنْدِك بَيْت" , meaning = "You (to a woman) have a house." } , { latin = "laysa 3ind juudii bayt" , kana = "ライサ アインド ジュウディー バイト" , arabic = "لَيْسَ عِنْد جودي بَيْت" , meaning = "Judy does not have a house." } , { latin = "laysa 3indii kalb" , kana = "ライサ アインド カルブ" , arabic = "لَيْسَ عِنْدي كَلْب" , meaning = "I do not have a dog." } , { latin = "laysa 3indika wishaaH" , kana = "ライサ アインディカ ウィシャーハ" , arabic = "لَيْسَ عِنْدِك وِشاح" , meaning = "You do not have a scarf. (to a woman)" } , { latin = "madiina suuriyya" , kana = "マディーナ スリーヤ" , arabic = "مَدينة سورِيّة" , meaning = "a Syrian city" } , { latin = "filasTiin makaan mashhuur" , kana = "フィラストィーン マカーン マシュフール" , arabic = "فِلَسْطين مَكان مَشْهور" , meaning = "Palestine is a famous place." } , { latin = "a-s-suudaan wa-l3iraaq" , kana = "アッスーダーン ワライラーク" , arabic = "اَلْسّودان وَالْعِراق" , meaning = "Sudan and Iraq" } , { latin = "al-3aaSima" , kana = "アルあーすぃマ" , arabic = "اَلْعاصِمة" , meaning = "the captal" } , { latin = "jabal" , kana = "ジャバル" , arabic = "جَبَل" , meaning = "a mountain" } , { latin = "a-th-thuudaan" , kana = "アッスーダーン" , arabic = "الشودان" , meaning = "Sudan" } , { latin = "bayt 2azraq" , kana = "バイト アズラク" , arabic = "بَيْت أَزْرَق" , meaning = "a blue house" } , { latin = "madiina zarqaa2" , kana = "マディーナ ザルかー" , arabic = "مَدينة زَرْقاء" , meaning = "a blue city" } , { latin = "al-bayt 2azraq" , kana = "アルバイト アズラク" , arabic = "اَلْبَيْت أَزْرَق" , meaning = "The house is blue" } , { latin = "al-madiina zarqaa2" , kana = "アル マディーナ ザルかー" , arabic = "اَلْمَدينة زَرْقاء" , meaning = "The city is blue." } , { latin = "2azraq zarqaa2" , kana = "アズらく ザルかー" , arabic = "أَزْرَق زَرْقاء" , meaning = "blue" } , { latin = "saam" , kana = "サーム" , arabic = "سام" , meaning = "Sam (maile name)" } , { latin = "Saam" , kana = "サーム" , arabic = "صام" , meaning = "to fast" } , { latin = "Sadiiqii Juurj 3ind-hu 3amal mumtaaz" , kana = "サディークィー ジュールジュ アインダフー アアマル ムムターズ" , arabic = "صَديقي جورْج عِنْدهُ عَمَل مُمْتاز" , meaning = "My friend George has excellent job." } , { latin = "ghaniyy" , kana = "ガニィイ" , arabic = "غَنِيّ" , meaning = "rich" } , { latin = "amra2a" , kana = "アムラア" , arabic = "اَمْرَأة" , meaning = "a woman" } , { latin = "2amaamaka" , kana = "アマーマカ" , arabic = "أَمامَك" , meaning = "in front of you" } , { latin = "khalfak" , kana = "ハルファク" , arabic = "خَلْفَك" , meaning = "behind you" } , { latin = "bijaanib" , kana = "ビジャーニブ" , arabic = "بِجانِب" , meaning = "next to" } , { latin = "2abii mashghuul daayman" , kana = "アビー マシュグール ダーイマン" , arabic = "أَبي مَشْغول دائِماً" , meaning = "My father is always busy." } , { latin = "su2aal" , kana = "スアール" , arabic = "سُؤال" , meaning = "question" } , { latin = "ma3ii" , kana = "マアイー" , arabic = "معي" , meaning = "with me" } , { latin = "labisa" , kana = "ラビサ" , arabic = "لابِسة" , meaning = "dress up" } , { latin = "man ma3ii" , kana = "マン マアイー" , arabic = "مَن مَعي؟" , meaning = "Who is this?" } , { latin = "Hanafiyya" , kana = "ハナフィーヤ" , arabic = "حَنَفِيّة" , meaning = "a faucet" } , { latin = "Sawt" , kana = "サウト" , arabic = "صَوْت" , meaning = "voice" } , { latin = "2adkhul" , kana = "アドホル" , arabic = "أَدْخُل" , meaning = "enter" } , { latin = "al-haatif mu3aTTal wa-t-tilfaaz 2ayDan" , kana = "アルハーティフ ムアッタル ワッティルファーズ アイダン" , arabic = "اَلْهاتِف مُعَطَّل وَالْتَّلْفاز أَيضاً" , meaning = "The telephone is out of order and the television also." } , { latin = "hunaak mushkila ma3a t-tilaaz" , kana = "フゥナーク ムシュキラ マア ッティルファーズ" , arabic = "هُناك مُشْكِلة مَعَ الْتِّلْفاز" , meaning = "There is a problem with the television." } , { latin = "2a3rif" , kana = "アーリフ" , arabic = "أَعْرِف" , meaning = "I know ..." } , { latin = "raqam" , kana = "ラカム" , arabic = "رَقَم" , meaning = "number" } , { latin = "la 2a3rif kul-l al-2aedaan" , kana = "ラー アーリフ クッラ ル アーダーン" , arabic = "لا أَعْرِف كُلّ اَلْأَعْداد" , meaning = "I do not know all the numbers." } , { latin = "ta3rifiin" , kana = "ターリフィーン" , arabic = "تَعْرِفين" , meaning = "You (female) know" } , { latin = "li2anna" , kana = "リアンナ" , arabic = "لِأَنَّ" , meaning = "because" } , { latin = "samna" , kana = "サムナ" , arabic = "سَمنة" , meaning = "ghee" } , { latin = "wilaaya" , kana = "ウィラーヤ" , arabic = "وِلايَة" , meaning = "a state" } , { latin = "zawjii wa-bnii" , kana = "ザウジー ワブニー" , arabic = "زَوجي وَابني" , meaning = "my husband and my son" } , { latin = "mumtaaz" , kana = "ムムターズ" , arabic = "مُمتاز" , meaning = "amazing, excellent" } , { latin = "abnii" , kana = "アブニー" , arabic = "اَبني" , meaning = "my son" } , { latin = "muHaasib" , kana = "ムハースィブ" , arabic = "مُحاسب" , meaning = "an accountant" } , { latin = "juz2" , kana = "ジュズ" , arabic = "جُزء" , meaning = "a part of" } , { latin = "fataa" , kana = "ファター" , arabic = "فَتاة" , meaning = "a young woman, a girl" } , { latin = "tis3a" , kana = "ティスア" , arabic = "تِسعة" , meaning = "nine" } , { latin = "hal l-lghat l-3arabiyya Sa3ba" , kana = "ハル ッルガト ルアラビーヤ サアバ" , arabic = "هَل اللُّغَة العَرَبية صَعبة" , meaning = "Is arabic language difficult?" } , { latin = "maadhaa fa3lta 2amsi" , kana = "マーザー ファアルタ アムスィ" , arabic = "ماذا فَعلتَ أَمسِ" , meaning = "What did you do yesterday?" } , { latin = "maadhaa 2akalta" , kana = "マーザー アカルタ" , arabic = "ماذا أَكَلتَ" , meaning = "What did you eat?" } , { latin = "shu2uun" , kana = "シュ ウーン" , arabic = "شُؤُون" , meaning = "affairs, things" } , { latin = "mataa waSalta" , kana = "マター ワサルタ" , arabic = "مَتي وَصَلتَ" , meaning = "When did you arrive?" } , { latin = "suuq" , kana = "スーク" , arabic = "سوق" , meaning = "market" } , { latin = "Haafila" , kana = "ハーフィラ" , arabic = "حافِلة" , meaning = "a bus" } , { latin = "tannuura" , kana = "タンヌーラ" , arabic = "تَنورة" , meaning = "a skirt" } , { latin = "laHaDha" , kana = "ラハザ" , arabic = "لَحَظة" , meaning = "a moment" } , { latin = "2ayna l-qiTTa" , kana = "アイナ ルキッタ" , arabic = "أَينَ القِطّة" , meaning = "Where is the cat?" } , { latin = "shaay" , kana = "シャーイ" , arabic = "شاي" , meaning = "tea" } , { latin = "hal haadhihi Haqiibatki" , kana = "ハル ハージヒ ハキーバトキ" , arabic = "هَل هَذِهِ حَقيبَتكِ" , meaning = "Is this your bag?" } , { latin = "Hakiiba" , kana = "ハキーバ" , arabic = "حَقيبَة" , meaning = "a bag" } , { latin = "Haal" , kana = "ハール" , arabic = "حال" , meaning = "condition" } , { latin = "SaHiifa" , kana = "サヒーファ" , arabic = "صَحيفة" , meaning = "newspaper" } , { latin = "maktab" , kana = "マクタブ" , arabic = "مَكْتَب" , meaning = "an office, a desk" } , { latin = "bunnii" , kana = "ブンニー" , arabic = "بُنّي" , meaning = "brown" } , { latin = "2ila l-liqaa2" , kana = "イラ ッリカー" , arabic = "إِلى اللِّقاء" , meaning = "Bye. See you again." } , { latin = "daa2iman" , kana = "ダーイマン" , arabic = "دائمًا" , meaning = "always" } , { latin = "Hasanan" , kana = "ハサナン" , arabic = "حَسَنًا" , meaning = "Okay, good, fantastic!" } , { latin = "2ayna l-Hammaam" , kana = "アイナ ル ハンマーン" , arabic = "أَينَ الحَمّام" , meaning = "Where is the bathroom?" } , { latin = "baqara" , kana = "バカラ" , arabic = "بَقَرة" , meaning = "a cow" } , { latin = "nasiij" , kana = "ナスィージ" , arabic = "نَسيج" , meaning = "texture" } , { latin = "Hajar" , kana = "ハジャル" , arabic = "حَجَر" , meaning = "a stone" } , { latin = "muthal-lath" , kana = "ムサッラス" , arabic = "مُثَلَّث" , meaning = "a triangle" } , { latin = "kathiir" , kana = "カシール" , arabic = "كَثير" , meaning = "many, a lot of" } , { latin = "thawm" , kana = "サウム" , arabic = "ثَوم" , meaning = "garlic" } , { latin = "qiTTatii Saghiira" , kana = "キッタティー サギーラ" , arabic = "قِطَّتي صَغيرة" , meaning = "my small cat" } , { latin = "dubb" , kana = "ドッブ" , arabic = "دُبّ" , meaning = "a bear" } , { latin = "Tabakh" , kana = "タバクハ" , arabic = "طَبَخ" , meaning = "to cook, cooking" } , { latin = "nakhl" , kana = "ナクヘル" , arabic = "نَخْل" , meaning = "date palm tree" } , { latin = "kharuuf" , kana = "クハルーフ" , arabic = "خَروف" , meaning = "a sheep" } , { latin = "samaHa" , kana = "サマハ" , arabic = "سَمَح" , meaning = "to allow, forgive" } , { latin = "tashar-rfnaa" , kana = "タシャッラフゥナー" , arabic = "تَثَرَّفنا" , meaning = "I am pleased to meet you." } , { latin = "Haliib" , kana = "ハリーブ" , arabic = "حَليب" , meaning = "milk (m)" } , { latin = "haatha l-maTar a-th-thaqiir Sa3b" , kana = "ハーザ ル マタル アッサキール サアブ" , arabic = "هَذا المَطَر الثقيل صَعب" , meaning = "This heavy rain is difficult." } , { latin = "al-maTar" , kana = "アルマタル" , arabic = "المَطَر" , meaning = "the rain" } , { latin = "muHaadatha" , kana = "ムハーダサ" , arabic = "مُحادَثة" , meaning = "conversation" } , { latin = "zawjatii ta3baana" , kana = "ザウジャティー タアバーナ" , arabic = "زَوجَتي تَعبانة" , meaning = "My wife is tired." } , { latin = "shukuran" , kana = "シュクラン" , arabic = "شُكْراً" , meaning = "thank you" } , { latin = "shukran jaziilan" , kana = "シュクラン ジャズィーラン" , arabic = "ثُكْراً جَزيلاً" , meaning = "Thank you very much." } , { latin = "jaw3aan" , kana = "ジャウあーン" , arabic = "جَوعان" , meaning = "hungry, starving" } , { latin = "2abyaD bayDaa2" , kana = "アビヤド バイダー" , arabic = "أَبْيَض بَيْضاء" , meaning = "white" } , { latin = "jadd wa-jadda" , kana = "ジャッド ワ ジャッダ" , arabic = "جَدّ وَجَدّة" , meaning = "grandfather and grandmother" } , { latin = "2aaluu" , kana = "アールー" , arabic = "آلو" , meaning = "Hello (on the phone)" } , { latin = "SabaaH l-khayr" , kana = "サバーフ ル クハイル" , arabic = "صَباح الخّير" , meaning = "good morning" } , { latin = "laakinn" , kana = "ラキン" , arabic = "لَكِنّ" , meaning = "but" } , { latin = "thaqaafa" , kana = "サカーファ" , arabic = "ثَقافة" , meaning = "culture" } , { latin = "Haarr" , kana = "ハール" , arabic = "حارّ" , meaning = "hot" } , { latin = "Taqs baarid" , kana = "タクス バーリド" , arabic = "طَقْس بارِد" , meaning = "cold weather" } , { latin = "tilfaaz" , kana = "ティルファーズ" , arabic = "تِلْفاز" , meaning = "a television" } , { latin = "tufaaHa" , kana = "トゥファーハ" , arabic = "تُفاحة" , meaning = "an apple" } , { latin = "sariir" , kana = "サリール" , arabic = "سَرير" , meaning = "a bed" } , { latin = "kursii" , kana = "クルスィー" , arabic = "كُرسي" , meaning = "a chair" } , { latin = "3an" , kana = "アン" , arabic = "عَن" , meaning = "about" } , { latin = "samaa2" , kana = "サマー" , arabic = "سَماء" , meaning = "sky (f)" } , { latin = "2iiTaalyaa" , kana = "イーターリヤー" , arabic = "إيطاليا" , meaning = "Italy" } , { latin = "2arD" , kana = "アルド" , arabic = "أَرض" , meaning = "a land (f)" } , { latin = "wilaayat taksaas" , kana = "ウィラーヤト タクサース" , arabic = "وِلاية تَكْساس" , meaning = "the state of Texas" } , { latin = "Sahfii Sahfiiya" , kana = "サハフィー サハフィーヤ" , arabic = "صَحفي صَحفية" , meaning = "a journalist" } , { latin = "bint suuriyya" , kana = "ビント スーリヤ" , arabic = "بِنْت سورِيّة" , meaning = "a Syrian girl" } , { latin = "2umm" , kana = "ウンム" , arabic = "أُمّ" , meaning = "a mother (f)" } , { latin = "3ayn" , kana = "アイン" , arabic = "عَيْن" , meaning = "an eye (f)" } , { latin = "qadam" , kana = "カダム" , arabic = "قَدَم" , meaning = "a foot (f)" } , { latin = "3an l-qiraa2a" , kana = "アニル キラーエ" , arabic = "عَن القِراءة" , meaning = "about reading" } , { latin = "a-s-safar" , kana = "アッサファル" , arabic = "السفر" , meaning = "travelling" } , { latin = "kulla yawm" , kana = "クッラ ヤウム" , arabic = "كُلَّ يَوم" , meaning = "every day" } , { latin = "2adrs fi l-jaami3a kulla yawm" , kana = "アドルス フィ ル ジャーミア クッラ ヤウム" , arabic = "أَدرس في الجامِعة كُلَّ يَوم" , meaning = "I study at the university every day." } , { latin = "dhahaba" , kana = "ザハバ" , arabic = "ذَهَبَ" , meaning = "He went" } , { latin = "katabaa" , kana = "カタバー" , arabic = "كَتَبَا" , meaning = "They (two male) wrote" } , { latin = "katabtu" , kana = "カタブトゥ" , arabic = "كَتَبْتُ" , meaning = "I wrote" } , { latin = "katabti" , kana = "カタブティ" , arabic = "كَتَبْتِ" , meaning = "You (female) wrote" } , { latin = "katabta" , kana = "カタブタ" , arabic = "كَتَبْتَ" , meaning = "You (male) wrote" } , { latin = "katabat" , kana = "カタバット" , arabic = "كَتَبَت" , meaning = "She wrote" } , { latin = "ramaDaan" , kana = "ラマダーン" , arabic = "رَمَضان" , meaning = "Ramadan" } , { latin = "qahwa" , kana = "かハワ" , arabic = "قَهوة" , meaning = "coffee" } , { latin = "al-2aan" , kana = "アル アーン" , arabic = "اَلآن" , meaning = "right now" } , { latin = "saa3at Haa2iT" , kana = "サーアト ハーイト" , arabic = "ساعة حائط" , meaning = "a wall clock" } , { latin = "kami s-saa3a l-2aan" , kana = "カミッサーア ルアーン" , arabic = "كَمِ الساعة الآن" , meaning = "What time is it now?" } , { latin = "a-s-saa3a kam" , kana = "アッサーア カム" , arabic = "الساعة كَم" , meaning = "What time is it?" } , { latin = "2a3Tinii" , kana = "アーティニー" , arabic = "أَعْطِني" , meaning = "Give me ..." } , { latin = "Tayyib" , kana = "タイイブ" , arabic = "طَيِّب" , meaning = "Ok, good" } , { latin = "2abuu shaqra" , kana = "アブーシャクラ" , arabic = "أَبو شَقرة" , meaning = "Abu Shakra (restaurant)" } , { latin = "haathihi T-Taawila Haara" , kana = "ハージヒ ッターウィラ ハーラ" , arabic = "هَذِهِ الطاوِلة حارة" , meaning = "This table is hot." } , { latin = "ma3Taf khafiif" , kana = "マアタフ クハフィーフ" , arabic = "معطَف خَفيف" , meaning = "a light coat" } , { latin = "maTar khafiif" , kana = "マタル クハフィーフ" , arabic = "مَطَر خَفيف" , meaning = "a light rain" } , { latin = "a-T-Taqs" , kana = "アッタクス" , arabic = "الطَّقس" , meaning = "the weather" } , { latin = "2alf" , kana = "アルフ" , arabic = "أَلف" , meaning = "a thousand" } , { latin = "mi3a" , kana = "ミア" , arabic = "مِئة" , meaning = "a hundred" } , { latin = "3ashara" , kana = "アシャラ" , arabic = "عَشرة" , meaning = "ten" } , { latin = "al-Hamdu li-l-laa" , kana = "アルハムド リッラー" , arabic = "الحَمدُ لِلَّه" , meaning = "Praise be to God." } , { latin = "Hubba" , kana = "フッバ" , arabic = "حُبَّ" , meaning = "love" } , { latin = "3ilka" , kana = "アイルカ" , arabic = "عِلكة" , meaning = "chewing gum" } , { latin = "thaqiil" , kana = "サキール" , arabic = "ثَقيل" , meaning = "heavy" } , { latin = "haatifii" , kana = "ハーティフィー" , arabic = "هاتِفي" , meaning = "my phone" } , { latin = "thamaaniya" , kana = "サマーニヤ" , arabic = "ثَمانية" , meaning = "eight" } , { latin = "sab3a" , kana = "サブア" , arabic = "سَبعة" , meaning = "seven" } , { latin = "sitta" , kana = "スィッタ" , arabic = "سِتَّة" , meaning = "six" } , { latin = "khamsa" , kana = "クハムサ" , arabic = "خَمسة" , meaning = "five" } , { latin = "2arba3a" , kana = "アルバア" , arabic = "أَربَعة" , meaning = "four" } , { latin = "thalaatha" , kana = "サラーサ" , arabic = "ثَلاثة" , meaning = "three" } , { latin = "2alif baa2 taa2 thaa2 jiim Haa2 khaa2" , kana = "アリフ バー ター さー ジーム はー クハー" , arabic = "أَلِف باء تاء ثاء جيم حاء خاء" , meaning = "ا ب ت ث ج ح خ" } , { latin = "daal dhaal raa2 zaay siin shiin" , kana = "ダール ざール らー ザーイ スィーン シーン" , arabic = "دال ذال راء زاي سين شين" , meaning = "د ذ ر ز س ش" } , { latin = "Saad Daad Taa2 Dhaa2 3ain ghain" , kana = "すぁード だード たー づぁー アイン ガイン" , arabic = "صاد ضاد طاء ظاء عَين غَين" , meaning = "ص ض ط ظ ع غ" } , { latin = "faa2 qaaf kaaf laam miim nuun" , kana = "ファー かーフ カーフ ラーム ミーム ヌーン" , arabic = "فاء قاف كاف لام ميم نون" , meaning = "ف ق ك ل م ن" } , { latin = "haa2 waaw yaa2 hamza" , kana = "ハー ワーウ ヤー ハムザ" , arabic = "هاء واو ياء هَمزة" , meaning = "ه و ي ء" } , { latin = "kaifa l-Haal" , kana = "カイファ ル はール" , arabic = "كَيفَ الحال" , meaning = "How are you? (How is the condition?)" } , { latin = "bi-khayr wa-l-Hamdu li-l-laa" , kana = "ビクハイルr ワルはムドゥ リッラー" , arabic = "بِخَير وَالحَمدُ لِلَّه" , meaning = "I am fine. Praise be to God." } , { latin = "2aHmar Hamraa2" , kana = "アフマる ハムらー" , arabic = "أَحمَر حَمراء" , meaning = "red" } , { latin = "muHaamii" , kana = "ムハーミー" , arabic = "مُحامي" , meaning = "an attorney, a lawyer" } , { latin = "haadhaa rakamii" , kana = "ハーザー らかミー" , arabic = "هَذا رَقَمي" , meaning = "This is my number." } , { latin = "samaka 2asmaak" , kana = "サマカ アスマーク" , arabic = "سَمَكة أَسماك" , meaning = "fish, fish (plural)" } , { latin = "shajara 2ashujaar" , kana = "シャジャら アシュジャーる" , arabic = "شَجَرة أَشجار" , meaning = "tree, trees" } , { latin = "manzil" , kana = "マンズィル" , arabic = "مَنزِل" , meaning = "a house, home" } , { latin = "bayt" , kana = "バイト" , arabic = "بَيْت" , meaning = "a house" } , { latin = "Hadiiqa" , kana = "はディーか" , arabic = "حَديقة" , meaning = "garden" } , { latin = "haadhihi Hadiiqa 3arabyya" , kana = "ハーじヒ はディーか アらビーヤ" , arabic = "هَذِهِ حَديقة عَرَبيّة" , meaning = "This is an Arab garden" } , { latin = "tafaD-Dal ijlis" , kana = "タファッダル イジュリス" , arabic = "تَفَضَّل اِجْلِس" , meaning = "Please sit down." } , { latin = "tafaD-Dalii" , kana = "タファッダリー" , arabic = "تَفَضَّلي" , meaning = "Please (female word)" } , { latin = "shaay min faDlika" , kana = "シャーイ ミン ファドリカ" , arabic = "شاي مِن فَضلِكَ" , meaning = "Tea please." } , { latin = "ma3a s-salaama" , kana = "マア ッサラーマ" , arabic = "مَعَ السَّلامة" , meaning = "Good bye." } , { latin = "ash-shams" , kana = "アッシャムス" , arabic = "الشَّمس" , meaning = "the sun" } , { latin = "haadha l-qalam" , kana = "ハーザ ル カラム" , arabic = "هَذا القَلَم" , meaning = "this pen" } , { latin = "muta2assif laa 3alayka" , kana = "ムタアッシフ ラー アライカ" , arabic = "مُتأَسِّف. لا عَلَيكَ." , meaning = "I am sorry. Do not mind." } , { latin = "al-qamar" , kana = "アルかマる" , arabic = "القَمَر" , meaning = "the moon" } , { latin = "walad al-walad" , kana = "ワラド アルワラド" , arabic = "وَلَد الوَلَد" , meaning = "boy , the boy" } , { latin = "madrasa" , kana = "マドらサ" , arabic = "مَدرَسة" , meaning = "a school" } , { latin = "saa2iq" , kana = "サーイク" , arabic = "سائق" , meaning = "a driver" } , { latin = "daftar" , kana = "ダフタる" , arabic = "دَفتَر" , meaning = "a notebook" } , { latin = "ba3da 2idhnika" , kana = "バァダ イズニカ" , arabic = "بَعدَ إِذنِكَ" , meaning = "After your permit. Excuse me." } , { latin = "muwaDh-Dhaf" , kana = "ムワッザフ" , arabic = "مُوَظَّف" , meaning = "an employee" } , { latin = "waaHid" , kana = "ワーヒド" , arabic = "واحِد" , meaning = "one" } , { latin = "2ithnaan" , kana = "イスナーン" , arabic = "اِثنان" , meaning = "two" } , { latin = "qamiiS" , kana = "カミース" , arabic = "قَميص" , meaning = "a shirt" } , { latin = "qaamuus" , kana = "かームース" , arabic = "قاموس" , meaning = "dictionary" } , { latin = "majal-la" , kana = "マジャッラ" , arabic = "مَجَلَّة" , meaning = "magazine" } , { latin = "2iijaarii" , kana = "イージャーりー" , arabic = "إيجاري" , meaning = "my rent" } , { latin = "maa haadhaa" , kana = "マー ハーザー" , arabic = "ما هَذا" , meaning = "What is this?" } , { latin = "khubz" , kana = "クフブズ" , arabic = "خُبز" , meaning = "bread" } , { latin = "riisha" , kana = "りーシャ" , arabic = "ريشة" , meaning = "feather" } , { latin = "Taa2ira" , kana = "たーイら" , arabic = "طائرة" , meaning = "an airplane" } , { latin = "Dhabii" , kana = "ザビー" , arabic = "ظَبي" , meaning = "an antelope" } , { latin = "Tabiib" , kana = "タビーブ" , arabic = "طَبيب" , meaning = "doctor" } , { latin = "laa 2a3rif 2ayna 2anaa" , kana = "ラー アーりフ アイナ アナー" , arabic = "لا أَعرِف أَين أَنا" , meaning = "I do not know where I am." } , { latin = "jaarii" , kana = "ジャーリー" , arabic = "جاري" , meaning = "my (male) neighbor" } , { latin = "huwa wa hiya wa hum" , kana = "フワ ワ ヒヤ ワ フム" , arabic = "هُوَ وَ هِيَ وَ هُم" , meaning = "he and she and they" } , { latin = "2anta wa 2anti wa 2antum" , kana = "アンタ ワ アンティ ワ アントゥム" , arabic = "أَنتَ وَ أَنتِ وَ أَنتُم" , meaning = "you (male) and you (female) and you (plural)" } , { latin = "naHnu" , kana = "ナフヌ" , arabic = "نَحنُ" , meaning = "we" } , { latin = "2akh" , kana = "アクハ" , arabic = "أَخ" , meaning = "a brother" } , { latin = "Hijaab" , kana = "ヒジャーブ" , arabic = "حِجاب" , meaning = "a barrier, Hijab" } , { latin = "2ustaadhii" , kana = "ウスタージー" , arabic = "أُستاذي" , meaning = "my professor" } , { latin = "SabaaH n-nuur" , kana = "さバーフ ン ヌーる" , arabic = "صَباح النور" , meaning = "Good morning." } , { latin = "mu3l-lamii" , kana = "ムアッラミー" , arabic = "مُعلَّمي" , meaning = "my teacher" } , { latin = "al-2qkl wa-n-nawm" , kana = "アル アクル ワ ン ナウム" , arabic = "الأَكْل وَالنَّوم" , meaning = "eating and sleeping" } , { latin = "2aiDan" , kana = "アイダン" , arabic = "أَيضاً" , meaning = "also" } , { latin = "al-jarii" , kana = "アル ジャりー" , arabic = "الجَري" , meaning = "running" } , { latin = "a-n-nawm" , kana = "アンナウム" , arabic = "النَّوم" , meaning = "sleeping" } , { latin = "bintii" , kana = "ビンティー" , arabic = "بِنتي" , meaning = "my daughter" } , { latin = "2amaama" , kana = "アマーマ" , arabic = "أَمامَ" , meaning = "in front of, before" } , { latin = "jaami3tii fii Tuukyuu" , kana = "ジャーミアティー フィー トーキョー" , arabic = "جامِعتي في طوكيو" , meaning = "My university is in Tokyo." } , { latin = "2ayn jaami3tka" , kana = "アイン ジャーミアトカ" , arabic = "أَين جامِعتكَ" , meaning = "Where is your university?" } , { latin = "a-t-taSwiir" , kana = "アッタすウィーる" , arabic = "التصْوير" , meaning = "photography" } , { latin = "jaaratii" , kana = "ジャーらティー" , arabic = "جارَتي" , meaning = "my (female) neighbor" } , { latin = "jaarii" , kana = "ジャーりー" , arabic = "جاري" , meaning = "my (male) neighbor" } , { latin = "Dawaahii" , kana = "だワーヒー" , arabic = "ضَواحي" , meaning = "suburbs" } , { latin = "2askn fii DawaaHii baghdaad" , kana = "アスクン フィー だワーひー バグダード" , arabic = "أَسكن في ضَواحي بَغداد" , meaning = "I live in the suburbs of Bagdad." } , { latin = "qar-yatii qariiba min madiinat bayruut" , kana = "かるヤティー かりーバ ミン マディーナト バイるート" , arabic = "قَريتي قَريبة مِن مَدينة بَيروت" , meaning = "My village is close to the city of Beirut." } , { latin = "3afwan" , kana = "アフワン" , arabic = "عَفواً" , meaning = "Excuse me. Sure, it's Ok. (Reply to thank you)" } , { latin = "2ahlan wa-sahlan" , kana = "アハラン ワ サハラン" , arabic = "أَهلاً وَسَهلاً" , meaning = "Welcome." } , { latin = "kitaab" , kana = "キターブ" , arabic = "كِتاب" , meaning = "a book" } , { latin = "Sadiiqat-hu ruuzaa qariibhu min baythu" , kana = "すぁディーかトフゥ るーザー かりーブフゥ ミン バイトフゥ" , arabic = "صَديقَته روزا قَريبة مِن بَيته" , meaning = "His friend Rosa is close to his house." } , { latin = "Sadiiqat-hu qariiba min manzil-hu" , kana = "すぁディーかトフゥ かりーバ ミン マンズィルフゥ" , arabic = "صَديقَته قَريبة مِن مَنزِله." , meaning = "His girlfriend is close to his home" } , { latin = "2amaam al-jaami3a" , kana = "アマーマ ル ジャーミア" , arabic = "أَمام اَلْجامِعة" , meaning = "in front of the university" } , { latin = "waraa2 l-maqhaa" , kana = "ワらーア ル マクハー" , arabic = "وَراء المَقهى" , meaning = "behind the cafe" } , { latin = "2anaa fi l-maqhaa" , kana = "アナ フィ ル マクハー" , arabic = "أَنا في المَقهى" , meaning = "I am in the cafe." } , { latin = "bi-l-layr" , kana = "ビッライる" , arabic = "بِاللَّيل" , meaning = "at night" } , { latin = "3an il-yaabaan" , kana = "あニル ヤーバーン" , arabic = "عَن اليابان" , meaning = "about Japan" } , { latin = "qabl a-s-saa3at l-khaamisa" , kana = "かブラ ッサーアト ル クハーミサ" , arabic = "قَبل الساعة الخامِسة" , meaning = "before the fifth hour" } , { latin = "ba3d a-Dh-Dhuhr" , kana = "バァダ ッづホる" , arabic = "بَعد الظُّهر" , meaning = "afternoon" } , { latin = "2uHibb a-n-nawm ba3d a-Dh-Dhuhr" , kana = "ウひッブ アンナウム バァダ ッづホる" , arabic = "أحِبّ اَلْنَّوْم بَعْد اَلْظَّهْر" , meaning = "I like sleeping in the afternoon." } , { latin = "alkalaam ma3a 2abii ba3d alDh-Dhuhr" , kana = "アルカラーム マア アビー バァダ ッづホる" , arabic = "اَلْكَلام معَ أَبي بَعْد اَلْظَّهْر" , meaning = "talking with my father in the afternoon" } , { latin = "a-s-salaamu 3alaykum" , kana = "アッサラーム アライクム" , arabic = "اَلْسَّلامُ عَلَيْكُم" , meaning = "Peace be upon you." } , { latin = "wa-3alaykumu a-s-salaam" , kana = "ワ アライクム アッサラーム" , arabic = "وَعَلَيكم السلام" , meaning = "And peace be upon you." } , { latin = "lil2asaf" , kana = "リルアサフ" , arabic = "لِلْأَسَف" , meaning = "unfortunately" } , { latin = "al-baHr al-2abyaD al-mutawas-siT" , kana = "アル バハる アル アビヤど アル ムタワッスィと" , arabic = "اَاْبَحْر اَلْأَبْيَض اَلْمُتَوَسِّط" , meaning = "the Meditteranean Sea" } , { latin = "2uHibb a-s-safar 2ila l-baHr al-2abyaD al-mutawas-siT" , kana = "ウひッブ アッサファら イラ ル バハる アル アビヤど アル ムタワッスィと" , arabic = "أُحِبّ اَلْسَّفَر إِلى الْبَحْر اَلْلأَبْيَض اَلْمُتَوَسِّط" , meaning = "I like travelling to the Mediterranean Sea." } , { latin = "ghadan" , kana = "ガダン" , arabic = "غَداً" , meaning = "tomorrow" } , { latin = "li-maadhaa" , kana = "リ マーザー" , arabic = "لَماذا" , meaning = "why" } , { latin = "3indii fikra" , kana = "アインディー フィクら" , arabic = "عِندي فِكْرة" , meaning = "I have an idea." } , { latin = "hal 3indaka haatif" , kana = "ハル アインダカ ハーティフ" , arabic = "هَل عِندَكَ هاتِف" , meaning = "Do you have a phone?" } , { latin = "fi l-T-Taabiq al-2awwal" , kana = "フィル ッタービク アルアッワル" , arabic = "في الْطّابِق اَلْأَوَّل" , meaning = "on the first floor" } , { latin = "a-sh-shaanii" , kana = "アッシャーニー" , arabic = "الثاني" , meaning = "the second" } , { latin = "fi l-T-Taabiq a-sh-sha-nii" , kana = "フィル ッタービク アッシャーニー" , arabic = "في الطابق الثاني" , meaning = "in the second floor" } , { latin = "al-laa" , kana = "アッラー" , arabic = "اَلله" , meaning = "God" } , { latin = "haadha l-bayt" , kana = "ハーザ ル バイト" , arabic = "هَذا البَيت" , meaning = "this house" } , { latin = "haadhihi l-madiina" , kana = "ハージヒ ル マディーナ" , arabic = "هَذِهِ المَدينة" , meaning = "this city" } , { latin = "hunaak bayt" , kana = "フゥナーク バイト" , arabic = "هُناك بَيْت" , meaning = "There is a house." } , { latin = "al-bayt hunaak" , kana = "アルバイト フゥナーク" , arabic = "اَلْبَيْت هُناك" , meaning = "The house is there." } , { latin = "hunaak washaaH 2abyaD" , kana = "フゥナーク ワシャーハ アビヤド" , arabic = ".هُناك وِشاح أَبْيَض" , meaning = "There is a white scarf." } , { latin = "al-washaaH hunaak" , kana = "アルワシャーハ フゥナーク" , arabic = "اَلْوِشاح هُناك" , meaning = "The scarf is there." } , { latin = "laysa hunaak bayt" , kana = "ライサ フゥナーク バイト" , arabic = "لَيْسَ هُناك بَيْت" , meaning = "There is no house." } , { latin = "laysa hunaak washaaH 2abyaD" , kana = "ライサ フゥナーク ワシャーハ アビヤド" , arabic = "لَيْسَ هُناك وِشاح أَبْيَض" , meaning = "There is no white scarf." } , { latin = "bayt buub" , kana = "バイト ブーブ" , arabic = "بَيْت بوب" , meaning = "Bob’s house" } , { latin = "baab karii" , kana = "バーブ カりー" , arabic = "باب كَري" , meaning = "Carrie’s door" } , { latin = "kalb al-bint" , kana = "カルブ アルビント" , arabic = "كَلْب اَلْبِنْت" , meaning = "the girl’s dog" } , { latin = "wishaaH al-walad" , kana = "ウィシャーハ アル ワラド" , arabic = "وِشاح اَلْوَلَد" , meaning = "the boy’s scarf" } , { latin = "madiinat buub" , kana = "マディーナト ブーブ" , arabic = "مَدينة بوب" , meaning = "Bob’s city" } , { latin = "jaami3at karii" , kana = "ジャミーアト カりー" , arabic = "جامِعة كَري" , meaning = "Carrie’s university" } , { latin = "qiT-Tat al-walad" , kana = "キッタト アルワラド" , arabic = "قِطّة اَلْوَلَد" , meaning = "the boy’s cat" } , { latin = "mi3Tafhu" , kana = "ミターフフゥ" , arabic = "مِعْطَفهُ" , meaning = "his coat" } , { latin = "mi3Tafhaa" , kana = "ミターフハー" , arabic = "مِعْطَفها" , meaning = "her coat" } , { latin = "baythu" , kana = "バイトフゥ" , arabic = "بَيْتهُ" , meaning = "his house" } , { latin = "baythaa" , kana = "バイトハー" , arabic = "بَيْتها" , meaning = "her house" } , { latin = "madiinathu" , kana = "マディーナトフ" , arabic = "مَدينَتهُ" , meaning = "his city" } , { latin = "madiinathaa" , kana = "マディーナトハー" , arabic = "مَدينَتها" , meaning = "her city" } , { latin = "qubba3athu" , kana = "クッバトフ" , arabic = "قُبَّعَتهُ" , meaning = "his hat" } , { latin = "qubba3athaa" , kana = "クッバトハー" , arabic = "قُبَّعَتها" , meaning = "her hat" } , { latin = "2abtasim" , kana = "アブタスィム" , arabic = "أَبْتَسِم" , meaning = "I smile" } , { latin = "2aTbukh" , kana = "アトブクフ" , arabic = "أَطْبُخ" , meaning = "I cook" } , { latin = "laa 2aTbukh" , kana = "ラー アトブクフ" , arabic = "لا أَطْبُخ" , meaning = "I do not cook." } , { latin = "li-d-diraasa" , kana = "リッディらーサ" , arabic = "للدراسة" , meaning = "to study" } , { latin = "ma3a 2ustaadh 2aHmad" , kana = "マア ウスターズ アハマド" , arabic = "مَعَ الأُستاذ أَحمَد" , meaning = "with Mr. Ahmed" } , { latin = "bi-l-yaabaaniyy" , kana = "ビルヤーバーニーイ" , arabic = "بالياباني" , meaning = "in Japanese" } , { latin = "bi-s-sayaara" , kana = "ビッサイヤーら" , arabic = "باالسيارة" , meaning = "by car" } , { latin = "li-2akhii" , kana = "リアクヒー" , arabic = "لِأَخي" , meaning = "for my brother" } , { latin = "3ala l-kursii" , kana = "アラ ル クるスィー" , arabic = "عَلى الكُرسي" , meaning = "on the chair" } , { latin = "taHt al-maktab" , kana = "タハタ ル マクタブ" , arabic = "تَحت المَكتَب" , meaning = "under the desk" } , { latin = "amaam al-maHaTTa" , kana = "アマーマ ル マハッタ" , arabic = "أَمام المَحطّة" , meaning = "in front of the station" } , { latin = "2atakal-lam" , kana = "アタカッラム" , arabic = "أَتَكَلَّم" , meaning = "I talk, I speak" } , { latin = "2uHibb al-kalaam" , kana = "ウひッブ アルカラーム" , arabic = "أُحِبّ اَلْكَلام." , meaning = "I like talking." } , { latin = "2uriid al-kalaam" , kana = "ウりード アルカラーム" , arabic = "أُريد اَلْكَلام" , meaning = "I want to talk." } , { latin = "al-kalaam jayyid" , kana = "アルカラーム ジャイイド" , arabic = "اَلْكَلام جَيِّد" , meaning = "The talking is good." } , { latin = "az-zawja" , kana = "アッザウジャ" , arabic = "اَلْزَّوْجة" , meaning = "the wife" } , { latin = "as-sayyaara" , kana = "アッサイヤーラ" , arabic = "اَلْسَّيّارة" , meaning = "the car" } , { latin = "ad-duktuur" , kana = "アッドクトゥール" , arabic = "ad-duktuur" , meaning = "the doctor" } , { latin = "ar-rajul" , kana = "アッラジュル" , arabic = "اَلْرَّجُل" , meaning = "the man" } , { latin = "as-suudaan" , kana = "アッスーダーン" , arabic = "اَلْسّودان" , meaning = "Sudan" } , { latin = "yabda2" , kana = "ヤブダ" , arabic = "يَبْدَأ" , meaning = "he begins" } , { latin = "shaadii l-mu3al-lim" , kana = "シャーディー ル ムアッリム" , arabic = "شادي المُعَلِّم" , meaning = "Shadi the teacher" } , { latin = "mahaa l-mutarjima" , kana = "マハー ル ムタルジマ" , arabic = "مَها المُتَرجِمة" , meaning = "Maha the translator" } , { latin = "fi l-bayt" , kana = "フィルバイト" , arabic = "في البَيت" , meaning = "in the house" } , { latin = "fi s-sayyaara" , kana = "フィッサイヤーラ" , arabic = "في السيارة" , meaning = "in the car" } , { latin = "2iDaafa" , kana = "イダーファ" , arabic = "إضافة" , meaning = "iDaafa, addition" } , { latin = "2aftaH" , kana = "アフタハ" , arabic = "أَفْتَح" , meaning = "I open" } , { latin = "tuHibb" , kana = "トゥヒッブ" , arabic = "تُحِبّ" , meaning = "you like (to a male), she likes" } , { latin = "tuHibbiin" , kana = "トゥヒッビーン" , arabic = "تُحِبّين" , meaning = "you like (to a female)" } , { latin = "yuHibb" , kana = "ユヒッブ" , arabic = "يُحِبّ" , meaning = "he likes" } , { latin = "tanaam" , kana = "タナーム" , arabic = "تَنام" , meaning = "you sleep (to a male), she sleeps" } , { latin = "tanaamiin" , kana = "タナーミーン" , arabic = "تَنامين" , meaning = "you sleep (to a female)" } , { latin = "yaanaam" , kana = "ヤナーム" , arabic = "يَنام" , meaning = "he sleeps" } , { latin = "haadhihi l-madiina laa tanaam" , kana = "ハージヒ ルマディーナ ラー タナーム" , arabic = "هٰذِهِ ٲلْمَدينة لا تَنام" , meaning = "This city does not sleep." } , { latin = "maa ra2yik" , kana = "マー ラ イイク" , arabic = "ما رَأْيِك؟" , meaning = "What do you think? (Literally: What is your opinion?)" } , { latin = "maadhaa tuHib-biin" , kana = "マーザー トゥヒッビーン" , arabic = "ماذا تُحِبّين؟" , meaning = "What do you like?" } , { latin = "maadhaa 2adrus" , kana = "マーザー アドルス" , arabic = "ماذا أَدْرُس؟" , meaning = "What do I study?" } , { latin = "as-saa3at ath-thaanya" , kana = "アッサーアト アッサーニア" , arabic = "اَلْسّاعة الْثّانْية" , meaning = "the second hour" } , { latin = "as-saa3at ath-thaalitha" , kana = "アッサーアト アッサーリサ" , arabic = "اَلْسّاعة الْثّالِثة" , meaning = "the third hour" } , { latin = "as-saa3at ar-raabi3a" , kana = "アッサーアト アッラービア" , arabic = "اَلْسّاعة الْرّابِعة" , meaning = "the fourth hour" } , { latin = "as-saa3at l-khaamisa" , kana = "アッサーアト ル クハーミサ" , arabic = "اَلْسّاعة الْخامِسة" , meaning = "the fifth hour" } , { latin = "as-saa3at as-saadisa" , kana = "アッサーアト アッサーディサ" , arabic = "اَلْسّاعة الْسّادِسة" , meaning = "the sixth hour" } , { latin = "as-saa3at as-saabi3a" , kana = "アッサーアト アッサービア" , arabic = "اَلْسّاعة الْسّابِعة" , meaning = "the seventh hour" } , { latin = "as-saa3at ath-thaamina" , kana = "アッサーアト アッサーミナ" , arabic = "اَلْسّاعة الْثّامِنة" , meaning = "the eighth hour" } , { latin = "as-saa3at at-taasi3a" , kana = "アッサーアト アッタースィア" , arabic = "اَلْسّاعة الْتّاسِعة" , meaning = "the ninth hour" } , { latin = "as-saa3at l-3aashira" , kana = "アッサーアト ル アーシラ" , arabic = "اَلْسّاعة الْعاشِرة" , meaning = "the tenth hour" } , { latin = "as-saa3at l-Haadya 3ashara" , kana = "アッサーアト ル ハーディヤ アシャラ" , arabic = "اَلْسّاعة الْحادْية عَشَرة" , meaning = "the eleventh hour" } , { latin = "as-saa3ag ath-thaanya 3ashara" , kana = "アッサーアト アッサーニヤ アシャラ" , arabic = "اَلْسّاعة الْثّانْية عَشَرة" , meaning = "the twelfth hour" } , { latin = "as-saa3at l-waaHida" , kana = "アッサーアト ル ワーヒダ" , arabic = "اَلْسّاعة الْواحِدة" , meaning = "the hour one" } , { latin = "as-saa3at ath-thaanya ba3d a-Dh-Dhuhr" , kana = "アッサーアト アッサーニヤ バァダ ッズホル" , arabic = "اَلْسّاعة الْثّانْية بَعْد اَلْظُّهْر" , meaning = "two o'clock in the afternon" } , { latin = "2anaa min lubanaan" , kana = "アナー ミン ルブナーン" , arabic = "أنا من لبنان" , meaning = "I am from Lebanon." } , { latin = "lastu min lubnaan" , kana = "ラストゥ ミン ルブナーン" , arabic = "لَسْتُ من لبنان" , meaning = "" } , { latin = "lastu mariiDa" , kana = "ラストゥ マリーダ" , arabic = "لَسْتُ مَريضة" , meaning = "I am not sick." } , { latin = "lastu fi l-bayt" , kana = "ラストゥ フィル バイト" , arabic = "لَسْتُ في الْبَيْت" , meaning = "I am not home." } , { latin = "lastu min hunaa" , kana = "ラストゥ ミン フゥナー" , arabic = "لَسْتُ مِن هُنا" , meaning = "I am not form here." } , { latin = "qarya" , kana = "かりヤー" , arabic = "قَرية" , meaning = "a village" } , { latin = "sahl" , kana = "サヘル" , arabic = "سَهل" , meaning = "easy" } , { latin = "a-T-Tabii3a" , kana = "アッタビーア" , arabic = "الطَّبيعة" , meaning = "nature" } , { latin = "fii 2ayy saa3a" , kana = "フィー アイイ サーア" , arabic = "في أي ساعة" , meaning = "at which hour, when" } , { latin = "al-iskandariyya" , kana = "アル イスカンダリーヤ" , arabic = "الاِسكَندَرِيّة" , meaning = "Alexandria in Egypt" } , { latin = "2ayna l-maHaT-Ta" , kana = "アイナ ル マハッタ" , arabic = "أَينَ المَحَطّة" , meaning = "Where is the station?" } , { latin = "3aDhiim jiddan" , kana = "アジーム ジッダン" , arabic = "عَظيم جِدّاً" , meaning = "Fantastic! Great!" } , { latin = "thalaatha mar-raat fi l-2usbuu3" , kana = "サラーサ マッラート フィル ウスブーア" , arabic = "ثَلاثَ مَرّات في الأُسبوع" , meaning = "three times a week" } , { latin = "2asaatidha" , kana = "アサーティザ" , arabic = "أَساتِذة" , meaning = "masters, professors" } , { latin = "2ikhwa" , kana = "イクフワ" , arabic = "إِخْوة" , meaning = "brothers" } , { latin = "Suura jamiila" , kana = "スーラ ジャミーラ" , arabic = "صورة جَميلة" , meaning = "beautiful picture" } , { latin = "al-Hkuuma l-2amriikiya" , kana = "アル フクーマ ル アムリーキーヤ" , arabic = "الحْكومة الأَمريكية" , meaning = "the American government" } , { latin = "HaDaara qadiima" , kana = "ハダーラ カディーマ" , arabic = "حَضارة قَديمة" , meaning = "old civilization" } , { latin = "Salaat" , kana = "サラート" , arabic = "صَلاة" , meaning = "prayer, worship" } , { latin = "zakaat" , kana = "ザカート" , arabic = "زَكاة" , meaning = "alms" } , { latin = "Hayaat" , kana = "ハヤート" , arabic = "حَياة" , meaning = "life" } , { latin = "ghurfat bintii" , kana = "グルファト ビンティー" , arabic = "غُرفة بِنتي" , meaning = "my daughter's room" } , { latin = "madiinat nyuuyuurk" , kana = "マディーナト ニューユールク" , arabic = "مَدينة نيويورك" , meaning = "city of New York" } , { latin = "sharika" , kana = "シャリカ" , arabic = "شَرِكة" , meaning = "a company" } , { latin = "sharikat khaalii" , kana = "シャリカト クハーリー" , arabic = "شَرِكة خالي" , meaning = "my uncle's company" } , { latin = "madrasatii" , kana = "マドラサティー" , arabic = "مَدرَسَتي" , meaning = "my school" } , { latin = "3alaaqatnaa" , kana = "アラーカトナー" , arabic = "عَلاقَتنا" , meaning = "our relationship" } , { latin = "shuhra" , kana = "シュフラ" , arabic = "شُهرة" , meaning = "fame" } , { latin = "shufrathu" , kana = "シュフラトフ" , arabic = "شُهرَته" , meaning = "his fame" } , { latin = "naz-zlnii hunaa" , kana = "ナッズィルニー フゥナー" , arabic = "نَزِّلني هنا" , meaning = "Download me here." } , { latin = "3alaa mahlika" , kana = "アラー マハリカ" , arabic = "عَلى مَهلِكَ" , meaning = "Slow down. Take it easy." } , { latin = "laysa kul-la yawm" , kana = "ライサ クッラ ヤウム" , arabic = "اَيْسَ كُلَّ يَوم" , meaning = "not every day" } , { latin = "kul-l l-naas" , kana = "クッル ル ナース" , arabic = "كُلّ الناس" , meaning = "all the people" } , { latin = "kul-l l-2awlaad" , kana = "クッル ル アウラード" , arabic = "كُلّ الأَولاد" , meaning = "all the boys, children" } , { latin = "mayk" , kana = "マイク" , arabic = "مايْك" , meaning = "Mike" } , { latin = "bikam haadhaa" , kana = "ビカム ハーザー" , arabic = "بِكَم هَذا" , meaning = "How much is this?" } , { latin = "dimashq" , kana = "ディマシュク" , arabic = "دِمَشق" , meaning = "Damascus" } , { latin = "2in shaa2a l-laa" , kana = "インシャーアッラー" , arabic = "إِن شاءَ اللَّه" , meaning = "on God's will" } , { latin = "yal-laa" , kana = "ヤッラー" , arabic = "يَلّا" , meaning = "alright" } , { latin = "3aailatii" , kana = "アーイラティー" , arabic = "عائلَتي" , meaning = "my family" } , { latin = "akhbaar" , kana = "アクフバール" , arabic = "أَخبار" , meaning = "news" } , { latin = "tadrsiin" , kana = "タドルスィーン" , arabic = "تَدرسين" , meaning = "you study" } , { latin = "3ilm al-Haasuub" , kana = "アイルム アル ハースーブ" , arabic = "عِلم الحاسوب" , meaning = "computer sicence" } , { latin = "muSawwir" , kana = "ムサウィル" , arabic = "مُصَوِّر" , meaning = "photographer" } , { latin = "laa 2uHib-b-hu" , kana = "ラー ウひッブフ" , arabic = "لا أُحِبّهُ" , meaning = "I do not love him." } , { latin = "ta3mal" , kana = "タアマル" , arabic = "نَعمَل" , meaning = "You work, we work" } , { latin = "2aakhar" , kana = "アークハル" , arabic = "آخَر" , meaning = "else, another, other than this" } , { latin = "lawn 2aakhar" , kana = "ラウン アークハル" , arabic = "لَوت آخَر" , meaning = "another lot, color" } , { latin = "rabba bayt" , kana = "ラッババイト" , arabic = "رَبّة بَيت" , meaning = "homemaker, housewife" } , { latin = "baaHith" , kana = "バーヒス" , arabic = "باحِث" , meaning = "a researcher" } , { latin = "last jaw3aana" , kana = "ラスト ジャウあーナ" , arabic = "لَسْت جَوعانة" , meaning = "I am not hungry." } , { latin = "hal juudii mutafarrigha" , kana = "ハル ジューディー ムタファルリガ" , arabic = "هَل جودي مُتَفَرِّغة؟" , meaning = "Is Judy free?" } , { latin = "nuuSf" , kana = "ヌースフ" , arabic = "نُّصْف" , meaning = "half" } , { latin = "fiilm 2aflaam" , kana = "フィールム アフラーム" , arabic = "فيلم ـ أَفلام" , meaning = "film - films" } , { latin = "dars duruus" , kana = "ダルス ドゥルース" , arabic = "دَرس ـ دُروس" , meaning = "lesson - lessons" } , { latin = "risaala - rasaa2il" , kana = "りサーラ らサーイル" , arabic = "رِسالة - رَسائِل" , meaning = "letter - letters" } , { latin = "qariib - 2aqaarib" , kana = "カリーブ アカーリブ" , arabic = "قَريب - أَقارِب" , meaning = "relative - relatives" } , { latin = "Sadiiq - 2aSdiqaa2" , kana = "サディーク アスディカー" , arabic = "صَديق - أَصْذِقاء" , meaning = "friend - friends" } , { latin = "kitaab - kutub" , kana = "キターブ クトゥブ" , arabic = "كِتاب - كُتُب" , meaning = "book - books" } , { latin = "lugha - lughaat" , kana = "ルガ ルガート" , arabic = "لُغة - لُغات" , meaning = "language - languages" } , { latin = "tuHibb al-kitaaba" , kana = "トゥヒッブ アルキターバ" , arabic = "تُحِبّ اَلْكِتابة" , meaning = "She likes writing." } , { latin = "kitaabat ar-rasaa2il mumti3a" , kana = "キターバト アッラサーイル ムムティア" , arabic = "كِتابة اَلْرَّسائِل مُمْتِعة" , meaning = "Writing of the letters is fun." } , { latin = "HaaDr siidii" , kana = "ハードル スィーディー" , arabic = "حاضر سيدي" , meaning = "Yes, sir." } , { latin = "waqt" , kana = "ワクト" , arabic = "وَقت" , meaning = "time" } , { latin = "risaala" , kana = "リサーラ" , arabic = "رِسالة" , meaning = "letter" } , { latin = "fann" , kana = "ファン" , arabic = "فَنّ" , meaning = "art" } , { latin = "Haziin" , kana = "ハズィーン" , arabic = "حَزين" , meaning = "sad" } , { latin = "3aa2ila" , kana = "アーイラ" , arabic = "عائِلة" , meaning = "family" } , { latin = "2uHibb qiraa2at al-kutub" , kana = "ウひッブ キラーアト アルクトゥブ" , arabic = "أُحِبّ قِراءة اَلْكُتُب" , meaning = "I like reading of the books." } , { latin = "2uHibb al-qiraa2a" , kana = "ウひッブ アルキラーエ" , arabic = "أُحِبّ اَلْقِراءة" , meaning = "I like the reading." } , { latin = "al-kitaaba mumti3a" , kana = "アルキターバ ムムティア" , arabic = "اَلْكِتابة مُمْتِعة" , meaning = "The writing is fun." } , { latin = "kura l-qadam" , kana = "クーラルカダム" , arabic = "كُرة اَلْقَدَم" , meaning = "soccer" } , { latin = "2uHibb ad-dajaaj min 2ams" , kana = "ウひッブ アッダジャージ ミン アムス" , arabic = "أُحِبّ اَلْدَّجاج مِن أَمْس" , meaning = "I like the chicken from yesterday." } , { latin = "2uHibb ad-dajaaj" , kana = "ウひッブ アッダジャージ" , arabic = "أُحِبّ اَلْدَّجاج" , meaning = "I like chicken." } , { latin = "2uHibb al-qawha" , kana = "ウひッブ アルかハワ" , arabic = "أُحِبّ اَلْقَهْوة" , meaning = "I like coffee." } , { latin = "2uriid dajaajan" , kana = "ウりード ダジャージャン" , arabic = "أُريد دَجاجاً" , meaning = "I want chicken." } , { latin = "2uriid qahwa" , kana = "ウりード かハワ" , arabic = "أُريد قَهْوة" , meaning = "I want coffee." } , { latin = "2aakul dajaajan" , kana = "アークル ダジャージャン" , arabic = "آكُل دَجاجاً" , meaning = "I eat chicken." } , { latin = "2ashrab qahwa kul-l SabaaH" , kana = "アシュらブ かハワ クッル さバーは" , arabic = "أَشْرَب قَهْوة كُلّ صَباح" , meaning = "I drink coffee every morning." } , { latin = "2uriid Sadiiqan" , kana = "ウりード すぁディーかン" , arabic = "أُريد صَديقاً" , meaning = "I want a friend." } , { latin = "2aakul khubzan" , kana = "アークル クフブザン" , arabic = "آكُل خُبْزاً" , meaning = "I eat bread." } , { latin = "2uriid baytan jadiidan" , kana = "ウりード バイタン ジャディーダン" , arabic = "أُريد بَيْتاً جَديداً" , meaning = "I want a new house." } , { latin = "matHaf" , kana = "マトはフ" , arabic = "مَتحَف" , meaning = "a museum" } , { latin = "laHm" , kana = "ラハム" , arabic = "لَحْم" , meaning = "meat" } , { latin = "baTaaTaa" , kana = "バターター" , arabic = "بَطاطا" , meaning = "potato" } , { latin = "yashrab al-Haliib" , kana = "ヤシュらブ アルハリーブ" , arabic = "يَشْرَب الحَليب" , meaning = "He drinks milk" } , { latin = "al-muqab-bilaat" , kana = "アルムカッビラート" , arabic = "المُقَبِّلات" , meaning = "appetizers" } , { latin = "Hummusan" , kana = "フンムサン" , arabic = "حُمُّصاً" , meaning = "chickpeas, hummus" } , { latin = "SaHiiH" , kana = "サヒーハ" , arabic = "صَحيح" , meaning = "true, right, correct" } , { latin = "3aSiir" , kana = "アアスィーる" , arabic = "عَصير" , meaning = "juice" } , { latin = "shuurba" , kana = "シューるバ" , arabic = "شورْبة" , meaning = "soupe" } , { latin = "salaTa" , kana = "サラタ" , arabic = "سَلَطة" , meaning = "salad" } , { latin = "s-saakhin" , kana = "ッサークヒン" , arabic = "سّاخِن" , meaning = "hot, warm" } , { latin = "Halwaa" , kana = "はルワー" , arabic = "حَلْوى" , meaning = "candy, dessert" } , { latin = "kib-ba" , kana = "キッバ" , arabic = "كِبّة" , meaning = "kibbeh" } , { latin = "a-T-Tabaq" , kana = "アッタバク" , arabic = "الطَّبّق" , meaning = "the plate, dish" } , { latin = "Tabaq" , kana = "タバク" , arabic = "طّبّق" , meaning = "plate, dish" } , { latin = "2aina 2antum" , kana = "アイナアントム" , arabic = "أَيْن أَنْتُم" , meaning = "Where are you?" } , { latin = "baaS" , kana = "バーすぅ" , arabic = "باص" , meaning = "bus" } , { latin = "tadhkara" , kana = "たずカら" , arabic = "تَذْكَرة" , meaning = "a ticket" } , { latin = "Saff" , kana = "すぁッフ" , arabic = "صَفّ" , meaning = "class" } , { latin = "qiTaar" , kana = "きたーる" , arabic = "قِطار" , meaning = "train" } , { latin = "khuDraawaat" , kana = "クフどらーワート" , arabic = "خُضْراوات" , meaning = "vegetables" } , { latin = "Taazij" , kana = "たーズィジ" , arabic = "طازِج" , meaning = "fresh" } , { latin = "laa 2ashtarii qahwa" , kana = "ラー アシュタりー かハワ" , arabic = "لا أَشْتَري قَهْوة" , meaning = "I do not buy coffee." } , { latin = "faakiha" , kana = "ファーキハ" , arabic = "فاكِهة" , meaning = "fruit" } , { latin = "yufaD-Dil" , kana = "ユファッでぃル" , arabic = "يُفَضِّل" , meaning = "he prefers" } , { latin = "tufaD-Dil" , kana = "トゥファッでぃル" , arabic = "تُفَضِّل" , meaning = "you prefer" } , { latin = "al-banaduura" , kana = "アルバナドゥーら" , arabic = "البَنَدورة" , meaning = "the tomato" } , { latin = "banaduura" , kana = "バナドゥーら" , arabic = "بَنَدورة" , meaning = "tomato" } , { latin = "limaadhaa" , kana = "リマーざー" , arabic = "لِماذا" , meaning = "Why?" } , { latin = "maw3id" , kana = "マウあイド" , arabic = "مَوْعِد" , meaning = "an appointment" } , { latin = "lam" , kana = "ラム" , arabic = "لَم" , meaning = "did not" } , { latin = "yasmaH" , kana = "ヤスマは" , arabic = "يَسْمَح" , meaning = "allow, permit" } , { latin = "khuruuj" , kana = "クフルージ" , arabic = "خُروج" , meaning = "exit, get out" } , { latin = "laa ya2atii" , kana = "ラー ヤアティー" , arabic = "لا يَأْتي" , meaning = "he does not come" } , { latin = "khaTiib" , kana = "クハてぃーブ" , arabic = "خَطيب" , meaning = "fiance" } , { latin = "2abadan" , kana = "アバダン" , arabic = "أَبَدا" , meaning = "never again" } , { latin = "2arkab T-Taa2ira" , kana = "アルカブ ッたーイら" , arabic = "أَرْكَب الطائرة" , meaning = "I ride the plane" } , { latin = "2a3uud" , kana = "アあぅード" , arabic = "أَعود" , meaning = "I come back, return" } , { latin = "maa saafart" , kana = "マー サーファるト" , arabic = "ما سافَرْت" , meaning = "I have not traveled" } , { latin = "li2an-nak" , kana = "リアンナク" , arabic = "لِأَنَّك" , meaning = "because you are" } , { latin = "al-2akl a-S-S-H-Hiyy" , kana = "アルアクル ッすぃひーユ" , arabic = "الأَكل الصِّحِّي" , meaning = "the healthy food" } , { latin = "yajib 2an" , kana = "ヤジブ アン" , arabic = "يَجِب أَن" , meaning = "must" } , { latin = "tashtarii" , kana = "タシュタりー" , arabic = "تَشْتَري" , meaning = "you buy" } , { latin = "baamiya" , kana = "バーミヤ" , arabic = "بامية" , meaning = "squash, zucchini, pumpkin, okra" } , { latin = "kuusaa" , kana = "クーサー" , arabic = "كوسا" , meaning = "zucchini" } , { latin = "Taazij" , kana = "たーズィジ" , arabic = "طازِج" , meaning = "fresh" } , { latin = "jazar" , kana = "ジャザる" , arabic = "جَزَر" , meaning = "carrots" } , { latin = "SiH-Hiya" , kana = "すぃッひーヤ" , arabic = "صِحِّية" , meaning = "healthy" } , { latin = "a2ashtarii" , kana = "アシュタりー" , arabic = "أَشْتَري" , meaning = "I buy" } , { latin = "tashtarii" , kana = "タシュタりー" , arabic = "تَشْتَري" , meaning = "you buy (to a male), she buys" } , { latin = "tashtariin" , kana = "タシュタりーン" , arabic = "تَشْتَرين" , meaning = "you buy (to a female)" } , { latin = "yashtarii" , kana = "ヤシュタりー" , arabic = "يَشْتَري" , meaning = "he buys" } , { latin = "nashtarii" , kana = "ナシュタりー" , arabic = "نَشْتَري" , meaning = "we buy" } , { latin = "tashtaruun" , kana = "タシュタるーン" , arabic = "تَشْتَرون" , meaning = "you all buy, they buy" } , { latin = "li2an-na l-3aalam ghariib" , kana = "リアンナ ルあーラム ガりーブ" , arabic = "لِأَنَّ ٱلْعالَم غَريب" , meaning = "Because the world is weird." } , { latin = "li2anna 2ukhtii tadhrus kathiiraan" , kana = "リアンナ ウクフティー タずるス カしーラン" , arabic = "لِأَنَّ أُخْتي تَذْرُس كَثيراً" , meaning = "Because my sister studies a lot." } , { latin = "li2an-nanii min misr" , kana = "リアンナニー ミン ミスる" , arabic = "لِأَنَّني مِن مِصر" , meaning = "Because I am from Egypt." } , { latin = "li2an-nik 2um-mii" , kana = "リアンニク ウムミー" , arabic = "لِأَنِّك أُمّي" , meaning = "Because you are my mother." } , { latin = "li2an-ni-haa mu3al-lma mumtaaza" , kana = "リアンナハー ムあッリマ ムムターザ" , arabic = "لِأَنَّها مُعَلِّمة مُمْتازة" , meaning = "Because she is an amazing teacher." } , { latin = "li-2an-na-hu sa3iid" , kana = "リアンナフゥ サあイード" , arabic = "لِأَنَّهُ سَعيد" , meaning = "Because he is happy." } , { latin = "li-2abii" , kana = "リアビー" , arabic = "لِأَبي" , meaning = "to/for my father" } , { latin = "li-haadhihi l-2ustaadha" , kana = "リハーじヒ ル ウスターざ" , arabic = "لِهٰذِهِ الْأُسْتاذة" , meaning = "to/for this professor" } , { latin = "li-bayruut" , kana = "リバイるート" , arabic = "لِبَيْروت" , meaning = "to/for Beirut" } , { latin = "li-l-bint" , kana = "リルビント" , arabic = "لِلْبِنْت" , meaning = "to/for the girl" } , { latin = "li-l-2ustaadha" , kana = "リルウスターざ" , arabic = "لِلْأُسْتاذة" , meaning = "to/for the professor" } , { latin = "li-l-qaahira" , kana = "リルかーヒら" , arabic = "لِلْقاهِرة" , meaning = "to/for Cairo" } , { latin = "al-maHal-l maHal-laka yaa 2ustaadh" , kana = "アルマはッル マはッラカ ヤー ウスターず" , arabic = "اَلْمَحَلّ مَحَلَّك يا أُسْتاذ!" , meaning = "The shop is your shop, sir." } , { latin = "hal turiid al-qaliil min al-maa2" , kana = "ハル トゥりード イル かリール ミナル マー" , arabic = "هَل تُريد اَلْقَليل مِن اَلْماء؟" , meaning = "Do you want a little water?" } , { latin = "3aada" , kana = "あーダ" , arabic = "عادة" , meaning = "usually" } , { latin = "ka3k" , kana = "カあク" , arabic = "كَعْك" , meaning = "cakes" } , { latin = "a2ashrab" , kana = "アシュらブ" , arabic = "أَشْرَب" , meaning = "I drink" } , { latin = "sa-2ashrab" , kana = "サ アシュらブ" , arabic = "سَأَشْرَب" , meaning = "I will drink" } , { latin = "tashrab" , kana = "タシュらブ" , arabic = "تَشْرَب" , meaning = "you drink (to a male), she drinks" } , { latin = "tashrabiin" , kana = "タシュらビーン" , arabic = "تَشْرَبين" , meaning = "you drink (to a female)" } , { latin = "yashrab" , kana = "ヤシュらブ" , arabic = "يَشْرَب" , meaning = "he drinks" } ]
52198
module Arabic001 exposing (main) -- backup 2020-06-07 16:51:47 import Browser import Html exposing (..) import Html.Attributes as HA import Html.Events as HE import Random main : Program () Model Msg main = Browser.element { init = init , update = update , subscriptions = subscriptions , view = view } type alias Model = { latin : String , kana : String , arabic : String , meaning : String , showanswer : Bool , list : List Arabicdata } type alias Arabicdata = { latin : String , kana : String , arabic : String , meaning : String } init : () -> ( Model, Cmd Msg ) init _ = ( Model "" "" "" "" False dict , Random.generate NewList (shuffle dict) ) type Msg = Delete | Next | NewRandom Int | Shuffle | NewList (List Arabicdata) | ShowAnswer Int update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of Delete -> ( model , Cmd.none ) Next -> ( model , Cmd.none ) NewRandom n -> case List.drop n dict of x :: _ -> ( { model | latin = x.latin , kana = x.kana , arabic = x.arabic , meaning = x.meaning } , Cmd.none ) [] -> ( model , Cmd.none ) Shuffle -> ( model , Random.generate NewList (shuffle dict) ) NewList newList -> ( { model | list = newList } , Cmd.none ) ShowAnswer index -> case List.drop index model.list of x :: _ -> ( { model | latin = x.latin , kana = x.kana , arabic = x.arabic , meaning = x.meaning , showanswer = True } , Cmd.none ) [] -> ( model , Cmd.none ) subscriptions : Model -> Sub Msg subscriptions model = Sub.none view : Model -> Html Msg view model = div [] [ text "Convert latin to arabic" , p [] [ text "SabaaH" ] , button [] [ text "Show Answer" ] , button [] [ text "Delete" ] , button [] [ text "Next" ] ] shuffle : List a -> Random.Generator (List a) shuffle list = let randomNumbers : Random.Generator (List Int) randomNumbers = Random.list (List.length list) <| Random.int Random.minInt Random.maxInt zipWithList : List Int -> List ( a, Int ) zipWithList intList = List.map2 Tuple.pair list intList listWithRandomNumbers : Random.Generator (List ( a, Int )) listWithRandomNumbers = Random.map zipWithList randomNumbers sortedGenerator : Random.Generator (List ( a, Int )) sortedGenerator = Random.map (List.sortBy Tuple.second) listWithRandomNumbers in Random.map (List.map Tuple.first) sortedGenerator dict = [ { latin = "a-s-salaamu" , kana = "アッサラーム" , arabic = "اَلسَّلَامُ" , meaning = "peace" } , { latin = "2alaykum" , kana = "アライクム" , arabic = "عَلَيْكُمْ" , meaning = "on you" } , { latin = "SabaaH" , kana = "サバーフ" , arabic = "صَبَاح" , meaning = "morning" } , { latin = "marHaban" , kana = "マルハバン" , arabic = "مَرْحَبًا" , meaning = "Hello" } , { latin = "2anaa bikhayr" , kana = "アナー ビクハイル" , arabic = "أَنا بِخَيْر" , meaning = "I'm fine" } , { latin = "kabir" , kana = "カビール" , arabic = "كَبير" , meaning = "large, big" } , { latin = "kabiira" , kana = "カビーラ" , arabic = "كبيرة" , meaning = "large, big" } , { latin = "siith" , kana = "スィース" , arabic = "سيث" , meaning = "Seth (male name)" } , { latin = "baluuza" , kana = "バルーザ" , arabic = "بَلوزة" , meaning = "blouse" } , { latin = "tii shiirt" , kana = "ティー シイールト" , arabic = "تي شيرْت" , meaning = "T-shirt" } , { latin = "ma3Taf" , kana = "マアタフ" , arabic = "معْطَف" , meaning = "a coat" } , { latin = "riim" , kana = "リーム" , arabic = "ريم" , meaning = "Reem (male name)" } , { latin = "tan-nuura" , kana = "タンヌーラ" , arabic = "تَنّورة" , meaning = "a skirt" } , { latin = "jadiid" , kana = "ジャディード" , arabic = "جَديد" , meaning = "new" } , { latin = "wishshaaH" , kana = "ウィシャーハ" , arabic = "وِشَاح" , meaning = "a scarf" } , { latin = "juudii" , kana = "ジューディー" , arabic = "جودي" , meaning = "Judy(name)" } , { latin = "jamiil" , kana = "ジャミール" , arabic = "جَميل" , meaning = "good, nice, pretty, beautiful" } , { latin = "kalb" , kana = "キャルブ" , arabic = "كَلْب" , meaning = "a dog" } , { latin = "2abyaD" , kana = "アビヤッド" , arabic = "أَبْيَض" , meaning = "white" } , { latin = "qub-b3a" , kana = "クッバ" , arabic = "قُبَّعة" , meaning = "a hat" } , { latin = "mruu2a" , kana = "ムルーア" , arabic = "مْروءة" , meaning = "chivalry" } , { latin = "Taawila" , kana = "ターウィラ" , arabic = "طاوِلة" , meaning = "a table" } , { latin = "haadhihi madiina qadiima" , kana = "ハージヒ マディーナ カディーマ" , arabic = "هَذِهِ مَدينة قَديمة" , meaning = "This is an ancient city" } , { latin = "haadhihi binaaya jamiila" , kana = "ハージヒ ビナーヤ ジャミーラ" , arabic = "هَذِهِ بِناية جَميلة" , meaning = "This is a beautiful building" } , { latin = "hadhaa muhammad" , kana = "ハーザー ムハンマド" , arabic = "هَذا مُحَمَّد" , meaning = "This is Mohammed" } , { latin = "haadhihi Hadiiqa jamiila" , kana = "ハージヒ ハディーカ ジャミーラ" , arabic = "هَذِهِ حَديقة جَميلة" , meaning = "This is a pretty garden" } , { latin = "haadhihi Hadiiqa qadiima" , kana = "ハージヒ ハディーカ カディーマ" , arabic = "هَذِهِ حَديقة قَديمة" , meaning = "This is an old garden" } , { latin = "al-Haa2iT" , kana = "アルハーイト" , arabic = "الْحائط" , meaning = "the wall" } , { latin = "Haa2iT" , kana = "ハーイト" , arabic = "حائِط" , meaning = "wall" } , { latin = "hadhaa al-Haa2iT kabiir" , kana = "ハーザ ル ハーイト カビール" , arabic = "هَذا الْحائِط كَبير" , meaning = "this wall is big" } , { latin = "al-kalb" , kana = "アル カルブ" , arabic = "الْكَلْب" , meaning = "the dog" } , { latin = "haadhihi al-binaaya" , kana = "ハージヒ アル ビナーヤ" , arabic = "هذِهِ الْبِناية" , meaning = "this building" } , { latin = "al-ghurfa" , kana = "アル グルファ" , arabic = "اَلْغُرفة" , meaning = "the room" } , { latin = "al-ghurfa kabiira" , kana = "アルグルファ カビーラ" , arabic = "اَلْغرْفة كَبيرة" , meaning = "Theroom is big" } , { latin = "haadhihi alghurfa kabiira" , kana = "ハージヒ アルグルファ カビーラ" , arabic = "هَذِهِ الْغُرْفة كَبيرة" , meaning = "this room is big" } , { latin = "hadhaa alkalb kalbii" , kana = "ハーザー アルカルブ カルビー" , arabic = "هَذا الْكَلْب كَْلبي" , meaning = "this dog is my dog" } , { latin = "hadhaa alkalb jaw3aan" , kana = "ハーザー アルカルブ ジャウあーン" , arabic = "هَذا الْكَلْب جَوْعان" , meaning = "this dog is hungry" } , { latin = "haadhihi al-binaaya waasi3a" , kana = "ハージヒ アルビナーヤ ワースィア" , arabic = "هَذِهِ الْبناية واسِعة" , meaning = "this building is spacious" } , { latin = "al-kalb ghariib" , kana = "アルカルブ ガリーブ" , arabic = "اَلْكَلْب غَريب" , meaning = "The dog is weird" } , { latin = "alkalb kalbii" , kana = "アルカルブ カルビー" , arabic = "اَلْكَلْب كَلْبي" , meaning = "The dog is my dog" } , { latin = "hunaak" , kana = "フゥナーク" , arabic = "هُناك" , meaning = "there" } , { latin = "hunaak bayt" , kana = "フゥナーク バイト" , arabic = "هُناك بَيْت" , meaning = "There is a house" } , { latin = "al-bayt hunaak" , kana = "アル バイト フゥナーク" , arabic = "اَلْبَيْت هُناك" , meaning = "The house is there" } , { latin = "hunaak wishaaH 2abyaD" , kana = "フゥナーク ウィシャーハ アビヤド" , arabic = "هُناك وِشاح أبْيَض" , meaning = "There is a white scarf" } , { latin = "alkalb munaak" , kana = "アルカルブ ムナーク" , arabic = "اَلْكَلْب مُناك" , meaning = "The dog is there" } , { latin = "fii shanTatii" , kana = "フィー シャンタティー" , arabic = "في شَنْطَتي" , meaning = "in my bag" } , { latin = "hal 3indak maHfaDha yaa juurj" , kana = "ハル アインダク マハファザ ヤー ジュールジュ" , arabic = "هَل عِنْدَك مَحْفَظة يا جورْج" , meaning = "do you have a wallet , george" } , { latin = "3indii shanTa ghaalya" , kana = "アインディー シャンタ ガーリヤ" , arabic = "عِنْدي شَنْطة غالْية" , meaning = "I have an expensive bag" } , { latin = "shanTatii fii shanTatik ya raanyaa" , kana = "シャンタティー フィー シャンタティク ヤー ラーニヤー" , arabic = "شِنْطَتي في شَنْطتِك يا رانْيا" , meaning = "my bag is in your bag rania" } , { latin = "huunak maHfaDha Saghiira" , kana = "フゥナーク マハファザ サギーラ" , arabic = "هُناك مَحْفَظة صَغيرة" , meaning = "There is a small wallet" } , { latin = "hunaak kitaab jadiid" , kana = "フゥナーク キターブ ジャディード" , arabic = "هَناك كِتاب جَديد" , meaning = "There is a new book" } , { latin = "hunaak kitaab Saghiir" , kana = "フゥナーク キターブ サギール" , arabic = "هُناك كِتاب صَغير" , meaning = "There is a small book" } , { latin = "hunaak qubb3a fii shanTatak yaa buub" , kana = "フゥナーク クッバア フィー シャンタタク ヤー ブーブ" , arabic = "هُناك قُبَّعة في شَنْطَتَك يا بوب" , meaning = "There is a hat in your bag bob" } , { latin = "hunaak shanTa Saghiira" , kana = "フゥナーク シャンタ サギーラ" , arabic = "هُناك شَنْطة صَغيرة" , meaning = "There is a small bag" } , { latin = "shanTatii hunaak" , kana = "シャンタティー フゥナーク" , arabic = "شَنْطَتي هُناك" , meaning = "my bag is over there" } , { latin = "hunaak kitaab Saghiir wa-wishaaH kabiir fii ShanTatii" , kana = "フゥナーク キターブ サギール ワ ウィシャーハ カビール フィー シャンタティー" , arabic = "هُناك كِتاب صَغير وَوِشاح كَبير في شَنْطَتي" , meaning = "There is a small book and a big scarf in my bag" } , { latin = "hunaak maHfaDha Saghiir fii shanTatii" , kana = "フゥナーク マハファザ サギール フィー シャンタティー" , arabic = "هُناك مَحْفَظة صَغيرة في شَنْطَتي" , meaning = "There is a small wallet in my bag" } , { latin = "aljaami3a hunaak" , kana = "アルジャーミア フゥナーク" , arabic = "اَلْجامِعة هُناك" , meaning = "The university is there" } , { latin = "hunaak kitaab" , kana = "フゥナーク キターブ" , arabic = "هُناك كِتاب" , meaning = "There is a book" } , { latin = "al-madiina hunaak" , kana = "アルマディーナ フゥナーク" , arabic = "اَلْمَدينة هُناك" , meaning = "Thecity is there" } , { latin = "hal 3indik shanTa ghaaliya yaa Riim" , kana = "ハル アインディク シャンタ ガーリヤ ヤー リーム" , arabic = "هَل عِندِك شَنْطة غالْية يا ريم" , meaning = "do you have an expensive bag Reem" } , { latin = "hal 3indik mashruub yaa saamya" , kana = "ハル アインディク マシュルーブ ヤー サーミヤ" , arabic = "هَل عِنْدِك مَشْروب يا سامْية" , meaning = "do you have a drink samia" } , { latin = "hunaak daftar rakhiiS" , kana = "フゥナーク ダフタル ラクヒース" , arabic = "هُناك دَفْتَر رَخيص" , meaning = "There is a cheep notebook" } , { latin = "laysa 3indii daftar" , kana = "ライサ アインディー ダフタル" , arabic = "لَيْسَ عِنْدي دَفْتَر" , meaning = "I do not have a notebook" } , { latin = "laysa hunaak masharuub fii shanTatii" , kana = "ライサ フゥナーク マシャルーブ フィー シャンタティー" , arabic = "لَيْسَ هُناك مَشْروب في شَنْطَتي" , meaning = "There is no drink in my bag" } , { latin = "laysa hunaak kitaab qaSiir fii baytii" , kana = "ライサ フゥナーク キターブ カスィール フィー バイティ" , arabic = "لَيْسَ هُناك كِتاب قَصير في بَيْتي" , meaning = "There is no short book in my house" } , { latin = "laysa hunaak daftar rakhiiS" , kana = "ライサ フゥナーク ダフタル ラクヒース" , arabic = "لَيْسَ هُناك دَفْتَر رَخيص" , meaning = "There is no cheap notebook" } , { latin = "laysa 3indii sii dii" , kana = "ライサ アインディー スィー ヂー" , arabic = "لَيْسَ عَنْدي سي دي" , meaning = "I do not have a CD" } , { latin = "laysa hunaak qalam fii shanTatii" , kana = "ライサ フゥナーク カラム フィー シャンタティー" , arabic = "لَيْسَ هُناك قَلَم في شَنْطَتي" , meaning = "There is no pen in my bag" } , { latin = "laysa hunaak kitaab qaSiir fii shanTatii" , kana = "ライサ フゥナーク キターブ カスィール フィー シャンタティー" , arabic = "لَيْسَ هُناك كِتاب قَصير في شَنْطَتي" , meaning = "There is no short book in my bag" } , { latin = "laysa hunaak daftar 2abyaD" , kana = "ライサ フゥナーク ダフタル アビヤド" , arabic = "لَيْسَ هُناك دَفْتَر أَبْيَض" , meaning = "There is no white notebook." } , { latin = "maTbakh" , kana = "マタバクフ" , arabic = "مَطْبَخ" , meaning = "a kitchen" } , { latin = "3ilka" , kana = "アイルカ" , arabic = "عِلْكة" , meaning = "chewing gum" } , { latin = "miftaaH" , kana = "ミフターフ" , arabic = "مفْتاح" , meaning = "a key" } , { latin = "tuub" , kana = "トゥーブ" , arabic = "توب" , meaning = "top" } , { latin = "nuquud" , kana = "ヌクード" , arabic = "نُقود" , meaning = "money, cash" } , { latin = "aljazeera" , kana = "アルジャズィーラ" , arabic = "الجزيرة" , meaning = "Al Jazeera" } , { latin = "kursii" , kana = "クルスィー" , arabic = "كَرْسي" , meaning = "a chair" } , { latin = "sari3" , kana = "サリア" , arabic = "سَريع" , meaning = "fast" } , { latin = "Haasuub" , kana = "ハースーブ" , arabic = "حاسوب" , meaning = "a computer" } , { latin = "maktab" , kana = "マクタブ" , arabic = "مَكْتَب" , meaning = "office, desk" } , { latin = "hadhaa maktab kabiir" , kana = "ハーザー マクタブ カビール" , arabic = "هَذا مَِكْتَب كَبير" , meaning = "This is a big office" } , { latin = "kursii alqiTTa" , kana = "クルスィー アルキッタ" , arabic = "كُرْسي الْقِطّة" , meaning = "the cat's chair" } , { latin = "Haasuub al-2ustaadha" , kana = "ハースーブ アル ウスターザ" , arabic = "حاسوب اَلْأُسْتاذة" , meaning = "professor's computer" } , { latin = "kursii jadiid" , kana = "クルスィー ジャディード" , arabic = "كُرْسي جَديد" , meaning = "a new chair" } , { latin = "SaHiifa" , kana = "サヒーファ" , arabic = "صَحيفة" , meaning = "newspaper" } , { latin = "haatif" , kana = "ハーティフ" , arabic = "هاتِف" , meaning = "phone" } , { latin = "2amriikiyy" , kana = "アムりーキーイ" , arabic = "أمْريكِي" , meaning = "American" } , { latin = "2amriikaa wa-a-S-Siin" , kana = "アムりーカー ワ アッスィーン" , arabic = "أَمْريكا وَالْصّين" , meaning = "America and China" } , { latin = "qahwa" , kana = "かハワ" , arabic = "قَهْوة" , meaning = "coffee" } , { latin = "Haliib" , kana = "ハリーブ" , arabic = "حَليب" , meaning = "milk" } , { latin = "muuza" , kana = "ムーザ" , arabic = "موزة" , meaning = "a banana" } , { latin = "2akl" , kana = "アクル" , arabic = "أَكْل" , meaning = "food" } , { latin = "2akl 3arabiyy wa-qahwa 3arabiyy" , kana = "アクル アラビーイ ワ かハワ アラビーイ" , arabic = "أَكْل عَرَبيّ وَقَهْوة عَرَبيّة" , meaning = "Arabic food and Arabic coffee" } , { latin = "ruzz" , kana = "ルッズ" , arabic = "رُزّ" , meaning = "rice" } , { latin = "ruzzii wa-qahwatii" , kana = "ルッズイー ワ かハワティー" , arabic = "رُزّي وَقَهْوَتي" , meaning = "my rice and my coffee" } , { latin = "qahwatii fii shanTatii" , kana = "かハワティー フィー シャンタティー" , arabic = "قَهْوَتي في شَنْطَتي" , meaning = "My coffee is in my bag" } , { latin = "qahwa <NAME>" , kana = "かハワ スィース" , arabic = "قَهْوَة سيث" , meaning = "Seth's coffee" } , { latin = "Sadiiqat-haa" , kana = "すぁディーかトハー" , arabic = "صَديقَتها" , meaning = "her friend" } , { latin = "jaarat-haa" , kana = "ジャーラト ハー" , arabic = "جارَتها" , meaning = "her neighbor" } , { latin = "2ukhtii" , kana = "ウクフティ" , arabic = "أُخْتي" , meaning = "my sister" } , { latin = "Sadiiqa jayyida" , kana = "サディーカ ジャイイダ" , arabic = "صَديقة جَيِّدة" , meaning = "a good friend" }أ , { latin = "2a3rif" , arabic = "أَعْرِف" , meaning = "I know" } , { latin = "2anaa 2a3rifhu" , kana = "アナー アーリフフゥ" , arabic = "أَنا أَعْرِفه" , meaning = "I know him" } , { latin = "Taawila Tawiila" , kana = "ターウィラ タウィーラ" , arabic = "طاوِلة طَويلة" , meaning = "a long table" } , { latin = "baytik wa-bayt-haa" , kana = "バイティク ワ バイトハー" , arabic = "بَيْتِك وَبَيْتها" , meaning = "your house and her house" } , { latin = "ism Tawiil" , kana = "イスム タウィール" , arabic = "اِسْم طَويل" , meaning = "long name" } , { latin = "baytii wa-baythaa" , kana = "バイティー ワ バイトハー" , arabic = "بَيْتي وَبَيْتها" , meaning = "my house and her house" } , { latin = "laysa hunaak lugha Sa3ba" , kana = "ライサ フゥナーク ルガ サアバ" , arabic = "لَيْسَ هُناك لُغة صَعْبة" , meaning = "There is no diffcult language." } , { latin = "hadhaa shay2 Sa3b" , kana = "ハーザー シャイ サアバ" , arabic = "هَذا شَيْء صَعْب" , meaning = "This is a difficult thing." } , { latin = "ismhu taamir" , kana = "イスムフゥ ターミル" , arabic = "اِسْمهُ تامِر" , meaning = "His name is Tamer." } , { latin = "laa 2a3rif 2ayn bayt-hu" , kana = "ラー アーリフ アイン バイトフゥ" , arabic = "لا أَعْرِف أَيْن بَيْته" , meaning = "I don't know where his house is" } , { latin = "laa 2a3rif 2ayn 2anaa" , kana = "ラー アーリフ アイン アナー" , arabic = "لا أعرف أين أنا." , meaning = "I don't know where I am." } , { latin = "bayt-hu qariib min al-jaami3a" , kana = "バイトフゥ カリーブ ミン アル ジャーミア" , arabic = "بيته قريب من الجامعة" , meaning = "His house is close to the university" } , { latin = "ismhaa arabiyy" , kana = "イスムハー アラビーイ" , arabic = "إسمها عربي" , meaning = "Her name is arabic." } , { latin = "riim Sadiiqa Sa3ba" , kana = "リーム サディーカ サアバ" , arabic = "ريم صديقة صعبة" , meaning = "Reem is a difficult friend." } , { latin = "ismhu bashiir" , kana = "イスムフゥ バシール" , arabic = "إسمه بشير" , meaning = "HIs name is <NAME>." } , { latin = "ismhaa Tawiil" , kana = "イスムハー タウィール" , arabic = "إسمها طويل" , meaning = "Her name is long." } , { latin = "Sadiiqhaa buub qariib min baythaa" , kana = "サディークハー ブーブ カリーブ ミン バイトハー" , arabic = "صديقها بوب قريب من بيتها" , meaning = "Her friend <NAME> is close to her house." } , { latin = "ismhu buub" , kana = "イスムフゥ ブーブ" , arabic = "إسمه بوب" , meaning = "His name is <NAME>." } , { latin = "baythu qariib min baythaa" , kana = "バイトフゥ カリーブ ミン バイトハー" , arabic = "بيته قريب من بيتها" , meaning = "His house is close to her house." } , { latin = "hadhaa shay2 Sa3b" , kana = "ハーザー シャイ サアブ" , arabic = "هذا شيء صعب" , meaning = "This is a difficult thing." } , { latin = "3alaaqa" , kana = "アラーカ" , arabic = "عَلاقَة" , meaning = "relationship" } , { latin = "al-qiTTa" , kana = "アルキッタ" , arabic = "اَلْقِطّة" , meaning = "the cat" } , { latin = "laa 2uhib" , kana = "ラー ウひッブ" , arabic = "لا أُحِب" , meaning = "I do not like" } , { latin = "al-2akl mumti3" , kana = "アルアクル ムムティア" , arabic = "اَلْأَكْل مُمْتع" , meaning = "Eating is fun." } , { latin = "al-qiraa2a" , kana = "アルキラーエ" , arabic = "اَلْقِراءة" , meaning = "reading" } , { latin = "alkitaaba" , kana = "アルキターバ" , arabic = "الْكِتابة" , meaning = "writing" } , { latin = "alkiraa2a wa-alkitaaba" , kana = "アルキラーエ ワ アルキターバ" , arabic = "اَلْقِراءة وَالْكِتابة" , meaning = "reading and writing" } , { latin = "muhimm" , kana = "ムヒンム" , arabic = "مُهِمّ" , meaning = "important" } , { latin = "alkiaaba shay2 muhimm" , kana = "アルキターバ シャイ ムヒンム" , arabic = "اَلْكِتابة شَيْء مُهِمّ" , meaning = "Writing is an important thing." } , { latin = "al-jaara wa-al-qiTTa" , kana = "アル ジャーラ ワ アル キッタ" , arabic = "اَلْجارة وَالْقِطّة" , meaning = "the neighbor and the cat" } , { latin = "qiTTa wa-alqiTTa" , kana = "キッタ ワ アルキッタ" , arabic = "قِطّة وَالْقِطّة" , meaning = "a cat and the cat" } , { latin = "2ayDan" , kana = "アイだン" , arabic = "أَيْضاً" , meaning = "also" } , { latin = "almaT3m" , kana = "アル マたあム" , arabic = "الْمَطْعْم" , meaning = "the restaurant" } , { latin = "maa2" , kana = "マー" , arabic = "ماء" , meaning = "water" } , { latin = "maT3am" , kana = "マタム" , arabic = "مَطْعَم" , meaning = "a restaurant" } , { latin = "a-t-taSwiir" , kana = "アッタスウィール" , arabic = "اَلْتَّصْوير" , meaning = "photography" } , { latin = "a-n-nawm" , kana = "アンナウム" , arabic = "اَلْنَّوْم" , meaning = "sleeping, sleep" } , { latin = "a-s-sibaaha" , kana = "アッスィバーハ" , arabic = "اَلْسِّباحة" , meaning = "swimming" } , { latin = "Sabaahan 2uhibb al-2akl hunaa" , kana = "サバーハン ウひッブ アルアクル フゥナー" , arabic = "صَباحاً أُحِبّ اَلْأَكْل هُنا" , meaning = "In the morning, I like eating here." } , { latin = "kathiiraan" , kana = "カシーラン" , arabic = "كَثيراً" , meaning = "much" } , { latin = "hunaa" , kana = "フゥナー" , arabic = "هُنا" , meaning = "here" } , { latin = "jiddan" , kana = "ジッダン" , arabic = "جِدَّاً" , meaning = "very" } , { latin = "3an" , kana = "アン" , arabic = "عَن" , meaning = "about" } , { latin = "2uhibb a-s-safar 2ilaa 2iiTaaliyaa" , kana = "ウひッブ アッサファル いらー イーターリヤー" , arabic = "أُحِبّ اَلْسَّفَر إِلى إيطالْيا" , meaning = "I like traveling to Italy." } , { latin = "al-kalaam ma3a 2abii" , kana = "アルカラーム マア アビー" , arabic = "اَلْكَلام مَعَ أَبي" , meaning = "talking with my father" } , { latin = "2uHibb aljarii bi-l-layl" , kana = "ウひッブ アルジャリー ビッライル" , arabic = "أُحِبّ اَلْجَري بِالْلَّيْل" , meaning = "I like running at night." } , { latin = "2uriidu" , kana = "ウりード" , arabic = "أُريدُ" , meaning = "I want" } , { latin = "2uHibb 2iiTaaliyaa 2ayDan" , kana = "ウひッブ イーターリヤー アイダン" , arabic = "أُحِبّ إيطاليا أَيْضاً" , meaning = "I like Italy also." } , { latin = "2uHibb alqiraa2a 3an kuubaa bi-l-layl" , kana = "ウひッブ アルキラーア アン クーバー ビッライル" , arabic = "أُحِبّ اَلْقِراءة عَن كوبا بِالْلَّيْل" , meaning = "I like reading about Cuba at night." } , { latin = "2uHibb al-kalaam 3an il-kitaaba" , kana = "ウひッブ アル カラーム アニル キターバ" , arabic = "أحِبّ اَلْكَلام عَن اَلْكِتابة" , meaning = "I like talking about writing." } , { latin = "alqur2aan" , kana = "アルクルアーン" , arabic = "اَلْقُرْآن" , meaning = "Koran" } , { latin = "bayt jamiil" , kana = "バイト ジャミール" , arabic = "بَيْت جَميل" , meaning = "a pretty house" } , { latin = "mutarjim mumtaaz" , kana = "ムタるジム ムムターズ" , arabic = "مُتَرْجِم مُمْتاز" , meaning = "an amazing translator" } , { latin = "jaami3a mash-huura" , kana = "ジャーミア マシュフーラ" , arabic = "جامِعة مَشْهورة" , meaning = "a famous university" } , { latin = "al-bayt al-jamiil" , kana = "アルバイト アルジャミール" , arabic = "اَلْبَيْت اَلْجَميل" , meaning = "the pretty house" } , { latin = "al-bint a-s-suuriyya" , kana = "アル ビンタ ッスーリヤ" , arabic = "اَلْبِنْت اَلْسّورِيّة" , meaning = "a Syrian girl" } , { latin = "al-mutarjim al-mumtaaz" , kana = "アルムタルジム アルムムターズ" , arabic = "اَلْمُتَرْجِم اَلْمُمْتاز" , meaning = "the amazing translator" } , { latin = "al-jaami3a al-mash-huura" , kana = "アルジャーミア アルマシュフーラ" , arabic = "اَلْجامِعة اَلْمَشْهورة" , meaning = "the famous university" } , { latin = "al-bayt jamiil" , kana = "アルバイト ジャミール" , arabic = "اَلْبَيْت جَميل" , meaning = "The house is pretty." } , { latin = "al-bint suuriyya" , kana = "アルビント スーリーヤ" , arabic = "البنت سورِيّة" , meaning = "The girl is Syrian." } , { latin = "al-mutarjim mumtaaz" , kana = "アルムタルジム ムムターズ" , arabic = "اَلْمُتَرْجِم مُمْتاز" , meaning = "The translator is amazing." } , { latin = "al-jaami3a mash-huura" , kana = "アルジャーミア マシュフーラ" , arabic = "اَلْجامِعة مَشْهورة" , meaning = "The university is famous." } , { latin = "maTar" , kana = "マタル" , arabic = "مَطَر" , meaning = "rain" } , { latin = "yawm Tawiil" , kana = "ヤウム タウィール" , arabic = "يَوْم طَويل" , meaning = "a long day" } , { latin = "haadhaa yawm Tawiil" , kana = "ハーザー ヤウム タウィール" , arabic = "هَذا يَوْم طَويل" , meaning = "This is a long day." } , { latin = "shanTa fafiifa" , kana = "シャンタ ファフィーファ" , arabic = "شَنْطة خَفيفة" , meaning = "a light bag" } , { latin = "al-maTar a-th-thaqiil mumtaaz" , kana = "アルマタル アッサキール ムムターズ" , arabic = "اَلْمَطَر اَلْثَّقيل مُمْتاز" , meaning = "The heavy rain is amazing." } , { latin = "Taqs ghariib" , kana = "タクス ガリーブ" , arabic = "طَقْس غَريب" , meaning = "a weird weather" } , { latin = "yawm Haarr" , kana = "ヤウム ハール" , arabic = "يَوْم حارّ" , meaning = "a hot day" } , { latin = "Taawila khafiifa" , kana = "ターウィラ クハフィーファ" , arabic = "طاوِلة خَفيفة" , meaning = "a light table" } , { latin = "Taqs jamiil" , kana = "タクス ジャミール" , arabic = "طَقْس جَميل" , meaning = "a pretty weather" } , { latin = "al-maTar a-th-thaqiil mumtaaz" , kana = "アルマタル アッサキール ムムターズ" , arabic = "اَلْمَطَر اَلْثَّقيل مُمْتاز" , meaning = "The heavy rain is amazing." } , { latin = "haadhaa yawm Haarr" , kana = "ハーザー ヤウム ハール" , arabic = "هَذا يَوْم حارّ" , meaning = "This is a hot day." } , { latin = "shanTa khafiifa" , kana = "シャンタ クハフィーファ" , arabic = "شَنْطة خَفيفة" , meaning = "a light bag" } , { latin = "hunaak maTar baarid jiddan" , kana = "フゥナーク マタル バーリド ジッダン" , arabic = "هُناك مَطَر بارِد جِدّاً" , meaning = "There is a very cold rain." } , { latin = "Sayf" , kana = "サイフ" , arabic = "صّيْف" , meaning = "summer" } , { latin = "shitaa2" , kana = "シター" , arabic = "شِتاء" , meaning = "winter" } , { latin = "shitaa2 baarid" , kana = "シター バーリド" , arabic = "شِتاء بارِد" , meaning = "cold winter" } , { latin = "binaaya 3aalya" , kana = "ビナーヤ アーリヤ" , arabic = "بِناية عالْية" , meaning = "a high building" } , { latin = "yawm baarid" , kana = "ヤウム バーリド" , arabic = "يَوْم بارِد" , meaning = "a cold day" } , { latin = "ruTuuba 3aalya" , kana = "ルトゥーバ アーリヤ" , arabic = "رُطوبة عالْية" , meaning = "high humidity" } , { latin = "Sayf mumTir" , kana = "サイフ ムムティル" , arabic = "صَيْف مُمْطِر" , meaning = "a rainy summer" } , { latin = "a-r-ruTuubat al3aalya" , kana = "アッルルトゥーバト アラーリヤ" , arabic = "اَلْرُّطوبة الْعالْية" , meaning = "the high humidity" } , { latin = "a-T-Taqs al-mushmis" , kana = "アッタクス アルムシュミス" , arabic = "اّلْطَّقْس الّْمُشْمِس" , meaning = "the sunny weather" } , { latin = "shitaa2 mumTir" , kana = "シター ムムティル" , arabic = "شِتاء مُمْطِر" , meaning = "a rainy winter" } , { latin = "Sayf Haarr" , kana = "サイフ ハール" , arabic = "صَيْف حارّ" , meaning = "a hot summer" } , { latin = "al-yawm yawm Tawiil" , kana = "アルヤウム ヤウム タウィール" , arabic = "اَلْيَوْم يَوْم طَويل" , meaning = "Today is a long day." } , { latin = "laa 2uhibb a-T-Taqs al-mushmis" , kana = "ラー ウひッブ アッタクス アルムシュミス" , arabic = "لا أُحِبّ اَلْطَقْس اَلْمُشْمِس" , meaning = "I do not like sunny weather." } , { latin = "a-T-Taqs mumTir jiddan al-yawm" , kana = "アッタクス ムムティル ジッダン アルヤウム" , arabic = "اَلْطَقْس مُمْطِر جِدّاً اَلْيَوْم" , meaning = "The weather is very rainy today." } , { latin = "laa 2uhibb a-T-Taqs al-mumTir" , kana = "ラー ウひッブ アッタクス アルムティル" , arabic = "لا أحِبّ اَلْطَّقْس اَلْمُمْطِر" , meaning = "I do not like the rainy weather." } , { latin = "a-T-Taqs mushmis al-yawm" , kana = "アッタクス ムシュミス アルヤウム" , arabic = "اَلْطَّقْس مُشْمِس اَلْيَوْم" , meaning = "The weather is sunny today." } , { latin = "khariif" , kana = "ハリーフ" , arabic = "خَريف" , meaning = "fall, autumn" } , { latin = "qamar" , kana = "カマル" , arabic = "قَمَر" , meaning = "moon" } , { latin = "rabii3" , kana = "ラビーア" , arabic = "رَبيع" , meaning = "spring" } , { latin = "a-sh-shitaa2 mumTir" , kana = "アッシター ムムティル" , arabic = "اَلْشِّتاء مُمْطِر" , meaning = "The winter is rainy." } , { latin = "a-S-Sayf al-baarid" , kana = "アッサイフ アルバーリド" , arabic = "اَلْصَّيْف اَلْبارِد" , meaning = "the cold summer" } , { latin = "al-qamar al-2abyaD" , kana = "アルカマル アルアビヤド" , arabic = "اَلْقَمَر اَلْأَبْيَض" , meaning = "the white moon" } , { latin = "a-sh-shitaa2 Tawiil wa-baarid" , kana = "アッシター タウィール ワ バーリド" , arabic = "اَلْشِّتاء طَويل وَبارِد" , meaning = "The winter is long and cold." } , { latin = "a-r-rabii3 mumTir al-2aan" , kana = "アッラビーア ムムティル アルアーン" , arabic = "اَلْرَّبيع مُمْطِر اَلآن" , meaning = "The spring is rainy now" } , { latin = "Saghiir" , kana = "サギール" , arabic = "صَغير" , meaning = "small" } , { latin = "kashiiran" , kana = "カシーラン" , arabic = "كَثيراً" , meaning = "a lot, much" } , { latin = "a-S-Siin" , kana = "アッスィーン" , arabic = "اَلْصّين" , meaning = "China" } , { latin = "al-qaahira" , kana = "アル カーヒラ" , arabic = "اَلْقاهِرة" , meaning = "Cairo" } , { latin = "al-bunduqiyya" , kana = "アル ブンドゥキーヤ" , arabic = "اَلْبُنْدُقِية" , meaning = "Venice" } , { latin = "filasTiin" , kana = "フィラスティーン" , arabic = "فِلَسْطين" , meaning = "Palestine" } , { latin = "huulandaa" , kana = "フーランダー" , arabic = "هولَنْدا" , meaning = "Netherlands, Holland" } , { latin = "baghdaad" , kana = "バグダード" , arabic = "بَغْداد" , meaning = "Bagdad" } , { latin = "Tuukyuu" , kana = "トーキョー" , arabic = "طوكْيو" , meaning = "Tokyo" } , { latin = "al-yaman" , kana = "アル ヤマン" , arabic = "اَلْيَمَن" , meaning = "Yemen" } , { latin = "SaaHil Tawiil" , kana = "サーヒル タウィール" , arabic = "ساحَل طَويل" , meaning = "a long coast" } , { latin = "al-2urdun" , kana = "アル ウルドゥン" , arabic = "اَلْأُرْدُن" , meaning = "Jordan" } , { latin = "haadha l-balad" , kana = "ハーザ ル バラド" , arabic = "هَذا الْبَلَد" , meaning = "this country" } , { latin = "2ayn baladik yaa riim" , kana = "アイン バラディク ヤー リーム" , arabic = "أَيْن بَلَدِك يا ريم" , meaning = "Where is your country, Reem?" } , { latin = "baladii mumtaaz" , kana = "バラディー ムムターズ" , arabic = "بَلَدي مُمْتاز" , meaning = "My country is amazing." } , { latin = "haadhaa balad-haa" , kana = "ハーザー バラドハー" , arabic = "هَذا بَلَدها" , meaning = "This is her country." } , { latin = "hal baladak jamiil yaa juurj?" , kana = "ハル バラダク ジャミール ヤー ジュールジュ" , arabic = "هَل بَلَدَك جَميل يا جورْج" , meaning = "Is your country pretty, George" } , { latin = "al-yaman balad Saghiir" , kana = "アルヤマン バラド サギール" , arabic = "اَلْيَمَن بَلَد صَغير" , meaning = "Yemen is a small country." } , { latin = "qaari2" , kana = "カーリー" , arabic = "قارِئ" , meaning = "reader" } , { latin = "ghaa2ib" , kana = "ガーイブ" , arabic = "غائِب" , meaning = "absent" } , { latin = "mas2uul" , kana = "マスウール" , arabic = "مَسْؤول" , meaning = "responsoble, administrator" } , { latin = "jaa2at" , kana = "ジャーアト" , arabic = "جاءَت" , meaning = "she came" } , { latin = "3indii" , kana = "アインディー" , arabic = "عِنْدي" , meaning = "I have" } , { latin = "3indik" , kana = "アインディク" , arabic = "عِنْدِك" , meaning = "you have" } , { latin = "ladii kitaab" , kana = "ラディー キターブ" , arabic = "لَدي كِتاب" , meaning = "I have a book." } , { latin = "3indhaa" , kana = "アインドハー" , arabic = "عِنْدها" , meaning = "she has" } , { latin = "3indhu" , kana = "アインドフゥ" , arabic = "عِنْدهُ" , meaning = "he has" } , { latin = "laysa 3indhu" , kana = "ライサ アインドフゥ" , arabic = "لَيْسَ عِنْدهُ" , meaning = "he does not have" } , { latin = "laysa 3indhaa" , kana = "ライサ アインドハー" , arabic = "لَيْسَ عِنْدها" , meaning = "she does not have" } , { latin = "hunaak maTar thaqiil" , kana = "フゥナーク マタル サキール" , arabic = "هُناك مَطَر ثَقيل" , meaning = "There is a heavy rain." } , { latin = "hunaak wishaaH fii shanTatii" , kana = "フゥナーク ウィシャーハ フィー シャンタティー" , arabic = "هُناك وِشاح في شَنْطتي" , meaning = "There is a scarf in my bag." } , { latin = "2amaamii rajul ghariib" , kana = "アマーマミー ラジュル ガリーブ" , arabic = "أَمامي رَجُل غَريب" , meaning = "There is a weird man in front of me." } , { latin = "fi l-khalfiyya bayt" , kana = "フィル クハルフィーヤ バイト" , arabic = "في الْخَلفِيْة بَيْت" , meaning = "There is a house in the background." } , { latin = "fii shanTatii wishaaH" , kana = "フィー シャンタティー ウィシャーハ" , arabic = "في شَنْطَتي وِشاح" , meaning = "There is a scarf in my bag." } , { latin = "2asad" , kana = "アサド" , arabic = "أَسَد" , meaning = "a lion" } , { latin = "2uHibb 2asadii laakinn laa 2uHibb 2asadhaa" , kana = "ウひッブ アサディ ラキン ラー ウひッブ アサドハー" , arabic = "أحِبَ أَسَدي لَكِنّ لا أُحِبّ أَسَدها" , meaning = "I like my lion but I do not like her lion." } , { latin = "laysa 3indhu" , kana = "ライサ アインドフゥ" , arabic = "لَيْسَ عِنْدهُ" , meaning = "he does not have" } , { latin = "3indhaa kalb wa-qiTTa" , kana = "アインドハー カルブ ワ キッタ" , arabic = "عِنْدها كَلْب وَقِطّة" , meaning = "She has a doc and a cat." } , { latin = "Sadiiqat-hu saamia ghaniyya" , kana = "すぁディーかトフゥ サーミヤ ガニーヤ" , arabic = "صَديقَتهُ سامْية غَنِيّة" , meaning = "His friend Samia is rich." } , { latin = "taariikhiyya" , kana = "ターリークヒーヤ" , arabic = "تاريخِيّة" , meaning = "historical" } , { latin = "juurj 3indhu 3amal mumtaaz" , kana = "ジュールジュ アインドフゥ アアマル ムムターズ" , arabic = "جورْج عِنْدهُ عَمَل مُمْتاز" , meaning = "George has an amazing work." } , { latin = "Sadiiqii taamir ghaniyy jiddan" , kana = "サディーキー ターミル ガニーイ ジッダン" , arabic = "صَديقي تامِر غَنِيّ جِدّاً" , meaning = "My friend <NAME> is very rich" } , { latin = "laa 2a3rif haadha l-2asad" , kana = "ラー アーリフ ハーザ ル アサド" , arabic = "لا أَعْرِف هَذا الْأَسّد" , meaning = "I do not know this lion." } , { latin = "laysa 3indhu ma3Taf" , kana = "ライサ アインドフゥ マアタフ" , arabic = "لَيْسَ عِنْدهُ معْطَف" , meaning = "He does not have a coat." } , { latin = "fi l-khalfiyya zawjatak yaa siith" , kana = "フィ ル クハルフィーヤ ザウジャタク ヤー スィース" , arabic = "في الْخَلْفِيّة زَوْجَتَك يا سيث" , meaning = "There is your wife in background, Seth" } , { latin = "su2uaal" , kana = "スウアール" , arabic = "سُؤال" , meaning = "a question" } , { latin = "Sadiiqat-hu saamya laabisa tannuura" , kana = "すぁディーかトフゥ サーミヤ ラービサ タンヌーラ" , arabic = "صدَيقَتهُ سامْية لابِسة تّنّورة" , meaning = "His friend <NAME> is wearing a skirt." } , { latin = "wa-hunaa fi l-khalfiyya rajul muD-Hik" , kana = "ワ フゥナー フィル クハルフィーヤ ラジュル ムドヒク" , arabic = "وَهُنا في الْخَلْفِتّة رَجُل مُضْحِك" , meaning = "And here in the background there is a funny man." } , { latin = "man haadhaa" , kana = "マン ハーザー" , arabic = "مَن هَذا" , meaning = "Who is this?" } , { latin = "hal 2anti labisa wishaaH yaa lamaa" , kana = "ハル アンティ ラビサ ウィシャーハ ヤー ラマー" , arabic = "هَل أَنْتِ لابِسة وِشاح يا لَمى" , meaning = "Are you wering a scarf, Lama?" } , { latin = "2akhii bashiir mashghuul" , kana = "アクヒー バシール マシュグール" , arabic = "أَخي بَشير مَشْغول" , meaning = "My brother <NAME> is busy." } , { latin = "fii haadhihi a-S-Suura imraa muD-Hika" , kana = "フィー ハージヒ アッスーラ イムラア ムドヒカ" , arabic = "في هَذِهِ الْصّورة اِمْرأة مُضْحِكة" , meaning = "Thre is a funny woman in this picture." } , { latin = "hal 2anta laabis qubb3a yaa siith" , kana = "ハル アンタ ラービス クッバ ヤー スィース" , arabic = "هَل أَنْتَ لابِس قُبَّعة يا سيث" , meaning = "Are you wearing a hat, Seth?" } , { latin = "fi l-khalfiyya rajul muD-Hik" , kana = "フィル クハルフィーヤ ラジュル ムドヒク" , arabic = "في الْخَلْفِيّة رَجُل مُضْحِك" , meaning = "There is a funny man in the background." } , { latin = "shub-baak" , kana = "シュッバーク" , arabic = "شُبّاك" , meaning = "a window" } , { latin = "sariir" , kana = "サリール" , arabic = "سَرير" , meaning = "a bed" } , { latin = "saadii 2ustaadhii" , kana = "サーディー ウスタージー" , arabic = "شادي أُسْتاذي" , meaning = "Sadie is my teacher." } , { latin = "2ummhu" , kana = "ウンムフゥ" , arabic = "أُمّهُ" , meaning = "his mother" } , { latin = "maa haadhaa a-S-Sawt" , kana = "マー ハーザー アッサウト" , arabic = "ما هَذا الْصَّوْت" , meaning = "What is this noise" } , { latin = "2adkhul al-Hammaam" , kana = "アドクフル アルハンマーム" , arabic = "أَدْخُل اَلْحَمّام" , meaning = "I enter the bathroom." } , { latin = "2uHibb a-s-sariir al-kabiir" , kana = "ウひッブ アッサリール アルカビール" , arabic = "أُحِبّ اَلْسَّرير اَلْكَبير" , meaning = "I love the big bed." } , { latin = "hunaak Sawt ghariib fi l-maTbakh" , kana = "フゥナーク サウト ガリーブ フィル マトバクフ" , arabic = "هُناك صَوْت غَريب في الْمَطْبَخ" , meaning = "There is a weird nose in the kitchen." } , { latin = "2anaam fi l-ghurfa" , kana = "アナーム フィル グルファ" , arabic = "أَنام في الْغُرْفة" , meaning = "I sleep in the room." } , { latin = "tilfaaz Saghiir fii Saaluun kabiir" , kana = "ティルファーズ サギール フィー サールーン カビール" , arabic = "تِلْفاز صَغير في صالون كَبير" , meaning = "a small television in a big living room" } , { latin = "2anaam fii sariir maksuur" , kana = "アナーム フィー サリール マクスール" , arabic = "أَنام في سَرير مَكْسور" , meaning = "I sleep in a broken bed." } , { latin = "a-s-sariir al-kabiir" , kana = "アッサリール アルカビール" , arabic = "اَلْسَّرير اَلْكَبير" , meaning = "the big bed" } , { latin = "maa haadhaa a-S-Swut" , kana = "マー ハーザー アッスウト" , arabic = "ما هَذا الصّوُت" , meaning = "What is this noise?" } , { latin = "sariirii mumtaaz al-Hamdu li-l-laa" , kana = "サリーリー ムムターズ アルハムド リッラー" , arabic = "سَريري مُمتاز اَلْحَمْدُ لِله" , meaning = "My bed is amazing, praise be to God" } , { latin = "2anaam kathiiran" , kana = "アナーム カシーラン" , arabic = "أَنام كَشيراً" , meaning = "I sleep a lot" } , { latin = "hunaak Sawt ghariib" , kana = "フゥナーク サウト ガリーブ" , arabic = "هُناك صَوْت غَريب" , meaning = "There is a weird noise." } , { latin = "shub-baak" , kana = "シュッバーク" , arabic = "شُبّاك" , meaning = "a window" } , { latin = "2anaam fii sariir Saghiir" , kana = "アナーム フィー サリール サギール" , arabic = "أَنام في سَرير صَغير" , meaning = "I sleep in a small bed." } , { latin = "muHammad 2ustaadhii" , kana = "ムハンマド ウスタージー" , arabic = "مُحَمَّد أُسْتاذي" , meaning = "Mohammed is my teacher." } , { latin = "mahaa 2ummhu" , kana = "マハー ウンムフゥ" , arabic = "مَها أُمّهُ" , meaning = "Maha is his mother." } , { latin = "fii haadhaa sh-shaari3 Sawt ghariib" , kana = "フィー ハーザー ッシャーリア サウト ガリーブ" , arabic = "في هٰذا ٱلْشّارِع صَوْت غَريب" , meaning = "There is a weird noise on this street" } , { latin = "2askun fii a-s-saaluun" , kana = "アスクン フィー アッサルーン" , arabic = "أَسْكُن في الْصّالون" , meaning = "I live in the living room." } , { latin = "haadhaa sh-shaari3" , kana = "ハーザー ッシャーリア" , arabic = "هَذا الْشّارِع" , meaning = "this street" } , { latin = "3ind-hu ghurfa nawm Saghiira" , kana = "アインドフゥ グルファ ナウム サギーラ" , arabic = "عِندهُ غُرْفة نَوْم صَغيرة" , meaning = "He has a small bedroom." } , { latin = "laa 2aftaH albaab bisabab l-T-Taqs" , kana = "ラー アフタフ アルバーブ ビサバブ ルッタクス" , arabic = "لا أَفْتَح اَلْباب بِسَبَب اّلْطَّقْس" , meaning = "I do not open the door because of the weather." } , { latin = "Sifr" , kana = "スィフル" , arabic = "صِفْر" , meaning = "zero" } , { latin = "3ashara" , kana = "アシャラ" , arabic = "عَشَرَة" , meaning = "ten" } , { latin = "waaHid" , kana = "ワーヒド" , arabic = "وَاحِد" , meaning = "one" } , { latin = "2ithnaan" , kana = "イスナーン" , arabic = "اِثْنان" , meaning = "two" } , { latin = "kayf ta3uddiin min waaHid 2ilaa sitta" , kana = "カイフ タアウッディーン ミン ワーヒド イラー スィッタ" , arabic = "كَيْف تَعُدّين مِن ١ إِلى ٦" , meaning = "How do you count from one to six?" } , { latin = "bil-lugha" , kana = "ビッルガ" , arabic = "بِالْلُّغة" , meaning = "in language" } , { latin = "bil-lugha l-3arabiya" , kana = "ビッルガルアラビーヤ" , arabic = "بِالْلُّغة الْعَرَبِيّة" , meaning = "in the arabic language" } , { latin = "ta3rifiin" , kana = "ターリフィーン" , arabic = "تَعْرِفين" , meaning = "you know" } , { latin = "hal ta3rifiin kull shay2 yaa mahaa" , kana = "ハル ターリフィーン クル シャイ ヤー マハー" , arabic = "هَل تَعْرِفين كُلّ شَيء يا مَها" , meaning = "Do you know everything Maha?" } , { latin = "kayf ta3udd yaa 3umar" , kana = "カイフ タアウッド ヤ ウマル" , arabic = "كَيْف تَعُدّ يا عُمَر" , meaning = "How do you count Omar?" } , { latin = "Kayf ta3udd min Sifr 2ilaa 2ashara yaa muHammad" , kana = "カイフ タアウッド ミン スィフル イラー アシャラ ヤー ムハンマド" , arabic = "كَيْف تَعُدّ مِن٠ إِلى ١٠ يا مُحَمَّد" , meaning = "How do you count from 0 to 10 , Mohammed?" } , { latin = "hal ta3rif yaa siith" , kana = "ハル ターリフ ヤー スィース" , arabic = "هَل تَعْرِف يا سيث" , meaning = "Do you know Seth?" } , { latin = "bayt buub" , kana = "バイト ブーブ" , arabic = "بَيْت بوب" , meaning = "Bob's house" } , { latin = "maT3am muHammad" , kana = "マタム ムハンマド" , arabic = "مَطْعَم مُحَمَّد" , meaning = "Mohammed's restaurant" } , { latin = "SaHiifat al-muhandis" , kana = "サヒーファト アル ムハンディス" , arabic = "صَحيفة اَلْمُهَنْدِس" , meaning = "the enginner's newspaper" } , { latin = "madiinat diitruuyt" , kana = "マディーナト ディートルーイト" , arabic = "مَدينة ديتْرويْت" , meaning = "the city of Detroit" } , { latin = "jaami3a juurj waashinTun" , kana = "ジャーミア ジュールジュ ワーシントン" , arabic = "جامِعة جورْج واشِنْطُن" , meaning = "George Washinton University" } , { latin = "SabaaHan" , kana = "サバーハン" , arabic = "صَباحاً" , meaning = "in the morning" } , { latin = "masaa2an" , kana = "マサーアン" , arabic = "مَساءً" , meaning = "in the evening" } , { latin = "wilaayatak" , kana = "ウィラーヤタク" , arabic = "وِلايَتَك" , meaning = "your state" } , { latin = "madiina saaHiliyya" , kana = "マディーナ サーヒリーヤ" , arabic = "مَدينة ساحِلِيّة" , meaning = "a coastal city" } , { latin = "muzdaHima" , kana = "ムズダヒマ" , arabic = "مُزْدَحِمة" , meaning = "crowded" } , { latin = "wilaaya kaaliifuurniyaa" , kana = "ウィラーヤ カーリーフールニヤー" , arabic = "وِلاية كاليفورْنْيا" , meaning = "the state of California" } , { latin = "baHr" , kana = "バハル" , arabic = "بَحْر" , meaning = "sea" } , { latin = "DawaaHii" , kana = "ダワーヒー" , arabic = "ضَواحي" , meaning = "suburbs" } , { latin = "taskuniin" , kana = "タスクニーン" , arabic = "تَسْكُنين" , meaning = "you live" } , { latin = "nyuuyuurk" , kana = "ニューユールク" , arabic = "نْيويورْك" , meaning = "New York" } , { latin = "qar-yatik" , kana = "かるヤティク" , arabic = "قَرْيَتِك" , meaning = "your (to female) village" } , { latin = "shubbaak" , kana = "シュッバーク" , arabic = "شُبّاك" , meaning = "a window" } , { latin = "jaziira" , kana = "ジャズィーラ" , arabic = "جَزيرة" , meaning = "an island" } , { latin = "Tabii3a" , kana = "タビーア" , arabic = "طَبيعة" , meaning = "nature" } , { latin = "al-2iskandariyya" , kana = "アル イスカンダリーヤ" , arabic = "اَلْإِسْكَندَرِيّة" , meaning = "Alexandria" } , { latin = "miSr" , kana = "ミスル" , arabic = "مِصْر" , meaning = "Egypt" } , { latin = "na3am" , kana = "ナアム" , arabic = "نَعَم" , meaning = "yes" } , { latin = "SabaaH l-khayr" , kana = "サバーフ ル クハイル" , arabic = "صَباح اَلْخَيْر" , meaning = "Good morning." } , { latin = "SabaaH an-nuur" , kana = "サバーフ アン ヌール" , arabic = "صَباح اَلْنّور" , meaning = "Good morning." } , { latin = "masaa2 al-khayr" , kana = "マサー アル クハイル" , arabic = "مَساء اَلْخَيْر" , meaning = "Good evening" } , { latin = "masaa2 an-nuur" , kana = "マサー アンヌール" , arabic = "مَساء اَلْنّور" , meaning = "Good evening." } , { latin = "tasharrafnaa" , kana = "タシャッラフゥナー" , arabic = "تَشَرَّفْنا" , meaning = "It's a pleasure to meet you." } , { latin = "hal 2anta bi-khyr" , kana = "ハル アンタ ビ クハイル" , arabic = "هَل أَنْتَ بِخَيْر" , meaning = "Are you well?" } , { latin = "kayfak" , kana = "カイファク" , arabic = "كَيْفَك" , meaning = "How are you?" } , { latin = "al-yawm" , kana = "アル ヤウム" , arabic = "اَلْيَوْم" , meaning = "today" } , { latin = "kayfik al-yawm" , kana = "カイフィク アル ヤウム" , arabic = "كَيْفِك اَلْيَوْم" , meaning = "How are you today?" } , { latin = "marHaban ismii buub" , kana = "マルハバン イスミー ブーブ" , arabic = "مَرْحَباً اِسْمي بوب" , meaning = "Hello, my name is <NAME>." } , { latin = "mariiD" , kana = "マリード" , arabic = "مَريض" , meaning = "sick" } , { latin = "yawm sa3iid" , kana = "ヤウム サアイード" , arabic = "يَوْم سَعيد" , meaning = "Have a nice day." } , { latin = "sa3iid" , kana = "サアイード" , arabic = "سَعيد" , meaning = "happy" } , { latin = "2anaa Haziinat l-yawm" , kana = "アナー ハズィーナト ル ヤウム" , arabic = "أَنا حَزينة الْيَوْم" , meaning = "I am sad today." } , { latin = "2anaa Haziin jiddan" , kana = "アナー ハズィーン ジッダン" , arabic = "أَنا حَزين جِدّاً" , meaning = "I am very sad." } , { latin = "2anaa mariiDa lil2asaf" , kana = "アナー マリーダ リルアサフ" , arabic = "أَنا مَريضة لِلْأَسَف" , meaning = "I am sick unfortunately." } , { latin = "2ilaa l-liqaa2 yaa Sadiiqii" , kana = "イラー ッリカー ヤー サディーキイ" , arabic = "إِلى الْلِّقاء يا صَديقي" , meaning = "Until next time, my friend." } , { latin = "na3saana" , kana = "ナアサーナ" , arabic = "نَعْسانة" , meaning = "sleepy" } , { latin = "mutaHammis" , kana = "ムタハムミス" , arabic = "مُتَحَمِّس" , meaning = "excited" } , { latin = "maa smak" , kana = "マー スマク" , arabic = "ما إسْمَك" , meaning = "What is your name?" } , { latin = "2anaa na3saan" , kana = "アナー ナアサーン" , arabic = "أَنا نَعْسان" , meaning = "I am sleepy." } , { latin = "yal-laa 2ilaa l-liqaa2" , kana = "ヤッラー イラー ッリカー" , arabic = "يَلّإِ إِلى الْلَّقاء" , meaning = "Alright, until next time." } , { latin = "ma3a as-salaama" , kana = "マア アッサラーマ" , arabic = "مَعَ الْسَّلامة" , meaning = "Goodbye." } , { latin = "tamaam" , kana = "タマーム" , arabic = "تَمام" , meaning = "OK" } , { latin = "2anaatamaam al-Hamdu li-l-laa" , kana = "アナ タマーム アル ハムドゥ リッラー" , arabic = "أَنا تَمام اَلْحَمْدُ لِله" , meaning = "I am OK , praise be to God." } , { latin = "maa al2akhbaar" , arabic = "ما الْأَخْبار" , meaning = "What is new?" } , { latin = "al-bathu alhii" , kana = "アル バス アルヒー" , arabic = "اَلْبَثُ اَلْحي" , meaning = "live broadcast" } , { latin = "2ikhtar" , kana = "イクフタル" , arabic = "إِخْتَر" , meaning = "choose" } , { latin = "sayyaara" , kana = "サイヤーラ" , arabic = "سَيّارة" , meaning = "a car" } , { latin = "2akh ghariib" , kana = "アクフ ガリーブ" , arabic = "أَخ غَريب" , meaning = "a weird brother" } , { latin = "2ukht muhimma" , kana = "ウクフト ムヒムマ" , arabic = "أُخْت مُهِمّة" , meaning = "an important sister" } , { latin = "ibn kariim wa-mumtaaz" , kana = "イブン カリーム ワ ムムターズ" , arabic = "اِبْن كَريم وَمُمْتاز" , meaning = "a generous and amazing son" } , { latin = "2ab" , kana = "アブ" , arabic = "أَب" , meaning = "a father" } , { latin = "2umm" , kana = "ウンム" , arabic = "أُمّ" , meaning = "a mother" } , { latin = "ibn" , kana = "イブン" , arabic = "اِبْن" , meaning = "a son" } , { latin = "mumti3" , kana = "ムムティア" , arabic = "مُمْتِع" , meaning = "fun" } , { latin = "muHaasib" , kana = "ムハースィブ" , arabic = "مُحاسِب" , meaning = "an accountant" } , { latin = "ma-smika ya 2ustaadha" , kana = "マスミカ ヤー ウスターザ" , arabic = "ما اسْمِك يا أُسْتاذة" , meaning = "What is your name ma'<NAME>?" } , { latin = "qiTTatak malika" , kana = "キッタタク マリカ" , arabic = "قِطَّتَك مَلِكة" , meaning = "Your cat is a queen." } , { latin = "jadda laTiifa wa-jadd laTiif" , kana = "ジャッダ ラティーファ ワ ジャッド ラティーフ" , arabic = "جَدّة لَطيفة وَجَدّ لَطيف" , meaning = "a kind grandmother and a kind grandfather" } , { latin = "qiTTa jadiida" , kana = "キッタ ジャディーダ" , arabic = "قِطّة جَديدة" , meaning = "a new cat" } , { latin = "hal jaddatak 2ustaadha" , kana = "ハル ジャーダタック ウスターザ" , arabic = "هَل جَدَّتَك أُسْتاذة" , meaning = "Is your grandmother a professor?" } , { latin = "hal zawjatak 2urduniyya" , arabic = "هَل زَوْجَتَك أُرْدُنِتّة" , meaning = "Is your wife a Jordanian?" } , { latin = "mu3allim" , kana = "ムアッリム" , arabic = "مُعَلِّم" , meaning = "a teacher" } , { latin = "dhakiyya" , kana = "ザキーヤ" , arabic = "ذَكِيّة" , meaning = "smart" } , { latin = "ma3Taf" , kana = "マアタフ" , arabic = "مَعْطَف" , meaning = "a coat" } , { latin = "qubba3a zarqaa2 wa-bunniyya" , kana = "くッバ ザルかー ワ ブンニーヤ" , arabic = "قُبَّعة زَرْقاء وَبُنّية" , meaning = "a blue ad brown hat" } , { latin = "bayDaa2" , kana = "バイダー" , arabic = "بَيْضاء" , meaning = "white" } , { latin = "al-2iijaar jayyid al-Hamdu li-l-laa" , kana = "アル イージャール ジャイイド アル ハムドゥ リッラー" , arabic = "اَلْإِيجار جَيِّد اَلْحَمْدُ لِله" , meaning = "The rent is good, praise be to God." } , { latin = "jaami3a ghaalya" , kana = "ジャーミア ガーリヤ" , arabic = "جامِعة غالْية" , meaning = "an expensive university" } , { latin = "haadhaa Saaluun qadiim" , kana = "ハーザー サルーン カディーム" , arabic = "هَذا صالون قَديم" , meaning = "This is an old living room." } , { latin = "haadhihi Hadiiqa 3arabiyya" , kana = "ハーディヒ ハディーカ アラビーヤ" , arabic = "هَذِهِ حَديقة عَرَبِيّة" , meaning = "This is an Arabian guarden." } , { latin = "al-HaaiT" , kana = "アル ハーイト" , arabic = "اَلْحائِط" , meaning = "the wall" } , { latin = "hunaak shanTa Saghiira" , kana = "フゥナーク シャンタ サギーラ" , arabic = "هُناك شَنطة صَغيرة" , meaning = "There is a small bag." } , { latin = "2abii hunaak" , kana = "アビー フゥナーク" , arabic = "أَبي هُناك" , meaning = "My father is there." } , { latin = "haatifak hunaak yaa buub" , kana = "ハーティファク フゥナーク ヤー ブーブ" , arabic = "هاتِفَك هُناك يا بوب" , meaning = "Your telephone is there, Bob." } , { latin = "haatifii hunaak" , kana = "ハーティフィー フゥナーク" , arabic = "هاتِفي هُناك" , meaning = "My telephone is there." } , { latin = "hunaak 3ilka wa-laab tuub fii shanTatik" , kana = "フゥナーク アイルカ ワ ラーブトゥーブ フィー シャンタティク" , arabic = "هُناك عِلكة وَلاب توب في شَنطَتِك" , meaning = "There is a chewing gum and a laptop in your bag." } , { latin = "raSaaS" , kana = "ラサース" , arabic = "رَصاص" , meaning = "lead" } , { latin = "qalam raSaaS" , kana = "カラム ラサース" , arabic = "قَلَم رَصاص" , meaning = "a pencil" } , { latin = "mu2al-lif" , kana = "ムアッリフ" , arabic = "مُؤَلِّف" , meaning = "an author" } , { latin = "shaahid al-bath-t il-Hayy" , kana = "シャーヒド アル バスト アル ハイイ" , arabic = "شاهد البث الحي" , meaning = "Watch the live braodcast" } , { latin = "2a3iish" , kana = "アーイーシュ" , arabic = "أَعيش" , meaning = "I live" } , { latin = "2a3iish fi l-yaabaan" , kana = "アーイーシュ フィ ル ヤーバーン" , arabic = "أَعيش في لايابان" , meaning = "I live in Japan." } , { latin = "2anaa 2ismii faaTima" , kana = "アナー イスミー ファーティマ" , arabic = "أَنا إِسمي فاطِمة" , meaning = "My name is <NAME> (female name)." } , { latin = "2a3iish fii miSr" , kana = "アーイーシュ フィー ミスル" , arabic = "أَعيش في مِصر" , meaning = "I live in Egypt." } , { latin = "al3mr" , kana = "アラームル" , arabic = "العمر" , meaning = "age" } , { latin = "2ukhtii wa-Sadiiqhaa juurj" , kana = "ウクフティー ワ サディークハー ジュールジュ" , arabic = "أُخْتي وَصَديقهل جورْج" , meaning = "my sister and her friend <NAME>" } , { latin = "3amalii" , kana = "アアマリー" , arabic = "عَمَلي" , meaning = "my work" } , { latin = "haadhihi Sadiiqat-hu saamiya" , kana = "ハージヒ すぁディーかトフゥ サーミア" , arabic = "هَذِهِ صَديقَتهُ سامية" , meaning = "This is his girlfriend <NAME>." } , { latin = "shitaa2" , kana = "シター" , arabic = "شِتاء" , meaning = "winter" } , { latin = "Sayf mumTil" , kana = "サイフ ムムティル" , arabic = "صَيْف مُمْطِر" , meaning = "a rainy summer" } , { latin = "3aalya" , kana = "アーリヤ" , arabic = "عالْية" , meaning = "high" } , { latin = "laa 2uHibb a-T-Taqs al mumTil" , kana = "ラー ウひッブ アッタクス アル ムムティル" , arabic = "لا أُحِبّ اَلْطَّقْس اَلْمُمْطِر" , meaning = "I do not like rainy weather." } , { latin = "Sayf Haarr Tawiil" , kana = "サイフ ハール タウィール" , arabic = "صَيْف حارّ طَويل" , meaning = "a long hot summer" } , { latin = "ruTuuba 3aalya" , kana = "ルトゥーバ アーリヤ" , arabic = "رُطوبة عالية" , meaning = "high humidity" } , { latin = "a-r-rTuubat l-3aalya" , kana = "アルトゥーバト ルアーリヤ" , arabic = "اَلْرُّطوبة الْعالْية" , meaning = "the high humidity" } , { latin = "al-yawm" , kana = "アルヤウム" , arabic = "اَلْيَوْم" , meaning = "today" } , { latin = "alyawm yawm baarid" , kana = "アルヤウム ヤウム バーリド" , arabic = "اَلْيَوْم يَوْم بارِد" , meaning = "Today is a cold day." } , { latin = "tashar-rfnaa" , kana = "タシャッラフゥナー" , arabic = "تشرفنا" , meaning = "Pleased to meet you." } , { latin = "a-S-Sayf l-baarid" , kana = "アッサイフ ル バーリド" , arabic = "اَلْصَّيْف اَلْبارِد" , meaning = "the cold summer" } , { latin = "a-r-rabii3" , kana = "アッラビーア" , arabic = "اَلْرَّبيع" , meaning = "the spring" } , { latin = "al-khariif mushmis" , kana = "アル ハリーフ ムシュミス" , arabic = "اَلْخَريف مُشْمِس" , meaning = "The fall is sunny." } , { latin = "rabii3 jamiil" , kana = "ラビーア ジャミール" , arabic = "رَبيع جَميل" , meaning = "a pretty spring" } , { latin = "rabii3 baarid fii 2iskutlandan" , kana = "ラビーア バアリド フィー スクトランダン" , arabic = "رَبيع بارِد في إِسْكُتْلَنْدا" , meaning = "a cold spring in Scotland" } , { latin = "kayfa" , kana = "カイファ" , arabic = "كَيْفَ" , meaning = "how" } , { latin = "kaifa Haalka" , kana = "カイファ ハールカ" , arabic = "كَيْفَ حالكَ" , meaning = "How are you?" } , { latin = "Hammaam" , kana = "ハンマーム" , arabic = "حَمّام" , meaning = "bathroom" } , { latin = "haadhaa balad-haa" , kana = "ハーザー バラドハー" , arabic = "هَذا بَلَدها" , meaning = "This is her country." } , { latin = "al-2urdun" , kana = "アル ウルドゥン" , arabic = "اَلْأُرْدُن" , meaning = "Jordan" } , { latin = "a-s-saaHil" , kana = "アッサーヒル" , arabic = "اَلْسّاحِل" , meaning = "the coast" } , { latin = "2uhibb a-s-safar 2ilaa 2almaaniiaa" , kana = "ウひッブ アッサファル イラ アルマニア" , arabic = "أُحِب اَلْسَّفَر إِلى أَلْمانيا" , meaning = "I like travelling to Germany" } , { latin = "hiyya" , kana = "ヒヤ" , arabic = "هِيَّ" , meaning = "she" } , { latin = "huwwa" , kana = "フワ" , arabic = "هُوَّ" , meaning = "he" } , { latin = "2anti" , kana = "アンティ" , arabic = "أَنْتِ" , meaning = "you (female)" } , { latin = "2anta" , kana = "アンタ" , arabic = "أَنْتَ" , meaning = "you (male)" } , { latin = "mutarjim dhakiyy" , kana = "ムタルジム ザキーイ" , arabic = "مُتَرْجِم ذَكِيّ" , meaning = "a smart translator (male)" } , { latin = "mutarjima dhakiyya" , kana = "ムタルジマ ザキーヤ" , arabic = "مُتَرْجِمة ذَكِيّة" , meaning = "a smart translator (female)" } , { latin = "2ustaadh 2amriikiyy" , kana = "ウスターズ アマリキーイ" , arabic = "أُسْتاذ أَمْريكِيّ" , meaning = "an American professor (male)" } , { latin = "2ustaadha 2amriikiyya" , kana = "ウスターザ アマリキーヤ" , arabic = "أُسْتاذة أَمْريكِيّة" , meaning = "an American professor (female)" } , { latin = "3alaa" , kana = "アラー" , arabic = "عَلى" , meaning = "on, on top of" } , { latin = "al-3arabiyya l-fuSHaa" , kana = "アルアラビーヤ ル フスハー" , arabic = "اَلْعَرَبِيّة الْفُصْحى" , meaning = "Standard Arabic" } , { latin = "bariiTaanyaa l-kubraa" , kana = "ブリターニヤー ル クブラー" , arabic = "بَريطانْيا الْكُبْرى" , meaning = "Great Britain" } , { latin = "balad 3arabiyy" , kana = "バラド アラビーイ" , arabic = "بَلَد عَرَبِيّ" , meaning = "an Arab country" } , { latin = "madiina 3arabiyya" , kana = "マディーナ アラビーヤ" , arabic = "مَدينة عَرَبِيّة" , meaning = "an Arab city" } , { latin = "bint jadiid" , kana = "ビント ジャディード" , arabic = "بَيْت جَديد" , meaning = "a new house" } , { latin = "jaami3a jadiida" , kana = "ジャーミア ジャディーダ" , arabic = "جامِعة جَديدة" , meaning = "a new university" } , { latin = "hadhaa Saaluun ghaalii" , kana = "ハーザー サールーン ガーリー" , arabic = "هَذا صالون غالي" , meaning = "This is an expensive living room" } , { latin = "ghaalii" , kana = "ガーリー" , arabic = "غالي" , meaning = "expensive, dear" } , { latin = "khaalii" , kana = "クハーリー" , arabic = "خالي" , meaning = "my mother’s brother, uncle" } , { latin = "taab" , kana = "ターブ" , arabic = "تاب" , meaning = "to repent" } , { latin = "Taab" , kana = "ターブ" , arabic = "طاب" , meaning = "to be good, pleasant" } , { latin = "2umm" , kana = "ウンム" , arabic = "أُمّ" , meaning = "mother" } , { latin = "2ukht" , kana = "ウフト" , arabic = "أُخْت" , meaning = "siter" } , { latin = "bint" , kana = "ビント" , arabic = "بِنْت" , meaning = "daughter, girl" } , { latin = "2ummii" , kana = "ウンミー" , arabic = "أُمّي" , meaning = "my mother" } , { latin = "ibnak" , kana = "イブナク" , arabic = "اِبْنَك" , meaning = "your son (to a man)" } , { latin = "ibnik" , kana = "イブニク" , arabic = "اِبْنِك" , meaning = "your son (to a woman)" } , { latin = "al-3iraaq" , kana = "アライラーク" , arabic = "اَلْعِراق" , meaning = "iraq" } , { latin = "nadhiir" , kana = "ナディール" , arabic = "نَذير" , meaning = "warner, herald" } , { latin = "naDhiir" , kana = "ナディール" , arabic = "نَظير" , meaning = "equal" } , { latin = "madiinatii" , kana = "マディーナティ" , arabic = "مَدينَتي" , meaning = "my city" } , { latin = "madiinatak" , kana = "マディーナタク" , arabic = "مَدينَتَك" , meaning = "your city (to a male)" } , { latin = "madiinatik" , kana = "マディーナティク" , arabic = "مَدينَتِك" , meaning = "your city (to a female)" } , { latin = "jaara" , kana = "ジャーラ" , arabic = "جارة" , meaning = "a neighbor (female)" } , { latin = "jaaratii" , kana = "ジャーラティ" , arabic = "جارَتي" , meaning = "my neighbor (female)" } , { latin = "jaaratak" , kana = "ジャーラタク" , arabic = "جارَتَك" , meaning = "your (female) neighbor (to a male)" } , { latin = "jaaratik" , kana = "ジャーラティク" , arabic = "جارَتِك" , meaning = "your (female) neighbor (to a female)" } , { latin = "al-bayt jamiil" , kana = "アルバイト ジャミール" , arabic = "اَلْبَيْت جَميل" , meaning = "The house is pretty" } , { latin = "al-madiina jamiila" , kana = "アルマディーナ ジャミーラ" , arabic = "اَلْمَدينة جَميلة" , meaning = "The city is pretty" } , { latin = "baytak jamiil" , kana = "バイタク ジャミール" , arabic = "بَيْتَك جَميل" , meaning = "Your house is pretty (to a male)" } , { latin = "madiinatak jamiila" , kana = "マディーナタク ジャミーラ" , arabic = "مَدينَتَك جَميلة" , meaning = "Your city is pretty (to a male)" } , { latin = "baytik jamiil" , kana = "バイティク ジャミール" , arabic = "بَيْتِك جَميل" , meaning = "Your house is pretty (to a female)" } , { latin = "madiinatik jamiila" , kana = "マディーナティク ジャミーラ" , arabic = "مَدينَتِك جَميلة" , meaning = "Your city is pretty (to a female)" } , { latin = "dall" , kana = "ダル" , arabic = "دَلّ" , meaning = "to show, guide" } , { latin = "Dall" , kana = "ダル" , arabic = "ضَلّ" , meaning = "to stray" } , { latin = "3ind juudii bayt" , kana = "アインド ジューディー バイト" , arabic = "عِنْد جودي بَيْت" , meaning = "Judy has a house." } , { latin = "3indii baitii" , kana = "アインディー バイティー" , arabic = "عِنْدي بَيْت" , meaning = "I have a house." } , { latin = "3indaka bayt" , kana = "アインダカ バイト" , arabic = "عِنْدَك بَيْت" , meaning = "You (to a man) have a house." } , { latin = "3indika bayt" , kana = "アインディカ バイト" , arabic = "عِنْدِك بَيْت" , meaning = "You (to a woman) have a house." } , { latin = "laysa 3ind juudii bayt" , kana = "ライサ アインド ジュウディー バイト" , arabic = "لَيْسَ عِنْد جودي بَيْت" , meaning = "Judy does not have a house." } , { latin = "laysa 3indii kalb" , kana = "ライサ アインド カルブ" , arabic = "لَيْسَ عِنْدي كَلْب" , meaning = "I do not have a dog." } , { latin = "laysa 3indika wishaaH" , kana = "ライサ アインディカ ウィシャーハ" , arabic = "لَيْسَ عِنْدِك وِشاح" , meaning = "You do not have a scarf. (to a woman)" } , { latin = "madiina suuriyya" , kana = "マディーナ スリーヤ" , arabic = "مَدينة سورِيّة" , meaning = "a Syrian city" } , { latin = "filasTiin makaan mashhuur" , kana = "フィラストィーン マカーン マシュフール" , arabic = "فِلَسْطين مَكان مَشْهور" , meaning = "Palestine is a famous place." } , { latin = "a-s-suudaan wa-l3iraaq" , kana = "アッスーダーン ワライラーク" , arabic = "اَلْسّودان وَالْعِراق" , meaning = "Sudan and Iraq" } , { latin = "al-3aaSima" , kana = "アルあーすぃマ" , arabic = "اَلْعاصِمة" , meaning = "the captal" } , { latin = "jabal" , kana = "ジャバル" , arabic = "جَبَل" , meaning = "a mountain" } , { latin = "a-th-thuudaan" , kana = "アッスーダーン" , arabic = "الشودان" , meaning = "Sudan" } , { latin = "bayt 2azraq" , kana = "バイト アズラク" , arabic = "بَيْت أَزْرَق" , meaning = "a blue house" } , { latin = "madiina zarqaa2" , kana = "マディーナ ザルかー" , arabic = "مَدينة زَرْقاء" , meaning = "a blue city" } , { latin = "al-bayt 2azraq" , kana = "アルバイト アズラク" , arabic = "اَلْبَيْت أَزْرَق" , meaning = "The house is blue" } , { latin = "al-madiina zarqaa2" , kana = "アル マディーナ ザルかー" , arabic = "اَلْمَدينة زَرْقاء" , meaning = "The city is blue." } , { latin = "2azraq zarqaa2" , kana = "アズらく ザルかー" , arabic = "أَزْرَق زَرْقاء" , meaning = "blue" } , { latin = "saam" , kana = "サーム" , arabic = "سام" , meaning = "Sam (maile name)" } , { latin = "Saam" , kana = "サーム" , arabic = "صام" , meaning = "to fast" } , { latin = "Sadiiqii Juurj 3ind-hu 3amal mumtaaz" , kana = "サディークィー ジュールジュ アインダフー アアマル ムムターズ" , arabic = "صَديقي جورْج عِنْدهُ عَمَل مُمْتاز" , meaning = "My friend <NAME>orge has excellent job." } , { latin = "ghaniyy" , kana = "ガニィイ" , arabic = "غَنِيّ" , meaning = "rich" } , { latin = "amra2a" , kana = "アムラア" , arabic = "اَمْرَأة" , meaning = "a woman" } , { latin = "2amaamaka" , kana = "アマーマカ" , arabic = "أَمامَك" , meaning = "in front of you" } , { latin = "khalfak" , kana = "ハルファク" , arabic = "خَلْفَك" , meaning = "behind you" } , { latin = "bijaanib" , kana = "ビジャーニブ" , arabic = "بِجانِب" , meaning = "next to" } , { latin = "2abii mashghuul daayman" , kana = "アビー マシュグール ダーイマン" , arabic = "أَبي مَشْغول دائِماً" , meaning = "My father is always busy." } , { latin = "su2aal" , kana = "スアール" , arabic = "سُؤال" , meaning = "question" } , { latin = "ma3ii" , kana = "マアイー" , arabic = "معي" , meaning = "with me" } , { latin = "labisa" , kana = "ラビサ" , arabic = "لابِسة" , meaning = "dress up" } , { latin = "man ma3ii" , kana = "マン マアイー" , arabic = "مَن مَعي؟" , meaning = "Who is this?" } , { latin = "Hanafiyya" , kana = "ハナフィーヤ" , arabic = "حَنَفِيّة" , meaning = "a faucet" } , { latin = "Sawt" , kana = "サウト" , arabic = "صَوْت" , meaning = "voice" } , { latin = "2adkhul" , kana = "アドホル" , arabic = "أَدْخُل" , meaning = "enter" } , { latin = "al-haatif mu3aTTal wa-t-tilfaaz 2ayDan" , kana = "アルハーティフ ムアッタル ワッティルファーズ アイダン" , arabic = "اَلْهاتِف مُعَطَّل وَالْتَّلْفاز أَيضاً" , meaning = "The telephone is out of order and the television also." } , { latin = "hunaak mushkila ma3a t-tilaaz" , kana = "フゥナーク ムシュキラ マア ッティルファーズ" , arabic = "هُناك مُشْكِلة مَعَ الْتِّلْفاز" , meaning = "There is a problem with the television." } , { latin = "2a3rif" , kana = "アーリフ" , arabic = "أَعْرِف" , meaning = "I know ..." } , { latin = "raqam" , kana = "ラカム" , arabic = "رَقَم" , meaning = "number" } , { latin = "la 2a3rif kul-l al-2aedaan" , kana = "ラー アーリフ クッラ ル アーダーン" , arabic = "لا أَعْرِف كُلّ اَلْأَعْداد" , meaning = "I do not know all the numbers." } , { latin = "ta3rifiin" , kana = "ターリフィーン" , arabic = "تَعْرِفين" , meaning = "You (female) know" } , { latin = "li2anna" , kana = "リアンナ" , arabic = "لِأَنَّ" , meaning = "because" } , { latin = "samna" , kana = "サムナ" , arabic = "سَمنة" , meaning = "ghee" } , { latin = "wilaaya" , kana = "ウィラーヤ" , arabic = "وِلايَة" , meaning = "a state" } , { latin = "zawjii wa-bnii" , kana = "ザウジー ワブニー" , arabic = "زَوجي وَابني" , meaning = "my husband and my son" } , { latin = "mumtaaz" , kana = "ムムターズ" , arabic = "مُمتاز" , meaning = "amazing, excellent" } , { latin = "abnii" , kana = "アブニー" , arabic = "اَبني" , meaning = "my son" } , { latin = "muHaasib" , kana = "ムハースィブ" , arabic = "مُحاسب" , meaning = "an accountant" } , { latin = "juz2" , kana = "ジュズ" , arabic = "جُزء" , meaning = "a part of" } , { latin = "fataa" , kana = "ファター" , arabic = "فَتاة" , meaning = "a young woman, a girl" } , { latin = "tis3a" , kana = "ティスア" , arabic = "تِسعة" , meaning = "nine" } , { latin = "hal l-lghat l-3arabiyya Sa3ba" , kana = "ハル ッルガト ルアラビーヤ サアバ" , arabic = "هَل اللُّغَة العَرَبية صَعبة" , meaning = "Is arabic language difficult?" } , { latin = "maadhaa fa3lta 2amsi" , kana = "マーザー ファアルタ アムスィ" , arabic = "ماذا فَعلتَ أَمسِ" , meaning = "What did you do yesterday?" } , { latin = "maadhaa 2akalta" , kana = "マーザー アカルタ" , arabic = "ماذا أَكَلتَ" , meaning = "What did you eat?" } , { latin = "shu2uun" , kana = "シュ ウーン" , arabic = "شُؤُون" , meaning = "affairs, things" } , { latin = "mataa waSalta" , kana = "マター ワサルタ" , arabic = "مَتي وَصَلتَ" , meaning = "When did you arrive?" } , { latin = "suuq" , kana = "スーク" , arabic = "سوق" , meaning = "market" } , { latin = "Haafila" , kana = "ハーフィラ" , arabic = "حافِلة" , meaning = "a bus" } , { latin = "tannuura" , kana = "タンヌーラ" , arabic = "تَنورة" , meaning = "a skirt" } , { latin = "laHaDha" , kana = "ラハザ" , arabic = "لَحَظة" , meaning = "a moment" } , { latin = "2ayna l-qiTTa" , kana = "アイナ ルキッタ" , arabic = "أَينَ القِطّة" , meaning = "Where is the cat?" } , { latin = "shaay" , kana = "シャーイ" , arabic = "شاي" , meaning = "tea" } , { latin = "hal haadhihi Haqiibatki" , kana = "ハル ハージヒ ハキーバトキ" , arabic = "هَل هَذِهِ حَقيبَتكِ" , meaning = "Is this your bag?" } , { latin = "Hakiiba" , kana = "ハキーバ" , arabic = "حَقيبَة" , meaning = "a bag" } , { latin = "Haal" , kana = "ハール" , arabic = "حال" , meaning = "condition" } , { latin = "SaHiifa" , kana = "サヒーファ" , arabic = "صَحيفة" , meaning = "newspaper" } , { latin = "maktab" , kana = "マクタブ" , arabic = "مَكْتَب" , meaning = "an office, a desk" } , { latin = "bunnii" , kana = "ブンニー" , arabic = "بُنّي" , meaning = "brown" } , { latin = "2ila l-liqaa2" , kana = "イラ ッリカー" , arabic = "إِلى اللِّقاء" , meaning = "Bye. See you again." } , { latin = "daa2iman" , kana = "ダーイマン" , arabic = "دائمًا" , meaning = "always" } , { latin = "Hasanan" , kana = "ハサナン" , arabic = "حَسَنًا" , meaning = "Okay, good, fantastic!" } , { latin = "2ayna l-Hammaam" , kana = "アイナ ル ハンマーン" , arabic = "أَينَ الحَمّام" , meaning = "Where is the bathroom?" } , { latin = "baqara" , kana = "バカラ" , arabic = "بَقَرة" , meaning = "a cow" } , { latin = "nasiij" , kana = "ナスィージ" , arabic = "نَسيج" , meaning = "texture" } , { latin = "Hajar" , kana = "ハジャル" , arabic = "حَجَر" , meaning = "a stone" } , { latin = "muthal-lath" , kana = "ムサッラス" , arabic = "مُثَلَّث" , meaning = "a triangle" } , { latin = "kathiir" , kana = "カシール" , arabic = "كَثير" , meaning = "many, a lot of" } , { latin = "thawm" , kana = "サウム" , arabic = "ثَوم" , meaning = "garlic" } , { latin = "qiTTatii Saghiira" , kana = "キッタティー サギーラ" , arabic = "قِطَّتي صَغيرة" , meaning = "my small cat" } , { latin = "dubb" , kana = "ドッブ" , arabic = "دُبّ" , meaning = "a bear" } , { latin = "Tabakh" , kana = "タバクハ" , arabic = "طَبَخ" , meaning = "to cook, cooking" } , { latin = "nakhl" , kana = "ナクヘル" , arabic = "نَخْل" , meaning = "date palm tree" } , { latin = "kharuuf" , kana = "クハルーフ" , arabic = "خَروف" , meaning = "a sheep" } , { latin = "samaHa" , kana = "サマハ" , arabic = "سَمَح" , meaning = "to allow, forgive" } , { latin = "tashar-rfnaa" , kana = "タシャッラフゥナー" , arabic = "تَثَرَّفنا" , meaning = "I am pleased to meet you." } , { latin = "Haliib" , kana = "ハリーブ" , arabic = "حَليب" , meaning = "milk (m)" } , { latin = "haatha l-maTar a-th-thaqiir Sa3b" , kana = "ハーザ ル マタル アッサキール サアブ" , arabic = "هَذا المَطَر الثقيل صَعب" , meaning = "This heavy rain is difficult." } , { latin = "al-maTar" , kana = "アルマタル" , arabic = "المَطَر" , meaning = "the rain" } , { latin = "muHaadatha" , kana = "ムハーダサ" , arabic = "مُحادَثة" , meaning = "conversation" } , { latin = "zawjatii ta3baana" , kana = "ザウジャティー タアバーナ" , arabic = "زَوجَتي تَعبانة" , meaning = "My wife is tired." } , { latin = "shukuran" , kana = "シュクラン" , arabic = "شُكْراً" , meaning = "thank you" } , { latin = "shukran jaziilan" , kana = "シュクラン ジャズィーラン" , arabic = "ثُكْراً جَزيلاً" , meaning = "Thank you very much." } , { latin = "jaw3aan" , kana = "ジャウあーン" , arabic = "جَوعان" , meaning = "hungry, starving" } , { latin = "2abyaD bayDaa2" , kana = "アビヤド バイダー" , arabic = "أَبْيَض بَيْضاء" , meaning = "white" } , { latin = "jadd wa-jadda" , kana = "ジャッド ワ ジャッダ" , arabic = "جَدّ وَجَدّة" , meaning = "grandfather and grandmother" } , { latin = "2aaluu" , kana = "アールー" , arabic = "آلو" , meaning = "Hello (on the phone)" } , { latin = "SabaaH l-khayr" , kana = "サバーフ ル クハイル" , arabic = "صَباح الخّير" , meaning = "good morning" } , { latin = "laakinn" , kana = "ラキン" , arabic = "لَكِنّ" , meaning = "but" } , { latin = "thaqaafa" , kana = "サカーファ" , arabic = "ثَقافة" , meaning = "culture" } , { latin = "Haarr" , kana = "ハール" , arabic = "حارّ" , meaning = "hot" } , { latin = "Taqs baarid" , kana = "タクス バーリド" , arabic = "طَقْس بارِد" , meaning = "cold weather" } , { latin = "tilfaaz" , kana = "ティルファーズ" , arabic = "تِلْفاز" , meaning = "a television" } , { latin = "tufaaHa" , kana = "トゥファーハ" , arabic = "تُفاحة" , meaning = "an apple" } , { latin = "sariir" , kana = "サリール" , arabic = "سَرير" , meaning = "a bed" } , { latin = "kursii" , kana = "クルスィー" , arabic = "كُرسي" , meaning = "a chair" } , { latin = "3an" , kana = "アン" , arabic = "عَن" , meaning = "about" } , { latin = "samaa2" , kana = "サマー" , arabic = "سَماء" , meaning = "sky (f)" } , { latin = "2iiTaalyaa" , kana = "イーターリヤー" , arabic = "إيطاليا" , meaning = "Italy" } , { latin = "2arD" , kana = "アルド" , arabic = "أَرض" , meaning = "a land (f)" } , { latin = "wilaayat taksaas" , kana = "ウィラーヤト タクサース" , arabic = "وِلاية تَكْساس" , meaning = "the state of Texas" } , { latin = "Sahfii Sahfiiya" , kana = "サハフィー サハフィーヤ" , arabic = "صَحفي صَحفية" , meaning = "a journalist" } , { latin = "bint suuriyya" , kana = "ビント スーリヤ" , arabic = "بِنْت سورِيّة" , meaning = "a Syrian girl" } , { latin = "2umm" , kana = "ウンム" , arabic = "أُمّ" , meaning = "a mother (f)" } , { latin = "3ayn" , kana = "アイン" , arabic = "عَيْن" , meaning = "an eye (f)" } , { latin = "qadam" , kana = "カダム" , arabic = "قَدَم" , meaning = "a foot (f)" } , { latin = "3an l-qiraa2a" , kana = "アニル キラーエ" , arabic = "عَن القِراءة" , meaning = "about reading" } , { latin = "a-s-safar" , kana = "アッサファル" , arabic = "السفر" , meaning = "travelling" } , { latin = "kulla yawm" , kana = "クッラ ヤウム" , arabic = "كُلَّ يَوم" , meaning = "every day" } , { latin = "2adrs fi l-jaami3a kulla yawm" , kana = "アドルス フィ ル ジャーミア クッラ ヤウム" , arabic = "أَدرس في الجامِعة كُلَّ يَوم" , meaning = "I study at the university every day." } , { latin = "dhahaba" , kana = "ザハバ" , arabic = "ذَهَبَ" , meaning = "He went" } , { latin = "katabaa" , kana = "カタバー" , arabic = "كَتَبَا" , meaning = "They (two male) wrote" } , { latin = "katabtu" , kana = "カタブトゥ" , arabic = "كَتَبْتُ" , meaning = "I wrote" } , { latin = "katabti" , kana = "カタブティ" , arabic = "كَتَبْتِ" , meaning = "You (female) wrote" } , { latin = "katabta" , kana = "カタブタ" , arabic = "كَتَبْتَ" , meaning = "You (male) wrote" } , { latin = "katabat" , kana = "カタバット" , arabic = "كَتَبَت" , meaning = "She wrote" } , { latin = "ramaDaan" , kana = "ラマダーン" , arabic = "رَمَضان" , meaning = "Ramadan" } , { latin = "qahwa" , kana = "かハワ" , arabic = "قَهوة" , meaning = "coffee" } , { latin = "al-2aan" , kana = "アル アーン" , arabic = "اَلآن" , meaning = "right now" } , { latin = "saa3at Haa2iT" , kana = "サーアト ハーイト" , arabic = "ساعة حائط" , meaning = "a wall clock" } , { latin = "kami s-saa3a l-2aan" , kana = "カミッサーア ルアーン" , arabic = "كَمِ الساعة الآن" , meaning = "What time is it now?" } , { latin = "a-s-saa3a kam" , kana = "アッサーア カム" , arabic = "الساعة كَم" , meaning = "What time is it?" } , { latin = "2a3Tinii" , kana = "アーティニー" , arabic = "أَعْطِني" , meaning = "Give me ..." } , { latin = "Tayyib" , kana = "タイイブ" , arabic = "طَيِّب" , meaning = "Ok, good" } , { latin = "2abuu shaqra" , kana = "アブーシャクラ" , arabic = "أَبو شَقرة" , meaning = "Abu Shakra (restaurant)" } , { latin = "haathihi T-Taawila Haara" , kana = "ハージヒ ッターウィラ ハーラ" , arabic = "هَذِهِ الطاوِلة حارة" , meaning = "This table is hot." } , { latin = "ma3Taf khafiif" , kana = "マアタフ クハフィーフ" , arabic = "معطَف خَفيف" , meaning = "a light coat" } , { latin = "maTar khafiif" , kana = "マタル クハフィーフ" , arabic = "مَطَر خَفيف" , meaning = "a light rain" } , { latin = "a-T-Taqs" , kana = "アッタクス" , arabic = "الطَّقس" , meaning = "the weather" } , { latin = "2alf" , kana = "アルフ" , arabic = "أَلف" , meaning = "a thousand" } , { latin = "mi3a" , kana = "ミア" , arabic = "مِئة" , meaning = "a hundred" } , { latin = "3ashara" , kana = "アシャラ" , arabic = "عَشرة" , meaning = "ten" } , { latin = "al-Hamdu li-l-laa" , kana = "アルハムド リッラー" , arabic = "الحَمدُ لِلَّه" , meaning = "Praise be to God." } , { latin = "Hubba" , kana = "フッバ" , arabic = "حُبَّ" , meaning = "love" } , { latin = "3ilka" , kana = "アイルカ" , arabic = "عِلكة" , meaning = "chewing gum" } , { latin = "thaqiil" , kana = "サキール" , arabic = "ثَقيل" , meaning = "heavy" } , { latin = "haatifii" , kana = "ハーティフィー" , arabic = "هاتِفي" , meaning = "my phone" } , { latin = "thamaaniya" , kana = "サマーニヤ" , arabic = "ثَمانية" , meaning = "eight" } , { latin = "sab3a" , kana = "サブア" , arabic = "سَبعة" , meaning = "seven" } , { latin = "sitta" , kana = "スィッタ" , arabic = "سِتَّة" , meaning = "six" } , { latin = "khamsa" , kana = "クハムサ" , arabic = "خَمسة" , meaning = "five" } , { latin = "2arba3a" , kana = "アルバア" , arabic = "أَربَعة" , meaning = "four" } , { latin = "thalaatha" , kana = "サラーサ" , arabic = "ثَلاثة" , meaning = "three" } , { latin = "2alif baa2 taa2 thaa2 jiim Haa2 khaa2" , kana = "アリフ バー ター さー ジーム はー クハー" , arabic = "أَلِف باء تاء ثاء جيم حاء خاء" , meaning = "ا ب ت ث ج ح خ" } , { latin = "daal dhaal raa2 zaay siin shiin" , kana = "ダール ざール らー ザーイ スィーン シーン" , arabic = "دال ذال راء زاي سين شين" , meaning = "د ذ ر ز س ش" } , { latin = "Saad Daad Taa2 Dhaa2 3ain ghain" , kana = "すぁード だード たー づぁー アイン ガイン" , arabic = "صاد ضاد طاء ظاء عَين غَين" , meaning = "ص ض ط ظ ع غ" } , { latin = "faa2 qaaf kaaf laam miim nuun" , kana = "ファー かーフ カーフ ラーム ミーム ヌーン" , arabic = "فاء قاف كاف لام ميم نون" , meaning = "ف ق ك ل م ن" } , { latin = "haa2 waaw yaa2 hamza" , kana = "ハー ワーウ ヤー ハムザ" , arabic = "هاء واو ياء هَمزة" , meaning = "ه و ي ء" } , { latin = "kaifa l-Haal" , kana = "カイファ ル はール" , arabic = "كَيفَ الحال" , meaning = "How are you? (How is the condition?)" } , { latin = "bi-khayr wa-l-Hamdu li-l-laa" , kana = "ビクハイルr ワルはムドゥ リッラー" , arabic = "بِخَير وَالحَمدُ لِلَّه" , meaning = "I am fine. Praise be to God." } , { latin = "2aHmar Hamraa2" , kana = "アフマる ハムらー" , arabic = "أَحمَر حَمراء" , meaning = "red" } , { latin = "muHaamii" , kana = "ムハーミー" , arabic = "مُحامي" , meaning = "an attorney, a lawyer" } , { latin = "haadhaa rakamii" , kana = "ハーザー らかミー" , arabic = "هَذا رَقَمي" , meaning = "This is my number." } , { latin = "samaka 2asmaak" , kana = "サマカ アスマーク" , arabic = "سَمَكة أَسماك" , meaning = "fish, fish (plural)" } , { latin = "shajara 2ashujaar" , kana = "シャジャら アシュジャーる" , arabic = "شَجَرة أَشجار" , meaning = "tree, trees" } , { latin = "manzil" , kana = "マンズィル" , arabic = "مَنزِل" , meaning = "a house, home" } , { latin = "bayt" , kana = "バイト" , arabic = "بَيْت" , meaning = "a house" } , { latin = "Hadiiqa" , kana = "はディーか" , arabic = "حَديقة" , meaning = "garden" } , { latin = "haadhihi Hadiiqa 3arabyya" , kana = "ハーじヒ はディーか アらビーヤ" , arabic = "هَذِهِ حَديقة عَرَبيّة" , meaning = "This is an Arab garden" } , { latin = "tafaD-Dal ijlis" , kana = "タファッダル イジュリス" , arabic = "تَفَضَّل اِجْلِس" , meaning = "Please sit down." } , { latin = "tafaD-Dalii" , kana = "タファッダリー" , arabic = "تَفَضَّلي" , meaning = "Please (female word)" } , { latin = "shaay min faDlika" , kana = "シャーイ ミン ファドリカ" , arabic = "شاي مِن فَضلِكَ" , meaning = "Tea please." } , { latin = "ma3a s-salaama" , kana = "マア ッサラーマ" , arabic = "مَعَ السَّلامة" , meaning = "Good bye." } , { latin = "ash-shams" , kana = "アッシャムス" , arabic = "الشَّمس" , meaning = "the sun" } , { latin = "haadha l-qalam" , kana = "ハーザ ル カラム" , arabic = "هَذا القَلَم" , meaning = "this pen" } , { latin = "muta2assif laa 3alayka" , kana = "ムタアッシフ ラー アライカ" , arabic = "مُتأَسِّف. لا عَلَيكَ." , meaning = "I am sorry. Do not mind." } , { latin = "al-qamar" , kana = "アルかマる" , arabic = "القَمَر" , meaning = "the moon" } , { latin = "walad al-walad" , kana = "ワラド アルワラド" , arabic = "وَلَد الوَلَد" , meaning = "boy , the boy" } , { latin = "madrasa" , kana = "マドらサ" , arabic = "مَدرَسة" , meaning = "a school" } , { latin = "saa2iq" , kana = "サーイク" , arabic = "سائق" , meaning = "a driver" } , { latin = "daftar" , kana = "ダフタる" , arabic = "دَفتَر" , meaning = "a notebook" } , { latin = "ba3da 2idhnika" , kana = "バァダ イズニカ" , arabic = "بَعدَ إِذنِكَ" , meaning = "After your permit. Excuse me." } , { latin = "muwaDh-Dhaf" , kana = "ムワッザフ" , arabic = "مُوَظَّف" , meaning = "an employee" } , { latin = "waaHid" , kana = "ワーヒド" , arabic = "واحِد" , meaning = "one" } , { latin = "2ithnaan" , kana = "イスナーン" , arabic = "اِثنان" , meaning = "two" } , { latin = "qamiiS" , kana = "カミース" , arabic = "قَميص" , meaning = "a shirt" } , { latin = "qaamuus" , kana = "かームース" , arabic = "قاموس" , meaning = "dictionary" } , { latin = "majal-la" , kana = "マジャッラ" , arabic = "مَجَلَّة" , meaning = "magazine" } , { latin = "2iijaarii" , kana = "イージャーりー" , arabic = "إيجاري" , meaning = "my rent" } , { latin = "maa haadhaa" , kana = "マー ハーザー" , arabic = "ما هَذا" , meaning = "What is this?" } , { latin = "khubz" , kana = "クフブズ" , arabic = "خُبز" , meaning = "bread" } , { latin = "riisha" , kana = "りーシャ" , arabic = "ريشة" , meaning = "feather" } , { latin = "Taa2ira" , kana = "たーイら" , arabic = "طائرة" , meaning = "an airplane" } , { latin = "Dhabii" , kana = "ザビー" , arabic = "ظَبي" , meaning = "an antelope" } , { latin = "Tabiib" , kana = "タビーブ" , arabic = "طَبيب" , meaning = "doctor" } , { latin = "laa 2a3rif 2ayna 2anaa" , kana = "ラー アーりフ アイナ アナー" , arabic = "لا أَعرِف أَين أَنا" , meaning = "I do not know where I am." } , { latin = "jaarii" , kana = "ジャーリー" , arabic = "جاري" , meaning = "my (male) neighbor" } , { latin = "huwa wa hiya wa hum" , kana = "フワ ワ ヒヤ ワ フム" , arabic = "هُوَ وَ هِيَ وَ هُم" , meaning = "he and she and they" } , { latin = "2anta wa 2anti wa 2antum" , kana = "アンタ ワ アンティ ワ アントゥム" , arabic = "أَنتَ وَ أَنتِ وَ أَنتُم" , meaning = "you (male) and you (female) and you (plural)" } , { latin = "naHnu" , kana = "ナフヌ" , arabic = "نَحنُ" , meaning = "we" } , { latin = "2akh" , kana = "アクハ" , arabic = "أَخ" , meaning = "a brother" } , { latin = "Hijaab" , kana = "ヒジャーブ" , arabic = "حِجاب" , meaning = "a barrier, Hijab" } , { latin = "2ustaadhii" , kana = "ウスタージー" , arabic = "أُستاذي" , meaning = "my professor" } , { latin = "SabaaH n-nuur" , kana = "さバーフ ン ヌーる" , arabic = "صَباح النور" , meaning = "Good morning." } , { latin = "mu3l-lamii" , kana = "ムアッラミー" , arabic = "مُعلَّمي" , meaning = "my teacher" } , { latin = "al-2qkl wa-n-nawm" , kana = "アル アクル ワ ン ナウム" , arabic = "الأَكْل وَالنَّوم" , meaning = "eating and sleeping" } , { latin = "2aiDan" , kana = "アイダン" , arabic = "أَيضاً" , meaning = "also" } , { latin = "al-jarii" , kana = "アル ジャりー" , arabic = "الجَري" , meaning = "running" } , { latin = "a-n-nawm" , kana = "アンナウム" , arabic = "النَّوم" , meaning = "sleeping" } , { latin = "bintii" , kana = "ビンティー" , arabic = "بِنتي" , meaning = "my daughter" } , { latin = "2amaama" , kana = "アマーマ" , arabic = "أَمامَ" , meaning = "in front of, before" } , { latin = "jaami3tii fii Tuukyuu" , kana = "ジャーミアティー フィー トーキョー" , arabic = "جامِعتي في طوكيو" , meaning = "My university is in Tokyo." } , { latin = "2ayn jaami3tka" , kana = "アイン ジャーミアトカ" , arabic = "أَين جامِعتكَ" , meaning = "Where is your university?" } , { latin = "a-t-taSwiir" , kana = "アッタすウィーる" , arabic = "التصْوير" , meaning = "photography" } , { latin = "jaaratii" , kana = "ジャーらティー" , arabic = "جارَتي" , meaning = "my (female) neighbor" } , { latin = "jaarii" , kana = "ジャーりー" , arabic = "جاري" , meaning = "my (male) neighbor" } , { latin = "Dawaahii" , kana = "だワーヒー" , arabic = "ضَواحي" , meaning = "suburbs" } , { latin = "2askn fii DawaaHii baghdaad" , kana = "アスクン フィー だワーひー バグダード" , arabic = "أَسكن في ضَواحي بَغداد" , meaning = "I live in the suburbs of Bagdad." } , { latin = "qar-yatii qariiba min madiinat bayruut" , kana = "かるヤティー かりーバ ミン マディーナト バイるート" , arabic = "قَريتي قَريبة مِن مَدينة بَيروت" , meaning = "My village is close to the city of Beirut." } , { latin = "3afwan" , kana = "アフワン" , arabic = "عَفواً" , meaning = "Excuse me. Sure, it's Ok. (Reply to thank you)" } , { latin = "2ahlan wa-sahlan" , kana = "アハラン ワ サハラン" , arabic = "أَهلاً وَسَهلاً" , meaning = "Welcome." } , { latin = "kitaab" , kana = "キターブ" , arabic = "كِتاب" , meaning = "a book" } , { latin = "Sadiiqat-hu ruuzaa qariibhu min baythu" , kana = "すぁディーかトフゥ るーザー かりーブフゥ ミン バイトフゥ" , arabic = "صَديقَته روزا قَريبة مِن بَيته" , meaning = "His friend <NAME> is close to his house." } , { latin = "Sadiiqat-hu qariiba min manzil-hu" , kana = "すぁディーかトフゥ かりーバ ミン マンズィルフゥ" , arabic = "صَديقَته قَريبة مِن مَنزِله." , meaning = "His girlfriend is close to his home" } , { latin = "2amaam al-jaami3a" , kana = "アマーマ ル ジャーミア" , arabic = "أَمام اَلْجامِعة" , meaning = "in front of the university" } , { latin = "waraa2 l-maqhaa" , kana = "ワらーア ル マクハー" , arabic = "وَراء المَقهى" , meaning = "behind the cafe" } , { latin = "2anaa fi l-maqhaa" , kana = "アナ フィ ル マクハー" , arabic = "أَنا في المَقهى" , meaning = "I am in the cafe." } , { latin = "bi-l-layr" , kana = "ビッライる" , arabic = "بِاللَّيل" , meaning = "at night" } , { latin = "3an il-yaabaan" , kana = "あニル ヤーバーン" , arabic = "عَن اليابان" , meaning = "about Japan" } , { latin = "qabl a-s-saa3at l-khaamisa" , kana = "かブラ ッサーアト ル クハーミサ" , arabic = "قَبل الساعة الخامِسة" , meaning = "before the fifth hour" } , { latin = "ba3d a-Dh-Dhuhr" , kana = "バァダ ッづホる" , arabic = "بَعد الظُّهر" , meaning = "afternoon" } , { latin = "2uHibb a-n-nawm ba3d a-Dh-Dhuhr" , kana = "ウひッブ アンナウム バァダ ッづホる" , arabic = "أحِبّ اَلْنَّوْم بَعْد اَلْظَّهْر" , meaning = "I like sleeping in the afternoon." } , { latin = "alkalaam ma3a 2abii ba3d alDh-Dhuhr" , kana = "アルカラーム マア アビー バァダ ッづホる" , arabic = "اَلْكَلام معَ أَبي بَعْد اَلْظَّهْر" , meaning = "talking with my father in the afternoon" } , { latin = "a-s-salaamu 3alaykum" , kana = "アッサラーム アライクム" , arabic = "اَلْسَّلامُ عَلَيْكُم" , meaning = "Peace be upon you." } , { latin = "wa-3alaykumu a-s-salaam" , kana = "ワ アライクム アッサラーム" , arabic = "وَعَلَيكم السلام" , meaning = "And peace be upon you." } , { latin = "lil2asaf" , kana = "リルアサフ" , arabic = "لِلْأَسَف" , meaning = "unfortunately" } , { latin = "al-baHr al-2abyaD al-mutawas-siT" , kana = "アル バハる アル アビヤど アル ムタワッスィと" , arabic = "اَاْبَحْر اَلْأَبْيَض اَلْمُتَوَسِّط" , meaning = "the Meditteranean Sea" } , { latin = "2uHibb a-s-safar 2ila l-baHr al-2abyaD al-mutawas-siT" , kana = "ウひッブ アッサファら イラ ル バハる アル アビヤど アル ムタワッスィと" , arabic = "أُحِبّ اَلْسَّفَر إِلى الْبَحْر اَلْلأَبْيَض اَلْمُتَوَسِّط" , meaning = "I like travelling to the Mediterranean Sea." } , { latin = "ghadan" , kana = "ガダン" , arabic = "غَداً" , meaning = "tomorrow" } , { latin = "li-maadhaa" , kana = "リ マーザー" , arabic = "لَماذا" , meaning = "why" } , { latin = "3indii fikra" , kana = "アインディー フィクら" , arabic = "عِندي فِكْرة" , meaning = "I have an idea." } , { latin = "hal 3indaka haatif" , kana = "ハル アインダカ ハーティフ" , arabic = "هَل عِندَكَ هاتِف" , meaning = "Do you have a phone?" } , { latin = "fi l-T-Taabiq al-2awwal" , kana = "フィル ッタービク アルアッワル" , arabic = "في الْطّابِق اَلْأَوَّل" , meaning = "on the first floor" } , { latin = "a-sh-shaanii" , kana = "アッシャーニー" , arabic = "الثاني" , meaning = "the second" } , { latin = "fi l-T-Taabiq a-sh-sha-nii" , kana = "フィル ッタービク アッシャーニー" , arabic = "في الطابق الثاني" , meaning = "in the second floor" } , { latin = "al-laa" , kana = "アッラー" , arabic = "اَلله" , meaning = "God" } , { latin = "haadha l-bayt" , kana = "ハーザ ル バイト" , arabic = "هَذا البَيت" , meaning = "this house" } , { latin = "haadhihi l-madiina" , kana = "ハージヒ ル マディーナ" , arabic = "هَذِهِ المَدينة" , meaning = "this city" } , { latin = "hunaak bayt" , kana = "フゥナーク バイト" , arabic = "هُناك بَيْت" , meaning = "There is a house." } , { latin = "al-bayt hunaak" , kana = "アルバイト フゥナーク" , arabic = "اَلْبَيْت هُناك" , meaning = "The house is there." } , { latin = "hunaak washaaH 2abyaD" , kana = "フゥナーク ワシャーハ アビヤド" , arabic = ".هُناك وِشاح أَبْيَض" , meaning = "There is a white scarf." } , { latin = "al-washaaH hunaak" , kana = "アルワシャーハ フゥナーク" , arabic = "اَلْوِشاح هُناك" , meaning = "The scarf is there." } , { latin = "laysa hunaak bayt" , kana = "ライサ フゥナーク バイト" , arabic = "لَيْسَ هُناك بَيْت" , meaning = "There is no house." } , { latin = "laysa hunaak washaaH 2abyaD" , kana = "ライサ フゥナーク ワシャーハ アビヤド" , arabic = "لَيْسَ هُناك وِشاح أَبْيَض" , meaning = "There is no white scarf." } , { latin = "bayt buub" , kana = "バイト ブーブ" , arabic = "بَيْت بوب" , meaning = "Bob’s house" } , { latin = "baab karii" , kana = "バーブ カりー" , arabic = "باب كَري" , meaning = "<NAME>’s door" } , { latin = "kalb al-bint" , kana = "カルブ アルビント" , arabic = "كَلْب اَلْبِنْت" , meaning = "the girl’s dog" } , { latin = "wishaaH al-walad" , kana = "ウィシャーハ アル ワラド" , arabic = "وِشاح اَلْوَلَد" , meaning = "the boy’s scarf" } , { latin = "madiinat buub" , kana = "マディーナト ブーブ" , arabic = "مَدينة بوب" , meaning = "Bob’s city" } , { latin = "jaami3at karii" , kana = "ジャミーアト カりー" , arabic = "جامِعة كَري" , meaning = "Carrie’s university" } , { latin = "qiT-Tat al-walad" , kana = "キッタト アルワラド" , arabic = "قِطّة اَلْوَلَد" , meaning = "the boy’s cat" } , { latin = "mi3Tafhu" , kana = "ミターフフゥ" , arabic = "مِعْطَفهُ" , meaning = "his coat" } , { latin = "mi3Tafhaa" , kana = "ミターフハー" , arabic = "مِعْطَفها" , meaning = "her coat" } , { latin = "baythu" , kana = "バイトフゥ" , arabic = "بَيْتهُ" , meaning = "his house" } , { latin = "baythaa" , kana = "バイトハー" , arabic = "بَيْتها" , meaning = "her house" } , { latin = "madiinathu" , kana = "マディーナトフ" , arabic = "مَدينَتهُ" , meaning = "his city" } , { latin = "madiinathaa" , kana = "マディーナトハー" , arabic = "مَدينَتها" , meaning = "her city" } , { latin = "qubba3athu" , kana = "クッバトフ" , arabic = "قُبَّعَتهُ" , meaning = "his hat" } , { latin = "qubba3athaa" , kana = "クッバトハー" , arabic = "قُبَّعَتها" , meaning = "her hat" } , { latin = "2abtasim" , kana = "アブタスィム" , arabic = "أَبْتَسِم" , meaning = "I smile" } , { latin = "2aTbukh" , kana = "アトブクフ" , arabic = "أَطْبُخ" , meaning = "I cook" } , { latin = "laa 2aTbukh" , kana = "ラー アトブクフ" , arabic = "لا أَطْبُخ" , meaning = "I do not cook." } , { latin = "li-d-diraasa" , kana = "リッディらーサ" , arabic = "للدراسة" , meaning = "to study" } , { latin = "ma3a 2ustaadh 2aHmad" , kana = "マア ウスターズ アハマド" , arabic = "مَعَ الأُستاذ أَحمَد" , meaning = "with Mr. Ahmed" } , { latin = "bi-l-yaabaaniyy" , kana = "ビルヤーバーニーイ" , arabic = "بالياباني" , meaning = "in Japanese" } , { latin = "bi-s-sayaara" , kana = "ビッサイヤーら" , arabic = "باالسيارة" , meaning = "by car" } , { latin = "li-2akhii" , kana = "リアクヒー" , arabic = "لِأَخي" , meaning = "for my brother" } , { latin = "3ala l-kursii" , kana = "アラ ル クるスィー" , arabic = "عَلى الكُرسي" , meaning = "on the chair" } , { latin = "taHt al-maktab" , kana = "タハタ ル マクタブ" , arabic = "تَحت المَكتَب" , meaning = "under the desk" } , { latin = "amaam al-maHaTTa" , kana = "アマーマ ル マハッタ" , arabic = "أَمام المَحطّة" , meaning = "in front of the station" } , { latin = "2atakal-lam" , kana = "アタカッラム" , arabic = "أَتَكَلَّم" , meaning = "I talk, I speak" } , { latin = "2uHibb al-kalaam" , kana = "ウひッブ アルカラーム" , arabic = "أُحِبّ اَلْكَلام." , meaning = "I like talking." } , { latin = "2uriid al-kalaam" , kana = "ウりード アルカラーム" , arabic = "أُريد اَلْكَلام" , meaning = "I want to talk." } , { latin = "al-kalaam jayyid" , kana = "アルカラーム ジャイイド" , arabic = "اَلْكَلام جَيِّد" , meaning = "The talking is good." } , { latin = "az-zawja" , kana = "アッザウジャ" , arabic = "اَلْزَّوْجة" , meaning = "the wife" } , { latin = "as-sayyaara" , kana = "アッサイヤーラ" , arabic = "اَلْسَّيّارة" , meaning = "the car" } , { latin = "ad-duktuur" , kana = "アッドクトゥール" , arabic = "ad-duktuur" , meaning = "the doctor" } , { latin = "ar-rajul" , kana = "アッラジュル" , arabic = "اَلْرَّجُل" , meaning = "the man" } , { latin = "as-suudaan" , kana = "アッスーダーン" , arabic = "اَلْسّودان" , meaning = "Sudan" } , { latin = "yabda2" , kana = "ヤブダ" , arabic = "يَبْدَأ" , meaning = "he begins" } , { latin = "shaadii l-mu3al-lim" , kana = "シャーディー ル ムアッリム" , arabic = "شادي المُعَلِّم" , meaning = "Shadi the teacher" } , { latin = "mahaa l-mutarjima" , kana = "マハー ル ムタルジマ" , arabic = "مَها المُتَرجِمة" , meaning = "Maha the translator" } , { latin = "fi l-bayt" , kana = "フィルバイト" , arabic = "في البَيت" , meaning = "in the house" } , { latin = "fi s-sayyaara" , kana = "フィッサイヤーラ" , arabic = "في السيارة" , meaning = "in the car" } , { latin = "2iDaafa" , kana = "イダーファ" , arabic = "إضافة" , meaning = "iDaafa, addition" } , { latin = "2aftaH" , kana = "アフタハ" , arabic = "أَفْتَح" , meaning = "I open" } , { latin = "tuHibb" , kana = "トゥヒッブ" , arabic = "تُحِبّ" , meaning = "you like (to a male), she likes" } , { latin = "tuHibbiin" , kana = "トゥヒッビーン" , arabic = "تُحِبّين" , meaning = "you like (to a female)" } , { latin = "yuHibb" , kana = "ユヒッブ" , arabic = "يُحِبّ" , meaning = "he likes" } , { latin = "tanaam" , kana = "タナーム" , arabic = "تَنام" , meaning = "you sleep (to a male), she sleeps" } , { latin = "tanaamiin" , kana = "タナーミーン" , arabic = "تَنامين" , meaning = "you sleep (to a female)" } , { latin = "yaanaam" , kana = "ヤナーム" , arabic = "يَنام" , meaning = "he sleeps" } , { latin = "haadhihi l-madiina laa tanaam" , kana = "ハージヒ ルマディーナ ラー タナーム" , arabic = "هٰذِهِ ٲلْمَدينة لا تَنام" , meaning = "This city does not sleep." } , { latin = "maa ra2yik" , kana = "マー ラ イイク" , arabic = "ما رَأْيِك؟" , meaning = "What do you think? (Literally: What is your opinion?)" } , { latin = "maadhaa tuHib-biin" , kana = "マーザー トゥヒッビーン" , arabic = "ماذا تُحِبّين؟" , meaning = "What do you like?" } , { latin = "maadhaa 2adrus" , kana = "マーザー アドルス" , arabic = "ماذا أَدْرُس؟" , meaning = "What do I study?" } , { latin = "as-saa3at ath-thaanya" , kana = "アッサーアト アッサーニア" , arabic = "اَلْسّاعة الْثّانْية" , meaning = "the second hour" } , { latin = "as-saa3at ath-thaalitha" , kana = "アッサーアト アッサーリサ" , arabic = "اَلْسّاعة الْثّالِثة" , meaning = "the third hour" } , { latin = "as-saa3at ar-raabi3a" , kana = "アッサーアト アッラービア" , arabic = "اَلْسّاعة الْرّابِعة" , meaning = "the fourth hour" } , { latin = "as-saa3at l-khaamisa" , kana = "アッサーアト ル クハーミサ" , arabic = "اَلْسّاعة الْخامِسة" , meaning = "the fifth hour" } , { latin = "as-saa3at as-saadisa" , kana = "アッサーアト アッサーディサ" , arabic = "اَلْسّاعة الْسّادِسة" , meaning = "the sixth hour" } , { latin = "as-saa3at as-saabi3a" , kana = "アッサーアト アッサービア" , arabic = "اَلْسّاعة الْسّابِعة" , meaning = "the seventh hour" } , { latin = "as-saa3at ath-thaamina" , kana = "アッサーアト アッサーミナ" , arabic = "اَلْسّاعة الْثّامِنة" , meaning = "the eighth hour" } , { latin = "as-saa3at at-taasi3a" , kana = "アッサーアト アッタースィア" , arabic = "اَلْسّاعة الْتّاسِعة" , meaning = "the ninth hour" } , { latin = "as-saa3at l-3aashira" , kana = "アッサーアト ル アーシラ" , arabic = "اَلْسّاعة الْعاشِرة" , meaning = "the tenth hour" } , { latin = "as-saa3at l-Haadya 3ashara" , kana = "アッサーアト ル ハーディヤ アシャラ" , arabic = "اَلْسّاعة الْحادْية عَشَرة" , meaning = "the eleventh hour" } , { latin = "as-saa3ag ath-thaanya 3ashara" , kana = "アッサーアト アッサーニヤ アシャラ" , arabic = "اَلْسّاعة الْثّانْية عَشَرة" , meaning = "the twelfth hour" } , { latin = "as-saa3at l-waaHida" , kana = "アッサーアト ル ワーヒダ" , arabic = "اَلْسّاعة الْواحِدة" , meaning = "the hour one" } , { latin = "as-saa3at ath-thaanya ba3d a-Dh-Dhuhr" , kana = "アッサーアト アッサーニヤ バァダ ッズホル" , arabic = "اَلْسّاعة الْثّانْية بَعْد اَلْظُّهْر" , meaning = "two o'clock in the afternon" } , { latin = "2anaa min lubanaan" , kana = "アナー ミン ルブナーン" , arabic = "أنا من لبنان" , meaning = "I am from Lebanon." } , { latin = "lastu min lubnaan" , kana = "ラストゥ ミン ルブナーン" , arabic = "لَسْتُ من لبنان" , meaning = "" } , { latin = "lastu mariiDa" , kana = "ラストゥ マリーダ" , arabic = "لَسْتُ مَريضة" , meaning = "I am not sick." } , { latin = "lastu fi l-bayt" , kana = "ラストゥ フィル バイト" , arabic = "لَسْتُ في الْبَيْت" , meaning = "I am not home." } , { latin = "lastu min hunaa" , kana = "ラストゥ ミン フゥナー" , arabic = "لَسْتُ مِن هُنا" , meaning = "I am not form here." } , { latin = "qarya" , kana = "かりヤー" , arabic = "قَرية" , meaning = "a village" } , { latin = "sahl" , kana = "サヘル" , arabic = "سَهل" , meaning = "easy" } , { latin = "a-T-Tabii3a" , kana = "アッタビーア" , arabic = "الطَّبيعة" , meaning = "nature" } , { latin = "fii 2ayy saa3a" , kana = "フィー アイイ サーア" , arabic = "في أي ساعة" , meaning = "at which hour, when" } , { latin = "al-iskandariyya" , kana = "アル イスカンダリーヤ" , arabic = "الاِسكَندَرِيّة" , meaning = "Alexandria in Egypt" } , { latin = "2ayna l-maHaT-Ta" , kana = "アイナ ル マハッタ" , arabic = "أَينَ المَحَطّة" , meaning = "Where is the station?" } , { latin = "3aDhiim jiddan" , kana = "アジーム ジッダン" , arabic = "عَظيم جِدّاً" , meaning = "Fantastic! Great!" } , { latin = "thalaatha mar-raat fi l-2usbuu3" , kana = "サラーサ マッラート フィル ウスブーア" , arabic = "ثَلاثَ مَرّات في الأُسبوع" , meaning = "three times a week" } , { latin = "2asaatidha" , kana = "アサーティザ" , arabic = "أَساتِذة" , meaning = "masters, professors" } , { latin = "2ikhwa" , kana = "イクフワ" , arabic = "إِخْوة" , meaning = "brothers" } , { latin = "Suura jamiila" , kana = "スーラ ジャミーラ" , arabic = "صورة جَميلة" , meaning = "beautiful picture" } , { latin = "al-Hkuuma l-2amriikiya" , kana = "アル フクーマ ル アムリーキーヤ" , arabic = "الحْكومة الأَمريكية" , meaning = "the American government" } , { latin = "HaDaara qadiima" , kana = "ハダーラ カディーマ" , arabic = "حَضارة قَديمة" , meaning = "old civilization" } , { latin = "Salaat" , kana = "サラート" , arabic = "صَلاة" , meaning = "prayer, worship" } , { latin = "zakaat" , kana = "ザカート" , arabic = "زَكاة" , meaning = "alms" } , { latin = "Hayaat" , kana = "ハヤート" , arabic = "حَياة" , meaning = "life" } , { latin = "ghurfat bintii" , kana = "グルファト ビンティー" , arabic = "غُرفة بِنتي" , meaning = "my daughter's room" } , { latin = "madiinat nyuuyuurk" , kana = "マディーナト ニューユールク" , arabic = "مَدينة نيويورك" , meaning = "city of New York" } , { latin = "sharika" , kana = "シャリカ" , arabic = "شَرِكة" , meaning = "a company" } , { latin = "sharikat khaalii" , kana = "シャリカト クハーリー" , arabic = "شَرِكة خالي" , meaning = "my uncle's company" } , { latin = "madrasatii" , kana = "マドラサティー" , arabic = "مَدرَسَتي" , meaning = "my school" } , { latin = "3alaaqatnaa" , kana = "アラーカトナー" , arabic = "عَلاقَتنا" , meaning = "our relationship" } , { latin = "shuhra" , kana = "シュフラ" , arabic = "شُهرة" , meaning = "fame" } , { latin = "shufrathu" , kana = "シュフラトフ" , arabic = "شُهرَته" , meaning = "his fame" } , { latin = "naz-zlnii hunaa" , kana = "ナッズィルニー フゥナー" , arabic = "نَزِّلني هنا" , meaning = "Download me here." } , { latin = "3alaa mahlika" , kana = "アラー マハリカ" , arabic = "عَلى مَهلِكَ" , meaning = "Slow down. Take it easy." } , { latin = "laysa kul-la yawm" , kana = "ライサ クッラ ヤウム" , arabic = "اَيْسَ كُلَّ يَوم" , meaning = "not every day" } , { latin = "kul-l l-naas" , kana = "クッル ル ナース" , arabic = "كُلّ الناس" , meaning = "all the people" } , { latin = "kul-l l-2awlaad" , kana = "クッル ル アウラード" , arabic = "كُلّ الأَولاد" , meaning = "all the boys, children" } , { latin = "mayk" , kana = "マイク" , arabic = "مايْك" , meaning = "Mike" } , { latin = "bikam haadhaa" , kana = "ビカム ハーザー" , arabic = "بِكَم هَذا" , meaning = "How much is this?" } , { latin = "dimashq" , kana = "ディマシュク" , arabic = "دِمَشق" , meaning = "Damascus" } , { latin = "2in shaa2a l-laa" , kana = "インシャーアッラー" , arabic = "إِن شاءَ اللَّه" , meaning = "on God's will" } , { latin = "yal-laa" , kana = "ヤッラー" , arabic = "يَلّا" , meaning = "alright" } , { latin = "3aailatii" , kana = "アーイラティー" , arabic = "عائلَتي" , meaning = "my family" } , { latin = "akhbaar" , kana = "アクフバール" , arabic = "أَخبار" , meaning = "news" } , { latin = "tadrsiin" , kana = "タドルスィーン" , arabic = "تَدرسين" , meaning = "you study" } , { latin = "3ilm al-Haasuub" , kana = "アイルム アル ハースーブ" , arabic = "عِلم الحاسوب" , meaning = "computer sicence" } , { latin = "muSawwir" , kana = "ムサウィル" , arabic = "مُصَوِّر" , meaning = "photographer" } , { latin = "laa 2uHib-b-hu" , kana = "ラー ウひッブフ" , arabic = "لا أُحِبّهُ" , meaning = "I do not love him." } , { latin = "ta3mal" , kana = "タアマル" , arabic = "نَعمَل" , meaning = "You work, we work" } , { latin = "2aakhar" , kana = "アークハル" , arabic = "آخَر" , meaning = "else, another, other than this" } , { latin = "lawn 2aakhar" , kana = "ラウン アークハル" , arabic = "لَوت آخَر" , meaning = "another lot, color" } , { latin = "rabba bayt" , kana = "ラッババイト" , arabic = "رَبّة بَيت" , meaning = "homemaker, housewife" } , { latin = "baaHith" , kana = "バーヒス" , arabic = "باحِث" , meaning = "a researcher" } , { latin = "last jaw3aana" , kana = "ラスト ジャウあーナ" , arabic = "لَسْت جَوعانة" , meaning = "I am not hungry." } , { latin = "hal juudii mutafarrigha" , kana = "ハル ジューディー ムタファルリガ" , arabic = "هَل جودي مُتَفَرِّغة؟" , meaning = "Is Judy free?" } , { latin = "nuuSf" , kana = "ヌースフ" , arabic = "نُّصْف" , meaning = "half" } , { latin = "fiilm 2aflaam" , kana = "フィールム アフラーム" , arabic = "فيلم ـ أَفلام" , meaning = "film - films" } , { latin = "dars duruus" , kana = "ダルス ドゥルース" , arabic = "دَرس ـ دُروس" , meaning = "lesson - lessons" } , { latin = "risaala - rasaa2il" , kana = "りサーラ らサーイル" , arabic = "رِسالة - رَسائِل" , meaning = "letter - letters" } , { latin = "qariib - 2aqaarib" , kana = "カリーブ アカーリブ" , arabic = "قَريب - أَقارِب" , meaning = "relative - relatives" } , { latin = "Sadiiq - 2aSdiqaa2" , kana = "サディーク アスディカー" , arabic = "صَديق - أَصْذِقاء" , meaning = "friend - friends" } , { latin = "kitaab - kutub" , kana = "キターブ クトゥブ" , arabic = "كِتاب - كُتُب" , meaning = "book - books" } , { latin = "lugha - lughaat" , kana = "ルガ ルガート" , arabic = "لُغة - لُغات" , meaning = "language - languages" } , { latin = "tuHibb al-kitaaba" , kana = "トゥヒッブ アルキターバ" , arabic = "تُحِبّ اَلْكِتابة" , meaning = "She likes writing." } , { latin = "kitaabat ar-rasaa2il mumti3a" , kana = "キターバト アッラサーイル ムムティア" , arabic = "كِتابة اَلْرَّسائِل مُمْتِعة" , meaning = "Writing of the letters is fun." } , { latin = "HaaDr siidii" , kana = "ハードル スィーディー" , arabic = "حاضر سيدي" , meaning = "Yes, sir." } , { latin = "waqt" , kana = "ワクト" , arabic = "وَقت" , meaning = "time" } , { latin = "risaala" , kana = "リサーラ" , arabic = "رِسالة" , meaning = "letter" } , { latin = "fann" , kana = "ファン" , arabic = "فَنّ" , meaning = "art" } , { latin = "Haziin" , kana = "ハズィーン" , arabic = "حَزين" , meaning = "sad" } , { latin = "3aa2ila" , kana = "アーイラ" , arabic = "عائِلة" , meaning = "family" } , { latin = "2uHibb qiraa2at al-kutub" , kana = "ウひッブ キラーアト アルクトゥブ" , arabic = "أُحِبّ قِراءة اَلْكُتُب" , meaning = "I like reading of the books." } , { latin = "2uHibb al-qiraa2a" , kana = "ウひッブ アルキラーエ" , arabic = "أُحِبّ اَلْقِراءة" , meaning = "I like the reading." } , { latin = "al-kitaaba mumti3a" , kana = "アルキターバ ムムティア" , arabic = "اَلْكِتابة مُمْتِعة" , meaning = "The writing is fun." } , { latin = "kura l-qadam" , kana = "クーラルカダム" , arabic = "كُرة اَلْقَدَم" , meaning = "soccer" } , { latin = "2uHibb ad-dajaaj min 2ams" , kana = "ウひッブ アッダジャージ ミン アムス" , arabic = "أُحِبّ اَلْدَّجاج مِن أَمْس" , meaning = "I like the chicken from yesterday." } , { latin = "2uHibb ad-dajaaj" , kana = "ウひッブ アッダジャージ" , arabic = "أُحِبّ اَلْدَّجاج" , meaning = "I like chicken." } , { latin = "2uHibb al-qawha" , kana = "ウひッブ アルかハワ" , arabic = "أُحِبّ اَلْقَهْوة" , meaning = "I like coffee." } , { latin = "2uriid dajaajan" , kana = "ウりード ダジャージャン" , arabic = "أُريد دَجاجاً" , meaning = "I want chicken." } , { latin = "2uriid qahwa" , kana = "ウりード かハワ" , arabic = "أُريد قَهْوة" , meaning = "I want coffee." } , { latin = "2aakul dajaajan" , kana = "アークル ダジャージャン" , arabic = "آكُل دَجاجاً" , meaning = "I eat chicken." } , { latin = "2ashrab qahwa kul-l SabaaH" , kana = "アシュらブ かハワ クッル さバーは" , arabic = "أَشْرَب قَهْوة كُلّ صَباح" , meaning = "I drink coffee every morning." } , { latin = "2uriid Sadiiqan" , kana = "ウりード すぁディーかン" , arabic = "أُريد صَديقاً" , meaning = "I want a friend." } , { latin = "2aakul khubzan" , kana = "アークル クフブザン" , arabic = "آكُل خُبْزاً" , meaning = "I eat bread." } , { latin = "2uriid baytan jadiidan" , kana = "ウりード バイタン ジャディーダン" , arabic = "أُريد بَيْتاً جَديداً" , meaning = "I want a new house." } , { latin = "matHaf" , kana = "マトはフ" , arabic = "مَتحَف" , meaning = "a museum" } , { latin = "laHm" , kana = "ラハム" , arabic = "لَحْم" , meaning = "meat" } , { latin = "baTaaTaa" , kana = "バターター" , arabic = "بَطاطا" , meaning = "potato" } , { latin = "yashrab al-Haliib" , kana = "ヤシュらブ アルハリーブ" , arabic = "يَشْرَب الحَليب" , meaning = "He drinks milk" } , { latin = "al-muqab-bilaat" , kana = "アルムカッビラート" , arabic = "المُقَبِّلات" , meaning = "appetizers" } , { latin = "Hummusan" , kana = "フンムサン" , arabic = "حُمُّصاً" , meaning = "chickpeas, hummus" } , { latin = "SaHiiH" , kana = "サヒーハ" , arabic = "صَحيح" , meaning = "true, right, correct" } , { latin = "3aSiir" , kana = "アアスィーる" , arabic = "عَصير" , meaning = "juice" } , { latin = "shuurba" , kana = "シューるバ" , arabic = "شورْبة" , meaning = "soupe" } , { latin = "salaTa" , kana = "サラタ" , arabic = "سَلَطة" , meaning = "salad" } , { latin = "s-saakhin" , kana = "ッサークヒン" , arabic = "سّاخِن" , meaning = "hot, warm" } , { latin = "Halwaa" , kana = "はルワー" , arabic = "حَلْوى" , meaning = "candy, dessert" } , { latin = "kib-ba" , kana = "キッバ" , arabic = "كِبّة" , meaning = "kibbeh" } , { latin = "a-T-Tabaq" , kana = "アッタバク" , arabic = "الطَّبّق" , meaning = "the plate, dish" } , { latin = "Tabaq" , kana = "タバク" , arabic = "طّبّق" , meaning = "plate, dish" } , { latin = "2aina 2antum" , kana = "アイナアントム" , arabic = "أَيْن أَنْتُم" , meaning = "Where are you?" } , { latin = "baaS" , kana = "バーすぅ" , arabic = "باص" , meaning = "bus" } , { latin = "tadhkara" , kana = "たずカら" , arabic = "تَذْكَرة" , meaning = "a ticket" } , { latin = "Saff" , kana = "すぁッフ" , arabic = "صَفّ" , meaning = "class" } , { latin = "qiTaar" , kana = "きたーる" , arabic = "قِطار" , meaning = "train" } , { latin = "khuDraawaat" , kana = "クフどらーワート" , arabic = "خُضْراوات" , meaning = "vegetables" } , { latin = "Taazij" , kana = "たーズィジ" , arabic = "طازِج" , meaning = "fresh" } , { latin = "laa 2ashtarii qahwa" , kana = "ラー アシュタりー かハワ" , arabic = "لا أَشْتَري قَهْوة" , meaning = "I do not buy coffee." } , { latin = "faakiha" , kana = "ファーキハ" , arabic = "فاكِهة" , meaning = "fruit" } , { latin = "yufaD-Dil" , kana = "ユファッでぃル" , arabic = "يُفَضِّل" , meaning = "he prefers" } , { latin = "tufaD-Dil" , kana = "トゥファッでぃル" , arabic = "تُفَضِّل" , meaning = "you prefer" } , { latin = "al-banaduura" , kana = "アルバナドゥーら" , arabic = "البَنَدورة" , meaning = "the tomato" } , { latin = "banaduura" , kana = "バナドゥーら" , arabic = "بَنَدورة" , meaning = "tomato" } , { latin = "limaadhaa" , kana = "リマーざー" , arabic = "لِماذا" , meaning = "Why?" } , { latin = "maw3id" , kana = "マウあイド" , arabic = "مَوْعِد" , meaning = "an appointment" } , { latin = "lam" , kana = "ラム" , arabic = "لَم" , meaning = "did not" } , { latin = "yasmaH" , kana = "ヤスマは" , arabic = "يَسْمَح" , meaning = "allow, permit" } , { latin = "khuruuj" , kana = "クフルージ" , arabic = "خُروج" , meaning = "exit, get out" } , { latin = "laa ya2atii" , kana = "ラー ヤアティー" , arabic = "لا يَأْتي" , meaning = "he does not come" } , { latin = "khaTiib" , kana = "クハてぃーブ" , arabic = "خَطيب" , meaning = "fiance" } , { latin = "2abadan" , kana = "アバダン" , arabic = "أَبَدا" , meaning = "never again" } , { latin = "2arkab T-Taa2ira" , kana = "アルカブ ッたーイら" , arabic = "أَرْكَب الطائرة" , meaning = "I ride the plane" } , { latin = "2a3uud" , kana = "アあぅード" , arabic = "أَعود" , meaning = "I come back, return" } , { latin = "maa saafart" , kana = "マー サーファるト" , arabic = "ما سافَرْت" , meaning = "I have not traveled" } , { latin = "li2an-nak" , kana = "リアンナク" , arabic = "لِأَنَّك" , meaning = "because you are" } , { latin = "al-2akl a-S-S-H-Hiyy" , kana = "アルアクル ッすぃひーユ" , arabic = "الأَكل الصِّحِّي" , meaning = "the healthy food" } , { latin = "yajib 2an" , kana = "ヤジブ アン" , arabic = "يَجِب أَن" , meaning = "must" } , { latin = "tashtarii" , kana = "タシュタりー" , arabic = "تَشْتَري" , meaning = "you buy" } , { latin = "baamiya" , kana = "バーミヤ" , arabic = "بامية" , meaning = "squash, zucchini, pumpkin, okra" } , { latin = "kuusaa" , kana = "クーサー" , arabic = "كوسا" , meaning = "zucchini" } , { latin = "Taazij" , kana = "たーズィジ" , arabic = "طازِج" , meaning = "fresh" } , { latin = "jazar" , kana = "ジャザる" , arabic = "جَزَر" , meaning = "carrots" } , { latin = "SiH-Hiya" , kana = "すぃッひーヤ" , arabic = "صِحِّية" , meaning = "healthy" } , { latin = "a2ashtarii" , kana = "アシュタりー" , arabic = "أَشْتَري" , meaning = "I buy" } , { latin = "tashtarii" , kana = "タシュタりー" , arabic = "تَشْتَري" , meaning = "you buy (to a male), she buys" } , { latin = "tashtariin" , kana = "タシュタりーン" , arabic = "تَشْتَرين" , meaning = "you buy (to a female)" } , { latin = "yashtarii" , kana = "ヤシュタりー" , arabic = "يَشْتَري" , meaning = "he buys" } , { latin = "nashtarii" , kana = "ナシュタりー" , arabic = "نَشْتَري" , meaning = "we buy" } , { latin = "tashtaruun" , kana = "タシュタるーン" , arabic = "تَشْتَرون" , meaning = "you all buy, they buy" } , { latin = "li2an-na l-3aalam ghariib" , kana = "リアンナ ルあーラム ガりーブ" , arabic = "لِأَنَّ ٱلْعالَم غَريب" , meaning = "Because the world is weird." } , { latin = "li2anna 2ukhtii tadhrus k<NAME>" , kana = "リアンナ ウクフティー タずるス カしーラン" , arabic = "لِأَنَّ أُخْتي تَذْرُس كَثيراً" , meaning = "Because my sister studies a lot." } , { latin = "li2an-nanii min misr" , kana = "リアンナニー ミン ミスる" , arabic = "لِأَنَّني مِن مِصر" , meaning = "Because I am from Egypt." } , { latin = "li2an-nik 2um-mii" , kana = "リアンニク ウムミー" , arabic = "لِأَنِّك أُمّي" , meaning = "Because you are my mother." } , { latin = "li2an-ni-haa mu3al-lma mumtaaza" , kana = "リアンナハー ムあッリマ ムムターザ" , arabic = "لِأَنَّها مُعَلِّمة مُمْتازة" , meaning = "Because she is an amazing teacher." } , { latin = "li-2an-na-hu sa3iid" , kana = "リアンナフゥ サあイード" , arabic = "لِأَنَّهُ سَعيد" , meaning = "Because he is happy." } , { latin = "li-2abii" , kana = "リアビー" , arabic = "لِأَبي" , meaning = "to/for my father" } , { latin = "li-haadhihi l-2ustaadha" , kana = "リハーじヒ ル ウスターざ" , arabic = "لِهٰذِهِ الْأُسْتاذة" , meaning = "to/for this professor" } , { latin = "li-bayruut" , kana = "リバイるート" , arabic = "لِبَيْروت" , meaning = "to/for Beirut" } , { latin = "li-l-bint" , kana = "リルビント" , arabic = "لِلْبِنْت" , meaning = "to/for the girl" } , { latin = "li-l-2ustaadha" , kana = "リルウスターざ" , arabic = "لِلْأُسْتاذة" , meaning = "to/for the professor" } , { latin = "li-l-qaahira" , kana = "リルかーヒら" , arabic = "لِلْقاهِرة" , meaning = "to/for Cairo" } , { latin = "al-maHal-l maHal-laka yaa 2ustaadh" , kana = "アルマはッル マはッラカ ヤー ウスターず" , arabic = "اَلْمَحَلّ مَحَلَّك يا أُسْتاذ!" , meaning = "The shop is your shop, sir." } , { latin = "hal turiid al-qaliil min al-maa2" , kana = "ハル トゥりード イル かリール ミナル マー" , arabic = "هَل تُريد اَلْقَليل مِن اَلْماء؟" , meaning = "Do you want a little water?" } , { latin = "3aada" , kana = "あーダ" , arabic = "عادة" , meaning = "usually" } , { latin = "ka3k" , kana = "カあク" , arabic = "كَعْك" , meaning = "cakes" } , { latin = "a2ashrab" , kana = "アシュらブ" , arabic = "أَشْرَب" , meaning = "I drink" } , { latin = "sa-2ashrab" , kana = "サ アシュらブ" , arabic = "سَأَشْرَب" , meaning = "I will drink" } , { latin = "tashrab" , kana = "タシュらブ" , arabic = "تَشْرَب" , meaning = "you drink (to a male), she drinks" } , { latin = "tashrabiin" , kana = "タシュらビーン" , arabic = "تَشْرَبين" , meaning = "you drink (to a female)" } , { latin = "yashrab" , kana = "ヤシュらブ" , arabic = "يَشْرَب" , meaning = "he drinks" } ]
true
module Arabic001 exposing (main) -- backup 2020-06-07 16:51:47 import Browser import Html exposing (..) import Html.Attributes as HA import Html.Events as HE import Random main : Program () Model Msg main = Browser.element { init = init , update = update , subscriptions = subscriptions , view = view } type alias Model = { latin : String , kana : String , arabic : String , meaning : String , showanswer : Bool , list : List Arabicdata } type alias Arabicdata = { latin : String , kana : String , arabic : String , meaning : String } init : () -> ( Model, Cmd Msg ) init _ = ( Model "" "" "" "" False dict , Random.generate NewList (shuffle dict) ) type Msg = Delete | Next | NewRandom Int | Shuffle | NewList (List Arabicdata) | ShowAnswer Int update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of Delete -> ( model , Cmd.none ) Next -> ( model , Cmd.none ) NewRandom n -> case List.drop n dict of x :: _ -> ( { model | latin = x.latin , kana = x.kana , arabic = x.arabic , meaning = x.meaning } , Cmd.none ) [] -> ( model , Cmd.none ) Shuffle -> ( model , Random.generate NewList (shuffle dict) ) NewList newList -> ( { model | list = newList } , Cmd.none ) ShowAnswer index -> case List.drop index model.list of x :: _ -> ( { model | latin = x.latin , kana = x.kana , arabic = x.arabic , meaning = x.meaning , showanswer = True } , Cmd.none ) [] -> ( model , Cmd.none ) subscriptions : Model -> Sub Msg subscriptions model = Sub.none view : Model -> Html Msg view model = div [] [ text "Convert latin to arabic" , p [] [ text "SabaaH" ] , button [] [ text "Show Answer" ] , button [] [ text "Delete" ] , button [] [ text "Next" ] ] shuffle : List a -> Random.Generator (List a) shuffle list = let randomNumbers : Random.Generator (List Int) randomNumbers = Random.list (List.length list) <| Random.int Random.minInt Random.maxInt zipWithList : List Int -> List ( a, Int ) zipWithList intList = List.map2 Tuple.pair list intList listWithRandomNumbers : Random.Generator (List ( a, Int )) listWithRandomNumbers = Random.map zipWithList randomNumbers sortedGenerator : Random.Generator (List ( a, Int )) sortedGenerator = Random.map (List.sortBy Tuple.second) listWithRandomNumbers in Random.map (List.map Tuple.first) sortedGenerator dict = [ { latin = "a-s-salaamu" , kana = "アッサラーム" , arabic = "اَلسَّلَامُ" , meaning = "peace" } , { latin = "2alaykum" , kana = "アライクム" , arabic = "عَلَيْكُمْ" , meaning = "on you" } , { latin = "SabaaH" , kana = "サバーフ" , arabic = "صَبَاح" , meaning = "morning" } , { latin = "marHaban" , kana = "マルハバン" , arabic = "مَرْحَبًا" , meaning = "Hello" } , { latin = "2anaa bikhayr" , kana = "アナー ビクハイル" , arabic = "أَنا بِخَيْر" , meaning = "I'm fine" } , { latin = "kabir" , kana = "カビール" , arabic = "كَبير" , meaning = "large, big" } , { latin = "kabiira" , kana = "カビーラ" , arabic = "كبيرة" , meaning = "large, big" } , { latin = "siith" , kana = "スィース" , arabic = "سيث" , meaning = "Seth (male name)" } , { latin = "baluuza" , kana = "バルーザ" , arabic = "بَلوزة" , meaning = "blouse" } , { latin = "tii shiirt" , kana = "ティー シイールト" , arabic = "تي شيرْت" , meaning = "T-shirt" } , { latin = "ma3Taf" , kana = "マアタフ" , arabic = "معْطَف" , meaning = "a coat" } , { latin = "riim" , kana = "リーム" , arabic = "ريم" , meaning = "Reem (male name)" } , { latin = "tan-nuura" , kana = "タンヌーラ" , arabic = "تَنّورة" , meaning = "a skirt" } , { latin = "jadiid" , kana = "ジャディード" , arabic = "جَديد" , meaning = "new" } , { latin = "wishshaaH" , kana = "ウィシャーハ" , arabic = "وِشَاح" , meaning = "a scarf" } , { latin = "juudii" , kana = "ジューディー" , arabic = "جودي" , meaning = "Judy(name)" } , { latin = "jamiil" , kana = "ジャミール" , arabic = "جَميل" , meaning = "good, nice, pretty, beautiful" } , { latin = "kalb" , kana = "キャルブ" , arabic = "كَلْب" , meaning = "a dog" } , { latin = "2abyaD" , kana = "アビヤッド" , arabic = "أَبْيَض" , meaning = "white" } , { latin = "qub-b3a" , kana = "クッバ" , arabic = "قُبَّعة" , meaning = "a hat" } , { latin = "mruu2a" , kana = "ムルーア" , arabic = "مْروءة" , meaning = "chivalry" } , { latin = "Taawila" , kana = "ターウィラ" , arabic = "طاوِلة" , meaning = "a table" } , { latin = "haadhihi madiina qadiima" , kana = "ハージヒ マディーナ カディーマ" , arabic = "هَذِهِ مَدينة قَديمة" , meaning = "This is an ancient city" } , { latin = "haadhihi binaaya jamiila" , kana = "ハージヒ ビナーヤ ジャミーラ" , arabic = "هَذِهِ بِناية جَميلة" , meaning = "This is a beautiful building" } , { latin = "hadhaa muhammad" , kana = "ハーザー ムハンマド" , arabic = "هَذا مُحَمَّد" , meaning = "This is Mohammed" } , { latin = "haadhihi Hadiiqa jamiila" , kana = "ハージヒ ハディーカ ジャミーラ" , arabic = "هَذِهِ حَديقة جَميلة" , meaning = "This is a pretty garden" } , { latin = "haadhihi Hadiiqa qadiima" , kana = "ハージヒ ハディーカ カディーマ" , arabic = "هَذِهِ حَديقة قَديمة" , meaning = "This is an old garden" } , { latin = "al-Haa2iT" , kana = "アルハーイト" , arabic = "الْحائط" , meaning = "the wall" } , { latin = "Haa2iT" , kana = "ハーイト" , arabic = "حائِط" , meaning = "wall" } , { latin = "hadhaa al-Haa2iT kabiir" , kana = "ハーザ ル ハーイト カビール" , arabic = "هَذا الْحائِط كَبير" , meaning = "this wall is big" } , { latin = "al-kalb" , kana = "アル カルブ" , arabic = "الْكَلْب" , meaning = "the dog" } , { latin = "haadhihi al-binaaya" , kana = "ハージヒ アル ビナーヤ" , arabic = "هذِهِ الْبِناية" , meaning = "this building" } , { latin = "al-ghurfa" , kana = "アル グルファ" , arabic = "اَلْغُرفة" , meaning = "the room" } , { latin = "al-ghurfa kabiira" , kana = "アルグルファ カビーラ" , arabic = "اَلْغرْفة كَبيرة" , meaning = "Theroom is big" } , { latin = "haadhihi alghurfa kabiira" , kana = "ハージヒ アルグルファ カビーラ" , arabic = "هَذِهِ الْغُرْفة كَبيرة" , meaning = "this room is big" } , { latin = "hadhaa alkalb kalbii" , kana = "ハーザー アルカルブ カルビー" , arabic = "هَذا الْكَلْب كَْلبي" , meaning = "this dog is my dog" } , { latin = "hadhaa alkalb jaw3aan" , kana = "ハーザー アルカルブ ジャウあーン" , arabic = "هَذا الْكَلْب جَوْعان" , meaning = "this dog is hungry" } , { latin = "haadhihi al-binaaya waasi3a" , kana = "ハージヒ アルビナーヤ ワースィア" , arabic = "هَذِهِ الْبناية واسِعة" , meaning = "this building is spacious" } , { latin = "al-kalb ghariib" , kana = "アルカルブ ガリーブ" , arabic = "اَلْكَلْب غَريب" , meaning = "The dog is weird" } , { latin = "alkalb kalbii" , kana = "アルカルブ カルビー" , arabic = "اَلْكَلْب كَلْبي" , meaning = "The dog is my dog" } , { latin = "hunaak" , kana = "フゥナーク" , arabic = "هُناك" , meaning = "there" } , { latin = "hunaak bayt" , kana = "フゥナーク バイト" , arabic = "هُناك بَيْت" , meaning = "There is a house" } , { latin = "al-bayt hunaak" , kana = "アル バイト フゥナーク" , arabic = "اَلْبَيْت هُناك" , meaning = "The house is there" } , { latin = "hunaak wishaaH 2abyaD" , kana = "フゥナーク ウィシャーハ アビヤド" , arabic = "هُناك وِشاح أبْيَض" , meaning = "There is a white scarf" } , { latin = "alkalb munaak" , kana = "アルカルブ ムナーク" , arabic = "اَلْكَلْب مُناك" , meaning = "The dog is there" } , { latin = "fii shanTatii" , kana = "フィー シャンタティー" , arabic = "في شَنْطَتي" , meaning = "in my bag" } , { latin = "hal 3indak maHfaDha yaa juurj" , kana = "ハル アインダク マハファザ ヤー ジュールジュ" , arabic = "هَل عِنْدَك مَحْفَظة يا جورْج" , meaning = "do you have a wallet , george" } , { latin = "3indii shanTa ghaalya" , kana = "アインディー シャンタ ガーリヤ" , arabic = "عِنْدي شَنْطة غالْية" , meaning = "I have an expensive bag" } , { latin = "shanTatii fii shanTatik ya raanyaa" , kana = "シャンタティー フィー シャンタティク ヤー ラーニヤー" , arabic = "شِنْطَتي في شَنْطتِك يا رانْيا" , meaning = "my bag is in your bag rania" } , { latin = "huunak maHfaDha Saghiira" , kana = "フゥナーク マハファザ サギーラ" , arabic = "هُناك مَحْفَظة صَغيرة" , meaning = "There is a small wallet" } , { latin = "hunaak kitaab jadiid" , kana = "フゥナーク キターブ ジャディード" , arabic = "هَناك كِتاب جَديد" , meaning = "There is a new book" } , { latin = "hunaak kitaab Saghiir" , kana = "フゥナーク キターブ サギール" , arabic = "هُناك كِتاب صَغير" , meaning = "There is a small book" } , { latin = "hunaak qubb3a fii shanTatak yaa buub" , kana = "フゥナーク クッバア フィー シャンタタク ヤー ブーブ" , arabic = "هُناك قُبَّعة في شَنْطَتَك يا بوب" , meaning = "There is a hat in your bag bob" } , { latin = "hunaak shanTa Saghiira" , kana = "フゥナーク シャンタ サギーラ" , arabic = "هُناك شَنْطة صَغيرة" , meaning = "There is a small bag" } , { latin = "shanTatii hunaak" , kana = "シャンタティー フゥナーク" , arabic = "شَنْطَتي هُناك" , meaning = "my bag is over there" } , { latin = "hunaak kitaab Saghiir wa-wishaaH kabiir fii ShanTatii" , kana = "フゥナーク キターブ サギール ワ ウィシャーハ カビール フィー シャンタティー" , arabic = "هُناك كِتاب صَغير وَوِشاح كَبير في شَنْطَتي" , meaning = "There is a small book and a big scarf in my bag" } , { latin = "hunaak maHfaDha Saghiir fii shanTatii" , kana = "フゥナーク マハファザ サギール フィー シャンタティー" , arabic = "هُناك مَحْفَظة صَغيرة في شَنْطَتي" , meaning = "There is a small wallet in my bag" } , { latin = "aljaami3a hunaak" , kana = "アルジャーミア フゥナーク" , arabic = "اَلْجامِعة هُناك" , meaning = "The university is there" } , { latin = "hunaak kitaab" , kana = "フゥナーク キターブ" , arabic = "هُناك كِتاب" , meaning = "There is a book" } , { latin = "al-madiina hunaak" , kana = "アルマディーナ フゥナーク" , arabic = "اَلْمَدينة هُناك" , meaning = "Thecity is there" } , { latin = "hal 3indik shanTa ghaaliya yaa Riim" , kana = "ハル アインディク シャンタ ガーリヤ ヤー リーム" , arabic = "هَل عِندِك شَنْطة غالْية يا ريم" , meaning = "do you have an expensive bag Reem" } , { latin = "hal 3indik mashruub yaa saamya" , kana = "ハル アインディク マシュルーブ ヤー サーミヤ" , arabic = "هَل عِنْدِك مَشْروب يا سامْية" , meaning = "do you have a drink samia" } , { latin = "hunaak daftar rakhiiS" , kana = "フゥナーク ダフタル ラクヒース" , arabic = "هُناك دَفْتَر رَخيص" , meaning = "There is a cheep notebook" } , { latin = "laysa 3indii daftar" , kana = "ライサ アインディー ダフタル" , arabic = "لَيْسَ عِنْدي دَفْتَر" , meaning = "I do not have a notebook" } , { latin = "laysa hunaak masharuub fii shanTatii" , kana = "ライサ フゥナーク マシャルーブ フィー シャンタティー" , arabic = "لَيْسَ هُناك مَشْروب في شَنْطَتي" , meaning = "There is no drink in my bag" } , { latin = "laysa hunaak kitaab qaSiir fii baytii" , kana = "ライサ フゥナーク キターブ カスィール フィー バイティ" , arabic = "لَيْسَ هُناك كِتاب قَصير في بَيْتي" , meaning = "There is no short book in my house" } , { latin = "laysa hunaak daftar rakhiiS" , kana = "ライサ フゥナーク ダフタル ラクヒース" , arabic = "لَيْسَ هُناك دَفْتَر رَخيص" , meaning = "There is no cheap notebook" } , { latin = "laysa 3indii sii dii" , kana = "ライサ アインディー スィー ヂー" , arabic = "لَيْسَ عَنْدي سي دي" , meaning = "I do not have a CD" } , { latin = "laysa hunaak qalam fii shanTatii" , kana = "ライサ フゥナーク カラム フィー シャンタティー" , arabic = "لَيْسَ هُناك قَلَم في شَنْطَتي" , meaning = "There is no pen in my bag" } , { latin = "laysa hunaak kitaab qaSiir fii shanTatii" , kana = "ライサ フゥナーク キターブ カスィール フィー シャンタティー" , arabic = "لَيْسَ هُناك كِتاب قَصير في شَنْطَتي" , meaning = "There is no short book in my bag" } , { latin = "laysa hunaak daftar 2abyaD" , kana = "ライサ フゥナーク ダフタル アビヤド" , arabic = "لَيْسَ هُناك دَفْتَر أَبْيَض" , meaning = "There is no white notebook." } , { latin = "maTbakh" , kana = "マタバクフ" , arabic = "مَطْبَخ" , meaning = "a kitchen" } , { latin = "3ilka" , kana = "アイルカ" , arabic = "عِلْكة" , meaning = "chewing gum" } , { latin = "miftaaH" , kana = "ミフターフ" , arabic = "مفْتاح" , meaning = "a key" } , { latin = "tuub" , kana = "トゥーブ" , arabic = "توب" , meaning = "top" } , { latin = "nuquud" , kana = "ヌクード" , arabic = "نُقود" , meaning = "money, cash" } , { latin = "aljazeera" , kana = "アルジャズィーラ" , arabic = "الجزيرة" , meaning = "Al Jazeera" } , { latin = "kursii" , kana = "クルスィー" , arabic = "كَرْسي" , meaning = "a chair" } , { latin = "sari3" , kana = "サリア" , arabic = "سَريع" , meaning = "fast" } , { latin = "Haasuub" , kana = "ハースーブ" , arabic = "حاسوب" , meaning = "a computer" } , { latin = "maktab" , kana = "マクタブ" , arabic = "مَكْتَب" , meaning = "office, desk" } , { latin = "hadhaa maktab kabiir" , kana = "ハーザー マクタブ カビール" , arabic = "هَذا مَِكْتَب كَبير" , meaning = "This is a big office" } , { latin = "kursii alqiTTa" , kana = "クルスィー アルキッタ" , arabic = "كُرْسي الْقِطّة" , meaning = "the cat's chair" } , { latin = "Haasuub al-2ustaadha" , kana = "ハースーブ アル ウスターザ" , arabic = "حاسوب اَلْأُسْتاذة" , meaning = "professor's computer" } , { latin = "kursii jadiid" , kana = "クルスィー ジャディード" , arabic = "كُرْسي جَديد" , meaning = "a new chair" } , { latin = "SaHiifa" , kana = "サヒーファ" , arabic = "صَحيفة" , meaning = "newspaper" } , { latin = "haatif" , kana = "ハーティフ" , arabic = "هاتِف" , meaning = "phone" } , { latin = "2amriikiyy" , kana = "アムりーキーイ" , arabic = "أمْريكِي" , meaning = "American" } , { latin = "2amriikaa wa-a-S-Siin" , kana = "アムりーカー ワ アッスィーン" , arabic = "أَمْريكا وَالْصّين" , meaning = "America and China" } , { latin = "qahwa" , kana = "かハワ" , arabic = "قَهْوة" , meaning = "coffee" } , { latin = "Haliib" , kana = "ハリーブ" , arabic = "حَليب" , meaning = "milk" } , { latin = "muuza" , kana = "ムーザ" , arabic = "موزة" , meaning = "a banana" } , { latin = "2akl" , kana = "アクル" , arabic = "أَكْل" , meaning = "food" } , { latin = "2akl 3arabiyy wa-qahwa 3arabiyy" , kana = "アクル アラビーイ ワ かハワ アラビーイ" , arabic = "أَكْل عَرَبيّ وَقَهْوة عَرَبيّة" , meaning = "Arabic food and Arabic coffee" } , { latin = "ruzz" , kana = "ルッズ" , arabic = "رُزّ" , meaning = "rice" } , { latin = "ruzzii wa-qahwatii" , kana = "ルッズイー ワ かハワティー" , arabic = "رُزّي وَقَهْوَتي" , meaning = "my rice and my coffee" } , { latin = "qahwatii fii shanTatii" , kana = "かハワティー フィー シャンタティー" , arabic = "قَهْوَتي في شَنْطَتي" , meaning = "My coffee is in my bag" } , { latin = "qahwa PI:NAME:<NAME>END_PI" , kana = "かハワ スィース" , arabic = "قَهْوَة سيث" , meaning = "Seth's coffee" } , { latin = "Sadiiqat-haa" , kana = "すぁディーかトハー" , arabic = "صَديقَتها" , meaning = "her friend" } , { latin = "jaarat-haa" , kana = "ジャーラト ハー" , arabic = "جارَتها" , meaning = "her neighbor" } , { latin = "2ukhtii" , kana = "ウクフティ" , arabic = "أُخْتي" , meaning = "my sister" } , { latin = "Sadiiqa jayyida" , kana = "サディーカ ジャイイダ" , arabic = "صَديقة جَيِّدة" , meaning = "a good friend" }أ , { latin = "2a3rif" , arabic = "أَعْرِف" , meaning = "I know" } , { latin = "2anaa 2a3rifhu" , kana = "アナー アーリフフゥ" , arabic = "أَنا أَعْرِفه" , meaning = "I know him" } , { latin = "Taawila Tawiila" , kana = "ターウィラ タウィーラ" , arabic = "طاوِلة طَويلة" , meaning = "a long table" } , { latin = "baytik wa-bayt-haa" , kana = "バイティク ワ バイトハー" , arabic = "بَيْتِك وَبَيْتها" , meaning = "your house and her house" } , { latin = "ism Tawiil" , kana = "イスム タウィール" , arabic = "اِسْم طَويل" , meaning = "long name" } , { latin = "baytii wa-baythaa" , kana = "バイティー ワ バイトハー" , arabic = "بَيْتي وَبَيْتها" , meaning = "my house and her house" } , { latin = "laysa hunaak lugha Sa3ba" , kana = "ライサ フゥナーク ルガ サアバ" , arabic = "لَيْسَ هُناك لُغة صَعْبة" , meaning = "There is no diffcult language." } , { latin = "hadhaa shay2 Sa3b" , kana = "ハーザー シャイ サアバ" , arabic = "هَذا شَيْء صَعْب" , meaning = "This is a difficult thing." } , { latin = "ismhu taamir" , kana = "イスムフゥ ターミル" , arabic = "اِسْمهُ تامِر" , meaning = "His name is Tamer." } , { latin = "laa 2a3rif 2ayn bayt-hu" , kana = "ラー アーリフ アイン バイトフゥ" , arabic = "لا أَعْرِف أَيْن بَيْته" , meaning = "I don't know where his house is" } , { latin = "laa 2a3rif 2ayn 2anaa" , kana = "ラー アーリフ アイン アナー" , arabic = "لا أعرف أين أنا." , meaning = "I don't know where I am." } , { latin = "bayt-hu qariib min al-jaami3a" , kana = "バイトフゥ カリーブ ミン アル ジャーミア" , arabic = "بيته قريب من الجامعة" , meaning = "His house is close to the university" } , { latin = "ismhaa arabiyy" , kana = "イスムハー アラビーイ" , arabic = "إسمها عربي" , meaning = "Her name is arabic." } , { latin = "riim Sadiiqa Sa3ba" , kana = "リーム サディーカ サアバ" , arabic = "ريم صديقة صعبة" , meaning = "Reem is a difficult friend." } , { latin = "ismhu bashiir" , kana = "イスムフゥ バシール" , arabic = "إسمه بشير" , meaning = "HIs name is PI:NAME:<NAME>END_PI." } , { latin = "ismhaa Tawiil" , kana = "イスムハー タウィール" , arabic = "إسمها طويل" , meaning = "Her name is long." } , { latin = "Sadiiqhaa buub qariib min baythaa" , kana = "サディークハー ブーブ カリーブ ミン バイトハー" , arabic = "صديقها بوب قريب من بيتها" , meaning = "Her friend PI:NAME:<NAME>END_PI is close to her house." } , { latin = "ismhu buub" , kana = "イスムフゥ ブーブ" , arabic = "إسمه بوب" , meaning = "His name is PI:NAME:<NAME>END_PI." } , { latin = "baythu qariib min baythaa" , kana = "バイトフゥ カリーブ ミン バイトハー" , arabic = "بيته قريب من بيتها" , meaning = "His house is close to her house." } , { latin = "hadhaa shay2 Sa3b" , kana = "ハーザー シャイ サアブ" , arabic = "هذا شيء صعب" , meaning = "This is a difficult thing." } , { latin = "3alaaqa" , kana = "アラーカ" , arabic = "عَلاقَة" , meaning = "relationship" } , { latin = "al-qiTTa" , kana = "アルキッタ" , arabic = "اَلْقِطّة" , meaning = "the cat" } , { latin = "laa 2uhib" , kana = "ラー ウひッブ" , arabic = "لا أُحِب" , meaning = "I do not like" } , { latin = "al-2akl mumti3" , kana = "アルアクル ムムティア" , arabic = "اَلْأَكْل مُمْتع" , meaning = "Eating is fun." } , { latin = "al-qiraa2a" , kana = "アルキラーエ" , arabic = "اَلْقِراءة" , meaning = "reading" } , { latin = "alkitaaba" , kana = "アルキターバ" , arabic = "الْكِتابة" , meaning = "writing" } , { latin = "alkiraa2a wa-alkitaaba" , kana = "アルキラーエ ワ アルキターバ" , arabic = "اَلْقِراءة وَالْكِتابة" , meaning = "reading and writing" } , { latin = "muhimm" , kana = "ムヒンム" , arabic = "مُهِمّ" , meaning = "important" } , { latin = "alkiaaba shay2 muhimm" , kana = "アルキターバ シャイ ムヒンム" , arabic = "اَلْكِتابة شَيْء مُهِمّ" , meaning = "Writing is an important thing." } , { latin = "al-jaara wa-al-qiTTa" , kana = "アル ジャーラ ワ アル キッタ" , arabic = "اَلْجارة وَالْقِطّة" , meaning = "the neighbor and the cat" } , { latin = "qiTTa wa-alqiTTa" , kana = "キッタ ワ アルキッタ" , arabic = "قِطّة وَالْقِطّة" , meaning = "a cat and the cat" } , { latin = "2ayDan" , kana = "アイだン" , arabic = "أَيْضاً" , meaning = "also" } , { latin = "almaT3m" , kana = "アル マたあム" , arabic = "الْمَطْعْم" , meaning = "the restaurant" } , { latin = "maa2" , kana = "マー" , arabic = "ماء" , meaning = "water" } , { latin = "maT3am" , kana = "マタム" , arabic = "مَطْعَم" , meaning = "a restaurant" } , { latin = "a-t-taSwiir" , kana = "アッタスウィール" , arabic = "اَلْتَّصْوير" , meaning = "photography" } , { latin = "a-n-nawm" , kana = "アンナウム" , arabic = "اَلْنَّوْم" , meaning = "sleeping, sleep" } , { latin = "a-s-sibaaha" , kana = "アッスィバーハ" , arabic = "اَلْسِّباحة" , meaning = "swimming" } , { latin = "Sabaahan 2uhibb al-2akl hunaa" , kana = "サバーハン ウひッブ アルアクル フゥナー" , arabic = "صَباحاً أُحِبّ اَلْأَكْل هُنا" , meaning = "In the morning, I like eating here." } , { latin = "kathiiraan" , kana = "カシーラン" , arabic = "كَثيراً" , meaning = "much" } , { latin = "hunaa" , kana = "フゥナー" , arabic = "هُنا" , meaning = "here" } , { latin = "jiddan" , kana = "ジッダン" , arabic = "جِدَّاً" , meaning = "very" } , { latin = "3an" , kana = "アン" , arabic = "عَن" , meaning = "about" } , { latin = "2uhibb a-s-safar 2ilaa 2iiTaaliyaa" , kana = "ウひッブ アッサファル いらー イーターリヤー" , arabic = "أُحِبّ اَلْسَّفَر إِلى إيطالْيا" , meaning = "I like traveling to Italy." } , { latin = "al-kalaam ma3a 2abii" , kana = "アルカラーム マア アビー" , arabic = "اَلْكَلام مَعَ أَبي" , meaning = "talking with my father" } , { latin = "2uHibb aljarii bi-l-layl" , kana = "ウひッブ アルジャリー ビッライル" , arabic = "أُحِبّ اَلْجَري بِالْلَّيْل" , meaning = "I like running at night." } , { latin = "2uriidu" , kana = "ウりード" , arabic = "أُريدُ" , meaning = "I want" } , { latin = "2uHibb 2iiTaaliyaa 2ayDan" , kana = "ウひッブ イーターリヤー アイダン" , arabic = "أُحِبّ إيطاليا أَيْضاً" , meaning = "I like Italy also." } , { latin = "2uHibb alqiraa2a 3an kuubaa bi-l-layl" , kana = "ウひッブ アルキラーア アン クーバー ビッライル" , arabic = "أُحِبّ اَلْقِراءة عَن كوبا بِالْلَّيْل" , meaning = "I like reading about Cuba at night." } , { latin = "2uHibb al-kalaam 3an il-kitaaba" , kana = "ウひッブ アル カラーム アニル キターバ" , arabic = "أحِبّ اَلْكَلام عَن اَلْكِتابة" , meaning = "I like talking about writing." } , { latin = "alqur2aan" , kana = "アルクルアーン" , arabic = "اَلْقُرْآن" , meaning = "Koran" } , { latin = "bayt jamiil" , kana = "バイト ジャミール" , arabic = "بَيْت جَميل" , meaning = "a pretty house" } , { latin = "mutarjim mumtaaz" , kana = "ムタるジム ムムターズ" , arabic = "مُتَرْجِم مُمْتاز" , meaning = "an amazing translator" } , { latin = "jaami3a mash-huura" , kana = "ジャーミア マシュフーラ" , arabic = "جامِعة مَشْهورة" , meaning = "a famous university" } , { latin = "al-bayt al-jamiil" , kana = "アルバイト アルジャミール" , arabic = "اَلْبَيْت اَلْجَميل" , meaning = "the pretty house" } , { latin = "al-bint a-s-suuriyya" , kana = "アル ビンタ ッスーリヤ" , arabic = "اَلْبِنْت اَلْسّورِيّة" , meaning = "a Syrian girl" } , { latin = "al-mutarjim al-mumtaaz" , kana = "アルムタルジム アルムムターズ" , arabic = "اَلْمُتَرْجِم اَلْمُمْتاز" , meaning = "the amazing translator" } , { latin = "al-jaami3a al-mash-huura" , kana = "アルジャーミア アルマシュフーラ" , arabic = "اَلْجامِعة اَلْمَشْهورة" , meaning = "the famous university" } , { latin = "al-bayt jamiil" , kana = "アルバイト ジャミール" , arabic = "اَلْبَيْت جَميل" , meaning = "The house is pretty." } , { latin = "al-bint suuriyya" , kana = "アルビント スーリーヤ" , arabic = "البنت سورِيّة" , meaning = "The girl is Syrian." } , { latin = "al-mutarjim mumtaaz" , kana = "アルムタルジム ムムターズ" , arabic = "اَلْمُتَرْجِم مُمْتاز" , meaning = "The translator is amazing." } , { latin = "al-jaami3a mash-huura" , kana = "アルジャーミア マシュフーラ" , arabic = "اَلْجامِعة مَشْهورة" , meaning = "The university is famous." } , { latin = "maTar" , kana = "マタル" , arabic = "مَطَر" , meaning = "rain" } , { latin = "yawm Tawiil" , kana = "ヤウム タウィール" , arabic = "يَوْم طَويل" , meaning = "a long day" } , { latin = "haadhaa yawm Tawiil" , kana = "ハーザー ヤウム タウィール" , arabic = "هَذا يَوْم طَويل" , meaning = "This is a long day." } , { latin = "shanTa fafiifa" , kana = "シャンタ ファフィーファ" , arabic = "شَنْطة خَفيفة" , meaning = "a light bag" } , { latin = "al-maTar a-th-thaqiil mumtaaz" , kana = "アルマタル アッサキール ムムターズ" , arabic = "اَلْمَطَر اَلْثَّقيل مُمْتاز" , meaning = "The heavy rain is amazing." } , { latin = "Taqs ghariib" , kana = "タクス ガリーブ" , arabic = "طَقْس غَريب" , meaning = "a weird weather" } , { latin = "yawm Haarr" , kana = "ヤウム ハール" , arabic = "يَوْم حارّ" , meaning = "a hot day" } , { latin = "Taawila khafiifa" , kana = "ターウィラ クハフィーファ" , arabic = "طاوِلة خَفيفة" , meaning = "a light table" } , { latin = "Taqs jamiil" , kana = "タクス ジャミール" , arabic = "طَقْس جَميل" , meaning = "a pretty weather" } , { latin = "al-maTar a-th-thaqiil mumtaaz" , kana = "アルマタル アッサキール ムムターズ" , arabic = "اَلْمَطَر اَلْثَّقيل مُمْتاز" , meaning = "The heavy rain is amazing." } , { latin = "haadhaa yawm Haarr" , kana = "ハーザー ヤウム ハール" , arabic = "هَذا يَوْم حارّ" , meaning = "This is a hot day." } , { latin = "shanTa khafiifa" , kana = "シャンタ クハフィーファ" , arabic = "شَنْطة خَفيفة" , meaning = "a light bag" } , { latin = "hunaak maTar baarid jiddan" , kana = "フゥナーク マタル バーリド ジッダン" , arabic = "هُناك مَطَر بارِد جِدّاً" , meaning = "There is a very cold rain." } , { latin = "Sayf" , kana = "サイフ" , arabic = "صّيْف" , meaning = "summer" } , { latin = "shitaa2" , kana = "シター" , arabic = "شِتاء" , meaning = "winter" } , { latin = "shitaa2 baarid" , kana = "シター バーリド" , arabic = "شِتاء بارِد" , meaning = "cold winter" } , { latin = "binaaya 3aalya" , kana = "ビナーヤ アーリヤ" , arabic = "بِناية عالْية" , meaning = "a high building" } , { latin = "yawm baarid" , kana = "ヤウム バーリド" , arabic = "يَوْم بارِد" , meaning = "a cold day" } , { latin = "ruTuuba 3aalya" , kana = "ルトゥーバ アーリヤ" , arabic = "رُطوبة عالْية" , meaning = "high humidity" } , { latin = "Sayf mumTir" , kana = "サイフ ムムティル" , arabic = "صَيْف مُمْطِر" , meaning = "a rainy summer" } , { latin = "a-r-ruTuubat al3aalya" , kana = "アッルルトゥーバト アラーリヤ" , arabic = "اَلْرُّطوبة الْعالْية" , meaning = "the high humidity" } , { latin = "a-T-Taqs al-mushmis" , kana = "アッタクス アルムシュミス" , arabic = "اّلْطَّقْس الّْمُشْمِس" , meaning = "the sunny weather" } , { latin = "shitaa2 mumTir" , kana = "シター ムムティル" , arabic = "شِتاء مُمْطِر" , meaning = "a rainy winter" } , { latin = "Sayf Haarr" , kana = "サイフ ハール" , arabic = "صَيْف حارّ" , meaning = "a hot summer" } , { latin = "al-yawm yawm Tawiil" , kana = "アルヤウム ヤウム タウィール" , arabic = "اَلْيَوْم يَوْم طَويل" , meaning = "Today is a long day." } , { latin = "laa 2uhibb a-T-Taqs al-mushmis" , kana = "ラー ウひッブ アッタクス アルムシュミス" , arabic = "لا أُحِبّ اَلْطَقْس اَلْمُشْمِس" , meaning = "I do not like sunny weather." } , { latin = "a-T-Taqs mumTir jiddan al-yawm" , kana = "アッタクス ムムティル ジッダン アルヤウム" , arabic = "اَلْطَقْس مُمْطِر جِدّاً اَلْيَوْم" , meaning = "The weather is very rainy today." } , { latin = "laa 2uhibb a-T-Taqs al-mumTir" , kana = "ラー ウひッブ アッタクス アルムティル" , arabic = "لا أحِبّ اَلْطَّقْس اَلْمُمْطِر" , meaning = "I do not like the rainy weather." } , { latin = "a-T-Taqs mushmis al-yawm" , kana = "アッタクス ムシュミス アルヤウム" , arabic = "اَلْطَّقْس مُشْمِس اَلْيَوْم" , meaning = "The weather is sunny today." } , { latin = "khariif" , kana = "ハリーフ" , arabic = "خَريف" , meaning = "fall, autumn" } , { latin = "qamar" , kana = "カマル" , arabic = "قَمَر" , meaning = "moon" } , { latin = "rabii3" , kana = "ラビーア" , arabic = "رَبيع" , meaning = "spring" } , { latin = "a-sh-shitaa2 mumTir" , kana = "アッシター ムムティル" , arabic = "اَلْشِّتاء مُمْطِر" , meaning = "The winter is rainy." } , { latin = "a-S-Sayf al-baarid" , kana = "アッサイフ アルバーリド" , arabic = "اَلْصَّيْف اَلْبارِد" , meaning = "the cold summer" } , { latin = "al-qamar al-2abyaD" , kana = "アルカマル アルアビヤド" , arabic = "اَلْقَمَر اَلْأَبْيَض" , meaning = "the white moon" } , { latin = "a-sh-shitaa2 Tawiil wa-baarid" , kana = "アッシター タウィール ワ バーリド" , arabic = "اَلْشِّتاء طَويل وَبارِد" , meaning = "The winter is long and cold." } , { latin = "a-r-rabii3 mumTir al-2aan" , kana = "アッラビーア ムムティル アルアーン" , arabic = "اَلْرَّبيع مُمْطِر اَلآن" , meaning = "The spring is rainy now" } , { latin = "Saghiir" , kana = "サギール" , arabic = "صَغير" , meaning = "small" } , { latin = "kashiiran" , kana = "カシーラン" , arabic = "كَثيراً" , meaning = "a lot, much" } , { latin = "a-S-Siin" , kana = "アッスィーン" , arabic = "اَلْصّين" , meaning = "China" } , { latin = "al-qaahira" , kana = "アル カーヒラ" , arabic = "اَلْقاهِرة" , meaning = "Cairo" } , { latin = "al-bunduqiyya" , kana = "アル ブンドゥキーヤ" , arabic = "اَلْبُنْدُقِية" , meaning = "Venice" } , { latin = "filasTiin" , kana = "フィラスティーン" , arabic = "فِلَسْطين" , meaning = "Palestine" } , { latin = "huulandaa" , kana = "フーランダー" , arabic = "هولَنْدا" , meaning = "Netherlands, Holland" } , { latin = "baghdaad" , kana = "バグダード" , arabic = "بَغْداد" , meaning = "Bagdad" } , { latin = "Tuukyuu" , kana = "トーキョー" , arabic = "طوكْيو" , meaning = "Tokyo" } , { latin = "al-yaman" , kana = "アル ヤマン" , arabic = "اَلْيَمَن" , meaning = "Yemen" } , { latin = "SaaHil Tawiil" , kana = "サーヒル タウィール" , arabic = "ساحَل طَويل" , meaning = "a long coast" } , { latin = "al-2urdun" , kana = "アル ウルドゥン" , arabic = "اَلْأُرْدُن" , meaning = "Jordan" } , { latin = "haadha l-balad" , kana = "ハーザ ル バラド" , arabic = "هَذا الْبَلَد" , meaning = "this country" } , { latin = "2ayn baladik yaa riim" , kana = "アイン バラディク ヤー リーム" , arabic = "أَيْن بَلَدِك يا ريم" , meaning = "Where is your country, Reem?" } , { latin = "baladii mumtaaz" , kana = "バラディー ムムターズ" , arabic = "بَلَدي مُمْتاز" , meaning = "My country is amazing." } , { latin = "haadhaa balad-haa" , kana = "ハーザー バラドハー" , arabic = "هَذا بَلَدها" , meaning = "This is her country." } , { latin = "hal baladak jamiil yaa juurj?" , kana = "ハル バラダク ジャミール ヤー ジュールジュ" , arabic = "هَل بَلَدَك جَميل يا جورْج" , meaning = "Is your country pretty, George" } , { latin = "al-yaman balad Saghiir" , kana = "アルヤマン バラド サギール" , arabic = "اَلْيَمَن بَلَد صَغير" , meaning = "Yemen is a small country." } , { latin = "qaari2" , kana = "カーリー" , arabic = "قارِئ" , meaning = "reader" } , { latin = "ghaa2ib" , kana = "ガーイブ" , arabic = "غائِب" , meaning = "absent" } , { latin = "mas2uul" , kana = "マスウール" , arabic = "مَسْؤول" , meaning = "responsoble, administrator" } , { latin = "jaa2at" , kana = "ジャーアト" , arabic = "جاءَت" , meaning = "she came" } , { latin = "3indii" , kana = "アインディー" , arabic = "عِنْدي" , meaning = "I have" } , { latin = "3indik" , kana = "アインディク" , arabic = "عِنْدِك" , meaning = "you have" } , { latin = "ladii kitaab" , kana = "ラディー キターブ" , arabic = "لَدي كِتاب" , meaning = "I have a book." } , { latin = "3indhaa" , kana = "アインドハー" , arabic = "عِنْدها" , meaning = "she has" } , { latin = "3indhu" , kana = "アインドフゥ" , arabic = "عِنْدهُ" , meaning = "he has" } , { latin = "laysa 3indhu" , kana = "ライサ アインドフゥ" , arabic = "لَيْسَ عِنْدهُ" , meaning = "he does not have" } , { latin = "laysa 3indhaa" , kana = "ライサ アインドハー" , arabic = "لَيْسَ عِنْدها" , meaning = "she does not have" } , { latin = "hunaak maTar thaqiil" , kana = "フゥナーク マタル サキール" , arabic = "هُناك مَطَر ثَقيل" , meaning = "There is a heavy rain." } , { latin = "hunaak wishaaH fii shanTatii" , kana = "フゥナーク ウィシャーハ フィー シャンタティー" , arabic = "هُناك وِشاح في شَنْطتي" , meaning = "There is a scarf in my bag." } , { latin = "2amaamii rajul ghariib" , kana = "アマーマミー ラジュル ガリーブ" , arabic = "أَمامي رَجُل غَريب" , meaning = "There is a weird man in front of me." } , { latin = "fi l-khalfiyya bayt" , kana = "フィル クハルフィーヤ バイト" , arabic = "في الْخَلفِيْة بَيْت" , meaning = "There is a house in the background." } , { latin = "fii shanTatii wishaaH" , kana = "フィー シャンタティー ウィシャーハ" , arabic = "في شَنْطَتي وِشاح" , meaning = "There is a scarf in my bag." } , { latin = "2asad" , kana = "アサド" , arabic = "أَسَد" , meaning = "a lion" } , { latin = "2uHibb 2asadii laakinn laa 2uHibb 2asadhaa" , kana = "ウひッブ アサディ ラキン ラー ウひッブ アサドハー" , arabic = "أحِبَ أَسَدي لَكِنّ لا أُحِبّ أَسَدها" , meaning = "I like my lion but I do not like her lion." } , { latin = "laysa 3indhu" , kana = "ライサ アインドフゥ" , arabic = "لَيْسَ عِنْدهُ" , meaning = "he does not have" } , { latin = "3indhaa kalb wa-qiTTa" , kana = "アインドハー カルブ ワ キッタ" , arabic = "عِنْدها كَلْب وَقِطّة" , meaning = "She has a doc and a cat." } , { latin = "Sadiiqat-hu saamia ghaniyya" , kana = "すぁディーかトフゥ サーミヤ ガニーヤ" , arabic = "صَديقَتهُ سامْية غَنِيّة" , meaning = "His friend Samia is rich." } , { latin = "taariikhiyya" , kana = "ターリークヒーヤ" , arabic = "تاريخِيّة" , meaning = "historical" } , { latin = "juurj 3indhu 3amal mumtaaz" , kana = "ジュールジュ アインドフゥ アアマル ムムターズ" , arabic = "جورْج عِنْدهُ عَمَل مُمْتاز" , meaning = "George has an amazing work." } , { latin = "Sadiiqii taamir ghaniyy jiddan" , kana = "サディーキー ターミル ガニーイ ジッダン" , arabic = "صَديقي تامِر غَنِيّ جِدّاً" , meaning = "My friend PI:NAME:<NAME>END_PI is very rich" } , { latin = "laa 2a3rif haadha l-2asad" , kana = "ラー アーリフ ハーザ ル アサド" , arabic = "لا أَعْرِف هَذا الْأَسّد" , meaning = "I do not know this lion." } , { latin = "laysa 3indhu ma3Taf" , kana = "ライサ アインドフゥ マアタフ" , arabic = "لَيْسَ عِنْدهُ معْطَف" , meaning = "He does not have a coat." } , { latin = "fi l-khalfiyya zawjatak yaa siith" , kana = "フィ ル クハルフィーヤ ザウジャタク ヤー スィース" , arabic = "في الْخَلْفِيّة زَوْجَتَك يا سيث" , meaning = "There is your wife in background, Seth" } , { latin = "su2uaal" , kana = "スウアール" , arabic = "سُؤال" , meaning = "a question" } , { latin = "Sadiiqat-hu saamya laabisa tannuura" , kana = "すぁディーかトフゥ サーミヤ ラービサ タンヌーラ" , arabic = "صدَيقَتهُ سامْية لابِسة تّنّورة" , meaning = "His friend PI:NAME:<NAME>END_PI is wearing a skirt." } , { latin = "wa-hunaa fi l-khalfiyya rajul muD-Hik" , kana = "ワ フゥナー フィル クハルフィーヤ ラジュル ムドヒク" , arabic = "وَهُنا في الْخَلْفِتّة رَجُل مُضْحِك" , meaning = "And here in the background there is a funny man." } , { latin = "man haadhaa" , kana = "マン ハーザー" , arabic = "مَن هَذا" , meaning = "Who is this?" } , { latin = "hal 2anti labisa wishaaH yaa lamaa" , kana = "ハル アンティ ラビサ ウィシャーハ ヤー ラマー" , arabic = "هَل أَنْتِ لابِسة وِشاح يا لَمى" , meaning = "Are you wering a scarf, Lama?" } , { latin = "2akhii bashiir mashghuul" , kana = "アクヒー バシール マシュグール" , arabic = "أَخي بَشير مَشْغول" , meaning = "My brother PI:NAME:<NAME>END_PI is busy." } , { latin = "fii haadhihi a-S-Suura imraa muD-Hika" , kana = "フィー ハージヒ アッスーラ イムラア ムドヒカ" , arabic = "في هَذِهِ الْصّورة اِمْرأة مُضْحِكة" , meaning = "Thre is a funny woman in this picture." } , { latin = "hal 2anta laabis qubb3a yaa siith" , kana = "ハル アンタ ラービス クッバ ヤー スィース" , arabic = "هَل أَنْتَ لابِس قُبَّعة يا سيث" , meaning = "Are you wearing a hat, Seth?" } , { latin = "fi l-khalfiyya rajul muD-Hik" , kana = "フィル クハルフィーヤ ラジュル ムドヒク" , arabic = "في الْخَلْفِيّة رَجُل مُضْحِك" , meaning = "There is a funny man in the background." } , { latin = "shub-baak" , kana = "シュッバーク" , arabic = "شُبّاك" , meaning = "a window" } , { latin = "sariir" , kana = "サリール" , arabic = "سَرير" , meaning = "a bed" } , { latin = "saadii 2ustaadhii" , kana = "サーディー ウスタージー" , arabic = "شادي أُسْتاذي" , meaning = "Sadie is my teacher." } , { latin = "2ummhu" , kana = "ウンムフゥ" , arabic = "أُمّهُ" , meaning = "his mother" } , { latin = "maa haadhaa a-S-Sawt" , kana = "マー ハーザー アッサウト" , arabic = "ما هَذا الْصَّوْت" , meaning = "What is this noise" } , { latin = "2adkhul al-Hammaam" , kana = "アドクフル アルハンマーム" , arabic = "أَدْخُل اَلْحَمّام" , meaning = "I enter the bathroom." } , { latin = "2uHibb a-s-sariir al-kabiir" , kana = "ウひッブ アッサリール アルカビール" , arabic = "أُحِبّ اَلْسَّرير اَلْكَبير" , meaning = "I love the big bed." } , { latin = "hunaak Sawt ghariib fi l-maTbakh" , kana = "フゥナーク サウト ガリーブ フィル マトバクフ" , arabic = "هُناك صَوْت غَريب في الْمَطْبَخ" , meaning = "There is a weird nose in the kitchen." } , { latin = "2anaam fi l-ghurfa" , kana = "アナーム フィル グルファ" , arabic = "أَنام في الْغُرْفة" , meaning = "I sleep in the room." } , { latin = "tilfaaz Saghiir fii Saaluun kabiir" , kana = "ティルファーズ サギール フィー サールーン カビール" , arabic = "تِلْفاز صَغير في صالون كَبير" , meaning = "a small television in a big living room" } , { latin = "2anaam fii sariir maksuur" , kana = "アナーム フィー サリール マクスール" , arabic = "أَنام في سَرير مَكْسور" , meaning = "I sleep in a broken bed." } , { latin = "a-s-sariir al-kabiir" , kana = "アッサリール アルカビール" , arabic = "اَلْسَّرير اَلْكَبير" , meaning = "the big bed" } , { latin = "maa haadhaa a-S-Swut" , kana = "マー ハーザー アッスウト" , arabic = "ما هَذا الصّوُت" , meaning = "What is this noise?" } , { latin = "sariirii mumtaaz al-Hamdu li-l-laa" , kana = "サリーリー ムムターズ アルハムド リッラー" , arabic = "سَريري مُمتاز اَلْحَمْدُ لِله" , meaning = "My bed is amazing, praise be to God" } , { latin = "2anaam kathiiran" , kana = "アナーム カシーラン" , arabic = "أَنام كَشيراً" , meaning = "I sleep a lot" } , { latin = "hunaak Sawt ghariib" , kana = "フゥナーク サウト ガリーブ" , arabic = "هُناك صَوْت غَريب" , meaning = "There is a weird noise." } , { latin = "shub-baak" , kana = "シュッバーク" , arabic = "شُبّاك" , meaning = "a window" } , { latin = "2anaam fii sariir Saghiir" , kana = "アナーム フィー サリール サギール" , arabic = "أَنام في سَرير صَغير" , meaning = "I sleep in a small bed." } , { latin = "muHammad 2ustaadhii" , kana = "ムハンマド ウスタージー" , arabic = "مُحَمَّد أُسْتاذي" , meaning = "Mohammed is my teacher." } , { latin = "mahaa 2ummhu" , kana = "マハー ウンムフゥ" , arabic = "مَها أُمّهُ" , meaning = "Maha is his mother." } , { latin = "fii haadhaa sh-shaari3 Sawt ghariib" , kana = "フィー ハーザー ッシャーリア サウト ガリーブ" , arabic = "في هٰذا ٱلْشّارِع صَوْت غَريب" , meaning = "There is a weird noise on this street" } , { latin = "2askun fii a-s-saaluun" , kana = "アスクン フィー アッサルーン" , arabic = "أَسْكُن في الْصّالون" , meaning = "I live in the living room." } , { latin = "haadhaa sh-shaari3" , kana = "ハーザー ッシャーリア" , arabic = "هَذا الْشّارِع" , meaning = "this street" } , { latin = "3ind-hu ghurfa nawm Saghiira" , kana = "アインドフゥ グルファ ナウム サギーラ" , arabic = "عِندهُ غُرْفة نَوْم صَغيرة" , meaning = "He has a small bedroom." } , { latin = "laa 2aftaH albaab bisabab l-T-Taqs" , kana = "ラー アフタフ アルバーブ ビサバブ ルッタクス" , arabic = "لا أَفْتَح اَلْباب بِسَبَب اّلْطَّقْس" , meaning = "I do not open the door because of the weather." } , { latin = "Sifr" , kana = "スィフル" , arabic = "صِفْر" , meaning = "zero" } , { latin = "3ashara" , kana = "アシャラ" , arabic = "عَشَرَة" , meaning = "ten" } , { latin = "waaHid" , kana = "ワーヒド" , arabic = "وَاحِد" , meaning = "one" } , { latin = "2ithnaan" , kana = "イスナーン" , arabic = "اِثْنان" , meaning = "two" } , { latin = "kayf ta3uddiin min waaHid 2ilaa sitta" , kana = "カイフ タアウッディーン ミン ワーヒド イラー スィッタ" , arabic = "كَيْف تَعُدّين مِن ١ إِلى ٦" , meaning = "How do you count from one to six?" } , { latin = "bil-lugha" , kana = "ビッルガ" , arabic = "بِالْلُّغة" , meaning = "in language" } , { latin = "bil-lugha l-3arabiya" , kana = "ビッルガルアラビーヤ" , arabic = "بِالْلُّغة الْعَرَبِيّة" , meaning = "in the arabic language" } , { latin = "ta3rifiin" , kana = "ターリフィーン" , arabic = "تَعْرِفين" , meaning = "you know" } , { latin = "hal ta3rifiin kull shay2 yaa mahaa" , kana = "ハル ターリフィーン クル シャイ ヤー マハー" , arabic = "هَل تَعْرِفين كُلّ شَيء يا مَها" , meaning = "Do you know everything Maha?" } , { latin = "kayf ta3udd yaa 3umar" , kana = "カイフ タアウッド ヤ ウマル" , arabic = "كَيْف تَعُدّ يا عُمَر" , meaning = "How do you count Omar?" } , { latin = "Kayf ta3udd min Sifr 2ilaa 2ashara yaa muHammad" , kana = "カイフ タアウッド ミン スィフル イラー アシャラ ヤー ムハンマド" , arabic = "كَيْف تَعُدّ مِن٠ إِلى ١٠ يا مُحَمَّد" , meaning = "How do you count from 0 to 10 , Mohammed?" } , { latin = "hal ta3rif yaa siith" , kana = "ハル ターリフ ヤー スィース" , arabic = "هَل تَعْرِف يا سيث" , meaning = "Do you know Seth?" } , { latin = "bayt buub" , kana = "バイト ブーブ" , arabic = "بَيْت بوب" , meaning = "Bob's house" } , { latin = "maT3am muHammad" , kana = "マタム ムハンマド" , arabic = "مَطْعَم مُحَمَّد" , meaning = "Mohammed's restaurant" } , { latin = "SaHiifat al-muhandis" , kana = "サヒーファト アル ムハンディス" , arabic = "صَحيفة اَلْمُهَنْدِس" , meaning = "the enginner's newspaper" } , { latin = "madiinat diitruuyt" , kana = "マディーナト ディートルーイト" , arabic = "مَدينة ديتْرويْت" , meaning = "the city of Detroit" } , { latin = "jaami3a juurj waashinTun" , kana = "ジャーミア ジュールジュ ワーシントン" , arabic = "جامِعة جورْج واشِنْطُن" , meaning = "George Washinton University" } , { latin = "SabaaHan" , kana = "サバーハン" , arabic = "صَباحاً" , meaning = "in the morning" } , { latin = "masaa2an" , kana = "マサーアン" , arabic = "مَساءً" , meaning = "in the evening" } , { latin = "wilaayatak" , kana = "ウィラーヤタク" , arabic = "وِلايَتَك" , meaning = "your state" } , { latin = "madiina saaHiliyya" , kana = "マディーナ サーヒリーヤ" , arabic = "مَدينة ساحِلِيّة" , meaning = "a coastal city" } , { latin = "muzdaHima" , kana = "ムズダヒマ" , arabic = "مُزْدَحِمة" , meaning = "crowded" } , { latin = "wilaaya kaaliifuurniyaa" , kana = "ウィラーヤ カーリーフールニヤー" , arabic = "وِلاية كاليفورْنْيا" , meaning = "the state of California" } , { latin = "baHr" , kana = "バハル" , arabic = "بَحْر" , meaning = "sea" } , { latin = "DawaaHii" , kana = "ダワーヒー" , arabic = "ضَواحي" , meaning = "suburbs" } , { latin = "taskuniin" , kana = "タスクニーン" , arabic = "تَسْكُنين" , meaning = "you live" } , { latin = "nyuuyuurk" , kana = "ニューユールク" , arabic = "نْيويورْك" , meaning = "New York" } , { latin = "qar-yatik" , kana = "かるヤティク" , arabic = "قَرْيَتِك" , meaning = "your (to female) village" } , { latin = "shubbaak" , kana = "シュッバーク" , arabic = "شُبّاك" , meaning = "a window" } , { latin = "jaziira" , kana = "ジャズィーラ" , arabic = "جَزيرة" , meaning = "an island" } , { latin = "Tabii3a" , kana = "タビーア" , arabic = "طَبيعة" , meaning = "nature" } , { latin = "al-2iskandariyya" , kana = "アル イスカンダリーヤ" , arabic = "اَلْإِسْكَندَرِيّة" , meaning = "Alexandria" } , { latin = "miSr" , kana = "ミスル" , arabic = "مِصْر" , meaning = "Egypt" } , { latin = "na3am" , kana = "ナアム" , arabic = "نَعَم" , meaning = "yes" } , { latin = "SabaaH l-khayr" , kana = "サバーフ ル クハイル" , arabic = "صَباح اَلْخَيْر" , meaning = "Good morning." } , { latin = "SabaaH an-nuur" , kana = "サバーフ アン ヌール" , arabic = "صَباح اَلْنّور" , meaning = "Good morning." } , { latin = "masaa2 al-khayr" , kana = "マサー アル クハイル" , arabic = "مَساء اَلْخَيْر" , meaning = "Good evening" } , { latin = "masaa2 an-nuur" , kana = "マサー アンヌール" , arabic = "مَساء اَلْنّور" , meaning = "Good evening." } , { latin = "tasharrafnaa" , kana = "タシャッラフゥナー" , arabic = "تَشَرَّفْنا" , meaning = "It's a pleasure to meet you." } , { latin = "hal 2anta bi-khyr" , kana = "ハル アンタ ビ クハイル" , arabic = "هَل أَنْتَ بِخَيْر" , meaning = "Are you well?" } , { latin = "kayfak" , kana = "カイファク" , arabic = "كَيْفَك" , meaning = "How are you?" } , { latin = "al-yawm" , kana = "アル ヤウム" , arabic = "اَلْيَوْم" , meaning = "today" } , { latin = "kayfik al-yawm" , kana = "カイフィク アル ヤウム" , arabic = "كَيْفِك اَلْيَوْم" , meaning = "How are you today?" } , { latin = "marHaban ismii buub" , kana = "マルハバン イスミー ブーブ" , arabic = "مَرْحَباً اِسْمي بوب" , meaning = "Hello, my name is PI:NAME:<NAME>END_PI." } , { latin = "mariiD" , kana = "マリード" , arabic = "مَريض" , meaning = "sick" } , { latin = "yawm sa3iid" , kana = "ヤウム サアイード" , arabic = "يَوْم سَعيد" , meaning = "Have a nice day." } , { latin = "sa3iid" , kana = "サアイード" , arabic = "سَعيد" , meaning = "happy" } , { latin = "2anaa Haziinat l-yawm" , kana = "アナー ハズィーナト ル ヤウム" , arabic = "أَنا حَزينة الْيَوْم" , meaning = "I am sad today." } , { latin = "2anaa Haziin jiddan" , kana = "アナー ハズィーン ジッダン" , arabic = "أَنا حَزين جِدّاً" , meaning = "I am very sad." } , { latin = "2anaa mariiDa lil2asaf" , kana = "アナー マリーダ リルアサフ" , arabic = "أَنا مَريضة لِلْأَسَف" , meaning = "I am sick unfortunately." } , { latin = "2ilaa l-liqaa2 yaa Sadiiqii" , kana = "イラー ッリカー ヤー サディーキイ" , arabic = "إِلى الْلِّقاء يا صَديقي" , meaning = "Until next time, my friend." } , { latin = "na3saana" , kana = "ナアサーナ" , arabic = "نَعْسانة" , meaning = "sleepy" } , { latin = "mutaHammis" , kana = "ムタハムミス" , arabic = "مُتَحَمِّس" , meaning = "excited" } , { latin = "maa smak" , kana = "マー スマク" , arabic = "ما إسْمَك" , meaning = "What is your name?" } , { latin = "2anaa na3saan" , kana = "アナー ナアサーン" , arabic = "أَنا نَعْسان" , meaning = "I am sleepy." } , { latin = "yal-laa 2ilaa l-liqaa2" , kana = "ヤッラー イラー ッリカー" , arabic = "يَلّإِ إِلى الْلَّقاء" , meaning = "Alright, until next time." } , { latin = "ma3a as-salaama" , kana = "マア アッサラーマ" , arabic = "مَعَ الْسَّلامة" , meaning = "Goodbye." } , { latin = "tamaam" , kana = "タマーム" , arabic = "تَمام" , meaning = "OK" } , { latin = "2anaatamaam al-Hamdu li-l-laa" , kana = "アナ タマーム アル ハムドゥ リッラー" , arabic = "أَنا تَمام اَلْحَمْدُ لِله" , meaning = "I am OK , praise be to God." } , { latin = "maa al2akhbaar" , arabic = "ما الْأَخْبار" , meaning = "What is new?" } , { latin = "al-bathu alhii" , kana = "アル バス アルヒー" , arabic = "اَلْبَثُ اَلْحي" , meaning = "live broadcast" } , { latin = "2ikhtar" , kana = "イクフタル" , arabic = "إِخْتَر" , meaning = "choose" } , { latin = "sayyaara" , kana = "サイヤーラ" , arabic = "سَيّارة" , meaning = "a car" } , { latin = "2akh ghariib" , kana = "アクフ ガリーブ" , arabic = "أَخ غَريب" , meaning = "a weird brother" } , { latin = "2ukht muhimma" , kana = "ウクフト ムヒムマ" , arabic = "أُخْت مُهِمّة" , meaning = "an important sister" } , { latin = "ibn kariim wa-mumtaaz" , kana = "イブン カリーム ワ ムムターズ" , arabic = "اِبْن كَريم وَمُمْتاز" , meaning = "a generous and amazing son" } , { latin = "2ab" , kana = "アブ" , arabic = "أَب" , meaning = "a father" } , { latin = "2umm" , kana = "ウンム" , arabic = "أُمّ" , meaning = "a mother" } , { latin = "ibn" , kana = "イブン" , arabic = "اِبْن" , meaning = "a son" } , { latin = "mumti3" , kana = "ムムティア" , arabic = "مُمْتِع" , meaning = "fun" } , { latin = "muHaasib" , kana = "ムハースィブ" , arabic = "مُحاسِب" , meaning = "an accountant" } , { latin = "ma-smika ya 2ustaadha" , kana = "マスミカ ヤー ウスターザ" , arabic = "ما اسْمِك يا أُسْتاذة" , meaning = "What is your name ma'PI:NAME:<NAME>END_PI?" } , { latin = "qiTTatak malika" , kana = "キッタタク マリカ" , arabic = "قِطَّتَك مَلِكة" , meaning = "Your cat is a queen." } , { latin = "jadda laTiifa wa-jadd laTiif" , kana = "ジャッダ ラティーファ ワ ジャッド ラティーフ" , arabic = "جَدّة لَطيفة وَجَدّ لَطيف" , meaning = "a kind grandmother and a kind grandfather" } , { latin = "qiTTa jadiida" , kana = "キッタ ジャディーダ" , arabic = "قِطّة جَديدة" , meaning = "a new cat" } , { latin = "hal jaddatak 2ustaadha" , kana = "ハル ジャーダタック ウスターザ" , arabic = "هَل جَدَّتَك أُسْتاذة" , meaning = "Is your grandmother a professor?" } , { latin = "hal zawjatak 2urduniyya" , arabic = "هَل زَوْجَتَك أُرْدُنِتّة" , meaning = "Is your wife a Jordanian?" } , { latin = "mu3allim" , kana = "ムアッリム" , arabic = "مُعَلِّم" , meaning = "a teacher" } , { latin = "dhakiyya" , kana = "ザキーヤ" , arabic = "ذَكِيّة" , meaning = "smart" } , { latin = "ma3Taf" , kana = "マアタフ" , arabic = "مَعْطَف" , meaning = "a coat" } , { latin = "qubba3a zarqaa2 wa-bunniyya" , kana = "くッバ ザルかー ワ ブンニーヤ" , arabic = "قُبَّعة زَرْقاء وَبُنّية" , meaning = "a blue ad brown hat" } , { latin = "bayDaa2" , kana = "バイダー" , arabic = "بَيْضاء" , meaning = "white" } , { latin = "al-2iijaar jayyid al-Hamdu li-l-laa" , kana = "アル イージャール ジャイイド アル ハムドゥ リッラー" , arabic = "اَلْإِيجار جَيِّد اَلْحَمْدُ لِله" , meaning = "The rent is good, praise be to God." } , { latin = "jaami3a ghaalya" , kana = "ジャーミア ガーリヤ" , arabic = "جامِعة غالْية" , meaning = "an expensive university" } , { latin = "haadhaa Saaluun qadiim" , kana = "ハーザー サルーン カディーム" , arabic = "هَذا صالون قَديم" , meaning = "This is an old living room." } , { latin = "haadhihi Hadiiqa 3arabiyya" , kana = "ハーディヒ ハディーカ アラビーヤ" , arabic = "هَذِهِ حَديقة عَرَبِيّة" , meaning = "This is an Arabian guarden." } , { latin = "al-HaaiT" , kana = "アル ハーイト" , arabic = "اَلْحائِط" , meaning = "the wall" } , { latin = "hunaak shanTa Saghiira" , kana = "フゥナーク シャンタ サギーラ" , arabic = "هُناك شَنطة صَغيرة" , meaning = "There is a small bag." } , { latin = "2abii hunaak" , kana = "アビー フゥナーク" , arabic = "أَبي هُناك" , meaning = "My father is there." } , { latin = "haatifak hunaak yaa buub" , kana = "ハーティファク フゥナーク ヤー ブーブ" , arabic = "هاتِفَك هُناك يا بوب" , meaning = "Your telephone is there, Bob." } , { latin = "haatifii hunaak" , kana = "ハーティフィー フゥナーク" , arabic = "هاتِفي هُناك" , meaning = "My telephone is there." } , { latin = "hunaak 3ilka wa-laab tuub fii shanTatik" , kana = "フゥナーク アイルカ ワ ラーブトゥーブ フィー シャンタティク" , arabic = "هُناك عِلكة وَلاب توب في شَنطَتِك" , meaning = "There is a chewing gum and a laptop in your bag." } , { latin = "raSaaS" , kana = "ラサース" , arabic = "رَصاص" , meaning = "lead" } , { latin = "qalam raSaaS" , kana = "カラム ラサース" , arabic = "قَلَم رَصاص" , meaning = "a pencil" } , { latin = "mu2al-lif" , kana = "ムアッリフ" , arabic = "مُؤَلِّف" , meaning = "an author" } , { latin = "shaahid al-bath-t il-Hayy" , kana = "シャーヒド アル バスト アル ハイイ" , arabic = "شاهد البث الحي" , meaning = "Watch the live braodcast" } , { latin = "2a3iish" , kana = "アーイーシュ" , arabic = "أَعيش" , meaning = "I live" } , { latin = "2a3iish fi l-yaabaan" , kana = "アーイーシュ フィ ル ヤーバーン" , arabic = "أَعيش في لايابان" , meaning = "I live in Japan." } , { latin = "2anaa 2ismii faaTima" , kana = "アナー イスミー ファーティマ" , arabic = "أَنا إِسمي فاطِمة" , meaning = "My name is PI:NAME:<NAME>END_PI (female name)." } , { latin = "2a3iish fii miSr" , kana = "アーイーシュ フィー ミスル" , arabic = "أَعيش في مِصر" , meaning = "I live in Egypt." } , { latin = "al3mr" , kana = "アラームル" , arabic = "العمر" , meaning = "age" } , { latin = "2ukhtii wa-Sadiiqhaa juurj" , kana = "ウクフティー ワ サディークハー ジュールジュ" , arabic = "أُخْتي وَصَديقهل جورْج" , meaning = "my sister and her friend PI:NAME:<NAME>END_PI" } , { latin = "3amalii" , kana = "アアマリー" , arabic = "عَمَلي" , meaning = "my work" } , { latin = "haadhihi Sadiiqat-hu saamiya" , kana = "ハージヒ すぁディーかトフゥ サーミア" , arabic = "هَذِهِ صَديقَتهُ سامية" , meaning = "This is his girlfriend PI:NAME:<NAME>END_PI." } , { latin = "shitaa2" , kana = "シター" , arabic = "شِتاء" , meaning = "winter" } , { latin = "Sayf mumTil" , kana = "サイフ ムムティル" , arabic = "صَيْف مُمْطِر" , meaning = "a rainy summer" } , { latin = "3aalya" , kana = "アーリヤ" , arabic = "عالْية" , meaning = "high" } , { latin = "laa 2uHibb a-T-Taqs al mumTil" , kana = "ラー ウひッブ アッタクス アル ムムティル" , arabic = "لا أُحِبّ اَلْطَّقْس اَلْمُمْطِر" , meaning = "I do not like rainy weather." } , { latin = "Sayf Haarr Tawiil" , kana = "サイフ ハール タウィール" , arabic = "صَيْف حارّ طَويل" , meaning = "a long hot summer" } , { latin = "ruTuuba 3aalya" , kana = "ルトゥーバ アーリヤ" , arabic = "رُطوبة عالية" , meaning = "high humidity" } , { latin = "a-r-rTuubat l-3aalya" , kana = "アルトゥーバト ルアーリヤ" , arabic = "اَلْرُّطوبة الْعالْية" , meaning = "the high humidity" } , { latin = "al-yawm" , kana = "アルヤウム" , arabic = "اَلْيَوْم" , meaning = "today" } , { latin = "alyawm yawm baarid" , kana = "アルヤウム ヤウム バーリド" , arabic = "اَلْيَوْم يَوْم بارِد" , meaning = "Today is a cold day." } , { latin = "tashar-rfnaa" , kana = "タシャッラフゥナー" , arabic = "تشرفنا" , meaning = "Pleased to meet you." } , { latin = "a-S-Sayf l-baarid" , kana = "アッサイフ ル バーリド" , arabic = "اَلْصَّيْف اَلْبارِد" , meaning = "the cold summer" } , { latin = "a-r-rabii3" , kana = "アッラビーア" , arabic = "اَلْرَّبيع" , meaning = "the spring" } , { latin = "al-khariif mushmis" , kana = "アル ハリーフ ムシュミス" , arabic = "اَلْخَريف مُشْمِس" , meaning = "The fall is sunny." } , { latin = "rabii3 jamiil" , kana = "ラビーア ジャミール" , arabic = "رَبيع جَميل" , meaning = "a pretty spring" } , { latin = "rabii3 baarid fii 2iskutlandan" , kana = "ラビーア バアリド フィー スクトランダン" , arabic = "رَبيع بارِد في إِسْكُتْلَنْدا" , meaning = "a cold spring in Scotland" } , { latin = "kayfa" , kana = "カイファ" , arabic = "كَيْفَ" , meaning = "how" } , { latin = "kaifa Haalka" , kana = "カイファ ハールカ" , arabic = "كَيْفَ حالكَ" , meaning = "How are you?" } , { latin = "Hammaam" , kana = "ハンマーム" , arabic = "حَمّام" , meaning = "bathroom" } , { latin = "haadhaa balad-haa" , kana = "ハーザー バラドハー" , arabic = "هَذا بَلَدها" , meaning = "This is her country." } , { latin = "al-2urdun" , kana = "アル ウルドゥン" , arabic = "اَلْأُرْدُن" , meaning = "Jordan" } , { latin = "a-s-saaHil" , kana = "アッサーヒル" , arabic = "اَلْسّاحِل" , meaning = "the coast" } , { latin = "2uhibb a-s-safar 2ilaa 2almaaniiaa" , kana = "ウひッブ アッサファル イラ アルマニア" , arabic = "أُحِب اَلْسَّفَر إِلى أَلْمانيا" , meaning = "I like travelling to Germany" } , { latin = "hiyya" , kana = "ヒヤ" , arabic = "هِيَّ" , meaning = "she" } , { latin = "huwwa" , kana = "フワ" , arabic = "هُوَّ" , meaning = "he" } , { latin = "2anti" , kana = "アンティ" , arabic = "أَنْتِ" , meaning = "you (female)" } , { latin = "2anta" , kana = "アンタ" , arabic = "أَنْتَ" , meaning = "you (male)" } , { latin = "mutarjim dhakiyy" , kana = "ムタルジム ザキーイ" , arabic = "مُتَرْجِم ذَكِيّ" , meaning = "a smart translator (male)" } , { latin = "mutarjima dhakiyya" , kana = "ムタルジマ ザキーヤ" , arabic = "مُتَرْجِمة ذَكِيّة" , meaning = "a smart translator (female)" } , { latin = "2ustaadh 2amriikiyy" , kana = "ウスターズ アマリキーイ" , arabic = "أُسْتاذ أَمْريكِيّ" , meaning = "an American professor (male)" } , { latin = "2ustaadha 2amriikiyya" , kana = "ウスターザ アマリキーヤ" , arabic = "أُسْتاذة أَمْريكِيّة" , meaning = "an American professor (female)" } , { latin = "3alaa" , kana = "アラー" , arabic = "عَلى" , meaning = "on, on top of" } , { latin = "al-3arabiyya l-fuSHaa" , kana = "アルアラビーヤ ル フスハー" , arabic = "اَلْعَرَبِيّة الْفُصْحى" , meaning = "Standard Arabic" } , { latin = "bariiTaanyaa l-kubraa" , kana = "ブリターニヤー ル クブラー" , arabic = "بَريطانْيا الْكُبْرى" , meaning = "Great Britain" } , { latin = "balad 3arabiyy" , kana = "バラド アラビーイ" , arabic = "بَلَد عَرَبِيّ" , meaning = "an Arab country" } , { latin = "madiina 3arabiyya" , kana = "マディーナ アラビーヤ" , arabic = "مَدينة عَرَبِيّة" , meaning = "an Arab city" } , { latin = "bint jadiid" , kana = "ビント ジャディード" , arabic = "بَيْت جَديد" , meaning = "a new house" } , { latin = "jaami3a jadiida" , kana = "ジャーミア ジャディーダ" , arabic = "جامِعة جَديدة" , meaning = "a new university" } , { latin = "hadhaa Saaluun ghaalii" , kana = "ハーザー サールーン ガーリー" , arabic = "هَذا صالون غالي" , meaning = "This is an expensive living room" } , { latin = "ghaalii" , kana = "ガーリー" , arabic = "غالي" , meaning = "expensive, dear" } , { latin = "khaalii" , kana = "クハーリー" , arabic = "خالي" , meaning = "my mother’s brother, uncle" } , { latin = "taab" , kana = "ターブ" , arabic = "تاب" , meaning = "to repent" } , { latin = "Taab" , kana = "ターブ" , arabic = "طاب" , meaning = "to be good, pleasant" } , { latin = "2umm" , kana = "ウンム" , arabic = "أُمّ" , meaning = "mother" } , { latin = "2ukht" , kana = "ウフト" , arabic = "أُخْت" , meaning = "siter" } , { latin = "bint" , kana = "ビント" , arabic = "بِنْت" , meaning = "daughter, girl" } , { latin = "2ummii" , kana = "ウンミー" , arabic = "أُمّي" , meaning = "my mother" } , { latin = "ibnak" , kana = "イブナク" , arabic = "اِبْنَك" , meaning = "your son (to a man)" } , { latin = "ibnik" , kana = "イブニク" , arabic = "اِبْنِك" , meaning = "your son (to a woman)" } , { latin = "al-3iraaq" , kana = "アライラーク" , arabic = "اَلْعِراق" , meaning = "iraq" } , { latin = "nadhiir" , kana = "ナディール" , arabic = "نَذير" , meaning = "warner, herald" } , { latin = "naDhiir" , kana = "ナディール" , arabic = "نَظير" , meaning = "equal" } , { latin = "madiinatii" , kana = "マディーナティ" , arabic = "مَدينَتي" , meaning = "my city" } , { latin = "madiinatak" , kana = "マディーナタク" , arabic = "مَدينَتَك" , meaning = "your city (to a male)" } , { latin = "madiinatik" , kana = "マディーナティク" , arabic = "مَدينَتِك" , meaning = "your city (to a female)" } , { latin = "jaara" , kana = "ジャーラ" , arabic = "جارة" , meaning = "a neighbor (female)" } , { latin = "jaaratii" , kana = "ジャーラティ" , arabic = "جارَتي" , meaning = "my neighbor (female)" } , { latin = "jaaratak" , kana = "ジャーラタク" , arabic = "جارَتَك" , meaning = "your (female) neighbor (to a male)" } , { latin = "jaaratik" , kana = "ジャーラティク" , arabic = "جارَتِك" , meaning = "your (female) neighbor (to a female)" } , { latin = "al-bayt jamiil" , kana = "アルバイト ジャミール" , arabic = "اَلْبَيْت جَميل" , meaning = "The house is pretty" } , { latin = "al-madiina jamiila" , kana = "アルマディーナ ジャミーラ" , arabic = "اَلْمَدينة جَميلة" , meaning = "The city is pretty" } , { latin = "baytak jamiil" , kana = "バイタク ジャミール" , arabic = "بَيْتَك جَميل" , meaning = "Your house is pretty (to a male)" } , { latin = "madiinatak jamiila" , kana = "マディーナタク ジャミーラ" , arabic = "مَدينَتَك جَميلة" , meaning = "Your city is pretty (to a male)" } , { latin = "baytik jamiil" , kana = "バイティク ジャミール" , arabic = "بَيْتِك جَميل" , meaning = "Your house is pretty (to a female)" } , { latin = "madiinatik jamiila" , kana = "マディーナティク ジャミーラ" , arabic = "مَدينَتِك جَميلة" , meaning = "Your city is pretty (to a female)" } , { latin = "dall" , kana = "ダル" , arabic = "دَلّ" , meaning = "to show, guide" } , { latin = "Dall" , kana = "ダル" , arabic = "ضَلّ" , meaning = "to stray" } , { latin = "3ind juudii bayt" , kana = "アインド ジューディー バイト" , arabic = "عِنْد جودي بَيْت" , meaning = "Judy has a house." } , { latin = "3indii baitii" , kana = "アインディー バイティー" , arabic = "عِنْدي بَيْت" , meaning = "I have a house." } , { latin = "3indaka bayt" , kana = "アインダカ バイト" , arabic = "عِنْدَك بَيْت" , meaning = "You (to a man) have a house." } , { latin = "3indika bayt" , kana = "アインディカ バイト" , arabic = "عِنْدِك بَيْت" , meaning = "You (to a woman) have a house." } , { latin = "laysa 3ind juudii bayt" , kana = "ライサ アインド ジュウディー バイト" , arabic = "لَيْسَ عِنْد جودي بَيْت" , meaning = "Judy does not have a house." } , { latin = "laysa 3indii kalb" , kana = "ライサ アインド カルブ" , arabic = "لَيْسَ عِنْدي كَلْب" , meaning = "I do not have a dog." } , { latin = "laysa 3indika wishaaH" , kana = "ライサ アインディカ ウィシャーハ" , arabic = "لَيْسَ عِنْدِك وِشاح" , meaning = "You do not have a scarf. (to a woman)" } , { latin = "madiina suuriyya" , kana = "マディーナ スリーヤ" , arabic = "مَدينة سورِيّة" , meaning = "a Syrian city" } , { latin = "filasTiin makaan mashhuur" , kana = "フィラストィーン マカーン マシュフール" , arabic = "فِلَسْطين مَكان مَشْهور" , meaning = "Palestine is a famous place." } , { latin = "a-s-suudaan wa-l3iraaq" , kana = "アッスーダーン ワライラーク" , arabic = "اَلْسّودان وَالْعِراق" , meaning = "Sudan and Iraq" } , { latin = "al-3aaSima" , kana = "アルあーすぃマ" , arabic = "اَلْعاصِمة" , meaning = "the captal" } , { latin = "jabal" , kana = "ジャバル" , arabic = "جَبَل" , meaning = "a mountain" } , { latin = "a-th-thuudaan" , kana = "アッスーダーン" , arabic = "الشودان" , meaning = "Sudan" } , { latin = "bayt 2azraq" , kana = "バイト アズラク" , arabic = "بَيْت أَزْرَق" , meaning = "a blue house" } , { latin = "madiina zarqaa2" , kana = "マディーナ ザルかー" , arabic = "مَدينة زَرْقاء" , meaning = "a blue city" } , { latin = "al-bayt 2azraq" , kana = "アルバイト アズラク" , arabic = "اَلْبَيْت أَزْرَق" , meaning = "The house is blue" } , { latin = "al-madiina zarqaa2" , kana = "アル マディーナ ザルかー" , arabic = "اَلْمَدينة زَرْقاء" , meaning = "The city is blue." } , { latin = "2azraq zarqaa2" , kana = "アズらく ザルかー" , arabic = "أَزْرَق زَرْقاء" , meaning = "blue" } , { latin = "saam" , kana = "サーム" , arabic = "سام" , meaning = "Sam (maile name)" } , { latin = "Saam" , kana = "サーム" , arabic = "صام" , meaning = "to fast" } , { latin = "Sadiiqii Juurj 3ind-hu 3amal mumtaaz" , kana = "サディークィー ジュールジュ アインダフー アアマル ムムターズ" , arabic = "صَديقي جورْج عِنْدهُ عَمَل مُمْتاز" , meaning = "My friend PI:NAME:<NAME>END_PIorge has excellent job." } , { latin = "ghaniyy" , kana = "ガニィイ" , arabic = "غَنِيّ" , meaning = "rich" } , { latin = "amra2a" , kana = "アムラア" , arabic = "اَمْرَأة" , meaning = "a woman" } , { latin = "2amaamaka" , kana = "アマーマカ" , arabic = "أَمامَك" , meaning = "in front of you" } , { latin = "khalfak" , kana = "ハルファク" , arabic = "خَلْفَك" , meaning = "behind you" } , { latin = "bijaanib" , kana = "ビジャーニブ" , arabic = "بِجانِب" , meaning = "next to" } , { latin = "2abii mashghuul daayman" , kana = "アビー マシュグール ダーイマン" , arabic = "أَبي مَشْغول دائِماً" , meaning = "My father is always busy." } , { latin = "su2aal" , kana = "スアール" , arabic = "سُؤال" , meaning = "question" } , { latin = "ma3ii" , kana = "マアイー" , arabic = "معي" , meaning = "with me" } , { latin = "labisa" , kana = "ラビサ" , arabic = "لابِسة" , meaning = "dress up" } , { latin = "man ma3ii" , kana = "マン マアイー" , arabic = "مَن مَعي؟" , meaning = "Who is this?" } , { latin = "Hanafiyya" , kana = "ハナフィーヤ" , arabic = "حَنَفِيّة" , meaning = "a faucet" } , { latin = "Sawt" , kana = "サウト" , arabic = "صَوْت" , meaning = "voice" } , { latin = "2adkhul" , kana = "アドホル" , arabic = "أَدْخُل" , meaning = "enter" } , { latin = "al-haatif mu3aTTal wa-t-tilfaaz 2ayDan" , kana = "アルハーティフ ムアッタル ワッティルファーズ アイダン" , arabic = "اَلْهاتِف مُعَطَّل وَالْتَّلْفاز أَيضاً" , meaning = "The telephone is out of order and the television also." } , { latin = "hunaak mushkila ma3a t-tilaaz" , kana = "フゥナーク ムシュキラ マア ッティルファーズ" , arabic = "هُناك مُشْكِلة مَعَ الْتِّلْفاز" , meaning = "There is a problem with the television." } , { latin = "2a3rif" , kana = "アーリフ" , arabic = "أَعْرِف" , meaning = "I know ..." } , { latin = "raqam" , kana = "ラカム" , arabic = "رَقَم" , meaning = "number" } , { latin = "la 2a3rif kul-l al-2aedaan" , kana = "ラー アーリフ クッラ ル アーダーン" , arabic = "لا أَعْرِف كُلّ اَلْأَعْداد" , meaning = "I do not know all the numbers." } , { latin = "ta3rifiin" , kana = "ターリフィーン" , arabic = "تَعْرِفين" , meaning = "You (female) know" } , { latin = "li2anna" , kana = "リアンナ" , arabic = "لِأَنَّ" , meaning = "because" } , { latin = "samna" , kana = "サムナ" , arabic = "سَمنة" , meaning = "ghee" } , { latin = "wilaaya" , kana = "ウィラーヤ" , arabic = "وِلايَة" , meaning = "a state" } , { latin = "zawjii wa-bnii" , kana = "ザウジー ワブニー" , arabic = "زَوجي وَابني" , meaning = "my husband and my son" } , { latin = "mumtaaz" , kana = "ムムターズ" , arabic = "مُمتاز" , meaning = "amazing, excellent" } , { latin = "abnii" , kana = "アブニー" , arabic = "اَبني" , meaning = "my son" } , { latin = "muHaasib" , kana = "ムハースィブ" , arabic = "مُحاسب" , meaning = "an accountant" } , { latin = "juz2" , kana = "ジュズ" , arabic = "جُزء" , meaning = "a part of" } , { latin = "fataa" , kana = "ファター" , arabic = "فَتاة" , meaning = "a young woman, a girl" } , { latin = "tis3a" , kana = "ティスア" , arabic = "تِسعة" , meaning = "nine" } , { latin = "hal l-lghat l-3arabiyya Sa3ba" , kana = "ハル ッルガト ルアラビーヤ サアバ" , arabic = "هَل اللُّغَة العَرَبية صَعبة" , meaning = "Is arabic language difficult?" } , { latin = "maadhaa fa3lta 2amsi" , kana = "マーザー ファアルタ アムスィ" , arabic = "ماذا فَعلتَ أَمسِ" , meaning = "What did you do yesterday?" } , { latin = "maadhaa 2akalta" , kana = "マーザー アカルタ" , arabic = "ماذا أَكَلتَ" , meaning = "What did you eat?" } , { latin = "shu2uun" , kana = "シュ ウーン" , arabic = "شُؤُون" , meaning = "affairs, things" } , { latin = "mataa waSalta" , kana = "マター ワサルタ" , arabic = "مَتي وَصَلتَ" , meaning = "When did you arrive?" } , { latin = "suuq" , kana = "スーク" , arabic = "سوق" , meaning = "market" } , { latin = "Haafila" , kana = "ハーフィラ" , arabic = "حافِلة" , meaning = "a bus" } , { latin = "tannuura" , kana = "タンヌーラ" , arabic = "تَنورة" , meaning = "a skirt" } , { latin = "laHaDha" , kana = "ラハザ" , arabic = "لَحَظة" , meaning = "a moment" } , { latin = "2ayna l-qiTTa" , kana = "アイナ ルキッタ" , arabic = "أَينَ القِطّة" , meaning = "Where is the cat?" } , { latin = "shaay" , kana = "シャーイ" , arabic = "شاي" , meaning = "tea" } , { latin = "hal haadhihi Haqiibatki" , kana = "ハル ハージヒ ハキーバトキ" , arabic = "هَل هَذِهِ حَقيبَتكِ" , meaning = "Is this your bag?" } , { latin = "Hakiiba" , kana = "ハキーバ" , arabic = "حَقيبَة" , meaning = "a bag" } , { latin = "Haal" , kana = "ハール" , arabic = "حال" , meaning = "condition" } , { latin = "SaHiifa" , kana = "サヒーファ" , arabic = "صَحيفة" , meaning = "newspaper" } , { latin = "maktab" , kana = "マクタブ" , arabic = "مَكْتَب" , meaning = "an office, a desk" } , { latin = "bunnii" , kana = "ブンニー" , arabic = "بُنّي" , meaning = "brown" } , { latin = "2ila l-liqaa2" , kana = "イラ ッリカー" , arabic = "إِلى اللِّقاء" , meaning = "Bye. See you again." } , { latin = "daa2iman" , kana = "ダーイマン" , arabic = "دائمًا" , meaning = "always" } , { latin = "Hasanan" , kana = "ハサナン" , arabic = "حَسَنًا" , meaning = "Okay, good, fantastic!" } , { latin = "2ayna l-Hammaam" , kana = "アイナ ル ハンマーン" , arabic = "أَينَ الحَمّام" , meaning = "Where is the bathroom?" } , { latin = "baqara" , kana = "バカラ" , arabic = "بَقَرة" , meaning = "a cow" } , { latin = "nasiij" , kana = "ナスィージ" , arabic = "نَسيج" , meaning = "texture" } , { latin = "Hajar" , kana = "ハジャル" , arabic = "حَجَر" , meaning = "a stone" } , { latin = "muthal-lath" , kana = "ムサッラス" , arabic = "مُثَلَّث" , meaning = "a triangle" } , { latin = "kathiir" , kana = "カシール" , arabic = "كَثير" , meaning = "many, a lot of" } , { latin = "thawm" , kana = "サウム" , arabic = "ثَوم" , meaning = "garlic" } , { latin = "qiTTatii Saghiira" , kana = "キッタティー サギーラ" , arabic = "قِطَّتي صَغيرة" , meaning = "my small cat" } , { latin = "dubb" , kana = "ドッブ" , arabic = "دُبّ" , meaning = "a bear" } , { latin = "Tabakh" , kana = "タバクハ" , arabic = "طَبَخ" , meaning = "to cook, cooking" } , { latin = "nakhl" , kana = "ナクヘル" , arabic = "نَخْل" , meaning = "date palm tree" } , { latin = "kharuuf" , kana = "クハルーフ" , arabic = "خَروف" , meaning = "a sheep" } , { latin = "samaHa" , kana = "サマハ" , arabic = "سَمَح" , meaning = "to allow, forgive" } , { latin = "tashar-rfnaa" , kana = "タシャッラフゥナー" , arabic = "تَثَرَّفنا" , meaning = "I am pleased to meet you." } , { latin = "Haliib" , kana = "ハリーブ" , arabic = "حَليب" , meaning = "milk (m)" } , { latin = "haatha l-maTar a-th-thaqiir Sa3b" , kana = "ハーザ ル マタル アッサキール サアブ" , arabic = "هَذا المَطَر الثقيل صَعب" , meaning = "This heavy rain is difficult." } , { latin = "al-maTar" , kana = "アルマタル" , arabic = "المَطَر" , meaning = "the rain" } , { latin = "muHaadatha" , kana = "ムハーダサ" , arabic = "مُحادَثة" , meaning = "conversation" } , { latin = "zawjatii ta3baana" , kana = "ザウジャティー タアバーナ" , arabic = "زَوجَتي تَعبانة" , meaning = "My wife is tired." } , { latin = "shukuran" , kana = "シュクラン" , arabic = "شُكْراً" , meaning = "thank you" } , { latin = "shukran jaziilan" , kana = "シュクラン ジャズィーラン" , arabic = "ثُكْراً جَزيلاً" , meaning = "Thank you very much." } , { latin = "jaw3aan" , kana = "ジャウあーン" , arabic = "جَوعان" , meaning = "hungry, starving" } , { latin = "2abyaD bayDaa2" , kana = "アビヤド バイダー" , arabic = "أَبْيَض بَيْضاء" , meaning = "white" } , { latin = "jadd wa-jadda" , kana = "ジャッド ワ ジャッダ" , arabic = "جَدّ وَجَدّة" , meaning = "grandfather and grandmother" } , { latin = "2aaluu" , kana = "アールー" , arabic = "آلو" , meaning = "Hello (on the phone)" } , { latin = "SabaaH l-khayr" , kana = "サバーフ ル クハイル" , arabic = "صَباح الخّير" , meaning = "good morning" } , { latin = "laakinn" , kana = "ラキン" , arabic = "لَكِنّ" , meaning = "but" } , { latin = "thaqaafa" , kana = "サカーファ" , arabic = "ثَقافة" , meaning = "culture" } , { latin = "Haarr" , kana = "ハール" , arabic = "حارّ" , meaning = "hot" } , { latin = "Taqs baarid" , kana = "タクス バーリド" , arabic = "طَقْس بارِد" , meaning = "cold weather" } , { latin = "tilfaaz" , kana = "ティルファーズ" , arabic = "تِلْفاز" , meaning = "a television" } , { latin = "tufaaHa" , kana = "トゥファーハ" , arabic = "تُفاحة" , meaning = "an apple" } , { latin = "sariir" , kana = "サリール" , arabic = "سَرير" , meaning = "a bed" } , { latin = "kursii" , kana = "クルスィー" , arabic = "كُرسي" , meaning = "a chair" } , { latin = "3an" , kana = "アン" , arabic = "عَن" , meaning = "about" } , { latin = "samaa2" , kana = "サマー" , arabic = "سَماء" , meaning = "sky (f)" } , { latin = "2iiTaalyaa" , kana = "イーターリヤー" , arabic = "إيطاليا" , meaning = "Italy" } , { latin = "2arD" , kana = "アルド" , arabic = "أَرض" , meaning = "a land (f)" } , { latin = "wilaayat taksaas" , kana = "ウィラーヤト タクサース" , arabic = "وِلاية تَكْساس" , meaning = "the state of Texas" } , { latin = "Sahfii Sahfiiya" , kana = "サハフィー サハフィーヤ" , arabic = "صَحفي صَحفية" , meaning = "a journalist" } , { latin = "bint suuriyya" , kana = "ビント スーリヤ" , arabic = "بِنْت سورِيّة" , meaning = "a Syrian girl" } , { latin = "2umm" , kana = "ウンム" , arabic = "أُمّ" , meaning = "a mother (f)" } , { latin = "3ayn" , kana = "アイン" , arabic = "عَيْن" , meaning = "an eye (f)" } , { latin = "qadam" , kana = "カダム" , arabic = "قَدَم" , meaning = "a foot (f)" } , { latin = "3an l-qiraa2a" , kana = "アニル キラーエ" , arabic = "عَن القِراءة" , meaning = "about reading" } , { latin = "a-s-safar" , kana = "アッサファル" , arabic = "السفر" , meaning = "travelling" } , { latin = "kulla yawm" , kana = "クッラ ヤウム" , arabic = "كُلَّ يَوم" , meaning = "every day" } , { latin = "2adrs fi l-jaami3a kulla yawm" , kana = "アドルス フィ ル ジャーミア クッラ ヤウム" , arabic = "أَدرس في الجامِعة كُلَّ يَوم" , meaning = "I study at the university every day." } , { latin = "dhahaba" , kana = "ザハバ" , arabic = "ذَهَبَ" , meaning = "He went" } , { latin = "katabaa" , kana = "カタバー" , arabic = "كَتَبَا" , meaning = "They (two male) wrote" } , { latin = "katabtu" , kana = "カタブトゥ" , arabic = "كَتَبْتُ" , meaning = "I wrote" } , { latin = "katabti" , kana = "カタブティ" , arabic = "كَتَبْتِ" , meaning = "You (female) wrote" } , { latin = "katabta" , kana = "カタブタ" , arabic = "كَتَبْتَ" , meaning = "You (male) wrote" } , { latin = "katabat" , kana = "カタバット" , arabic = "كَتَبَت" , meaning = "She wrote" } , { latin = "ramaDaan" , kana = "ラマダーン" , arabic = "رَمَضان" , meaning = "Ramadan" } , { latin = "qahwa" , kana = "かハワ" , arabic = "قَهوة" , meaning = "coffee" } , { latin = "al-2aan" , kana = "アル アーン" , arabic = "اَلآن" , meaning = "right now" } , { latin = "saa3at Haa2iT" , kana = "サーアト ハーイト" , arabic = "ساعة حائط" , meaning = "a wall clock" } , { latin = "kami s-saa3a l-2aan" , kana = "カミッサーア ルアーン" , arabic = "كَمِ الساعة الآن" , meaning = "What time is it now?" } , { latin = "a-s-saa3a kam" , kana = "アッサーア カム" , arabic = "الساعة كَم" , meaning = "What time is it?" } , { latin = "2a3Tinii" , kana = "アーティニー" , arabic = "أَعْطِني" , meaning = "Give me ..." } , { latin = "Tayyib" , kana = "タイイブ" , arabic = "طَيِّب" , meaning = "Ok, good" } , { latin = "2abuu shaqra" , kana = "アブーシャクラ" , arabic = "أَبو شَقرة" , meaning = "Abu Shakra (restaurant)" } , { latin = "haathihi T-Taawila Haara" , kana = "ハージヒ ッターウィラ ハーラ" , arabic = "هَذِهِ الطاوِلة حارة" , meaning = "This table is hot." } , { latin = "ma3Taf khafiif" , kana = "マアタフ クハフィーフ" , arabic = "معطَف خَفيف" , meaning = "a light coat" } , { latin = "maTar khafiif" , kana = "マタル クハフィーフ" , arabic = "مَطَر خَفيف" , meaning = "a light rain" } , { latin = "a-T-Taqs" , kana = "アッタクス" , arabic = "الطَّقس" , meaning = "the weather" } , { latin = "2alf" , kana = "アルフ" , arabic = "أَلف" , meaning = "a thousand" } , { latin = "mi3a" , kana = "ミア" , arabic = "مِئة" , meaning = "a hundred" } , { latin = "3ashara" , kana = "アシャラ" , arabic = "عَشرة" , meaning = "ten" } , { latin = "al-Hamdu li-l-laa" , kana = "アルハムド リッラー" , arabic = "الحَمدُ لِلَّه" , meaning = "Praise be to God." } , { latin = "Hubba" , kana = "フッバ" , arabic = "حُبَّ" , meaning = "love" } , { latin = "3ilka" , kana = "アイルカ" , arabic = "عِلكة" , meaning = "chewing gum" } , { latin = "thaqiil" , kana = "サキール" , arabic = "ثَقيل" , meaning = "heavy" } , { latin = "haatifii" , kana = "ハーティフィー" , arabic = "هاتِفي" , meaning = "my phone" } , { latin = "thamaaniya" , kana = "サマーニヤ" , arabic = "ثَمانية" , meaning = "eight" } , { latin = "sab3a" , kana = "サブア" , arabic = "سَبعة" , meaning = "seven" } , { latin = "sitta" , kana = "スィッタ" , arabic = "سِتَّة" , meaning = "six" } , { latin = "khamsa" , kana = "クハムサ" , arabic = "خَمسة" , meaning = "five" } , { latin = "2arba3a" , kana = "アルバア" , arabic = "أَربَعة" , meaning = "four" } , { latin = "thalaatha" , kana = "サラーサ" , arabic = "ثَلاثة" , meaning = "three" } , { latin = "2alif baa2 taa2 thaa2 jiim Haa2 khaa2" , kana = "アリフ バー ター さー ジーム はー クハー" , arabic = "أَلِف باء تاء ثاء جيم حاء خاء" , meaning = "ا ب ت ث ج ح خ" } , { latin = "daal dhaal raa2 zaay siin shiin" , kana = "ダール ざール らー ザーイ スィーン シーン" , arabic = "دال ذال راء زاي سين شين" , meaning = "د ذ ر ز س ش" } , { latin = "Saad Daad Taa2 Dhaa2 3ain ghain" , kana = "すぁード だード たー づぁー アイン ガイン" , arabic = "صاد ضاد طاء ظاء عَين غَين" , meaning = "ص ض ط ظ ع غ" } , { latin = "faa2 qaaf kaaf laam miim nuun" , kana = "ファー かーフ カーフ ラーム ミーム ヌーン" , arabic = "فاء قاف كاف لام ميم نون" , meaning = "ف ق ك ل م ن" } , { latin = "haa2 waaw yaa2 hamza" , kana = "ハー ワーウ ヤー ハムザ" , arabic = "هاء واو ياء هَمزة" , meaning = "ه و ي ء" } , { latin = "kaifa l-Haal" , kana = "カイファ ル はール" , arabic = "كَيفَ الحال" , meaning = "How are you? (How is the condition?)" } , { latin = "bi-khayr wa-l-Hamdu li-l-laa" , kana = "ビクハイルr ワルはムドゥ リッラー" , arabic = "بِخَير وَالحَمدُ لِلَّه" , meaning = "I am fine. Praise be to God." } , { latin = "2aHmar Hamraa2" , kana = "アフマる ハムらー" , arabic = "أَحمَر حَمراء" , meaning = "red" } , { latin = "muHaamii" , kana = "ムハーミー" , arabic = "مُحامي" , meaning = "an attorney, a lawyer" } , { latin = "haadhaa rakamii" , kana = "ハーザー らかミー" , arabic = "هَذا رَقَمي" , meaning = "This is my number." } , { latin = "samaka 2asmaak" , kana = "サマカ アスマーク" , arabic = "سَمَكة أَسماك" , meaning = "fish, fish (plural)" } , { latin = "shajara 2ashujaar" , kana = "シャジャら アシュジャーる" , arabic = "شَجَرة أَشجار" , meaning = "tree, trees" } , { latin = "manzil" , kana = "マンズィル" , arabic = "مَنزِل" , meaning = "a house, home" } , { latin = "bayt" , kana = "バイト" , arabic = "بَيْت" , meaning = "a house" } , { latin = "Hadiiqa" , kana = "はディーか" , arabic = "حَديقة" , meaning = "garden" } , { latin = "haadhihi Hadiiqa 3arabyya" , kana = "ハーじヒ はディーか アらビーヤ" , arabic = "هَذِهِ حَديقة عَرَبيّة" , meaning = "This is an Arab garden" } , { latin = "tafaD-Dal ijlis" , kana = "タファッダル イジュリス" , arabic = "تَفَضَّل اِجْلِس" , meaning = "Please sit down." } , { latin = "tafaD-Dalii" , kana = "タファッダリー" , arabic = "تَفَضَّلي" , meaning = "Please (female word)" } , { latin = "shaay min faDlika" , kana = "シャーイ ミン ファドリカ" , arabic = "شاي مِن فَضلِكَ" , meaning = "Tea please." } , { latin = "ma3a s-salaama" , kana = "マア ッサラーマ" , arabic = "مَعَ السَّلامة" , meaning = "Good bye." } , { latin = "ash-shams" , kana = "アッシャムス" , arabic = "الشَّمس" , meaning = "the sun" } , { latin = "haadha l-qalam" , kana = "ハーザ ル カラム" , arabic = "هَذا القَلَم" , meaning = "this pen" } , { latin = "muta2assif laa 3alayka" , kana = "ムタアッシフ ラー アライカ" , arabic = "مُتأَسِّف. لا عَلَيكَ." , meaning = "I am sorry. Do not mind." } , { latin = "al-qamar" , kana = "アルかマる" , arabic = "القَمَر" , meaning = "the moon" } , { latin = "walad al-walad" , kana = "ワラド アルワラド" , arabic = "وَلَد الوَلَد" , meaning = "boy , the boy" } , { latin = "madrasa" , kana = "マドらサ" , arabic = "مَدرَسة" , meaning = "a school" } , { latin = "saa2iq" , kana = "サーイク" , arabic = "سائق" , meaning = "a driver" } , { latin = "daftar" , kana = "ダフタる" , arabic = "دَفتَر" , meaning = "a notebook" } , { latin = "ba3da 2idhnika" , kana = "バァダ イズニカ" , arabic = "بَعدَ إِذنِكَ" , meaning = "After your permit. Excuse me." } , { latin = "muwaDh-Dhaf" , kana = "ムワッザフ" , arabic = "مُوَظَّف" , meaning = "an employee" } , { latin = "waaHid" , kana = "ワーヒド" , arabic = "واحِد" , meaning = "one" } , { latin = "2ithnaan" , kana = "イスナーン" , arabic = "اِثنان" , meaning = "two" } , { latin = "qamiiS" , kana = "カミース" , arabic = "قَميص" , meaning = "a shirt" } , { latin = "qaamuus" , kana = "かームース" , arabic = "قاموس" , meaning = "dictionary" } , { latin = "majal-la" , kana = "マジャッラ" , arabic = "مَجَلَّة" , meaning = "magazine" } , { latin = "2iijaarii" , kana = "イージャーりー" , arabic = "إيجاري" , meaning = "my rent" } , { latin = "maa haadhaa" , kana = "マー ハーザー" , arabic = "ما هَذا" , meaning = "What is this?" } , { latin = "khubz" , kana = "クフブズ" , arabic = "خُبز" , meaning = "bread" } , { latin = "riisha" , kana = "りーシャ" , arabic = "ريشة" , meaning = "feather" } , { latin = "Taa2ira" , kana = "たーイら" , arabic = "طائرة" , meaning = "an airplane" } , { latin = "Dhabii" , kana = "ザビー" , arabic = "ظَبي" , meaning = "an antelope" } , { latin = "Tabiib" , kana = "タビーブ" , arabic = "طَبيب" , meaning = "doctor" } , { latin = "laa 2a3rif 2ayna 2anaa" , kana = "ラー アーりフ アイナ アナー" , arabic = "لا أَعرِف أَين أَنا" , meaning = "I do not know where I am." } , { latin = "jaarii" , kana = "ジャーリー" , arabic = "جاري" , meaning = "my (male) neighbor" } , { latin = "huwa wa hiya wa hum" , kana = "フワ ワ ヒヤ ワ フム" , arabic = "هُوَ وَ هِيَ وَ هُم" , meaning = "he and she and they" } , { latin = "2anta wa 2anti wa 2antum" , kana = "アンタ ワ アンティ ワ アントゥム" , arabic = "أَنتَ وَ أَنتِ وَ أَنتُم" , meaning = "you (male) and you (female) and you (plural)" } , { latin = "naHnu" , kana = "ナフヌ" , arabic = "نَحنُ" , meaning = "we" } , { latin = "2akh" , kana = "アクハ" , arabic = "أَخ" , meaning = "a brother" } , { latin = "Hijaab" , kana = "ヒジャーブ" , arabic = "حِجاب" , meaning = "a barrier, Hijab" } , { latin = "2ustaadhii" , kana = "ウスタージー" , arabic = "أُستاذي" , meaning = "my professor" } , { latin = "SabaaH n-nuur" , kana = "さバーフ ン ヌーる" , arabic = "صَباح النور" , meaning = "Good morning." } , { latin = "mu3l-lamii" , kana = "ムアッラミー" , arabic = "مُعلَّمي" , meaning = "my teacher" } , { latin = "al-2qkl wa-n-nawm" , kana = "アル アクル ワ ン ナウム" , arabic = "الأَكْل وَالنَّوم" , meaning = "eating and sleeping" } , { latin = "2aiDan" , kana = "アイダン" , arabic = "أَيضاً" , meaning = "also" } , { latin = "al-jarii" , kana = "アル ジャりー" , arabic = "الجَري" , meaning = "running" } , { latin = "a-n-nawm" , kana = "アンナウム" , arabic = "النَّوم" , meaning = "sleeping" } , { latin = "bintii" , kana = "ビンティー" , arabic = "بِنتي" , meaning = "my daughter" } , { latin = "2amaama" , kana = "アマーマ" , arabic = "أَمامَ" , meaning = "in front of, before" } , { latin = "jaami3tii fii Tuukyuu" , kana = "ジャーミアティー フィー トーキョー" , arabic = "جامِعتي في طوكيو" , meaning = "My university is in Tokyo." } , { latin = "2ayn jaami3tka" , kana = "アイン ジャーミアトカ" , arabic = "أَين جامِعتكَ" , meaning = "Where is your university?" } , { latin = "a-t-taSwiir" , kana = "アッタすウィーる" , arabic = "التصْوير" , meaning = "photography" } , { latin = "jaaratii" , kana = "ジャーらティー" , arabic = "جارَتي" , meaning = "my (female) neighbor" } , { latin = "jaarii" , kana = "ジャーりー" , arabic = "جاري" , meaning = "my (male) neighbor" } , { latin = "Dawaahii" , kana = "だワーヒー" , arabic = "ضَواحي" , meaning = "suburbs" } , { latin = "2askn fii DawaaHii baghdaad" , kana = "アスクン フィー だワーひー バグダード" , arabic = "أَسكن في ضَواحي بَغداد" , meaning = "I live in the suburbs of Bagdad." } , { latin = "qar-yatii qariiba min madiinat bayruut" , kana = "かるヤティー かりーバ ミン マディーナト バイるート" , arabic = "قَريتي قَريبة مِن مَدينة بَيروت" , meaning = "My village is close to the city of Beirut." } , { latin = "3afwan" , kana = "アフワン" , arabic = "عَفواً" , meaning = "Excuse me. Sure, it's Ok. (Reply to thank you)" } , { latin = "2ahlan wa-sahlan" , kana = "アハラン ワ サハラン" , arabic = "أَهلاً وَسَهلاً" , meaning = "Welcome." } , { latin = "kitaab" , kana = "キターブ" , arabic = "كِتاب" , meaning = "a book" } , { latin = "Sadiiqat-hu ruuzaa qariibhu min baythu" , kana = "すぁディーかトフゥ るーザー かりーブフゥ ミン バイトフゥ" , arabic = "صَديقَته روزا قَريبة مِن بَيته" , meaning = "His friend PI:NAME:<NAME>END_PI is close to his house." } , { latin = "Sadiiqat-hu qariiba min manzil-hu" , kana = "すぁディーかトフゥ かりーバ ミン マンズィルフゥ" , arabic = "صَديقَته قَريبة مِن مَنزِله." , meaning = "His girlfriend is close to his home" } , { latin = "2amaam al-jaami3a" , kana = "アマーマ ル ジャーミア" , arabic = "أَمام اَلْجامِعة" , meaning = "in front of the university" } , { latin = "waraa2 l-maqhaa" , kana = "ワらーア ル マクハー" , arabic = "وَراء المَقهى" , meaning = "behind the cafe" } , { latin = "2anaa fi l-maqhaa" , kana = "アナ フィ ル マクハー" , arabic = "أَنا في المَقهى" , meaning = "I am in the cafe." } , { latin = "bi-l-layr" , kana = "ビッライる" , arabic = "بِاللَّيل" , meaning = "at night" } , { latin = "3an il-yaabaan" , kana = "あニル ヤーバーン" , arabic = "عَن اليابان" , meaning = "about Japan" } , { latin = "qabl a-s-saa3at l-khaamisa" , kana = "かブラ ッサーアト ル クハーミサ" , arabic = "قَبل الساعة الخامِسة" , meaning = "before the fifth hour" } , { latin = "ba3d a-Dh-Dhuhr" , kana = "バァダ ッづホる" , arabic = "بَعد الظُّهر" , meaning = "afternoon" } , { latin = "2uHibb a-n-nawm ba3d a-Dh-Dhuhr" , kana = "ウひッブ アンナウム バァダ ッづホる" , arabic = "أحِبّ اَلْنَّوْم بَعْد اَلْظَّهْر" , meaning = "I like sleeping in the afternoon." } , { latin = "alkalaam ma3a 2abii ba3d alDh-Dhuhr" , kana = "アルカラーム マア アビー バァダ ッづホる" , arabic = "اَلْكَلام معَ أَبي بَعْد اَلْظَّهْر" , meaning = "talking with my father in the afternoon" } , { latin = "a-s-salaamu 3alaykum" , kana = "アッサラーム アライクム" , arabic = "اَلْسَّلامُ عَلَيْكُم" , meaning = "Peace be upon you." } , { latin = "wa-3alaykumu a-s-salaam" , kana = "ワ アライクム アッサラーム" , arabic = "وَعَلَيكم السلام" , meaning = "And peace be upon you." } , { latin = "lil2asaf" , kana = "リルアサフ" , arabic = "لِلْأَسَف" , meaning = "unfortunately" } , { latin = "al-baHr al-2abyaD al-mutawas-siT" , kana = "アル バハる アル アビヤど アル ムタワッスィと" , arabic = "اَاْبَحْر اَلْأَبْيَض اَلْمُتَوَسِّط" , meaning = "the Meditteranean Sea" } , { latin = "2uHibb a-s-safar 2ila l-baHr al-2abyaD al-mutawas-siT" , kana = "ウひッブ アッサファら イラ ル バハる アル アビヤど アル ムタワッスィと" , arabic = "أُحِبّ اَلْسَّفَر إِلى الْبَحْر اَلْلأَبْيَض اَلْمُتَوَسِّط" , meaning = "I like travelling to the Mediterranean Sea." } , { latin = "ghadan" , kana = "ガダン" , arabic = "غَداً" , meaning = "tomorrow" } , { latin = "li-maadhaa" , kana = "リ マーザー" , arabic = "لَماذا" , meaning = "why" } , { latin = "3indii fikra" , kana = "アインディー フィクら" , arabic = "عِندي فِكْرة" , meaning = "I have an idea." } , { latin = "hal 3indaka haatif" , kana = "ハル アインダカ ハーティフ" , arabic = "هَل عِندَكَ هاتِف" , meaning = "Do you have a phone?" } , { latin = "fi l-T-Taabiq al-2awwal" , kana = "フィル ッタービク アルアッワル" , arabic = "في الْطّابِق اَلْأَوَّل" , meaning = "on the first floor" } , { latin = "a-sh-shaanii" , kana = "アッシャーニー" , arabic = "الثاني" , meaning = "the second" } , { latin = "fi l-T-Taabiq a-sh-sha-nii" , kana = "フィル ッタービク アッシャーニー" , arabic = "في الطابق الثاني" , meaning = "in the second floor" } , { latin = "al-laa" , kana = "アッラー" , arabic = "اَلله" , meaning = "God" } , { latin = "haadha l-bayt" , kana = "ハーザ ル バイト" , arabic = "هَذا البَيت" , meaning = "this house" } , { latin = "haadhihi l-madiina" , kana = "ハージヒ ル マディーナ" , arabic = "هَذِهِ المَدينة" , meaning = "this city" } , { latin = "hunaak bayt" , kana = "フゥナーク バイト" , arabic = "هُناك بَيْت" , meaning = "There is a house." } , { latin = "al-bayt hunaak" , kana = "アルバイト フゥナーク" , arabic = "اَلْبَيْت هُناك" , meaning = "The house is there." } , { latin = "hunaak washaaH 2abyaD" , kana = "フゥナーク ワシャーハ アビヤド" , arabic = ".هُناك وِشاح أَبْيَض" , meaning = "There is a white scarf." } , { latin = "al-washaaH hunaak" , kana = "アルワシャーハ フゥナーク" , arabic = "اَلْوِشاح هُناك" , meaning = "The scarf is there." } , { latin = "laysa hunaak bayt" , kana = "ライサ フゥナーク バイト" , arabic = "لَيْسَ هُناك بَيْت" , meaning = "There is no house." } , { latin = "laysa hunaak washaaH 2abyaD" , kana = "ライサ フゥナーク ワシャーハ アビヤド" , arabic = "لَيْسَ هُناك وِشاح أَبْيَض" , meaning = "There is no white scarf." } , { latin = "bayt buub" , kana = "バイト ブーブ" , arabic = "بَيْت بوب" , meaning = "Bob’s house" } , { latin = "baab karii" , kana = "バーブ カりー" , arabic = "باب كَري" , meaning = "PI:NAME:<NAME>END_PI’s door" } , { latin = "kalb al-bint" , kana = "カルブ アルビント" , arabic = "كَلْب اَلْبِنْت" , meaning = "the girl’s dog" } , { latin = "wishaaH al-walad" , kana = "ウィシャーハ アル ワラド" , arabic = "وِشاح اَلْوَلَد" , meaning = "the boy’s scarf" } , { latin = "madiinat buub" , kana = "マディーナト ブーブ" , arabic = "مَدينة بوب" , meaning = "Bob’s city" } , { latin = "jaami3at karii" , kana = "ジャミーアト カりー" , arabic = "جامِعة كَري" , meaning = "Carrie’s university" } , { latin = "qiT-Tat al-walad" , kana = "キッタト アルワラド" , arabic = "قِطّة اَلْوَلَد" , meaning = "the boy’s cat" } , { latin = "mi3Tafhu" , kana = "ミターフフゥ" , arabic = "مِعْطَفهُ" , meaning = "his coat" } , { latin = "mi3Tafhaa" , kana = "ミターフハー" , arabic = "مِعْطَفها" , meaning = "her coat" } , { latin = "baythu" , kana = "バイトフゥ" , arabic = "بَيْتهُ" , meaning = "his house" } , { latin = "baythaa" , kana = "バイトハー" , arabic = "بَيْتها" , meaning = "her house" } , { latin = "madiinathu" , kana = "マディーナトフ" , arabic = "مَدينَتهُ" , meaning = "his city" } , { latin = "madiinathaa" , kana = "マディーナトハー" , arabic = "مَدينَتها" , meaning = "her city" } , { latin = "qubba3athu" , kana = "クッバトフ" , arabic = "قُبَّعَتهُ" , meaning = "his hat" } , { latin = "qubba3athaa" , kana = "クッバトハー" , arabic = "قُبَّعَتها" , meaning = "her hat" } , { latin = "2abtasim" , kana = "アブタスィム" , arabic = "أَبْتَسِم" , meaning = "I smile" } , { latin = "2aTbukh" , kana = "アトブクフ" , arabic = "أَطْبُخ" , meaning = "I cook" } , { latin = "laa 2aTbukh" , kana = "ラー アトブクフ" , arabic = "لا أَطْبُخ" , meaning = "I do not cook." } , { latin = "li-d-diraasa" , kana = "リッディらーサ" , arabic = "للدراسة" , meaning = "to study" } , { latin = "ma3a 2ustaadh 2aHmad" , kana = "マア ウスターズ アハマド" , arabic = "مَعَ الأُستاذ أَحمَد" , meaning = "with Mr. Ahmed" } , { latin = "bi-l-yaabaaniyy" , kana = "ビルヤーバーニーイ" , arabic = "بالياباني" , meaning = "in Japanese" } , { latin = "bi-s-sayaara" , kana = "ビッサイヤーら" , arabic = "باالسيارة" , meaning = "by car" } , { latin = "li-2akhii" , kana = "リアクヒー" , arabic = "لِأَخي" , meaning = "for my brother" } , { latin = "3ala l-kursii" , kana = "アラ ル クるスィー" , arabic = "عَلى الكُرسي" , meaning = "on the chair" } , { latin = "taHt al-maktab" , kana = "タハタ ル マクタブ" , arabic = "تَحت المَكتَب" , meaning = "under the desk" } , { latin = "amaam al-maHaTTa" , kana = "アマーマ ル マハッタ" , arabic = "أَمام المَحطّة" , meaning = "in front of the station" } , { latin = "2atakal-lam" , kana = "アタカッラム" , arabic = "أَتَكَلَّم" , meaning = "I talk, I speak" } , { latin = "2uHibb al-kalaam" , kana = "ウひッブ アルカラーム" , arabic = "أُحِبّ اَلْكَلام." , meaning = "I like talking." } , { latin = "2uriid al-kalaam" , kana = "ウりード アルカラーム" , arabic = "أُريد اَلْكَلام" , meaning = "I want to talk." } , { latin = "al-kalaam jayyid" , kana = "アルカラーム ジャイイド" , arabic = "اَلْكَلام جَيِّد" , meaning = "The talking is good." } , { latin = "az-zawja" , kana = "アッザウジャ" , arabic = "اَلْزَّوْجة" , meaning = "the wife" } , { latin = "as-sayyaara" , kana = "アッサイヤーラ" , arabic = "اَلْسَّيّارة" , meaning = "the car" } , { latin = "ad-duktuur" , kana = "アッドクトゥール" , arabic = "ad-duktuur" , meaning = "the doctor" } , { latin = "ar-rajul" , kana = "アッラジュル" , arabic = "اَلْرَّجُل" , meaning = "the man" } , { latin = "as-suudaan" , kana = "アッスーダーン" , arabic = "اَلْسّودان" , meaning = "Sudan" } , { latin = "yabda2" , kana = "ヤブダ" , arabic = "يَبْدَأ" , meaning = "he begins" } , { latin = "shaadii l-mu3al-lim" , kana = "シャーディー ル ムアッリム" , arabic = "شادي المُعَلِّم" , meaning = "Shadi the teacher" } , { latin = "mahaa l-mutarjima" , kana = "マハー ル ムタルジマ" , arabic = "مَها المُتَرجِمة" , meaning = "Maha the translator" } , { latin = "fi l-bayt" , kana = "フィルバイト" , arabic = "في البَيت" , meaning = "in the house" } , { latin = "fi s-sayyaara" , kana = "フィッサイヤーラ" , arabic = "في السيارة" , meaning = "in the car" } , { latin = "2iDaafa" , kana = "イダーファ" , arabic = "إضافة" , meaning = "iDaafa, addition" } , { latin = "2aftaH" , kana = "アフタハ" , arabic = "أَفْتَح" , meaning = "I open" } , { latin = "tuHibb" , kana = "トゥヒッブ" , arabic = "تُحِبّ" , meaning = "you like (to a male), she likes" } , { latin = "tuHibbiin" , kana = "トゥヒッビーン" , arabic = "تُحِبّين" , meaning = "you like (to a female)" } , { latin = "yuHibb" , kana = "ユヒッブ" , arabic = "يُحِبّ" , meaning = "he likes" } , { latin = "tanaam" , kana = "タナーム" , arabic = "تَنام" , meaning = "you sleep (to a male), she sleeps" } , { latin = "tanaamiin" , kana = "タナーミーン" , arabic = "تَنامين" , meaning = "you sleep (to a female)" } , { latin = "yaanaam" , kana = "ヤナーム" , arabic = "يَنام" , meaning = "he sleeps" } , { latin = "haadhihi l-madiina laa tanaam" , kana = "ハージヒ ルマディーナ ラー タナーム" , arabic = "هٰذِهِ ٲلْمَدينة لا تَنام" , meaning = "This city does not sleep." } , { latin = "maa ra2yik" , kana = "マー ラ イイク" , arabic = "ما رَأْيِك؟" , meaning = "What do you think? (Literally: What is your opinion?)" } , { latin = "maadhaa tuHib-biin" , kana = "マーザー トゥヒッビーン" , arabic = "ماذا تُحِبّين؟" , meaning = "What do you like?" } , { latin = "maadhaa 2adrus" , kana = "マーザー アドルス" , arabic = "ماذا أَدْرُس؟" , meaning = "What do I study?" } , { latin = "as-saa3at ath-thaanya" , kana = "アッサーアト アッサーニア" , arabic = "اَلْسّاعة الْثّانْية" , meaning = "the second hour" } , { latin = "as-saa3at ath-thaalitha" , kana = "アッサーアト アッサーリサ" , arabic = "اَلْسّاعة الْثّالِثة" , meaning = "the third hour" } , { latin = "as-saa3at ar-raabi3a" , kana = "アッサーアト アッラービア" , arabic = "اَلْسّاعة الْرّابِعة" , meaning = "the fourth hour" } , { latin = "as-saa3at l-khaamisa" , kana = "アッサーアト ル クハーミサ" , arabic = "اَلْسّاعة الْخامِسة" , meaning = "the fifth hour" } , { latin = "as-saa3at as-saadisa" , kana = "アッサーアト アッサーディサ" , arabic = "اَلْسّاعة الْسّادِسة" , meaning = "the sixth hour" } , { latin = "as-saa3at as-saabi3a" , kana = "アッサーアト アッサービア" , arabic = "اَلْسّاعة الْسّابِعة" , meaning = "the seventh hour" } , { latin = "as-saa3at ath-thaamina" , kana = "アッサーアト アッサーミナ" , arabic = "اَلْسّاعة الْثّامِنة" , meaning = "the eighth hour" } , { latin = "as-saa3at at-taasi3a" , kana = "アッサーアト アッタースィア" , arabic = "اَلْسّاعة الْتّاسِعة" , meaning = "the ninth hour" } , { latin = "as-saa3at l-3aashira" , kana = "アッサーアト ル アーシラ" , arabic = "اَلْسّاعة الْعاشِرة" , meaning = "the tenth hour" } , { latin = "as-saa3at l-Haadya 3ashara" , kana = "アッサーアト ル ハーディヤ アシャラ" , arabic = "اَلْسّاعة الْحادْية عَشَرة" , meaning = "the eleventh hour" } , { latin = "as-saa3ag ath-thaanya 3ashara" , kana = "アッサーアト アッサーニヤ アシャラ" , arabic = "اَلْسّاعة الْثّانْية عَشَرة" , meaning = "the twelfth hour" } , { latin = "as-saa3at l-waaHida" , kana = "アッサーアト ル ワーヒダ" , arabic = "اَلْسّاعة الْواحِدة" , meaning = "the hour one" } , { latin = "as-saa3at ath-thaanya ba3d a-Dh-Dhuhr" , kana = "アッサーアト アッサーニヤ バァダ ッズホル" , arabic = "اَلْسّاعة الْثّانْية بَعْد اَلْظُّهْر" , meaning = "two o'clock in the afternon" } , { latin = "2anaa min lubanaan" , kana = "アナー ミン ルブナーン" , arabic = "أنا من لبنان" , meaning = "I am from Lebanon." } , { latin = "lastu min lubnaan" , kana = "ラストゥ ミン ルブナーン" , arabic = "لَسْتُ من لبنان" , meaning = "" } , { latin = "lastu mariiDa" , kana = "ラストゥ マリーダ" , arabic = "لَسْتُ مَريضة" , meaning = "I am not sick." } , { latin = "lastu fi l-bayt" , kana = "ラストゥ フィル バイト" , arabic = "لَسْتُ في الْبَيْت" , meaning = "I am not home." } , { latin = "lastu min hunaa" , kana = "ラストゥ ミン フゥナー" , arabic = "لَسْتُ مِن هُنا" , meaning = "I am not form here." } , { latin = "qarya" , kana = "かりヤー" , arabic = "قَرية" , meaning = "a village" } , { latin = "sahl" , kana = "サヘル" , arabic = "سَهل" , meaning = "easy" } , { latin = "a-T-Tabii3a" , kana = "アッタビーア" , arabic = "الطَّبيعة" , meaning = "nature" } , { latin = "fii 2ayy saa3a" , kana = "フィー アイイ サーア" , arabic = "في أي ساعة" , meaning = "at which hour, when" } , { latin = "al-iskandariyya" , kana = "アル イスカンダリーヤ" , arabic = "الاِسكَندَرِيّة" , meaning = "Alexandria in Egypt" } , { latin = "2ayna l-maHaT-Ta" , kana = "アイナ ル マハッタ" , arabic = "أَينَ المَحَطّة" , meaning = "Where is the station?" } , { latin = "3aDhiim jiddan" , kana = "アジーム ジッダン" , arabic = "عَظيم جِدّاً" , meaning = "Fantastic! Great!" } , { latin = "thalaatha mar-raat fi l-2usbuu3" , kana = "サラーサ マッラート フィル ウスブーア" , arabic = "ثَلاثَ مَرّات في الأُسبوع" , meaning = "three times a week" } , { latin = "2asaatidha" , kana = "アサーティザ" , arabic = "أَساتِذة" , meaning = "masters, professors" } , { latin = "2ikhwa" , kana = "イクフワ" , arabic = "إِخْوة" , meaning = "brothers" } , { latin = "Suura jamiila" , kana = "スーラ ジャミーラ" , arabic = "صورة جَميلة" , meaning = "beautiful picture" } , { latin = "al-Hkuuma l-2amriikiya" , kana = "アル フクーマ ル アムリーキーヤ" , arabic = "الحْكومة الأَمريكية" , meaning = "the American government" } , { latin = "HaDaara qadiima" , kana = "ハダーラ カディーマ" , arabic = "حَضارة قَديمة" , meaning = "old civilization" } , { latin = "Salaat" , kana = "サラート" , arabic = "صَلاة" , meaning = "prayer, worship" } , { latin = "zakaat" , kana = "ザカート" , arabic = "زَكاة" , meaning = "alms" } , { latin = "Hayaat" , kana = "ハヤート" , arabic = "حَياة" , meaning = "life" } , { latin = "ghurfat bintii" , kana = "グルファト ビンティー" , arabic = "غُرفة بِنتي" , meaning = "my daughter's room" } , { latin = "madiinat nyuuyuurk" , kana = "マディーナト ニューユールク" , arabic = "مَدينة نيويورك" , meaning = "city of New York" } , { latin = "sharika" , kana = "シャリカ" , arabic = "شَرِكة" , meaning = "a company" } , { latin = "sharikat khaalii" , kana = "シャリカト クハーリー" , arabic = "شَرِكة خالي" , meaning = "my uncle's company" } , { latin = "madrasatii" , kana = "マドラサティー" , arabic = "مَدرَسَتي" , meaning = "my school" } , { latin = "3alaaqatnaa" , kana = "アラーカトナー" , arabic = "عَلاقَتنا" , meaning = "our relationship" } , { latin = "shuhra" , kana = "シュフラ" , arabic = "شُهرة" , meaning = "fame" } , { latin = "shufrathu" , kana = "シュフラトフ" , arabic = "شُهرَته" , meaning = "his fame" } , { latin = "naz-zlnii hunaa" , kana = "ナッズィルニー フゥナー" , arabic = "نَزِّلني هنا" , meaning = "Download me here." } , { latin = "3alaa mahlika" , kana = "アラー マハリカ" , arabic = "عَلى مَهلِكَ" , meaning = "Slow down. Take it easy." } , { latin = "laysa kul-la yawm" , kana = "ライサ クッラ ヤウム" , arabic = "اَيْسَ كُلَّ يَوم" , meaning = "not every day" } , { latin = "kul-l l-naas" , kana = "クッル ル ナース" , arabic = "كُلّ الناس" , meaning = "all the people" } , { latin = "kul-l l-2awlaad" , kana = "クッル ル アウラード" , arabic = "كُلّ الأَولاد" , meaning = "all the boys, children" } , { latin = "mayk" , kana = "マイク" , arabic = "مايْك" , meaning = "Mike" } , { latin = "bikam haadhaa" , kana = "ビカム ハーザー" , arabic = "بِكَم هَذا" , meaning = "How much is this?" } , { latin = "dimashq" , kana = "ディマシュク" , arabic = "دِمَشق" , meaning = "Damascus" } , { latin = "2in shaa2a l-laa" , kana = "インシャーアッラー" , arabic = "إِن شاءَ اللَّه" , meaning = "on God's will" } , { latin = "yal-laa" , kana = "ヤッラー" , arabic = "يَلّا" , meaning = "alright" } , { latin = "3aailatii" , kana = "アーイラティー" , arabic = "عائلَتي" , meaning = "my family" } , { latin = "akhbaar" , kana = "アクフバール" , arabic = "أَخبار" , meaning = "news" } , { latin = "tadrsiin" , kana = "タドルスィーン" , arabic = "تَدرسين" , meaning = "you study" } , { latin = "3ilm al-Haasuub" , kana = "アイルム アル ハースーブ" , arabic = "عِلم الحاسوب" , meaning = "computer sicence" } , { latin = "muSawwir" , kana = "ムサウィル" , arabic = "مُصَوِّر" , meaning = "photographer" } , { latin = "laa 2uHib-b-hu" , kana = "ラー ウひッブフ" , arabic = "لا أُحِبّهُ" , meaning = "I do not love him." } , { latin = "ta3mal" , kana = "タアマル" , arabic = "نَعمَل" , meaning = "You work, we work" } , { latin = "2aakhar" , kana = "アークハル" , arabic = "آخَر" , meaning = "else, another, other than this" } , { latin = "lawn 2aakhar" , kana = "ラウン アークハル" , arabic = "لَوت آخَر" , meaning = "another lot, color" } , { latin = "rabba bayt" , kana = "ラッババイト" , arabic = "رَبّة بَيت" , meaning = "homemaker, housewife" } , { latin = "baaHith" , kana = "バーヒス" , arabic = "باحِث" , meaning = "a researcher" } , { latin = "last jaw3aana" , kana = "ラスト ジャウあーナ" , arabic = "لَسْت جَوعانة" , meaning = "I am not hungry." } , { latin = "hal juudii mutafarrigha" , kana = "ハル ジューディー ムタファルリガ" , arabic = "هَل جودي مُتَفَرِّغة؟" , meaning = "Is Judy free?" } , { latin = "nuuSf" , kana = "ヌースフ" , arabic = "نُّصْف" , meaning = "half" } , { latin = "fiilm 2aflaam" , kana = "フィールム アフラーム" , arabic = "فيلم ـ أَفلام" , meaning = "film - films" } , { latin = "dars duruus" , kana = "ダルス ドゥルース" , arabic = "دَرس ـ دُروس" , meaning = "lesson - lessons" } , { latin = "risaala - rasaa2il" , kana = "りサーラ らサーイル" , arabic = "رِسالة - رَسائِل" , meaning = "letter - letters" } , { latin = "qariib - 2aqaarib" , kana = "カリーブ アカーリブ" , arabic = "قَريب - أَقارِب" , meaning = "relative - relatives" } , { latin = "Sadiiq - 2aSdiqaa2" , kana = "サディーク アスディカー" , arabic = "صَديق - أَصْذِقاء" , meaning = "friend - friends" } , { latin = "kitaab - kutub" , kana = "キターブ クトゥブ" , arabic = "كِتاب - كُتُب" , meaning = "book - books" } , { latin = "lugha - lughaat" , kana = "ルガ ルガート" , arabic = "لُغة - لُغات" , meaning = "language - languages" } , { latin = "tuHibb al-kitaaba" , kana = "トゥヒッブ アルキターバ" , arabic = "تُحِبّ اَلْكِتابة" , meaning = "She likes writing." } , { latin = "kitaabat ar-rasaa2il mumti3a" , kana = "キターバト アッラサーイル ムムティア" , arabic = "كِتابة اَلْرَّسائِل مُمْتِعة" , meaning = "Writing of the letters is fun." } , { latin = "HaaDr siidii" , kana = "ハードル スィーディー" , arabic = "حاضر سيدي" , meaning = "Yes, sir." } , { latin = "waqt" , kana = "ワクト" , arabic = "وَقت" , meaning = "time" } , { latin = "risaala" , kana = "リサーラ" , arabic = "رِسالة" , meaning = "letter" } , { latin = "fann" , kana = "ファン" , arabic = "فَنّ" , meaning = "art" } , { latin = "Haziin" , kana = "ハズィーン" , arabic = "حَزين" , meaning = "sad" } , { latin = "3aa2ila" , kana = "アーイラ" , arabic = "عائِلة" , meaning = "family" } , { latin = "2uHibb qiraa2at al-kutub" , kana = "ウひッブ キラーアト アルクトゥブ" , arabic = "أُحِبّ قِراءة اَلْكُتُب" , meaning = "I like reading of the books." } , { latin = "2uHibb al-qiraa2a" , kana = "ウひッブ アルキラーエ" , arabic = "أُحِبّ اَلْقِراءة" , meaning = "I like the reading." } , { latin = "al-kitaaba mumti3a" , kana = "アルキターバ ムムティア" , arabic = "اَلْكِتابة مُمْتِعة" , meaning = "The writing is fun." } , { latin = "kura l-qadam" , kana = "クーラルカダム" , arabic = "كُرة اَلْقَدَم" , meaning = "soccer" } , { latin = "2uHibb ad-dajaaj min 2ams" , kana = "ウひッブ アッダジャージ ミン アムス" , arabic = "أُحِبّ اَلْدَّجاج مِن أَمْس" , meaning = "I like the chicken from yesterday." } , { latin = "2uHibb ad-dajaaj" , kana = "ウひッブ アッダジャージ" , arabic = "أُحِبّ اَلْدَّجاج" , meaning = "I like chicken." } , { latin = "2uHibb al-qawha" , kana = "ウひッブ アルかハワ" , arabic = "أُحِبّ اَلْقَهْوة" , meaning = "I like coffee." } , { latin = "2uriid dajaajan" , kana = "ウりード ダジャージャン" , arabic = "أُريد دَجاجاً" , meaning = "I want chicken." } , { latin = "2uriid qahwa" , kana = "ウりード かハワ" , arabic = "أُريد قَهْوة" , meaning = "I want coffee." } , { latin = "2aakul dajaajan" , kana = "アークル ダジャージャン" , arabic = "آكُل دَجاجاً" , meaning = "I eat chicken." } , { latin = "2ashrab qahwa kul-l SabaaH" , kana = "アシュらブ かハワ クッル さバーは" , arabic = "أَشْرَب قَهْوة كُلّ صَباح" , meaning = "I drink coffee every morning." } , { latin = "2uriid Sadiiqan" , kana = "ウりード すぁディーかン" , arabic = "أُريد صَديقاً" , meaning = "I want a friend." } , { latin = "2aakul khubzan" , kana = "アークル クフブザン" , arabic = "آكُل خُبْزاً" , meaning = "I eat bread." } , { latin = "2uriid baytan jadiidan" , kana = "ウりード バイタン ジャディーダン" , arabic = "أُريد بَيْتاً جَديداً" , meaning = "I want a new house." } , { latin = "matHaf" , kana = "マトはフ" , arabic = "مَتحَف" , meaning = "a museum" } , { latin = "laHm" , kana = "ラハム" , arabic = "لَحْم" , meaning = "meat" } , { latin = "baTaaTaa" , kana = "バターター" , arabic = "بَطاطا" , meaning = "potato" } , { latin = "yashrab al-Haliib" , kana = "ヤシュらブ アルハリーブ" , arabic = "يَشْرَب الحَليب" , meaning = "He drinks milk" } , { latin = "al-muqab-bilaat" , kana = "アルムカッビラート" , arabic = "المُقَبِّلات" , meaning = "appetizers" } , { latin = "Hummusan" , kana = "フンムサン" , arabic = "حُمُّصاً" , meaning = "chickpeas, hummus" } , { latin = "SaHiiH" , kana = "サヒーハ" , arabic = "صَحيح" , meaning = "true, right, correct" } , { latin = "3aSiir" , kana = "アアスィーる" , arabic = "عَصير" , meaning = "juice" } , { latin = "shuurba" , kana = "シューるバ" , arabic = "شورْبة" , meaning = "soupe" } , { latin = "salaTa" , kana = "サラタ" , arabic = "سَلَطة" , meaning = "salad" } , { latin = "s-saakhin" , kana = "ッサークヒン" , arabic = "سّاخِن" , meaning = "hot, warm" } , { latin = "Halwaa" , kana = "はルワー" , arabic = "حَلْوى" , meaning = "candy, dessert" } , { latin = "kib-ba" , kana = "キッバ" , arabic = "كِبّة" , meaning = "kibbeh" } , { latin = "a-T-Tabaq" , kana = "アッタバク" , arabic = "الطَّبّق" , meaning = "the plate, dish" } , { latin = "Tabaq" , kana = "タバク" , arabic = "طّبّق" , meaning = "plate, dish" } , { latin = "2aina 2antum" , kana = "アイナアントム" , arabic = "أَيْن أَنْتُم" , meaning = "Where are you?" } , { latin = "baaS" , kana = "バーすぅ" , arabic = "باص" , meaning = "bus" } , { latin = "tadhkara" , kana = "たずカら" , arabic = "تَذْكَرة" , meaning = "a ticket" } , { latin = "Saff" , kana = "すぁッフ" , arabic = "صَفّ" , meaning = "class" } , { latin = "qiTaar" , kana = "きたーる" , arabic = "قِطار" , meaning = "train" } , { latin = "khuDraawaat" , kana = "クフどらーワート" , arabic = "خُضْراوات" , meaning = "vegetables" } , { latin = "Taazij" , kana = "たーズィジ" , arabic = "طازِج" , meaning = "fresh" } , { latin = "laa 2ashtarii qahwa" , kana = "ラー アシュタりー かハワ" , arabic = "لا أَشْتَري قَهْوة" , meaning = "I do not buy coffee." } , { latin = "faakiha" , kana = "ファーキハ" , arabic = "فاكِهة" , meaning = "fruit" } , { latin = "yufaD-Dil" , kana = "ユファッでぃル" , arabic = "يُفَضِّل" , meaning = "he prefers" } , { latin = "tufaD-Dil" , kana = "トゥファッでぃル" , arabic = "تُفَضِّل" , meaning = "you prefer" } , { latin = "al-banaduura" , kana = "アルバナドゥーら" , arabic = "البَنَدورة" , meaning = "the tomato" } , { latin = "banaduura" , kana = "バナドゥーら" , arabic = "بَنَدورة" , meaning = "tomato" } , { latin = "limaadhaa" , kana = "リマーざー" , arabic = "لِماذا" , meaning = "Why?" } , { latin = "maw3id" , kana = "マウあイド" , arabic = "مَوْعِد" , meaning = "an appointment" } , { latin = "lam" , kana = "ラム" , arabic = "لَم" , meaning = "did not" } , { latin = "yasmaH" , kana = "ヤスマは" , arabic = "يَسْمَح" , meaning = "allow, permit" } , { latin = "khuruuj" , kana = "クフルージ" , arabic = "خُروج" , meaning = "exit, get out" } , { latin = "laa ya2atii" , kana = "ラー ヤアティー" , arabic = "لا يَأْتي" , meaning = "he does not come" } , { latin = "khaTiib" , kana = "クハてぃーブ" , arabic = "خَطيب" , meaning = "fiance" } , { latin = "2abadan" , kana = "アバダン" , arabic = "أَبَدا" , meaning = "never again" } , { latin = "2arkab T-Taa2ira" , kana = "アルカブ ッたーイら" , arabic = "أَرْكَب الطائرة" , meaning = "I ride the plane" } , { latin = "2a3uud" , kana = "アあぅード" , arabic = "أَعود" , meaning = "I come back, return" } , { latin = "maa saafart" , kana = "マー サーファるト" , arabic = "ما سافَرْت" , meaning = "I have not traveled" } , { latin = "li2an-nak" , kana = "リアンナク" , arabic = "لِأَنَّك" , meaning = "because you are" } , { latin = "al-2akl a-S-S-H-Hiyy" , kana = "アルアクル ッすぃひーユ" , arabic = "الأَكل الصِّحِّي" , meaning = "the healthy food" } , { latin = "yajib 2an" , kana = "ヤジブ アン" , arabic = "يَجِب أَن" , meaning = "must" } , { latin = "tashtarii" , kana = "タシュタりー" , arabic = "تَشْتَري" , meaning = "you buy" } , { latin = "baamiya" , kana = "バーミヤ" , arabic = "بامية" , meaning = "squash, zucchini, pumpkin, okra" } , { latin = "kuusaa" , kana = "クーサー" , arabic = "كوسا" , meaning = "zucchini" } , { latin = "Taazij" , kana = "たーズィジ" , arabic = "طازِج" , meaning = "fresh" } , { latin = "jazar" , kana = "ジャザる" , arabic = "جَزَر" , meaning = "carrots" } , { latin = "SiH-Hiya" , kana = "すぃッひーヤ" , arabic = "صِحِّية" , meaning = "healthy" } , { latin = "a2ashtarii" , kana = "アシュタりー" , arabic = "أَشْتَري" , meaning = "I buy" } , { latin = "tashtarii" , kana = "タシュタりー" , arabic = "تَشْتَري" , meaning = "you buy (to a male), she buys" } , { latin = "tashtariin" , kana = "タシュタりーン" , arabic = "تَشْتَرين" , meaning = "you buy (to a female)" } , { latin = "yashtarii" , kana = "ヤシュタりー" , arabic = "يَشْتَري" , meaning = "he buys" } , { latin = "nashtarii" , kana = "ナシュタりー" , arabic = "نَشْتَري" , meaning = "we buy" } , { latin = "tashtaruun" , kana = "タシュタるーン" , arabic = "تَشْتَرون" , meaning = "you all buy, they buy" } , { latin = "li2an-na l-3aalam ghariib" , kana = "リアンナ ルあーラム ガりーブ" , arabic = "لِأَنَّ ٱلْعالَم غَريب" , meaning = "Because the world is weird." } , { latin = "li2anna 2ukhtii tadhrus kPI:NAME:<NAME>END_PI" , kana = "リアンナ ウクフティー タずるス カしーラン" , arabic = "لِأَنَّ أُخْتي تَذْرُس كَثيراً" , meaning = "Because my sister studies a lot." } , { latin = "li2an-nanii min misr" , kana = "リアンナニー ミン ミスる" , arabic = "لِأَنَّني مِن مِصر" , meaning = "Because I am from Egypt." } , { latin = "li2an-nik 2um-mii" , kana = "リアンニク ウムミー" , arabic = "لِأَنِّك أُمّي" , meaning = "Because you are my mother." } , { latin = "li2an-ni-haa mu3al-lma mumtaaza" , kana = "リアンナハー ムあッリマ ムムターザ" , arabic = "لِأَنَّها مُعَلِّمة مُمْتازة" , meaning = "Because she is an amazing teacher." } , { latin = "li-2an-na-hu sa3iid" , kana = "リアンナフゥ サあイード" , arabic = "لِأَنَّهُ سَعيد" , meaning = "Because he is happy." } , { latin = "li-2abii" , kana = "リアビー" , arabic = "لِأَبي" , meaning = "to/for my father" } , { latin = "li-haadhihi l-2ustaadha" , kana = "リハーじヒ ル ウスターざ" , arabic = "لِهٰذِهِ الْأُسْتاذة" , meaning = "to/for this professor" } , { latin = "li-bayruut" , kana = "リバイるート" , arabic = "لِبَيْروت" , meaning = "to/for Beirut" } , { latin = "li-l-bint" , kana = "リルビント" , arabic = "لِلْبِنْت" , meaning = "to/for the girl" } , { latin = "li-l-2ustaadha" , kana = "リルウスターざ" , arabic = "لِلْأُسْتاذة" , meaning = "to/for the professor" } , { latin = "li-l-qaahira" , kana = "リルかーヒら" , arabic = "لِلْقاهِرة" , meaning = "to/for Cairo" } , { latin = "al-maHal-l maHal-laka yaa 2ustaadh" , kana = "アルマはッル マはッラカ ヤー ウスターず" , arabic = "اَلْمَحَلّ مَحَلَّك يا أُسْتاذ!" , meaning = "The shop is your shop, sir." } , { latin = "hal turiid al-qaliil min al-maa2" , kana = "ハル トゥりード イル かリール ミナル マー" , arabic = "هَل تُريد اَلْقَليل مِن اَلْماء؟" , meaning = "Do you want a little water?" } , { latin = "3aada" , kana = "あーダ" , arabic = "عادة" , meaning = "usually" } , { latin = "ka3k" , kana = "カあク" , arabic = "كَعْك" , meaning = "cakes" } , { latin = "a2ashrab" , kana = "アシュらブ" , arabic = "أَشْرَب" , meaning = "I drink" } , { latin = "sa-2ashrab" , kana = "サ アシュらブ" , arabic = "سَأَشْرَب" , meaning = "I will drink" } , { latin = "tashrab" , kana = "タシュらブ" , arabic = "تَشْرَب" , meaning = "you drink (to a male), she drinks" } , { latin = "tashrabiin" , kana = "タシュらビーン" , arabic = "تَشْرَبين" , meaning = "you drink (to a female)" } , { latin = "yashrab" , kana = "ヤシュらブ" , arabic = "يَشْرَب" , meaning = "he drinks" } ]
elm
[ { "context": "rg\" <|\n \\() ->\n \"--name=Picard\"\n |> EqualsSplitter.split\n ", "end": 814, "score": 0.9974803925, "start": 808, "tag": "NAME", "value": "Picard" }, { "context": " { name = \"name\", value = \"Picard\" }\n )\n ]\n", "end": 1007, "score": 0.9983922243, "start": 1001, "tag": "NAME", "value": "Picard" } ]
tests/Tokenizer/EqualsSplitterTests.elm
harrysarson/elm-cli-options-parser
47
module Tokenizer.EqualsSplitterTests exposing (all) import Expect exposing (Expectation) import Test exposing (..) import Tokenizer.EqualsSplitter as EqualsSplitter type Msg = Help | Version | OpenUrl String | OpenUrlWithFlag String Bool | Name String | FullName String String all : Test all = describe "equals splitter" [ test "not option" <| \() -> "operand" |> EqualsSplitter.split |> Expect.equal EqualsSplitter.NotOption , test "option without arg" <| \() -> "--name" |> EqualsSplitter.split |> Expect.equal (EqualsSplitter.Option "name") , test "option with arg" <| \() -> "--name=Picard" |> EqualsSplitter.split |> Expect.equal (EqualsSplitter.KeywordArg { name = "name", value = "Picard" } ) ]
13191
module Tokenizer.EqualsSplitterTests exposing (all) import Expect exposing (Expectation) import Test exposing (..) import Tokenizer.EqualsSplitter as EqualsSplitter type Msg = Help | Version | OpenUrl String | OpenUrlWithFlag String Bool | Name String | FullName String String all : Test all = describe "equals splitter" [ test "not option" <| \() -> "operand" |> EqualsSplitter.split |> Expect.equal EqualsSplitter.NotOption , test "option without arg" <| \() -> "--name" |> EqualsSplitter.split |> Expect.equal (EqualsSplitter.Option "name") , test "option with arg" <| \() -> "--name=<NAME>" |> EqualsSplitter.split |> Expect.equal (EqualsSplitter.KeywordArg { name = "name", value = "<NAME>" } ) ]
true
module Tokenizer.EqualsSplitterTests exposing (all) import Expect exposing (Expectation) import Test exposing (..) import Tokenizer.EqualsSplitter as EqualsSplitter type Msg = Help | Version | OpenUrl String | OpenUrlWithFlag String Bool | Name String | FullName String String all : Test all = describe "equals splitter" [ test "not option" <| \() -> "operand" |> EqualsSplitter.split |> Expect.equal EqualsSplitter.NotOption , test "option without arg" <| \() -> "--name" |> EqualsSplitter.split |> Expect.equal (EqualsSplitter.Option "name") , test "option with arg" <| \() -> "--name=PI:NAME:<NAME>END_PI" |> EqualsSplitter.split |> Expect.equal (EqualsSplitter.KeywordArg { name = "name", value = "PI:NAME:<NAME>END_PI" } ) ]
elm
[ { "context": "ook\", text \"▷\" ], url = \"https://www.facebook.com/RockogRull/\" }\n ]\n , el [] none\n\n ", "end": 3183, "score": 0.9997344017, "start": 3173, "tag": "USERNAME", "value": "RockogRull" }, { "context": " centerX ] { label = row [ UI.mSpacing ] [ text \"Meld interesse\", text \"▷\" ], url = \"mailto:booking@rønsenrock.no", "end": 4148, "score": 0.7225198746, "start": 4135, "tag": "NAME", "value": "eld interesse" }, { "context": " text \"Meld interesse\", text \"▷\" ], url = \"mailto:booking@rønsenrock.no\" }\n -- ]\n -- , el [ centerX", "end": 4198, "score": 0.999927938, "start": 4177, "tag": "EMAIL", "value": "booking@rønsenrock.no" } ]
src/Page/Landing.elm
hanshenrik/ronsenrock
1
module Page.Landing exposing (view) import Color import Countdown import Element exposing (..) import Element.Background as Background import Element.Border as Border import Element.Font as Font import Html.Attributes import Type.Window exposing (Window) import UI view : { a | window : Window, time : Int } -> Element msg view { window, time } = let deviceClass = (classifyDevice window).class ( ( logoSize, dividerImageSize ), ( responsivePadding, dateHeading ) ) = case deviceClass of Phone -> ( ( 300, 300 ), ( UI.lPadding, UI.h2 ) ) BigDesktop -> ( ( 700, 1000 ), ( UI.xxlPadding, UI.h1 ) ) _ -> ( ( 600, 600 ), ( UI.xxlPadding, UI.h1 ) ) in column [ UI.fillWidth, centerY, UI.xxlSpacing, paddingEach { top = 4 * 9, right = 0, bottom = 0, left = 0 } ] [ column [ UI.sSpacing, centerX ] [ -- el [ centerX ] <| dateHeading [ Font.color Color.yellow, htmlAttribute <| Html.Attributes.style "transform" "rotate(-10deg)" ] <| text "2. – 5. juli", image [ centerX , centerY , height <| px <| round <| logoSize / 1.5 , width <| px logoSize , UI.class "shake" ] { src = "/images/logo-2020-mm-transparent.png", description = "Logo" } ] , column [ centerX, UI.mPadding, UI.xsSpacing ] [ el [ centerX ] <| column [ Font.center, centerX, UI.mSpacing, UI.lPadding, Background.color Color.lightYellow, Font.color Color.black, UI.sRoundedCorners ] [ UI.p <| text "RønsenROCK 2021 er dessverre også avlyst på grunn av koronasituasjonen 💔" ] , el [ centerX, Font.center, UI.lPadding ] <| UI.p <| text "Men! Vi håper vi sees på RønsenROCK 2022 om ca. …" ] , el [ centerX ] <| Countdown.view window time , el [ UI.fillWidth, height <| px dividerImageSize, Background.image "/images/tak-2019-tk.jpg" ] none , el (centerX :: (case deviceClass of Phone -> [ UI.sPadding ] _ -> [] ) ) <| el [ UI.mPadding ] <| column (Font.center :: UI.lSpacing :: responsivePadding :: UI.boxed ) [ column [ UI.mSpacing ] [ paragraph [ Font.center, UI.fillWidth ] [ UI.h3 [] <| text "Få oppdateringer på Facebook" ] , paragraph [ Font.center ] [ text "Ikke gå glipp av nyheter om neste års festival – lik Rønsenrock festivallag på Facebook." ] ] , UI.buttonLink [ UI.class "hoverable", centerX ] { label = row [ UI.mSpacing, UI.mPadding ] [ text "Til Facebook", text "▷" ], url = "https://www.facebook.com/RockogRull/" } ] , el [] none -- , el -- (centerX -- :: (case deviceClass of -- Phone -> -- [ UI.sPadding ] -- _ -> -- [] -- ) -- ) -- <| -- column -- (Font.center -- :: UI.lSpacing -- :: responsivePadding -- :: UI.boxed -- ) -- [ column [ UI.mSpacing ] -- [ paragraph [ Font.center, UI.fillWidth ] [ UI.h3 [] <| text "Spille på RønsenROCK 2020?" ] -- , paragraph [ Font.center ] -- [ text "Vi tar i mot henvendelser frem til mars." ] -- ] -- , UI.buttonLink [ UI.class "hoverable", centerX ] { label = row [ UI.mSpacing ] [ text "Meld interesse", text "▷" ], url = "mailto:booking@rønsenrock.no" } -- ] -- , el [ centerX, width <| px 200 ] <| UI.horisontalDivider -- , el [ centerX ] <| -- html <| -- Html.iframe -- [ Html.Attributes.src "https://open.spotify.com/embed/user/1113006308/playlist/6FfNqW0AcFkrhlUaDfqfpD?si=S36Q1tleRB6w5MYvFWtS2g" -- , Html.Attributes.style "border" "none" -- , Html.Attributes.style "height" "400px" -- , Html.Attributes.style "width" "600px" -- , Html.Attributes.style "max-width" "100%" -- , Html.Attributes.style "border-radius" "4px" -- ] -- [] , el [ UI.fillWidth, height <| px dividerImageSize, Background.image "/images/chill-2018.jpg" ] none ]
42054
module Page.Landing exposing (view) import Color import Countdown import Element exposing (..) import Element.Background as Background import Element.Border as Border import Element.Font as Font import Html.Attributes import Type.Window exposing (Window) import UI view : { a | window : Window, time : Int } -> Element msg view { window, time } = let deviceClass = (classifyDevice window).class ( ( logoSize, dividerImageSize ), ( responsivePadding, dateHeading ) ) = case deviceClass of Phone -> ( ( 300, 300 ), ( UI.lPadding, UI.h2 ) ) BigDesktop -> ( ( 700, 1000 ), ( UI.xxlPadding, UI.h1 ) ) _ -> ( ( 600, 600 ), ( UI.xxlPadding, UI.h1 ) ) in column [ UI.fillWidth, centerY, UI.xxlSpacing, paddingEach { top = 4 * 9, right = 0, bottom = 0, left = 0 } ] [ column [ UI.sSpacing, centerX ] [ -- el [ centerX ] <| dateHeading [ Font.color Color.yellow, htmlAttribute <| Html.Attributes.style "transform" "rotate(-10deg)" ] <| text "2. – 5. juli", image [ centerX , centerY , height <| px <| round <| logoSize / 1.5 , width <| px logoSize , UI.class "shake" ] { src = "/images/logo-2020-mm-transparent.png", description = "Logo" } ] , column [ centerX, UI.mPadding, UI.xsSpacing ] [ el [ centerX ] <| column [ Font.center, centerX, UI.mSpacing, UI.lPadding, Background.color Color.lightYellow, Font.color Color.black, UI.sRoundedCorners ] [ UI.p <| text "RønsenROCK 2021 er dessverre også avlyst på grunn av koronasituasjonen 💔" ] , el [ centerX, Font.center, UI.lPadding ] <| UI.p <| text "Men! Vi håper vi sees på RønsenROCK 2022 om ca. …" ] , el [ centerX ] <| Countdown.view window time , el [ UI.fillWidth, height <| px dividerImageSize, Background.image "/images/tak-2019-tk.jpg" ] none , el (centerX :: (case deviceClass of Phone -> [ UI.sPadding ] _ -> [] ) ) <| el [ UI.mPadding ] <| column (Font.center :: UI.lSpacing :: responsivePadding :: UI.boxed ) [ column [ UI.mSpacing ] [ paragraph [ Font.center, UI.fillWidth ] [ UI.h3 [] <| text "Få oppdateringer på Facebook" ] , paragraph [ Font.center ] [ text "Ikke gå glipp av nyheter om neste års festival – lik Rønsenrock festivallag på Facebook." ] ] , UI.buttonLink [ UI.class "hoverable", centerX ] { label = row [ UI.mSpacing, UI.mPadding ] [ text "Til Facebook", text "▷" ], url = "https://www.facebook.com/RockogRull/" } ] , el [] none -- , el -- (centerX -- :: (case deviceClass of -- Phone -> -- [ UI.sPadding ] -- _ -> -- [] -- ) -- ) -- <| -- column -- (Font.center -- :: UI.lSpacing -- :: responsivePadding -- :: UI.boxed -- ) -- [ column [ UI.mSpacing ] -- [ paragraph [ Font.center, UI.fillWidth ] [ UI.h3 [] <| text "Spille på RønsenROCK 2020?" ] -- , paragraph [ Font.center ] -- [ text "Vi tar i mot henvendelser frem til mars." ] -- ] -- , UI.buttonLink [ UI.class "hoverable", centerX ] { label = row [ UI.mSpacing ] [ text "M<NAME>", text "▷" ], url = "mailto:<EMAIL>" } -- ] -- , el [ centerX, width <| px 200 ] <| UI.horisontalDivider -- , el [ centerX ] <| -- html <| -- Html.iframe -- [ Html.Attributes.src "https://open.spotify.com/embed/user/1113006308/playlist/6FfNqW0AcFkrhlUaDfqfpD?si=S36Q1tleRB6w5MYvFWtS2g" -- , Html.Attributes.style "border" "none" -- , Html.Attributes.style "height" "400px" -- , Html.Attributes.style "width" "600px" -- , Html.Attributes.style "max-width" "100%" -- , Html.Attributes.style "border-radius" "4px" -- ] -- [] , el [ UI.fillWidth, height <| px dividerImageSize, Background.image "/images/chill-2018.jpg" ] none ]
true
module Page.Landing exposing (view) import Color import Countdown import Element exposing (..) import Element.Background as Background import Element.Border as Border import Element.Font as Font import Html.Attributes import Type.Window exposing (Window) import UI view : { a | window : Window, time : Int } -> Element msg view { window, time } = let deviceClass = (classifyDevice window).class ( ( logoSize, dividerImageSize ), ( responsivePadding, dateHeading ) ) = case deviceClass of Phone -> ( ( 300, 300 ), ( UI.lPadding, UI.h2 ) ) BigDesktop -> ( ( 700, 1000 ), ( UI.xxlPadding, UI.h1 ) ) _ -> ( ( 600, 600 ), ( UI.xxlPadding, UI.h1 ) ) in column [ UI.fillWidth, centerY, UI.xxlSpacing, paddingEach { top = 4 * 9, right = 0, bottom = 0, left = 0 } ] [ column [ UI.sSpacing, centerX ] [ -- el [ centerX ] <| dateHeading [ Font.color Color.yellow, htmlAttribute <| Html.Attributes.style "transform" "rotate(-10deg)" ] <| text "2. – 5. juli", image [ centerX , centerY , height <| px <| round <| logoSize / 1.5 , width <| px logoSize , UI.class "shake" ] { src = "/images/logo-2020-mm-transparent.png", description = "Logo" } ] , column [ centerX, UI.mPadding, UI.xsSpacing ] [ el [ centerX ] <| column [ Font.center, centerX, UI.mSpacing, UI.lPadding, Background.color Color.lightYellow, Font.color Color.black, UI.sRoundedCorners ] [ UI.p <| text "RønsenROCK 2021 er dessverre også avlyst på grunn av koronasituasjonen 💔" ] , el [ centerX, Font.center, UI.lPadding ] <| UI.p <| text "Men! Vi håper vi sees på RønsenROCK 2022 om ca. …" ] , el [ centerX ] <| Countdown.view window time , el [ UI.fillWidth, height <| px dividerImageSize, Background.image "/images/tak-2019-tk.jpg" ] none , el (centerX :: (case deviceClass of Phone -> [ UI.sPadding ] _ -> [] ) ) <| el [ UI.mPadding ] <| column (Font.center :: UI.lSpacing :: responsivePadding :: UI.boxed ) [ column [ UI.mSpacing ] [ paragraph [ Font.center, UI.fillWidth ] [ UI.h3 [] <| text "Få oppdateringer på Facebook" ] , paragraph [ Font.center ] [ text "Ikke gå glipp av nyheter om neste års festival – lik Rønsenrock festivallag på Facebook." ] ] , UI.buttonLink [ UI.class "hoverable", centerX ] { label = row [ UI.mSpacing, UI.mPadding ] [ text "Til Facebook", text "▷" ], url = "https://www.facebook.com/RockogRull/" } ] , el [] none -- , el -- (centerX -- :: (case deviceClass of -- Phone -> -- [ UI.sPadding ] -- _ -> -- [] -- ) -- ) -- <| -- column -- (Font.center -- :: UI.lSpacing -- :: responsivePadding -- :: UI.boxed -- ) -- [ column [ UI.mSpacing ] -- [ paragraph [ Font.center, UI.fillWidth ] [ UI.h3 [] <| text "Spille på RønsenROCK 2020?" ] -- , paragraph [ Font.center ] -- [ text "Vi tar i mot henvendelser frem til mars." ] -- ] -- , UI.buttonLink [ UI.class "hoverable", centerX ] { label = row [ UI.mSpacing ] [ text "MPI:NAME:<NAME>END_PI", text "▷" ], url = "mailto:PI:EMAIL:<EMAIL>END_PI" } -- ] -- , el [ centerX, width <| px 200 ] <| UI.horisontalDivider -- , el [ centerX ] <| -- html <| -- Html.iframe -- [ Html.Attributes.src "https://open.spotify.com/embed/user/1113006308/playlist/6FfNqW0AcFkrhlUaDfqfpD?si=S36Q1tleRB6w5MYvFWtS2g" -- , Html.Attributes.style "border" "none" -- , Html.Attributes.style "height" "400px" -- , Html.Attributes.style "width" "600px" -- , Html.Attributes.style "max-width" "100%" -- , Html.Attributes.style "border-radius" "4px" -- ] -- [] , el [ UI.fillWidth, height <| px dividerImageSize, Background.image "/images/chill-2018.jpg" ] none ]
elm
[ { "context": "ion : Int\n }\n\n\ninitialModel =\n { message = \"Abjurer.\"\n , rotation = 13\n }\n\n\n\n-- UPDATE\n\n\ntype M", "end": 342, "score": 0.9874124527, "start": 335, "tag": "NAME", "value": "Abjurer" } ]
OffsetCipher.elm
chigby/offset-cipher
0
module OffsetCipher exposing (..) import Char import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onInput) import String exposing (fromChar, indexes, length, map, slice, uncons) -- MODEL type alias Model = { message : String , rotation : Int } initialModel = { message = "Abjurer." , rotation = 13 } -- UPDATE type Msg = NoOp | UpdateString String | UpdateNum String update : Msg -> Model -> Model update action model = case action of NoOp -> model UpdateString contents -> { model | message = contents } UpdateNum i -> { model | rotation = parseInt i } parseInt : String -> Int parseInt string = case String.toInt string of Ok value -> value Err error -> 0 alphabet = "abcdefghijklmnopqrstuvwxyz" rotateString : Int -> String -> String rotateString n message = String.map (\ch -> if Char.isUpper ch then Char.toUpper (rotate n (Char.toLower ch)) else rotate n ch ) message rotate : Int -> Char -> Char rotate n ch = let start = valueOf ch in case start of (-1) -> ch p -> charValue ((p + n) % length alphabet) charValue : Int -> Char charValue i = case slice i (i + 1) alphabet |> String.toList |> List.head of Nothing -> '?' Just ch -> Char.toLower ch valueOf : Char -> Int valueOf ch = case List.head (indexes (fromChar (Char.toLower ch)) alphabet) of Nothing -> -1 Just i -> i -- VIEW view : Model -> Html Msg view model = div [ id "container" ] [ div [] [ textarea [ cols 40, rows 13, value model.message, onInput UpdateString, autofocus True ] [] ] , div [] [ textarea [ cols 40, rows 13, value (rotateString model.rotation model.message) ] [] ] , div [] [ input [ type_ "number", onInput UpdateNum, value (toString model.rotation) ] [] ] ] --main : Signal Html main = Html.beginnerProgram { model = initialModel, view = view, update = update }
57019
module OffsetCipher exposing (..) import Char import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onInput) import String exposing (fromChar, indexes, length, map, slice, uncons) -- MODEL type alias Model = { message : String , rotation : Int } initialModel = { message = "<NAME>." , rotation = 13 } -- UPDATE type Msg = NoOp | UpdateString String | UpdateNum String update : Msg -> Model -> Model update action model = case action of NoOp -> model UpdateString contents -> { model | message = contents } UpdateNum i -> { model | rotation = parseInt i } parseInt : String -> Int parseInt string = case String.toInt string of Ok value -> value Err error -> 0 alphabet = "abcdefghijklmnopqrstuvwxyz" rotateString : Int -> String -> String rotateString n message = String.map (\ch -> if Char.isUpper ch then Char.toUpper (rotate n (Char.toLower ch)) else rotate n ch ) message rotate : Int -> Char -> Char rotate n ch = let start = valueOf ch in case start of (-1) -> ch p -> charValue ((p + n) % length alphabet) charValue : Int -> Char charValue i = case slice i (i + 1) alphabet |> String.toList |> List.head of Nothing -> '?' Just ch -> Char.toLower ch valueOf : Char -> Int valueOf ch = case List.head (indexes (fromChar (Char.toLower ch)) alphabet) of Nothing -> -1 Just i -> i -- VIEW view : Model -> Html Msg view model = div [ id "container" ] [ div [] [ textarea [ cols 40, rows 13, value model.message, onInput UpdateString, autofocus True ] [] ] , div [] [ textarea [ cols 40, rows 13, value (rotateString model.rotation model.message) ] [] ] , div [] [ input [ type_ "number", onInput UpdateNum, value (toString model.rotation) ] [] ] ] --main : Signal Html main = Html.beginnerProgram { model = initialModel, view = view, update = update }
true
module OffsetCipher exposing (..) import Char import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onInput) import String exposing (fromChar, indexes, length, map, slice, uncons) -- MODEL type alias Model = { message : String , rotation : Int } initialModel = { message = "PI:NAME:<NAME>END_PI." , rotation = 13 } -- UPDATE type Msg = NoOp | UpdateString String | UpdateNum String update : Msg -> Model -> Model update action model = case action of NoOp -> model UpdateString contents -> { model | message = contents } UpdateNum i -> { model | rotation = parseInt i } parseInt : String -> Int parseInt string = case String.toInt string of Ok value -> value Err error -> 0 alphabet = "abcdefghijklmnopqrstuvwxyz" rotateString : Int -> String -> String rotateString n message = String.map (\ch -> if Char.isUpper ch then Char.toUpper (rotate n (Char.toLower ch)) else rotate n ch ) message rotate : Int -> Char -> Char rotate n ch = let start = valueOf ch in case start of (-1) -> ch p -> charValue ((p + n) % length alphabet) charValue : Int -> Char charValue i = case slice i (i + 1) alphabet |> String.toList |> List.head of Nothing -> '?' Just ch -> Char.toLower ch valueOf : Char -> Int valueOf ch = case List.head (indexes (fromChar (Char.toLower ch)) alphabet) of Nothing -> -1 Just i -> i -- VIEW view : Model -> Html Msg view model = div [ id "container" ] [ div [] [ textarea [ cols 40, rows 13, value model.message, onInput UpdateString, autofocus True ] [] ] , div [] [ textarea [ cols 40, rows 13, value (rotateString model.rotation model.message) ] [] ] , div [] [ input [ type_ "number", onInput UpdateNum, value (toString model.rotation) ] [] ] ] --main : Signal Html main = Html.beginnerProgram { model = initialModel, view = view, update = update }
elm
[ { "context": "ou are reading!\n\n [download]: https://github.com/elm-lang/Elm/blob/master/README.md#install\n [changes]: ht", "end": 2559, "score": 0.8745046258, "start": 2551, "tag": "USERNAME", "value": "elm-lang" }, { "context": "README.md#install\n [changes]: https://github.com/elm-lang/Elm/blob/master/changelog.txt\n\n<br/>\n\n## Type che", "end": 2634, "score": 0.8092911839, "start": 2626, "tag": "USERNAME", "value": "elm-lang" }, { "context": "was a really big project, so I want to first thank Prezi\nfor making all of this work possible! Also, tha", "end": 2772, "score": 0.5829998851, "start": 2769, "tag": "NAME", "value": "Pre" }, { "context": "king all of this work possible! Also, thank you to Spiros and\nLaszlo for talking through issues with me as ", "end": 2838, "score": 0.9993190765, "start": 2832, "tag": "NAME", "value": "Spiros" }, { "context": "this work possible! Also, thank you to Spiros and\nLaszlo for talking through issues with me as they came u", "end": 2849, "score": 0.9995160699, "start": 2843, "tag": "NAME", "value": "Laszlo" }, { "context": " \"title\" : \"Narcissus and Goldmund\",\n \"author\": \"Hermann Hesse\",\n \"pages\" : 320\n}\n\\\"\\\"\\\"\n```\n\n<h4 id=\"record-co", "end": 8157, "score": 0.9998817444, "start": 8144, "tag": "NAME", "value": "Hermann Hesse" }, { "context": "degrees 90)\n```\n\n## Final Notes\n\nHuge thank you to Prezi and the community on the [elm-discuss lists][list", "end": 9369, "score": 0.9868136644, "start": 9364, "tag": "NAME", "value": "Prezi" }, { "context": "-discuss\n\nNow for some 0.9 specifics. Thank you to Andrew who added `as` patterns and\ntype annotations in l", "end": 9781, "score": 0.9809908867, "start": 9775, "tag": "NAME", "value": "Andrew" }, { "context": "e annotations in let expressions. And thank you to Max New who significantly\nsped up this website.\n\nThank yo", "end": 9871, "score": 0.9997584224, "start": 9864, "tag": "NAME", "value": "Max New" } ]
frontend/public/blog/announce/0.9.elm
arsatiki/elm-lang.org
0
import Graphics.Element (..) import Markdown import Signal (Signal, (<~)) import Website.Skeleton (skeleton) import Window port title : String port title = "Elm 0.9 - Fix the type-checker" main : Signal Element main = skeleton "Blog" everything <~ Window.dimensions everything : Int -> Element everything wid = let w = min 600 wid in width w intro intro : Element intro = Markdown.toElement """ <h1><div style="text-align:center">Elm 0.9 <div style="font-size:0.5em;font-weight:normal">Fast and reliable static checks</div></div> </h1> Before this release, my primary priority was: prove that FRP is pleasant and practical. If FRP is not the right way, it does not matter how good or bad the type checker is. I recently started to feel that poor error messages had become the primary barrier for Elm. Questions started to shift from &ldquo;is this possible with FRP?&rdquo; to &ldquo;I am doing this with FRP, how can the tools be better?&rdquo; This is a very positive sign! To begin improving tools for FRP and Elm, the type checker has been completely rewritten. The key improvements are: * Undefined values are errors * All type errors are caught and reported * Error messages are more specific and easier to read * It&rsquo;s fast This is a huge step forward. It also creates a solid foundation for further improvement. This release also introduces many frequently requested syntax improvements. The most notable are as follows: * [Unary negation](#unary-negation) * [Pattern matching on literals and `as` patterns](#pattern-matching) * [Multi-line strings](#multi-line-strings) * [Record constructors](#record-constructors) Finally, there are a bunch of miscellaneous improvements: * `elm-server` can serve multi-module projects * [Detect mouse hover][hover] * [Transparency in collages][alpha] and many bug fixes * [`Text.height`][height] use pixels instead of [ems][], after [much debate][] [hover]: http://docs.elm-lang.org/library/Graphics/Input.elm#hoverable [alpha]: http://docs.elm-lang.org/library/Graphics/Collage.elm#alpha [height]: http://docs.elm-lang.org/library/Text.elm#height [much debate]: https://groups.google.com/forum/?fromgroups#!searchin/elm-discuss/specifying$20size$20of$20text/elm-discuss/3Iz-HpV1QRg/oHPoqWDgrmEJ [ems]: http://en.wikipedia.org/wiki/Em_(typography) The rest of this post will try to cover [all of the changes][changes] in more detail. Maybe start the [download process][download] while you are reading! [download]: https://github.com/elm-lang/Elm/blob/master/README.md#install [changes]: https://github.com/elm-lang/Elm/blob/master/changelog.txt <br/> ## Type checker and Build Improvements This was a really big project, so I want to first thank Prezi for making all of this work possible! Also, thank you to Spiros and Laszlo for talking through issues with me as they came up; this was a huge help! A big part of improving the type checker was making it possible for information to flow between modules. This meant improving the build system. Elm now creates two directories when compiling: * The `cache/` directory holds intermediate files. These hold metadata about types, type aliases, fixity of infix ops, etc. This information is used to pass information between modules and to build the final result. It also caches information from previous compilation passes, so if a file is unchanged, it does not need to be recompiled. This speeds up the build. * The `build/` directory holds only the generated `.html` and `.js` files, things you want to run and distribute. This directory should match the directory structure of your project, making it easy to export these files and start serving them. You can use the `--cache-dir` and `--build-dir` flags to change the name or location of these two directories. We [discussed a bunch of naming options][dirs] for them, but ultimately, maybe you still know better :P [dirs]: https://groups.google.com/forum/?fromgroups#!topic/elm-discuss/bkEEN1P5f9U These improvements make it possible to allow user-defined fixity and associativity for infix operators, so that should be arriving in a future release. #### Notes on the Type Checker With this build infrastructure in place, cross-module type checking became possible. The next task was understand and implement an efficienct type inference algorithm. To summarize, it is very tricky and there are few resources available that even *discuss* efficient practical implementations, let alone give details on specific techniques and strategies. I am planning to do a &ldquo;field guide to efficient type inference&rdquo; to make it easier for others to create a type inferencer that is correct and *fast*. For now, take a look at [this chapter][] of Advanced Topics in Types and Programming Languages. It is one of the best resources I have found. [this chapter]: http://www.cs.cmu.edu/~rwh/courses/refinements/papers/PottierRemy04/hmx.pdf ## Syntax Improvements <h4 id="pattern-matching">Pattern Matching</h4> You can now pattern match on literals like numbers, strings, and booleans. ```haskell removeZeros numbers = case numbers of [] -> numbers 0 :: rest -> removeZeros rest n :: rest -> n :: removeZeros rest isOrigin pos = case pos of (0,0) -> True _ -> False ``` You can also use `as` patterns now, thanks to Andrew! ```haskell move time ({x,y,vx,vy} as object) = { object | x <- x + vx * time , y <- y + vy * time } ``` This lets you name a structure and match on its sub-structure. The `as` keyword binds very loosely, so it often needs parentheses. One example might be: ```haskell data World = World Mario [Goomba] [Brick] step input (World mario goombas bricks as world) = ... ``` <h4 id="unary-negation">Unary negation</h4> I was very hesitant to add this feature because I had not seen a statically-typed functional language that I felt got this right. You get questions like: is `(x -1)` subtraction? Is `(f -1)` function application with a negative argument? From the perspective of the parser they are exactly the same, even though we can figure it out based on context. Writing `(x -1)` to mean subtraction is not recommended and is considered sloppy, whereas `(f -1)` is definitely going to come up quite quickly ([it does in OCaml][ocaml]). After [discussing many options][negate], we decided to optimize for function application. [ocaml]: http://stackoverflow.com/questions/8984661/unary-minus-and-floating-point-number-in-ocaml [negate]: https://groups.google.com/forum/?fromgroups#!searchin/elm-discuss/negation/elm-discuss/DcvoUKPzM_M/KIogCVoL9G0J In Elm, any unary negation operator must meet **both** of these requirements: 1. It is preceded by whitespace or `(` or `[` or `,` 2. It is *not* followed by whitespace Where whitespace means spaces, newlines, and comments. The following expressions show many cases you might encounter in the wild: ```haskell n - 1 -- subtraction n-1 -- subtraction, breaks requirement 1 -10 -- negative ten - 10 -- parse error, breaks requirement 2 ( -1, -1 ) -- point in quadrant III [-1,-1,-1] -- a list of negative ones abs -1 -- abs (-1) max -2 -4 -- max (-2) (-4) h - 3 - 5 -- subtraction twice n - -1 -- n + 1 ``` Another way to describe these rules is &ldquo;unary negation binds tighter than function application and infix operations.&rdquo; In practice, I have found that this is how my brain parses code. I definitely read `(max -2 -4)` as a function, my brain blocks each syntactic unit into a semantic unit. This is similar to how `(.)` can mean many different things depending on spacing. It is unfortunate to overload, but I think this is the best solution given the constraints. <h4 id="multi-line-strings">Multi-line Strings</h4> Just like Python, you can use multi-line strings if you use the triple-quote. This will make it easier to embed plain-text or JSON if the text uses `"`. ```haskell json = \"\"\" { "title" : "Narcissus and Goldmund", "author": "Hermann Hesse", "pages" : 320 } \"\"\" ``` <h4 id="record-constructors">Record Constructors</h4> When you create a type alias for a record, you also create a &ldquo;record constructor&rdquo;. ```haskell type Book = { title:String, author:String, pages:Int } -- This creates the following record constructor: -- Book : String -> String -> Int -> Book book : Book book = Book "Foundation" "Asimov" 255 ``` The arguments to `Book` must be given in the order they appear in the type alias. Record constructors also work for extensible records: ```haskell type Positioned a = { a | x:Float, y:Float } -- This creates the following record constructor: -- Positioned : Float -> Float -> a -> Positioned a myBook : Positioned Book myBook = Positioned 3 4 book ``` Notice that the record we are extending is the *last* argument. This convention makes it much easier to compose a chain of record extensions. ```haskell type Moving a = { a | velocity:Float, angle:Float } projectile : Moving (Positioned Book) projectile = Moving 100 (degrees 30) myBook projectile' : Moving (Positioned Book) projectile' = book |> Positioned 0 0 |> Moving 100 (degrees 90) ``` ## Final Notes Huge thank you to Prezi and the community on the [elm-discuss lists][list]. The diversity of opinions and experiences on the list is extremely helpful for Elm. I find that bringing an idea up on the lists always results in a thoughtful discussion and ultimately leads to more refined design choices, so thank you! [list]: https://groups.google.com/forum/?fromgroups#!forum/elm-discuss Now for some 0.9 specifics. Thank you to Andrew who added `as` patterns and type annotations in let expressions. And thank you to Max New who significantly sped up this website. Thank you to the beginners who came to my programming class in Budapest. Not only was it super fun, but you found a bug in the compiler! This experience also convinced me that unary negation was a good idea. """
36684
import Graphics.Element (..) import Markdown import Signal (Signal, (<~)) import Website.Skeleton (skeleton) import Window port title : String port title = "Elm 0.9 - Fix the type-checker" main : Signal Element main = skeleton "Blog" everything <~ Window.dimensions everything : Int -> Element everything wid = let w = min 600 wid in width w intro intro : Element intro = Markdown.toElement """ <h1><div style="text-align:center">Elm 0.9 <div style="font-size:0.5em;font-weight:normal">Fast and reliable static checks</div></div> </h1> Before this release, my primary priority was: prove that FRP is pleasant and practical. If FRP is not the right way, it does not matter how good or bad the type checker is. I recently started to feel that poor error messages had become the primary barrier for Elm. Questions started to shift from &ldquo;is this possible with FRP?&rdquo; to &ldquo;I am doing this with FRP, how can the tools be better?&rdquo; This is a very positive sign! To begin improving tools for FRP and Elm, the type checker has been completely rewritten. The key improvements are: * Undefined values are errors * All type errors are caught and reported * Error messages are more specific and easier to read * It&rsquo;s fast This is a huge step forward. It also creates a solid foundation for further improvement. This release also introduces many frequently requested syntax improvements. The most notable are as follows: * [Unary negation](#unary-negation) * [Pattern matching on literals and `as` patterns](#pattern-matching) * [Multi-line strings](#multi-line-strings) * [Record constructors](#record-constructors) Finally, there are a bunch of miscellaneous improvements: * `elm-server` can serve multi-module projects * [Detect mouse hover][hover] * [Transparency in collages][alpha] and many bug fixes * [`Text.height`][height] use pixels instead of [ems][], after [much debate][] [hover]: http://docs.elm-lang.org/library/Graphics/Input.elm#hoverable [alpha]: http://docs.elm-lang.org/library/Graphics/Collage.elm#alpha [height]: http://docs.elm-lang.org/library/Text.elm#height [much debate]: https://groups.google.com/forum/?fromgroups#!searchin/elm-discuss/specifying$20size$20of$20text/elm-discuss/3Iz-HpV1QRg/oHPoqWDgrmEJ [ems]: http://en.wikipedia.org/wiki/Em_(typography) The rest of this post will try to cover [all of the changes][changes] in more detail. Maybe start the [download process][download] while you are reading! [download]: https://github.com/elm-lang/Elm/blob/master/README.md#install [changes]: https://github.com/elm-lang/Elm/blob/master/changelog.txt <br/> ## Type checker and Build Improvements This was a really big project, so I want to first thank <NAME>zi for making all of this work possible! Also, thank you to <NAME> and <NAME> for talking through issues with me as they came up; this was a huge help! A big part of improving the type checker was making it possible for information to flow between modules. This meant improving the build system. Elm now creates two directories when compiling: * The `cache/` directory holds intermediate files. These hold metadata about types, type aliases, fixity of infix ops, etc. This information is used to pass information between modules and to build the final result. It also caches information from previous compilation passes, so if a file is unchanged, it does not need to be recompiled. This speeds up the build. * The `build/` directory holds only the generated `.html` and `.js` files, things you want to run and distribute. This directory should match the directory structure of your project, making it easy to export these files and start serving them. You can use the `--cache-dir` and `--build-dir` flags to change the name or location of these two directories. We [discussed a bunch of naming options][dirs] for them, but ultimately, maybe you still know better :P [dirs]: https://groups.google.com/forum/?fromgroups#!topic/elm-discuss/bkEEN1P5f9U These improvements make it possible to allow user-defined fixity and associativity for infix operators, so that should be arriving in a future release. #### Notes on the Type Checker With this build infrastructure in place, cross-module type checking became possible. The next task was understand and implement an efficienct type inference algorithm. To summarize, it is very tricky and there are few resources available that even *discuss* efficient practical implementations, let alone give details on specific techniques and strategies. I am planning to do a &ldquo;field guide to efficient type inference&rdquo; to make it easier for others to create a type inferencer that is correct and *fast*. For now, take a look at [this chapter][] of Advanced Topics in Types and Programming Languages. It is one of the best resources I have found. [this chapter]: http://www.cs.cmu.edu/~rwh/courses/refinements/papers/PottierRemy04/hmx.pdf ## Syntax Improvements <h4 id="pattern-matching">Pattern Matching</h4> You can now pattern match on literals like numbers, strings, and booleans. ```haskell removeZeros numbers = case numbers of [] -> numbers 0 :: rest -> removeZeros rest n :: rest -> n :: removeZeros rest isOrigin pos = case pos of (0,0) -> True _ -> False ``` You can also use `as` patterns now, thanks to Andrew! ```haskell move time ({x,y,vx,vy} as object) = { object | x <- x + vx * time , y <- y + vy * time } ``` This lets you name a structure and match on its sub-structure. The `as` keyword binds very loosely, so it often needs parentheses. One example might be: ```haskell data World = World Mario [Goomba] [Brick] step input (World mario goombas bricks as world) = ... ``` <h4 id="unary-negation">Unary negation</h4> I was very hesitant to add this feature because I had not seen a statically-typed functional language that I felt got this right. You get questions like: is `(x -1)` subtraction? Is `(f -1)` function application with a negative argument? From the perspective of the parser they are exactly the same, even though we can figure it out based on context. Writing `(x -1)` to mean subtraction is not recommended and is considered sloppy, whereas `(f -1)` is definitely going to come up quite quickly ([it does in OCaml][ocaml]). After [discussing many options][negate], we decided to optimize for function application. [ocaml]: http://stackoverflow.com/questions/8984661/unary-minus-and-floating-point-number-in-ocaml [negate]: https://groups.google.com/forum/?fromgroups#!searchin/elm-discuss/negation/elm-discuss/DcvoUKPzM_M/KIogCVoL9G0J In Elm, any unary negation operator must meet **both** of these requirements: 1. It is preceded by whitespace or `(` or `[` or `,` 2. It is *not* followed by whitespace Where whitespace means spaces, newlines, and comments. The following expressions show many cases you might encounter in the wild: ```haskell n - 1 -- subtraction n-1 -- subtraction, breaks requirement 1 -10 -- negative ten - 10 -- parse error, breaks requirement 2 ( -1, -1 ) -- point in quadrant III [-1,-1,-1] -- a list of negative ones abs -1 -- abs (-1) max -2 -4 -- max (-2) (-4) h - 3 - 5 -- subtraction twice n - -1 -- n + 1 ``` Another way to describe these rules is &ldquo;unary negation binds tighter than function application and infix operations.&rdquo; In practice, I have found that this is how my brain parses code. I definitely read `(max -2 -4)` as a function, my brain blocks each syntactic unit into a semantic unit. This is similar to how `(.)` can mean many different things depending on spacing. It is unfortunate to overload, but I think this is the best solution given the constraints. <h4 id="multi-line-strings">Multi-line Strings</h4> Just like Python, you can use multi-line strings if you use the triple-quote. This will make it easier to embed plain-text or JSON if the text uses `"`. ```haskell json = \"\"\" { "title" : "Narcissus and Goldmund", "author": "<NAME>", "pages" : 320 } \"\"\" ``` <h4 id="record-constructors">Record Constructors</h4> When you create a type alias for a record, you also create a &ldquo;record constructor&rdquo;. ```haskell type Book = { title:String, author:String, pages:Int } -- This creates the following record constructor: -- Book : String -> String -> Int -> Book book : Book book = Book "Foundation" "Asimov" 255 ``` The arguments to `Book` must be given in the order they appear in the type alias. Record constructors also work for extensible records: ```haskell type Positioned a = { a | x:Float, y:Float } -- This creates the following record constructor: -- Positioned : Float -> Float -> a -> Positioned a myBook : Positioned Book myBook = Positioned 3 4 book ``` Notice that the record we are extending is the *last* argument. This convention makes it much easier to compose a chain of record extensions. ```haskell type Moving a = { a | velocity:Float, angle:Float } projectile : Moving (Positioned Book) projectile = Moving 100 (degrees 30) myBook projectile' : Moving (Positioned Book) projectile' = book |> Positioned 0 0 |> Moving 100 (degrees 90) ``` ## Final Notes Huge thank you to <NAME> and the community on the [elm-discuss lists][list]. The diversity of opinions and experiences on the list is extremely helpful for Elm. I find that bringing an idea up on the lists always results in a thoughtful discussion and ultimately leads to more refined design choices, so thank you! [list]: https://groups.google.com/forum/?fromgroups#!forum/elm-discuss Now for some 0.9 specifics. Thank you to <NAME> who added `as` patterns and type annotations in let expressions. And thank you to <NAME> who significantly sped up this website. Thank you to the beginners who came to my programming class in Budapest. Not only was it super fun, but you found a bug in the compiler! This experience also convinced me that unary negation was a good idea. """
true
import Graphics.Element (..) import Markdown import Signal (Signal, (<~)) import Website.Skeleton (skeleton) import Window port title : String port title = "Elm 0.9 - Fix the type-checker" main : Signal Element main = skeleton "Blog" everything <~ Window.dimensions everything : Int -> Element everything wid = let w = min 600 wid in width w intro intro : Element intro = Markdown.toElement """ <h1><div style="text-align:center">Elm 0.9 <div style="font-size:0.5em;font-weight:normal">Fast and reliable static checks</div></div> </h1> Before this release, my primary priority was: prove that FRP is pleasant and practical. If FRP is not the right way, it does not matter how good or bad the type checker is. I recently started to feel that poor error messages had become the primary barrier for Elm. Questions started to shift from &ldquo;is this possible with FRP?&rdquo; to &ldquo;I am doing this with FRP, how can the tools be better?&rdquo; This is a very positive sign! To begin improving tools for FRP and Elm, the type checker has been completely rewritten. The key improvements are: * Undefined values are errors * All type errors are caught and reported * Error messages are more specific and easier to read * It&rsquo;s fast This is a huge step forward. It also creates a solid foundation for further improvement. This release also introduces many frequently requested syntax improvements. The most notable are as follows: * [Unary negation](#unary-negation) * [Pattern matching on literals and `as` patterns](#pattern-matching) * [Multi-line strings](#multi-line-strings) * [Record constructors](#record-constructors) Finally, there are a bunch of miscellaneous improvements: * `elm-server` can serve multi-module projects * [Detect mouse hover][hover] * [Transparency in collages][alpha] and many bug fixes * [`Text.height`][height] use pixels instead of [ems][], after [much debate][] [hover]: http://docs.elm-lang.org/library/Graphics/Input.elm#hoverable [alpha]: http://docs.elm-lang.org/library/Graphics/Collage.elm#alpha [height]: http://docs.elm-lang.org/library/Text.elm#height [much debate]: https://groups.google.com/forum/?fromgroups#!searchin/elm-discuss/specifying$20size$20of$20text/elm-discuss/3Iz-HpV1QRg/oHPoqWDgrmEJ [ems]: http://en.wikipedia.org/wiki/Em_(typography) The rest of this post will try to cover [all of the changes][changes] in more detail. Maybe start the [download process][download] while you are reading! [download]: https://github.com/elm-lang/Elm/blob/master/README.md#install [changes]: https://github.com/elm-lang/Elm/blob/master/changelog.txt <br/> ## Type checker and Build Improvements This was a really big project, so I want to first thank PI:NAME:<NAME>END_PIzi for making all of this work possible! Also, thank you to PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI for talking through issues with me as they came up; this was a huge help! A big part of improving the type checker was making it possible for information to flow between modules. This meant improving the build system. Elm now creates two directories when compiling: * The `cache/` directory holds intermediate files. These hold metadata about types, type aliases, fixity of infix ops, etc. This information is used to pass information between modules and to build the final result. It also caches information from previous compilation passes, so if a file is unchanged, it does not need to be recompiled. This speeds up the build. * The `build/` directory holds only the generated `.html` and `.js` files, things you want to run and distribute. This directory should match the directory structure of your project, making it easy to export these files and start serving them. You can use the `--cache-dir` and `--build-dir` flags to change the name or location of these two directories. We [discussed a bunch of naming options][dirs] for them, but ultimately, maybe you still know better :P [dirs]: https://groups.google.com/forum/?fromgroups#!topic/elm-discuss/bkEEN1P5f9U These improvements make it possible to allow user-defined fixity and associativity for infix operators, so that should be arriving in a future release. #### Notes on the Type Checker With this build infrastructure in place, cross-module type checking became possible. The next task was understand and implement an efficienct type inference algorithm. To summarize, it is very tricky and there are few resources available that even *discuss* efficient practical implementations, let alone give details on specific techniques and strategies. I am planning to do a &ldquo;field guide to efficient type inference&rdquo; to make it easier for others to create a type inferencer that is correct and *fast*. For now, take a look at [this chapter][] of Advanced Topics in Types and Programming Languages. It is one of the best resources I have found. [this chapter]: http://www.cs.cmu.edu/~rwh/courses/refinements/papers/PottierRemy04/hmx.pdf ## Syntax Improvements <h4 id="pattern-matching">Pattern Matching</h4> You can now pattern match on literals like numbers, strings, and booleans. ```haskell removeZeros numbers = case numbers of [] -> numbers 0 :: rest -> removeZeros rest n :: rest -> n :: removeZeros rest isOrigin pos = case pos of (0,0) -> True _ -> False ``` You can also use `as` patterns now, thanks to Andrew! ```haskell move time ({x,y,vx,vy} as object) = { object | x <- x + vx * time , y <- y + vy * time } ``` This lets you name a structure and match on its sub-structure. The `as` keyword binds very loosely, so it often needs parentheses. One example might be: ```haskell data World = World Mario [Goomba] [Brick] step input (World mario goombas bricks as world) = ... ``` <h4 id="unary-negation">Unary negation</h4> I was very hesitant to add this feature because I had not seen a statically-typed functional language that I felt got this right. You get questions like: is `(x -1)` subtraction? Is `(f -1)` function application with a negative argument? From the perspective of the parser they are exactly the same, even though we can figure it out based on context. Writing `(x -1)` to mean subtraction is not recommended and is considered sloppy, whereas `(f -1)` is definitely going to come up quite quickly ([it does in OCaml][ocaml]). After [discussing many options][negate], we decided to optimize for function application. [ocaml]: http://stackoverflow.com/questions/8984661/unary-minus-and-floating-point-number-in-ocaml [negate]: https://groups.google.com/forum/?fromgroups#!searchin/elm-discuss/negation/elm-discuss/DcvoUKPzM_M/KIogCVoL9G0J In Elm, any unary negation operator must meet **both** of these requirements: 1. It is preceded by whitespace or `(` or `[` or `,` 2. It is *not* followed by whitespace Where whitespace means spaces, newlines, and comments. The following expressions show many cases you might encounter in the wild: ```haskell n - 1 -- subtraction n-1 -- subtraction, breaks requirement 1 -10 -- negative ten - 10 -- parse error, breaks requirement 2 ( -1, -1 ) -- point in quadrant III [-1,-1,-1] -- a list of negative ones abs -1 -- abs (-1) max -2 -4 -- max (-2) (-4) h - 3 - 5 -- subtraction twice n - -1 -- n + 1 ``` Another way to describe these rules is &ldquo;unary negation binds tighter than function application and infix operations.&rdquo; In practice, I have found that this is how my brain parses code. I definitely read `(max -2 -4)` as a function, my brain blocks each syntactic unit into a semantic unit. This is similar to how `(.)` can mean many different things depending on spacing. It is unfortunate to overload, but I think this is the best solution given the constraints. <h4 id="multi-line-strings">Multi-line Strings</h4> Just like Python, you can use multi-line strings if you use the triple-quote. This will make it easier to embed plain-text or JSON if the text uses `"`. ```haskell json = \"\"\" { "title" : "Narcissus and Goldmund", "author": "PI:NAME:<NAME>END_PI", "pages" : 320 } \"\"\" ``` <h4 id="record-constructors">Record Constructors</h4> When you create a type alias for a record, you also create a &ldquo;record constructor&rdquo;. ```haskell type Book = { title:String, author:String, pages:Int } -- This creates the following record constructor: -- Book : String -> String -> Int -> Book book : Book book = Book "Foundation" "Asimov" 255 ``` The arguments to `Book` must be given in the order they appear in the type alias. Record constructors also work for extensible records: ```haskell type Positioned a = { a | x:Float, y:Float } -- This creates the following record constructor: -- Positioned : Float -> Float -> a -> Positioned a myBook : Positioned Book myBook = Positioned 3 4 book ``` Notice that the record we are extending is the *last* argument. This convention makes it much easier to compose a chain of record extensions. ```haskell type Moving a = { a | velocity:Float, angle:Float } projectile : Moving (Positioned Book) projectile = Moving 100 (degrees 30) myBook projectile' : Moving (Positioned Book) projectile' = book |> Positioned 0 0 |> Moving 100 (degrees 90) ``` ## Final Notes Huge thank you to PI:NAME:<NAME>END_PI and the community on the [elm-discuss lists][list]. The diversity of opinions and experiences on the list is extremely helpful for Elm. I find that bringing an idea up on the lists always results in a thoughtful discussion and ultimately leads to more refined design choices, so thank you! [list]: https://groups.google.com/forum/?fromgroups#!forum/elm-discuss Now for some 0.9 specifics. Thank you to PI:NAME:<NAME>END_PI who added `as` patterns and type annotations in let expressions. And thank you to PI:NAME:<NAME>END_PI who significantly sped up this website. Thank you to the beginners who came to my programming class in Budapest. Not only was it super fun, but you found a bug in the compiler! This experience also convinced me that unary negation was a good idea. """
elm
[ { "context": " value = \"\", text = \"Ordering\" }\n , { value = \"username\", text = \"Username ↑\" }\n , { value = \"-usernam", "end": 1101, "score": 0.9527136087, "start": 1093, "tag": "USERNAME", "value": "username" }, { "context": " [ tr []\n [ th [] [ text \"Username\" ]\n , th [] [ text \"First Name\" ]\n", "end": 6869, "score": 0.8903128505, "start": 6861, "tag": "USERNAME", "value": "Username" }, { "context": "text \"Username\" ]\n , th [] [ text \"First Name\" ]\n , th [] [ text \"Last Name\" ]\n ", "end": 6915, "score": 0.9989599586, "start": 6905, "tag": "NAME", "value": "First Name" }, { "context": "User user =\n tr []\n [ th [] [ text user.username ]\n , th [] [ text user.first_name ]\n ", "end": 7203, "score": 0.9907026291, "start": 7195, "tag": "USERNAME", "value": "username" }, { "context": "Ascending ->\n UB.string \"ordering\" \"username\" :: list\n\n UsernameDescending ->\n ", "end": 9770, "score": 0.9105417728, "start": 9762, "tag": "USERNAME", "value": "username" }, { "context": "arameter value list =\n if List.member value [ \"username\", \"-username\", \"first_name\", \"-first_name\", \"last", "end": 10656, "score": 0.9693925977, "start": 10648, "tag": "USERNAME", "value": "username" } ]
src/Users.elm
jlebunetel/django-webpack-elm
0
module Users exposing (main) import Browser import Html exposing (Html, button, div, fieldset, form, h1, h2, hr, i, input, label, option, p, select, span, table, tbody, text, th, thead, tr) import Html.Attributes exposing (checked, class, classList, disabled, id, name, placeholder, selected, style, type_, value) import Html.Events exposing (..) import Http import Json.Decode as JD exposing (Decoder, field, int, list, map2, map3, map4, string) import Url.Builder as UB exposing (QueryParameter, absolute, string) main : Program () Model Msg main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions } type Msg = InputChanged String --| LimitChanged (Result String Int) | LimitChanged String | IsStaffChanged String | OrderingChanged String | FormSubmitted | ResponseReceived (Result Http.Error UsersList) | ClearFilters type alias Option = { value : String , text : String } orderingModel = [ { value = "", text = "Ordering" } , { value = "username", text = "Username ↑" } , { value = "-username", text = "Username ↓" } , { value = "first_name", text = "First Name ↑" } , { value = "-first_name", text = "First Name ↓" } , { value = "last_name", text = "Last Name ↑" } , { value = "-last_name", text = "Last Name ↓" } ] limitModel = [ { value = "", text = "Show" } , { value = "5", text = "5" } , { value = "10", text = "10" } ] type alias User = { username : String , first_name : String , last_name : String , is_staff : Bool } type alias UsersList = { total : Int , results : List User } type alias Model = { ordering : String , limit : String , searchTerms : String , usersList : UsersList , message : String , isStaff : String , loading : Bool } initialModel = { ordering = "" , limit = "" , searchTerms = "" , usersList = { total = 0 , results = [] } , message = "" , isStaff = "" , loading = False } init : () -> ( Model, Cmd Msg ) init _ = update FormSubmitted initialModel view : Model -> Html Msg view model = div [ id "users" ] [ h1 [ class "title" ] [ text "Users list" ] , h2 [ class "title is-4" ] [ text "Filters" ] , viewForm model , hr [] [] , if model.message == "" then h2 [ class "title is-4" ] [ text "Results (", text <| String.fromInt model.usersList.total, text ")" ] else h2 [ class "title is-4" ] [ text "Error" ] , if model.message == "" then viewResults model else viewError model ] viewForm : Model -> Html Msg viewForm model = form [ onSubmit FormSubmitted ] [ fieldset [] [ div [ class "field is-grouped" ] [ div [ class "control has-icons-left" ] [ input [ type_ "text" , classList [ ( "input", True ) , ( "is-primary", model.searchTerms /= "" ) ] , placeholder "Search" , onInput InputChanged , value model.searchTerms ] [] , span [ class "icon is-small is-left" ] [ i [ class "fas fa-search" ] [] ] ] , viewSelect OrderingChanged model.ordering orderingModel "fas fa-sort" , viewSelect LimitChanged model.limit limitModel "fas fa-filter" , div [ class "control" ] [ button [ classList [ ( "button is-primary", True ), ( "is-loading", model.loading ) ] , disabled (model.searchTerms == "" && model.ordering == "" && model.limit == "" && model.isStaff == "") , onClick ClearFilters ] [ text "Clear" ] ] ] , div [ class "field is-grouped" ] [ label [ class "label mr-1" ] [ text "Is Staff?" ] , div [ class "control" ] [ label [ class "radio" ] [ input [ type_ "radio" , name "is_staff" , value "" , checked (model.isStaff == "") , onInput IsStaffChanged ] [] , span [ class "ml-1" ] [ text "All" ] ] , label [ class "radio" ] [ input [ type_ "radio" , name "is_staff" , value "true" , checked (model.isStaff == "true") , onInput IsStaffChanged ] [] , span [ class "ml-1" ] [ text "Yes" ] ] , label [ class "radio" ] [ input [ type_ "radio" , name "is_staff" , value "false" , checked (model.isStaff == "false") , onInput IsStaffChanged ] [] , span [ class "ml-1" ] [ text "No" ] ] ] ] ] ] viewSelect : (String -> Msg) -> String -> List Option -> String -> Html Msg viewSelect command current list icon_class = p [ class "control has-icons-left" ] [ span [ classList [ ( "select", True ) , ( "is-primary", current /= "" ) ] ] [ select [ onInput command ] (List.map (viewOption current) list) ] , span [ class "icon is-small is-left" ] [ i [ class icon_class ] [] ] ] viewOption : String -> Option -> Html Msg viewOption current select = option [ value select.value , selected (current == select.value) ] [ text select.text ] viewResults : Model -> Html Msg viewResults model = table [ class "table is-striped is-hoverable is-fullwidth" ] [ thead [] [ tr [] [ th [] [ text "Username" ] , th [] [ text "First Name" ] , th [] [ text "Last Name" ] , th [] [ text "Staff?" ] ] ] , tbody [] (List.map viewUser model.usersList.results) ] viewUser : User -> Html Msg viewUser user = tr [] [ th [] [ text user.username ] , th [] [ text user.first_name ] , th [] [ text user.last_name ] , th [] [ if user.is_staff then span [ class "icon has-text-success" ] [ i [ class "fas fa-check-circle" ] [] ] else span [ class "icon has-text-danger" ] [ i [ class "fas fa-times-circle" ] [] ] ] ] viewError : Model -> Html Msg viewError model = div [ class "notification is-danger" ] [ button [ class "delete" ] [] , text model.message ] update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of InputChanged value -> update FormSubmitted { model | searchTerms = value } LimitChanged value -> update FormSubmitted { model | limit = value } IsStaffChanged value -> update FormSubmitted { model | isStaff = value } OrderingChanged value -> update FormSubmitted { model | ordering = value } FormSubmitted -> ( { model | loading = True }, getUsersList model ) ResponseReceived (Ok usersList) -> ( { model | usersList = usersList, loading = False }, Cmd.none ) ResponseReceived (Err _) -> ( { model | message = "Communication error", loading = False }, Cmd.none ) ClearFilters -> update FormSubmitted initialModel getUsersList : Model -> Cmd Msg getUsersList model = Http.get { url = absolute [ "api", "v1", "users" ] (getQueryParameterList model) , expect = Http.expectJson ResponseReceived usersListDecoder } getQueryParameterList : Model -> List QueryParameter getQueryParameterList model = [] |> appendSearchParameter model.searchTerms |> appendLimitParameter model.limit |> appendOrderingParameter model.ordering |> appendIsStaffParameter model.isStaff appendIsStaffParameter : String -> List QueryParameter -> List QueryParameter appendIsStaffParameter value list = case value of "true" -> UB.string "is_staff" "true" :: list "false" -> UB.string "is_staff" "false" :: list _ -> list {- appendOrderingParameter : Ordering -> List QueryParameter -> List QueryParameter appendOrderingParameter maybe list = case maybe of UsernameAscending -> UB.string "ordering" "username" :: list UsernameDescending -> UB.string "ordering" "-username" :: list FirstNameAscending -> UB.string "ordering" "first_name" :: list FirstNameDescending -> UB.string "ordering" "-first_name" :: list LastNameAscending -> UB.string "ordering" "last_name" :: list LastNameDescending -> UB.string "ordering" "-last_name" :: list Default -> list -} appendSearchParameter : String -> List QueryParameter -> List QueryParameter appendSearchParameter value list = case value of "" -> list _ -> UB.string "search" value :: list appendOrderingParameter : String -> List QueryParameter -> List QueryParameter appendOrderingParameter value list = if List.member value [ "username", "-username", "first_name", "-first_name", "last_name", "-last_name" ] then UB.string "ordering" value :: list else list appendLimitParameter : String -> List QueryParameter -> List QueryParameter appendLimitParameter value list = if List.member value [ "5", "10" ] then UB.string "limit" value :: list else list userDecoder : Decoder User userDecoder = map4 User (field "username" JD.string) (field "first_name" JD.string) (field "last_name" JD.string) (field "is_staff" JD.bool) personListDecoder : Decoder (List User) personListDecoder = JD.list userDecoder usersListDecoder : Decoder UsersList usersListDecoder = map2 UsersList (field "count" int) (field "results" personListDecoder) subscriptions : Model -> Sub Msg subscriptions model = Sub.none
12346
module Users exposing (main) import Browser import Html exposing (Html, button, div, fieldset, form, h1, h2, hr, i, input, label, option, p, select, span, table, tbody, text, th, thead, tr) import Html.Attributes exposing (checked, class, classList, disabled, id, name, placeholder, selected, style, type_, value) import Html.Events exposing (..) import Http import Json.Decode as JD exposing (Decoder, field, int, list, map2, map3, map4, string) import Url.Builder as UB exposing (QueryParameter, absolute, string) main : Program () Model Msg main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions } type Msg = InputChanged String --| LimitChanged (Result String Int) | LimitChanged String | IsStaffChanged String | OrderingChanged String | FormSubmitted | ResponseReceived (Result Http.Error UsersList) | ClearFilters type alias Option = { value : String , text : String } orderingModel = [ { value = "", text = "Ordering" } , { value = "username", text = "Username ↑" } , { value = "-username", text = "Username ↓" } , { value = "first_name", text = "First Name ↑" } , { value = "-first_name", text = "First Name ↓" } , { value = "last_name", text = "Last Name ↑" } , { value = "-last_name", text = "Last Name ↓" } ] limitModel = [ { value = "", text = "Show" } , { value = "5", text = "5" } , { value = "10", text = "10" } ] type alias User = { username : String , first_name : String , last_name : String , is_staff : Bool } type alias UsersList = { total : Int , results : List User } type alias Model = { ordering : String , limit : String , searchTerms : String , usersList : UsersList , message : String , isStaff : String , loading : Bool } initialModel = { ordering = "" , limit = "" , searchTerms = "" , usersList = { total = 0 , results = [] } , message = "" , isStaff = "" , loading = False } init : () -> ( Model, Cmd Msg ) init _ = update FormSubmitted initialModel view : Model -> Html Msg view model = div [ id "users" ] [ h1 [ class "title" ] [ text "Users list" ] , h2 [ class "title is-4" ] [ text "Filters" ] , viewForm model , hr [] [] , if model.message == "" then h2 [ class "title is-4" ] [ text "Results (", text <| String.fromInt model.usersList.total, text ")" ] else h2 [ class "title is-4" ] [ text "Error" ] , if model.message == "" then viewResults model else viewError model ] viewForm : Model -> Html Msg viewForm model = form [ onSubmit FormSubmitted ] [ fieldset [] [ div [ class "field is-grouped" ] [ div [ class "control has-icons-left" ] [ input [ type_ "text" , classList [ ( "input", True ) , ( "is-primary", model.searchTerms /= "" ) ] , placeholder "Search" , onInput InputChanged , value model.searchTerms ] [] , span [ class "icon is-small is-left" ] [ i [ class "fas fa-search" ] [] ] ] , viewSelect OrderingChanged model.ordering orderingModel "fas fa-sort" , viewSelect LimitChanged model.limit limitModel "fas fa-filter" , div [ class "control" ] [ button [ classList [ ( "button is-primary", True ), ( "is-loading", model.loading ) ] , disabled (model.searchTerms == "" && model.ordering == "" && model.limit == "" && model.isStaff == "") , onClick ClearFilters ] [ text "Clear" ] ] ] , div [ class "field is-grouped" ] [ label [ class "label mr-1" ] [ text "Is Staff?" ] , div [ class "control" ] [ label [ class "radio" ] [ input [ type_ "radio" , name "is_staff" , value "" , checked (model.isStaff == "") , onInput IsStaffChanged ] [] , span [ class "ml-1" ] [ text "All" ] ] , label [ class "radio" ] [ input [ type_ "radio" , name "is_staff" , value "true" , checked (model.isStaff == "true") , onInput IsStaffChanged ] [] , span [ class "ml-1" ] [ text "Yes" ] ] , label [ class "radio" ] [ input [ type_ "radio" , name "is_staff" , value "false" , checked (model.isStaff == "false") , onInput IsStaffChanged ] [] , span [ class "ml-1" ] [ text "No" ] ] ] ] ] ] viewSelect : (String -> Msg) -> String -> List Option -> String -> Html Msg viewSelect command current list icon_class = p [ class "control has-icons-left" ] [ span [ classList [ ( "select", True ) , ( "is-primary", current /= "" ) ] ] [ select [ onInput command ] (List.map (viewOption current) list) ] , span [ class "icon is-small is-left" ] [ i [ class icon_class ] [] ] ] viewOption : String -> Option -> Html Msg viewOption current select = option [ value select.value , selected (current == select.value) ] [ text select.text ] viewResults : Model -> Html Msg viewResults model = table [ class "table is-striped is-hoverable is-fullwidth" ] [ thead [] [ tr [] [ th [] [ text "Username" ] , th [] [ text "<NAME>" ] , th [] [ text "Last Name" ] , th [] [ text "Staff?" ] ] ] , tbody [] (List.map viewUser model.usersList.results) ] viewUser : User -> Html Msg viewUser user = tr [] [ th [] [ text user.username ] , th [] [ text user.first_name ] , th [] [ text user.last_name ] , th [] [ if user.is_staff then span [ class "icon has-text-success" ] [ i [ class "fas fa-check-circle" ] [] ] else span [ class "icon has-text-danger" ] [ i [ class "fas fa-times-circle" ] [] ] ] ] viewError : Model -> Html Msg viewError model = div [ class "notification is-danger" ] [ button [ class "delete" ] [] , text model.message ] update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of InputChanged value -> update FormSubmitted { model | searchTerms = value } LimitChanged value -> update FormSubmitted { model | limit = value } IsStaffChanged value -> update FormSubmitted { model | isStaff = value } OrderingChanged value -> update FormSubmitted { model | ordering = value } FormSubmitted -> ( { model | loading = True }, getUsersList model ) ResponseReceived (Ok usersList) -> ( { model | usersList = usersList, loading = False }, Cmd.none ) ResponseReceived (Err _) -> ( { model | message = "Communication error", loading = False }, Cmd.none ) ClearFilters -> update FormSubmitted initialModel getUsersList : Model -> Cmd Msg getUsersList model = Http.get { url = absolute [ "api", "v1", "users" ] (getQueryParameterList model) , expect = Http.expectJson ResponseReceived usersListDecoder } getQueryParameterList : Model -> List QueryParameter getQueryParameterList model = [] |> appendSearchParameter model.searchTerms |> appendLimitParameter model.limit |> appendOrderingParameter model.ordering |> appendIsStaffParameter model.isStaff appendIsStaffParameter : String -> List QueryParameter -> List QueryParameter appendIsStaffParameter value list = case value of "true" -> UB.string "is_staff" "true" :: list "false" -> UB.string "is_staff" "false" :: list _ -> list {- appendOrderingParameter : Ordering -> List QueryParameter -> List QueryParameter appendOrderingParameter maybe list = case maybe of UsernameAscending -> UB.string "ordering" "username" :: list UsernameDescending -> UB.string "ordering" "-username" :: list FirstNameAscending -> UB.string "ordering" "first_name" :: list FirstNameDescending -> UB.string "ordering" "-first_name" :: list LastNameAscending -> UB.string "ordering" "last_name" :: list LastNameDescending -> UB.string "ordering" "-last_name" :: list Default -> list -} appendSearchParameter : String -> List QueryParameter -> List QueryParameter appendSearchParameter value list = case value of "" -> list _ -> UB.string "search" value :: list appendOrderingParameter : String -> List QueryParameter -> List QueryParameter appendOrderingParameter value list = if List.member value [ "username", "-username", "first_name", "-first_name", "last_name", "-last_name" ] then UB.string "ordering" value :: list else list appendLimitParameter : String -> List QueryParameter -> List QueryParameter appendLimitParameter value list = if List.member value [ "5", "10" ] then UB.string "limit" value :: list else list userDecoder : Decoder User userDecoder = map4 User (field "username" JD.string) (field "first_name" JD.string) (field "last_name" JD.string) (field "is_staff" JD.bool) personListDecoder : Decoder (List User) personListDecoder = JD.list userDecoder usersListDecoder : Decoder UsersList usersListDecoder = map2 UsersList (field "count" int) (field "results" personListDecoder) subscriptions : Model -> Sub Msg subscriptions model = Sub.none
true
module Users exposing (main) import Browser import Html exposing (Html, button, div, fieldset, form, h1, h2, hr, i, input, label, option, p, select, span, table, tbody, text, th, thead, tr) import Html.Attributes exposing (checked, class, classList, disabled, id, name, placeholder, selected, style, type_, value) import Html.Events exposing (..) import Http import Json.Decode as JD exposing (Decoder, field, int, list, map2, map3, map4, string) import Url.Builder as UB exposing (QueryParameter, absolute, string) main : Program () Model Msg main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions } type Msg = InputChanged String --| LimitChanged (Result String Int) | LimitChanged String | IsStaffChanged String | OrderingChanged String | FormSubmitted | ResponseReceived (Result Http.Error UsersList) | ClearFilters type alias Option = { value : String , text : String } orderingModel = [ { value = "", text = "Ordering" } , { value = "username", text = "Username ↑" } , { value = "-username", text = "Username ↓" } , { value = "first_name", text = "First Name ↑" } , { value = "-first_name", text = "First Name ↓" } , { value = "last_name", text = "Last Name ↑" } , { value = "-last_name", text = "Last Name ↓" } ] limitModel = [ { value = "", text = "Show" } , { value = "5", text = "5" } , { value = "10", text = "10" } ] type alias User = { username : String , first_name : String , last_name : String , is_staff : Bool } type alias UsersList = { total : Int , results : List User } type alias Model = { ordering : String , limit : String , searchTerms : String , usersList : UsersList , message : String , isStaff : String , loading : Bool } initialModel = { ordering = "" , limit = "" , searchTerms = "" , usersList = { total = 0 , results = [] } , message = "" , isStaff = "" , loading = False } init : () -> ( Model, Cmd Msg ) init _ = update FormSubmitted initialModel view : Model -> Html Msg view model = div [ id "users" ] [ h1 [ class "title" ] [ text "Users list" ] , h2 [ class "title is-4" ] [ text "Filters" ] , viewForm model , hr [] [] , if model.message == "" then h2 [ class "title is-4" ] [ text "Results (", text <| String.fromInt model.usersList.total, text ")" ] else h2 [ class "title is-4" ] [ text "Error" ] , if model.message == "" then viewResults model else viewError model ] viewForm : Model -> Html Msg viewForm model = form [ onSubmit FormSubmitted ] [ fieldset [] [ div [ class "field is-grouped" ] [ div [ class "control has-icons-left" ] [ input [ type_ "text" , classList [ ( "input", True ) , ( "is-primary", model.searchTerms /= "" ) ] , placeholder "Search" , onInput InputChanged , value model.searchTerms ] [] , span [ class "icon is-small is-left" ] [ i [ class "fas fa-search" ] [] ] ] , viewSelect OrderingChanged model.ordering orderingModel "fas fa-sort" , viewSelect LimitChanged model.limit limitModel "fas fa-filter" , div [ class "control" ] [ button [ classList [ ( "button is-primary", True ), ( "is-loading", model.loading ) ] , disabled (model.searchTerms == "" && model.ordering == "" && model.limit == "" && model.isStaff == "") , onClick ClearFilters ] [ text "Clear" ] ] ] , div [ class "field is-grouped" ] [ label [ class "label mr-1" ] [ text "Is Staff?" ] , div [ class "control" ] [ label [ class "radio" ] [ input [ type_ "radio" , name "is_staff" , value "" , checked (model.isStaff == "") , onInput IsStaffChanged ] [] , span [ class "ml-1" ] [ text "All" ] ] , label [ class "radio" ] [ input [ type_ "radio" , name "is_staff" , value "true" , checked (model.isStaff == "true") , onInput IsStaffChanged ] [] , span [ class "ml-1" ] [ text "Yes" ] ] , label [ class "radio" ] [ input [ type_ "radio" , name "is_staff" , value "false" , checked (model.isStaff == "false") , onInput IsStaffChanged ] [] , span [ class "ml-1" ] [ text "No" ] ] ] ] ] ] viewSelect : (String -> Msg) -> String -> List Option -> String -> Html Msg viewSelect command current list icon_class = p [ class "control has-icons-left" ] [ span [ classList [ ( "select", True ) , ( "is-primary", current /= "" ) ] ] [ select [ onInput command ] (List.map (viewOption current) list) ] , span [ class "icon is-small is-left" ] [ i [ class icon_class ] [] ] ] viewOption : String -> Option -> Html Msg viewOption current select = option [ value select.value , selected (current == select.value) ] [ text select.text ] viewResults : Model -> Html Msg viewResults model = table [ class "table is-striped is-hoverable is-fullwidth" ] [ thead [] [ tr [] [ th [] [ text "Username" ] , th [] [ text "PI:NAME:<NAME>END_PI" ] , th [] [ text "Last Name" ] , th [] [ text "Staff?" ] ] ] , tbody [] (List.map viewUser model.usersList.results) ] viewUser : User -> Html Msg viewUser user = tr [] [ th [] [ text user.username ] , th [] [ text user.first_name ] , th [] [ text user.last_name ] , th [] [ if user.is_staff then span [ class "icon has-text-success" ] [ i [ class "fas fa-check-circle" ] [] ] else span [ class "icon has-text-danger" ] [ i [ class "fas fa-times-circle" ] [] ] ] ] viewError : Model -> Html Msg viewError model = div [ class "notification is-danger" ] [ button [ class "delete" ] [] , text model.message ] update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of InputChanged value -> update FormSubmitted { model | searchTerms = value } LimitChanged value -> update FormSubmitted { model | limit = value } IsStaffChanged value -> update FormSubmitted { model | isStaff = value } OrderingChanged value -> update FormSubmitted { model | ordering = value } FormSubmitted -> ( { model | loading = True }, getUsersList model ) ResponseReceived (Ok usersList) -> ( { model | usersList = usersList, loading = False }, Cmd.none ) ResponseReceived (Err _) -> ( { model | message = "Communication error", loading = False }, Cmd.none ) ClearFilters -> update FormSubmitted initialModel getUsersList : Model -> Cmd Msg getUsersList model = Http.get { url = absolute [ "api", "v1", "users" ] (getQueryParameterList model) , expect = Http.expectJson ResponseReceived usersListDecoder } getQueryParameterList : Model -> List QueryParameter getQueryParameterList model = [] |> appendSearchParameter model.searchTerms |> appendLimitParameter model.limit |> appendOrderingParameter model.ordering |> appendIsStaffParameter model.isStaff appendIsStaffParameter : String -> List QueryParameter -> List QueryParameter appendIsStaffParameter value list = case value of "true" -> UB.string "is_staff" "true" :: list "false" -> UB.string "is_staff" "false" :: list _ -> list {- appendOrderingParameter : Ordering -> List QueryParameter -> List QueryParameter appendOrderingParameter maybe list = case maybe of UsernameAscending -> UB.string "ordering" "username" :: list UsernameDescending -> UB.string "ordering" "-username" :: list FirstNameAscending -> UB.string "ordering" "first_name" :: list FirstNameDescending -> UB.string "ordering" "-first_name" :: list LastNameAscending -> UB.string "ordering" "last_name" :: list LastNameDescending -> UB.string "ordering" "-last_name" :: list Default -> list -} appendSearchParameter : String -> List QueryParameter -> List QueryParameter appendSearchParameter value list = case value of "" -> list _ -> UB.string "search" value :: list appendOrderingParameter : String -> List QueryParameter -> List QueryParameter appendOrderingParameter value list = if List.member value [ "username", "-username", "first_name", "-first_name", "last_name", "-last_name" ] then UB.string "ordering" value :: list else list appendLimitParameter : String -> List QueryParameter -> List QueryParameter appendLimitParameter value list = if List.member value [ "5", "10" ] then UB.string "limit" value :: list else list userDecoder : Decoder User userDecoder = map4 User (field "username" JD.string) (field "first_name" JD.string) (field "last_name" JD.string) (field "is_staff" JD.bool) personListDecoder : Decoder (List User) personListDecoder = JD.list userDecoder usersListDecoder : Decoder UsersList usersListDecoder = map2 UsersList (field "count" int) (field "results" personListDecoder) subscriptions : Model -> Sub Msg subscriptions model = Sub.none
elm
[ { "context": "anually edit this file, it was auto-generated by dillonkearns/elm-graphql\n-- https://github.com/dillonkearns/el", "end": 72, "score": 0.6543979049, "start": 61, "tag": "USERNAME", "value": "illonkearns" }, { "context": "by dillonkearns/elm-graphql\n-- https://github.com/dillonkearns/elm-graphql\n\n\nmodule Graphql.InputObject exposing", "end": 119, "score": 0.9976151586, "start": 107, "tag": "USERNAME", "value": "dillonkearns" }, { "context": "econd = optionals____.expSecond, password = optionals____.password, allowIPList = optionals____.allowIPList, allowEm", "end": 7796, "score": 0.7069047093, "start": 7780, "tag": "PASSWORD", "value": "als____.password" } ]
web/src/Graphql/Graphql/InputObject.elm
harehare/textusm
97
-- Do not manually edit this file, it was auto-generated by dillonkearns/elm-graphql -- https://github.com/dillonkearns/elm-graphql module Graphql.InputObject exposing (..) import Graphql.Enum.Diagram import Graphql.Internal.Encode as Encode exposing (Value) import Graphql.OptionalArgument exposing (OptionalArgument(..)) import Graphql.Scalar import Graphql.ScalarCodecs buildInputColor : InputColorRequiredFields -> InputColor buildInputColor required____ = { foregroundColor = required____.foregroundColor, backgroundColor = required____.backgroundColor } type alias InputColorRequiredFields = { foregroundColor : String , backgroundColor : String } {-| Type for the InputColor input object. -} type alias InputColor = { foregroundColor : String , backgroundColor : String } {-| Encode a InputColor into a value that can be used as an argument. -} encodeInputColor : InputColor -> Value encodeInputColor input____ = Encode.maybeObject [ ( "foregroundColor", Encode.string input____.foregroundColor |> Just ), ( "backgroundColor", Encode.string input____.backgroundColor |> Just ) ] buildInputGistItem : InputGistItemRequiredFields -> (InputGistItemOptionalFields -> InputGistItemOptionalFields) -> InputGistItem buildInputGistItem required____ fillOptionals____ = let optionals____ = fillOptionals____ { id = Absent, thumbnail = Absent } in { id = optionals____.id, title = required____.title, thumbnail = optionals____.thumbnail, diagram = required____.diagram, isBookmark = required____.isBookmark, url = required____.url } type alias InputGistItemRequiredFields = { title : String , diagram : Graphql.Enum.Diagram.Diagram , isBookmark : Bool , url : String } type alias InputGistItemOptionalFields = { id : OptionalArgument Graphql.ScalarCodecs.GistIdScalar , thumbnail : OptionalArgument String } {-| Type for the InputGistItem input object. -} type alias InputGistItem = { id : OptionalArgument Graphql.ScalarCodecs.GistIdScalar , title : String , thumbnail : OptionalArgument String , diagram : Graphql.Enum.Diagram.Diagram , isBookmark : Bool , url : String } {-| Encode a InputGistItem into a value that can be used as an argument. -} encodeInputGistItem : InputGistItem -> Value encodeInputGistItem input____ = Encode.maybeObject [ ( "id", (Graphql.ScalarCodecs.codecs |> Graphql.Scalar.unwrapEncoder .codecGistIdScalar) |> Encode.optional input____.id ), ( "title", Encode.string input____.title |> Just ), ( "thumbnail", Encode.string |> Encode.optional input____.thumbnail ), ( "diagram", Encode.enum Graphql.Enum.Diagram.toString input____.diagram |> Just ), ( "isBookmark", Encode.bool input____.isBookmark |> Just ), ( "url", Encode.string input____.url |> Just ) ] buildInputItem : InputItemRequiredFields -> (InputItemOptionalFields -> InputItemOptionalFields) -> InputItem buildInputItem required____ fillOptionals____ = let optionals____ = fillOptionals____ { id = Absent, thumbnail = Absent } in { id = optionals____.id, title = required____.title, text = required____.text, thumbnail = optionals____.thumbnail, diagram = required____.diagram, isPublic = required____.isPublic, isBookmark = required____.isBookmark } type alias InputItemRequiredFields = { title : String , text : String , diagram : Graphql.Enum.Diagram.Diagram , isPublic : Bool , isBookmark : Bool } type alias InputItemOptionalFields = { id : OptionalArgument Graphql.ScalarCodecs.ItemIdScalar , thumbnail : OptionalArgument String } {-| Type for the InputItem input object. -} type alias InputItem = { id : OptionalArgument Graphql.ScalarCodecs.ItemIdScalar , title : String , text : String , thumbnail : OptionalArgument String , diagram : Graphql.Enum.Diagram.Diagram , isPublic : Bool , isBookmark : Bool } {-| Encode a InputItem into a value that can be used as an argument. -} encodeInputItem : InputItem -> Value encodeInputItem input____ = Encode.maybeObject [ ( "id", (Graphql.ScalarCodecs.codecs |> Graphql.Scalar.unwrapEncoder .codecItemIdScalar) |> Encode.optional input____.id ), ( "title", Encode.string input____.title |> Just ), ( "text", Encode.string input____.text |> Just ), ( "thumbnail", Encode.string |> Encode.optional input____.thumbnail ), ( "diagram", Encode.enum Graphql.Enum.Diagram.toString input____.diagram |> Just ), ( "isPublic", Encode.bool input____.isPublic |> Just ), ( "isBookmark", Encode.bool input____.isBookmark |> Just ) ] buildInputSettings : InputSettingsRequiredFields -> (InputSettingsOptionalFields -> InputSettingsOptionalFields) -> InputSettings buildInputSettings required____ fillOptionals____ = let optionals____ = fillOptionals____ { textColor = Absent, zoomControl = Absent, scale = Absent } in { font = required____.font, width = required____.width, height = required____.height, backgroundColor = required____.backgroundColor, activityColor = required____.activityColor, taskColor = required____.taskColor, storyColor = required____.storyColor, lineColor = required____.lineColor, labelColor = required____.labelColor, textColor = optionals____.textColor, zoomControl = optionals____.zoomControl, scale = optionals____.scale } type alias InputSettingsRequiredFields = { font : String , width : Int , height : Int , backgroundColor : String , activityColor : InputColor , taskColor : InputColor , storyColor : InputColor , lineColor : String , labelColor : String } type alias InputSettingsOptionalFields = { textColor : OptionalArgument String , zoomControl : OptionalArgument Bool , scale : OptionalArgument Float } {-| Type for the InputSettings input object. -} type alias InputSettings = { font : String , width : Int , height : Int , backgroundColor : String , activityColor : InputColor , taskColor : InputColor , storyColor : InputColor , lineColor : String , labelColor : String , textColor : OptionalArgument String , zoomControl : OptionalArgument Bool , scale : OptionalArgument Float } {-| Encode a InputSettings into a value that can be used as an argument. -} encodeInputSettings : InputSettings -> Value encodeInputSettings input____ = Encode.maybeObject [ ( "font", Encode.string input____.font |> Just ), ( "width", Encode.int input____.width |> Just ), ( "height", Encode.int input____.height |> Just ), ( "backgroundColor", Encode.string input____.backgroundColor |> Just ), ( "activityColor", encodeInputColor input____.activityColor |> Just ), ( "taskColor", encodeInputColor input____.taskColor |> Just ), ( "storyColor", encodeInputColor input____.storyColor |> Just ), ( "lineColor", Encode.string input____.lineColor |> Just ), ( "labelColor", Encode.string input____.labelColor |> Just ), ( "textColor", Encode.string |> Encode.optional input____.textColor ), ( "zoomControl", Encode.bool |> Encode.optional input____.zoomControl ), ( "scale", Encode.float |> Encode.optional input____.scale ) ] buildInputShareItem : InputShareItemRequiredFields -> (InputShareItemOptionalFields -> InputShareItemOptionalFields) -> InputShareItem buildInputShareItem required____ fillOptionals____ = let optionals____ = fillOptionals____ { expSecond = Absent, password = Absent, allowIPList = Absent, allowEmailList = Absent } in { itemID = required____.itemID, expSecond = optionals____.expSecond, password = optionals____.password, allowIPList = optionals____.allowIPList, allowEmailList = optionals____.allowEmailList } type alias InputShareItemRequiredFields = { itemID : Graphql.ScalarCodecs.ItemIdScalar } type alias InputShareItemOptionalFields = { expSecond : OptionalArgument Int , password : OptionalArgument String , allowIPList : OptionalArgument (List String) , allowEmailList : OptionalArgument (List String) } {-| Type for the InputShareItem input object. -} type alias InputShareItem = { itemID : Graphql.ScalarCodecs.ItemIdScalar , expSecond : OptionalArgument Int , password : OptionalArgument String , allowIPList : OptionalArgument (List String) , allowEmailList : OptionalArgument (List String) } {-| Encode a InputShareItem into a value that can be used as an argument. -} encodeInputShareItem : InputShareItem -> Value encodeInputShareItem input____ = Encode.maybeObject [ ( "itemID", (Graphql.ScalarCodecs.codecs |> Graphql.Scalar.unwrapEncoder .codecItemIdScalar) input____.itemID |> Just ), ( "expSecond", Encode.int |> Encode.optional input____.expSecond ), ( "password", Encode.string |> Encode.optional input____.password ), ( "allowIPList", (Encode.string |> Encode.list) |> Encode.optional input____.allowIPList ), ( "allowEmailList", (Encode.string |> Encode.list) |> Encode.optional input____.allowEmailList ) ]
35765
-- Do not manually edit this file, it was auto-generated by dillonkearns/elm-graphql -- https://github.com/dillonkearns/elm-graphql module Graphql.InputObject exposing (..) import Graphql.Enum.Diagram import Graphql.Internal.Encode as Encode exposing (Value) import Graphql.OptionalArgument exposing (OptionalArgument(..)) import Graphql.Scalar import Graphql.ScalarCodecs buildInputColor : InputColorRequiredFields -> InputColor buildInputColor required____ = { foregroundColor = required____.foregroundColor, backgroundColor = required____.backgroundColor } type alias InputColorRequiredFields = { foregroundColor : String , backgroundColor : String } {-| Type for the InputColor input object. -} type alias InputColor = { foregroundColor : String , backgroundColor : String } {-| Encode a InputColor into a value that can be used as an argument. -} encodeInputColor : InputColor -> Value encodeInputColor input____ = Encode.maybeObject [ ( "foregroundColor", Encode.string input____.foregroundColor |> Just ), ( "backgroundColor", Encode.string input____.backgroundColor |> Just ) ] buildInputGistItem : InputGistItemRequiredFields -> (InputGistItemOptionalFields -> InputGistItemOptionalFields) -> InputGistItem buildInputGistItem required____ fillOptionals____ = let optionals____ = fillOptionals____ { id = Absent, thumbnail = Absent } in { id = optionals____.id, title = required____.title, thumbnail = optionals____.thumbnail, diagram = required____.diagram, isBookmark = required____.isBookmark, url = required____.url } type alias InputGistItemRequiredFields = { title : String , diagram : Graphql.Enum.Diagram.Diagram , isBookmark : Bool , url : String } type alias InputGistItemOptionalFields = { id : OptionalArgument Graphql.ScalarCodecs.GistIdScalar , thumbnail : OptionalArgument String } {-| Type for the InputGistItem input object. -} type alias InputGistItem = { id : OptionalArgument Graphql.ScalarCodecs.GistIdScalar , title : String , thumbnail : OptionalArgument String , diagram : Graphql.Enum.Diagram.Diagram , isBookmark : Bool , url : String } {-| Encode a InputGistItem into a value that can be used as an argument. -} encodeInputGistItem : InputGistItem -> Value encodeInputGistItem input____ = Encode.maybeObject [ ( "id", (Graphql.ScalarCodecs.codecs |> Graphql.Scalar.unwrapEncoder .codecGistIdScalar) |> Encode.optional input____.id ), ( "title", Encode.string input____.title |> Just ), ( "thumbnail", Encode.string |> Encode.optional input____.thumbnail ), ( "diagram", Encode.enum Graphql.Enum.Diagram.toString input____.diagram |> Just ), ( "isBookmark", Encode.bool input____.isBookmark |> Just ), ( "url", Encode.string input____.url |> Just ) ] buildInputItem : InputItemRequiredFields -> (InputItemOptionalFields -> InputItemOptionalFields) -> InputItem buildInputItem required____ fillOptionals____ = let optionals____ = fillOptionals____ { id = Absent, thumbnail = Absent } in { id = optionals____.id, title = required____.title, text = required____.text, thumbnail = optionals____.thumbnail, diagram = required____.diagram, isPublic = required____.isPublic, isBookmark = required____.isBookmark } type alias InputItemRequiredFields = { title : String , text : String , diagram : Graphql.Enum.Diagram.Diagram , isPublic : Bool , isBookmark : Bool } type alias InputItemOptionalFields = { id : OptionalArgument Graphql.ScalarCodecs.ItemIdScalar , thumbnail : OptionalArgument String } {-| Type for the InputItem input object. -} type alias InputItem = { id : OptionalArgument Graphql.ScalarCodecs.ItemIdScalar , title : String , text : String , thumbnail : OptionalArgument String , diagram : Graphql.Enum.Diagram.Diagram , isPublic : Bool , isBookmark : Bool } {-| Encode a InputItem into a value that can be used as an argument. -} encodeInputItem : InputItem -> Value encodeInputItem input____ = Encode.maybeObject [ ( "id", (Graphql.ScalarCodecs.codecs |> Graphql.Scalar.unwrapEncoder .codecItemIdScalar) |> Encode.optional input____.id ), ( "title", Encode.string input____.title |> Just ), ( "text", Encode.string input____.text |> Just ), ( "thumbnail", Encode.string |> Encode.optional input____.thumbnail ), ( "diagram", Encode.enum Graphql.Enum.Diagram.toString input____.diagram |> Just ), ( "isPublic", Encode.bool input____.isPublic |> Just ), ( "isBookmark", Encode.bool input____.isBookmark |> Just ) ] buildInputSettings : InputSettingsRequiredFields -> (InputSettingsOptionalFields -> InputSettingsOptionalFields) -> InputSettings buildInputSettings required____ fillOptionals____ = let optionals____ = fillOptionals____ { textColor = Absent, zoomControl = Absent, scale = Absent } in { font = required____.font, width = required____.width, height = required____.height, backgroundColor = required____.backgroundColor, activityColor = required____.activityColor, taskColor = required____.taskColor, storyColor = required____.storyColor, lineColor = required____.lineColor, labelColor = required____.labelColor, textColor = optionals____.textColor, zoomControl = optionals____.zoomControl, scale = optionals____.scale } type alias InputSettingsRequiredFields = { font : String , width : Int , height : Int , backgroundColor : String , activityColor : InputColor , taskColor : InputColor , storyColor : InputColor , lineColor : String , labelColor : String } type alias InputSettingsOptionalFields = { textColor : OptionalArgument String , zoomControl : OptionalArgument Bool , scale : OptionalArgument Float } {-| Type for the InputSettings input object. -} type alias InputSettings = { font : String , width : Int , height : Int , backgroundColor : String , activityColor : InputColor , taskColor : InputColor , storyColor : InputColor , lineColor : String , labelColor : String , textColor : OptionalArgument String , zoomControl : OptionalArgument Bool , scale : OptionalArgument Float } {-| Encode a InputSettings into a value that can be used as an argument. -} encodeInputSettings : InputSettings -> Value encodeInputSettings input____ = Encode.maybeObject [ ( "font", Encode.string input____.font |> Just ), ( "width", Encode.int input____.width |> Just ), ( "height", Encode.int input____.height |> Just ), ( "backgroundColor", Encode.string input____.backgroundColor |> Just ), ( "activityColor", encodeInputColor input____.activityColor |> Just ), ( "taskColor", encodeInputColor input____.taskColor |> Just ), ( "storyColor", encodeInputColor input____.storyColor |> Just ), ( "lineColor", Encode.string input____.lineColor |> Just ), ( "labelColor", Encode.string input____.labelColor |> Just ), ( "textColor", Encode.string |> Encode.optional input____.textColor ), ( "zoomControl", Encode.bool |> Encode.optional input____.zoomControl ), ( "scale", Encode.float |> Encode.optional input____.scale ) ] buildInputShareItem : InputShareItemRequiredFields -> (InputShareItemOptionalFields -> InputShareItemOptionalFields) -> InputShareItem buildInputShareItem required____ fillOptionals____ = let optionals____ = fillOptionals____ { expSecond = Absent, password = Absent, allowIPList = Absent, allowEmailList = Absent } in { itemID = required____.itemID, expSecond = optionals____.expSecond, password = option<PASSWORD>, allowIPList = optionals____.allowIPList, allowEmailList = optionals____.allowEmailList } type alias InputShareItemRequiredFields = { itemID : Graphql.ScalarCodecs.ItemIdScalar } type alias InputShareItemOptionalFields = { expSecond : OptionalArgument Int , password : OptionalArgument String , allowIPList : OptionalArgument (List String) , allowEmailList : OptionalArgument (List String) } {-| Type for the InputShareItem input object. -} type alias InputShareItem = { itemID : Graphql.ScalarCodecs.ItemIdScalar , expSecond : OptionalArgument Int , password : OptionalArgument String , allowIPList : OptionalArgument (List String) , allowEmailList : OptionalArgument (List String) } {-| Encode a InputShareItem into a value that can be used as an argument. -} encodeInputShareItem : InputShareItem -> Value encodeInputShareItem input____ = Encode.maybeObject [ ( "itemID", (Graphql.ScalarCodecs.codecs |> Graphql.Scalar.unwrapEncoder .codecItemIdScalar) input____.itemID |> Just ), ( "expSecond", Encode.int |> Encode.optional input____.expSecond ), ( "password", Encode.string |> Encode.optional input____.password ), ( "allowIPList", (Encode.string |> Encode.list) |> Encode.optional input____.allowIPList ), ( "allowEmailList", (Encode.string |> Encode.list) |> Encode.optional input____.allowEmailList ) ]
true
-- Do not manually edit this file, it was auto-generated by dillonkearns/elm-graphql -- https://github.com/dillonkearns/elm-graphql module Graphql.InputObject exposing (..) import Graphql.Enum.Diagram import Graphql.Internal.Encode as Encode exposing (Value) import Graphql.OptionalArgument exposing (OptionalArgument(..)) import Graphql.Scalar import Graphql.ScalarCodecs buildInputColor : InputColorRequiredFields -> InputColor buildInputColor required____ = { foregroundColor = required____.foregroundColor, backgroundColor = required____.backgroundColor } type alias InputColorRequiredFields = { foregroundColor : String , backgroundColor : String } {-| Type for the InputColor input object. -} type alias InputColor = { foregroundColor : String , backgroundColor : String } {-| Encode a InputColor into a value that can be used as an argument. -} encodeInputColor : InputColor -> Value encodeInputColor input____ = Encode.maybeObject [ ( "foregroundColor", Encode.string input____.foregroundColor |> Just ), ( "backgroundColor", Encode.string input____.backgroundColor |> Just ) ] buildInputGistItem : InputGistItemRequiredFields -> (InputGistItemOptionalFields -> InputGistItemOptionalFields) -> InputGistItem buildInputGistItem required____ fillOptionals____ = let optionals____ = fillOptionals____ { id = Absent, thumbnail = Absent } in { id = optionals____.id, title = required____.title, thumbnail = optionals____.thumbnail, diagram = required____.diagram, isBookmark = required____.isBookmark, url = required____.url } type alias InputGistItemRequiredFields = { title : String , diagram : Graphql.Enum.Diagram.Diagram , isBookmark : Bool , url : String } type alias InputGistItemOptionalFields = { id : OptionalArgument Graphql.ScalarCodecs.GistIdScalar , thumbnail : OptionalArgument String } {-| Type for the InputGistItem input object. -} type alias InputGistItem = { id : OptionalArgument Graphql.ScalarCodecs.GistIdScalar , title : String , thumbnail : OptionalArgument String , diagram : Graphql.Enum.Diagram.Diagram , isBookmark : Bool , url : String } {-| Encode a InputGistItem into a value that can be used as an argument. -} encodeInputGistItem : InputGistItem -> Value encodeInputGistItem input____ = Encode.maybeObject [ ( "id", (Graphql.ScalarCodecs.codecs |> Graphql.Scalar.unwrapEncoder .codecGistIdScalar) |> Encode.optional input____.id ), ( "title", Encode.string input____.title |> Just ), ( "thumbnail", Encode.string |> Encode.optional input____.thumbnail ), ( "diagram", Encode.enum Graphql.Enum.Diagram.toString input____.diagram |> Just ), ( "isBookmark", Encode.bool input____.isBookmark |> Just ), ( "url", Encode.string input____.url |> Just ) ] buildInputItem : InputItemRequiredFields -> (InputItemOptionalFields -> InputItemOptionalFields) -> InputItem buildInputItem required____ fillOptionals____ = let optionals____ = fillOptionals____ { id = Absent, thumbnail = Absent } in { id = optionals____.id, title = required____.title, text = required____.text, thumbnail = optionals____.thumbnail, diagram = required____.diagram, isPublic = required____.isPublic, isBookmark = required____.isBookmark } type alias InputItemRequiredFields = { title : String , text : String , diagram : Graphql.Enum.Diagram.Diagram , isPublic : Bool , isBookmark : Bool } type alias InputItemOptionalFields = { id : OptionalArgument Graphql.ScalarCodecs.ItemIdScalar , thumbnail : OptionalArgument String } {-| Type for the InputItem input object. -} type alias InputItem = { id : OptionalArgument Graphql.ScalarCodecs.ItemIdScalar , title : String , text : String , thumbnail : OptionalArgument String , diagram : Graphql.Enum.Diagram.Diagram , isPublic : Bool , isBookmark : Bool } {-| Encode a InputItem into a value that can be used as an argument. -} encodeInputItem : InputItem -> Value encodeInputItem input____ = Encode.maybeObject [ ( "id", (Graphql.ScalarCodecs.codecs |> Graphql.Scalar.unwrapEncoder .codecItemIdScalar) |> Encode.optional input____.id ), ( "title", Encode.string input____.title |> Just ), ( "text", Encode.string input____.text |> Just ), ( "thumbnail", Encode.string |> Encode.optional input____.thumbnail ), ( "diagram", Encode.enum Graphql.Enum.Diagram.toString input____.diagram |> Just ), ( "isPublic", Encode.bool input____.isPublic |> Just ), ( "isBookmark", Encode.bool input____.isBookmark |> Just ) ] buildInputSettings : InputSettingsRequiredFields -> (InputSettingsOptionalFields -> InputSettingsOptionalFields) -> InputSettings buildInputSettings required____ fillOptionals____ = let optionals____ = fillOptionals____ { textColor = Absent, zoomControl = Absent, scale = Absent } in { font = required____.font, width = required____.width, height = required____.height, backgroundColor = required____.backgroundColor, activityColor = required____.activityColor, taskColor = required____.taskColor, storyColor = required____.storyColor, lineColor = required____.lineColor, labelColor = required____.labelColor, textColor = optionals____.textColor, zoomControl = optionals____.zoomControl, scale = optionals____.scale } type alias InputSettingsRequiredFields = { font : String , width : Int , height : Int , backgroundColor : String , activityColor : InputColor , taskColor : InputColor , storyColor : InputColor , lineColor : String , labelColor : String } type alias InputSettingsOptionalFields = { textColor : OptionalArgument String , zoomControl : OptionalArgument Bool , scale : OptionalArgument Float } {-| Type for the InputSettings input object. -} type alias InputSettings = { font : String , width : Int , height : Int , backgroundColor : String , activityColor : InputColor , taskColor : InputColor , storyColor : InputColor , lineColor : String , labelColor : String , textColor : OptionalArgument String , zoomControl : OptionalArgument Bool , scale : OptionalArgument Float } {-| Encode a InputSettings into a value that can be used as an argument. -} encodeInputSettings : InputSettings -> Value encodeInputSettings input____ = Encode.maybeObject [ ( "font", Encode.string input____.font |> Just ), ( "width", Encode.int input____.width |> Just ), ( "height", Encode.int input____.height |> Just ), ( "backgroundColor", Encode.string input____.backgroundColor |> Just ), ( "activityColor", encodeInputColor input____.activityColor |> Just ), ( "taskColor", encodeInputColor input____.taskColor |> Just ), ( "storyColor", encodeInputColor input____.storyColor |> Just ), ( "lineColor", Encode.string input____.lineColor |> Just ), ( "labelColor", Encode.string input____.labelColor |> Just ), ( "textColor", Encode.string |> Encode.optional input____.textColor ), ( "zoomControl", Encode.bool |> Encode.optional input____.zoomControl ), ( "scale", Encode.float |> Encode.optional input____.scale ) ] buildInputShareItem : InputShareItemRequiredFields -> (InputShareItemOptionalFields -> InputShareItemOptionalFields) -> InputShareItem buildInputShareItem required____ fillOptionals____ = let optionals____ = fillOptionals____ { expSecond = Absent, password = Absent, allowIPList = Absent, allowEmailList = Absent } in { itemID = required____.itemID, expSecond = optionals____.expSecond, password = optionPI:PASSWORD:<PASSWORD>END_PI, allowIPList = optionals____.allowIPList, allowEmailList = optionals____.allowEmailList } type alias InputShareItemRequiredFields = { itemID : Graphql.ScalarCodecs.ItemIdScalar } type alias InputShareItemOptionalFields = { expSecond : OptionalArgument Int , password : OptionalArgument String , allowIPList : OptionalArgument (List String) , allowEmailList : OptionalArgument (List String) } {-| Type for the InputShareItem input object. -} type alias InputShareItem = { itemID : Graphql.ScalarCodecs.ItemIdScalar , expSecond : OptionalArgument Int , password : OptionalArgument String , allowIPList : OptionalArgument (List String) , allowEmailList : OptionalArgument (List String) } {-| Encode a InputShareItem into a value that can be used as an argument. -} encodeInputShareItem : InputShareItem -> Value encodeInputShareItem input____ = Encode.maybeObject [ ( "itemID", (Graphql.ScalarCodecs.codecs |> Graphql.Scalar.unwrapEncoder .codecItemIdScalar) input____.itemID |> Just ), ( "expSecond", Encode.int |> Encode.optional input____.expSecond ), ( "password", Encode.string |> Encode.optional input____.password ), ( "allowIPList", (Encode.string |> Encode.list) |> Encode.optional input____.allowIPList ), ( "allowEmailList", (Encode.string |> Encode.list) |> Encode.optional input____.allowEmailList ) ]
elm
[ { "context": "{- Copyright (c) 2019 Orange\n This code is released under the MIT license.\n\n", "end": 28, "score": 0.700394094, "start": 22, "tag": "NAME", "value": "Orange" } ]
src/Grid/Parsers.elm
doktorBreizh/elm-advanced-grid
1
{- Copyright (c) 2019 Orange This code is released under the MIT license. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} module Grid.Parsers exposing ( boolParser , containsParser , equalityParser , greaterThanParser , lessThanParser , stringParser ) import Parser exposing ((|.), Parser, chompUntilEndOr, getChompedString, keyword, oneOf, spaces, succeed, symbol) equalityParser : Parser (a -> a) equalityParser = succeed identity |. spaces |. symbol "=" |. spaces containsParser : Parser (a -> a) containsParser = succeed identity lessThanParser : Parser (a -> a) lessThanParser = succeed identity |. spaces |. symbol "<" |. spaces greaterThanParser : Parser (a -> a) greaterThanParser = succeed identity |. spaces |. symbol ">" |. spaces stringParser : Parser String stringParser = -- the input string cannot contain "\t" -- another implementation is: -- getChompedString <| chompWhile (\c -> True) getChompedString <| chompUntilEndOr "\u{0000}" boolParser : Parser Bool boolParser = oneOf [ succeed True |. keyword "true" , succeed False |. keyword "false" ]
12940
{- Copyright (c) 2019 <NAME> This code is released under the MIT license. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} module Grid.Parsers exposing ( boolParser , containsParser , equalityParser , greaterThanParser , lessThanParser , stringParser ) import Parser exposing ((|.), Parser, chompUntilEndOr, getChompedString, keyword, oneOf, spaces, succeed, symbol) equalityParser : Parser (a -> a) equalityParser = succeed identity |. spaces |. symbol "=" |. spaces containsParser : Parser (a -> a) containsParser = succeed identity lessThanParser : Parser (a -> a) lessThanParser = succeed identity |. spaces |. symbol "<" |. spaces greaterThanParser : Parser (a -> a) greaterThanParser = succeed identity |. spaces |. symbol ">" |. spaces stringParser : Parser String stringParser = -- the input string cannot contain "\t" -- another implementation is: -- getChompedString <| chompWhile (\c -> True) getChompedString <| chompUntilEndOr "\u{0000}" boolParser : Parser Bool boolParser = oneOf [ succeed True |. keyword "true" , succeed False |. keyword "false" ]
true
{- Copyright (c) 2019 PI:NAME:<NAME>END_PI This code is released under the MIT license. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} module Grid.Parsers exposing ( boolParser , containsParser , equalityParser , greaterThanParser , lessThanParser , stringParser ) import Parser exposing ((|.), Parser, chompUntilEndOr, getChompedString, keyword, oneOf, spaces, succeed, symbol) equalityParser : Parser (a -> a) equalityParser = succeed identity |. spaces |. symbol "=" |. spaces containsParser : Parser (a -> a) containsParser = succeed identity lessThanParser : Parser (a -> a) lessThanParser = succeed identity |. spaces |. symbol "<" |. spaces greaterThanParser : Parser (a -> a) greaterThanParser = succeed identity |. spaces |. symbol ">" |. spaces stringParser : Parser String stringParser = -- the input string cannot contain "\t" -- another implementation is: -- getChompedString <| chompWhile (\c -> True) getChompedString <| chompUntilEndOr "\u{0000}" boolParser : Parser Bool boolParser = oneOf [ succeed True |. keyword "true" , succeed False |. keyword "false" ]
elm
[ { "context": "\n , credentials = Client.Credentials \"welkin\" \"foobar\"\n }\n in\n ( { cli", "end": 742, "score": 0.6790133715, "start": 740, "tag": "PASSWORD", "value": "el" } ]
examples/src/Main.elm
ericnething/elm-xmpp
1
module Main exposing (main) import Browser import Html exposing (Html, button, div, input, pre, text) import Html.Attributes exposing (class, value) import Html.Events exposing (onClick, onInput) import Http import Client -- MAIN main = Browser.element { init = init , update = update , subscriptions = subscriptions , view = view } -- MODEL type alias Model = { client : Client.Model , toSend : String , sentMessages : List String , receivedMessages : List String } init : () -> ( Model, Cmd Msg ) init _ = let (client, cmd) = Client.init { url = "ws://localhost:5280/ws-xmpp" , credentials = Client.Credentials "welkin" "foobar" } in ( { client = client , toSend = """<open xmlns="urn:ietf:params:xml:ns:xmpp-framing" xml:lang="en" to="localhost" version="1.0"/>""" , sentMessages = [] , receivedMessages = [] } , Cmd.map ClientMsg cmd ) -- UPDATE type Msg = ClientMsg Client.Msg | UpdateInput String | SendString update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ClientMsg clientMsg -> let (newClient, cmd, externalMsg) = Client.update clientMsg model.client (updatedModel, externalCmd) = handleClientMsg externalMsg { model | client = newClient} in ( updatedModel , Cmd.batch [ Cmd.map ClientMsg cmd , externalCmd ] ) UpdateInput string -> ( { model | toSend = string }, Cmd.none ) SendString -> ( { model | sentMessages = model.toSend :: model.sentMessages } , Cmd.map ClientMsg (Client.send model.toSend) ) handleClientMsg : Client.ExternalMsg -> Model -> (Model, Cmd Msg) handleClientMsg msg model = case msg of Client.None -> (model, Cmd.none) Client.Message message -> ({ model | receivedMessages = message :: model.receivedMessages } , Cmd.none) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.map ClientMsg (Client.subscriptions model.client) -- VIEW view : Model -> Html Msg view model = div [] [ connectionState model , stringMsgControls model ] connectionState model = div [] [ case model.client.socketInfo of Nothing -> text "Connecting..." Just info -> div [] [ text "Connected to " , text info.url ] ] stringMsgControls : Model -> Html Msg stringMsgControls model = div [] [ div [] [ button [ onClick SendString ] [ text "Send" ] , input [ onInput UpdateInput, value model.toSend ] [] ] , div [] [ div [ class "sent" ] (div [] [ text "Sent" ] :: List.map messageInfo model.sentMessages ) , div [] (div [] [ text "Received" ] :: List.map messageInfo model.receivedMessages ) ] ] messageInfo : String -> Html Msg messageInfo message = div [] [ text message ]
36780
module Main exposing (main) import Browser import Html exposing (Html, button, div, input, pre, text) import Html.Attributes exposing (class, value) import Html.Events exposing (onClick, onInput) import Http import Client -- MAIN main = Browser.element { init = init , update = update , subscriptions = subscriptions , view = view } -- MODEL type alias Model = { client : Client.Model , toSend : String , sentMessages : List String , receivedMessages : List String } init : () -> ( Model, Cmd Msg ) init _ = let (client, cmd) = Client.init { url = "ws://localhost:5280/ws-xmpp" , credentials = Client.Credentials "w<PASSWORD>kin" "foobar" } in ( { client = client , toSend = """<open xmlns="urn:ietf:params:xml:ns:xmpp-framing" xml:lang="en" to="localhost" version="1.0"/>""" , sentMessages = [] , receivedMessages = [] } , Cmd.map ClientMsg cmd ) -- UPDATE type Msg = ClientMsg Client.Msg | UpdateInput String | SendString update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ClientMsg clientMsg -> let (newClient, cmd, externalMsg) = Client.update clientMsg model.client (updatedModel, externalCmd) = handleClientMsg externalMsg { model | client = newClient} in ( updatedModel , Cmd.batch [ Cmd.map ClientMsg cmd , externalCmd ] ) UpdateInput string -> ( { model | toSend = string }, Cmd.none ) SendString -> ( { model | sentMessages = model.toSend :: model.sentMessages } , Cmd.map ClientMsg (Client.send model.toSend) ) handleClientMsg : Client.ExternalMsg -> Model -> (Model, Cmd Msg) handleClientMsg msg model = case msg of Client.None -> (model, Cmd.none) Client.Message message -> ({ model | receivedMessages = message :: model.receivedMessages } , Cmd.none) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.map ClientMsg (Client.subscriptions model.client) -- VIEW view : Model -> Html Msg view model = div [] [ connectionState model , stringMsgControls model ] connectionState model = div [] [ case model.client.socketInfo of Nothing -> text "Connecting..." Just info -> div [] [ text "Connected to " , text info.url ] ] stringMsgControls : Model -> Html Msg stringMsgControls model = div [] [ div [] [ button [ onClick SendString ] [ text "Send" ] , input [ onInput UpdateInput, value model.toSend ] [] ] , div [] [ div [ class "sent" ] (div [] [ text "Sent" ] :: List.map messageInfo model.sentMessages ) , div [] (div [] [ text "Received" ] :: List.map messageInfo model.receivedMessages ) ] ] messageInfo : String -> Html Msg messageInfo message = div [] [ text message ]
true
module Main exposing (main) import Browser import Html exposing (Html, button, div, input, pre, text) import Html.Attributes exposing (class, value) import Html.Events exposing (onClick, onInput) import Http import Client -- MAIN main = Browser.element { init = init , update = update , subscriptions = subscriptions , view = view } -- MODEL type alias Model = { client : Client.Model , toSend : String , sentMessages : List String , receivedMessages : List String } init : () -> ( Model, Cmd Msg ) init _ = let (client, cmd) = Client.init { url = "ws://localhost:5280/ws-xmpp" , credentials = Client.Credentials "wPI:PASSWORD:<PASSWORD>END_PIkin" "foobar" } in ( { client = client , toSend = """<open xmlns="urn:ietf:params:xml:ns:xmpp-framing" xml:lang="en" to="localhost" version="1.0"/>""" , sentMessages = [] , receivedMessages = [] } , Cmd.map ClientMsg cmd ) -- UPDATE type Msg = ClientMsg Client.Msg | UpdateInput String | SendString update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ClientMsg clientMsg -> let (newClient, cmd, externalMsg) = Client.update clientMsg model.client (updatedModel, externalCmd) = handleClientMsg externalMsg { model | client = newClient} in ( updatedModel , Cmd.batch [ Cmd.map ClientMsg cmd , externalCmd ] ) UpdateInput string -> ( { model | toSend = string }, Cmd.none ) SendString -> ( { model | sentMessages = model.toSend :: model.sentMessages } , Cmd.map ClientMsg (Client.send model.toSend) ) handleClientMsg : Client.ExternalMsg -> Model -> (Model, Cmd Msg) handleClientMsg msg model = case msg of Client.None -> (model, Cmd.none) Client.Message message -> ({ model | receivedMessages = message :: model.receivedMessages } , Cmd.none) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.map ClientMsg (Client.subscriptions model.client) -- VIEW view : Model -> Html Msg view model = div [] [ connectionState model , stringMsgControls model ] connectionState model = div [] [ case model.client.socketInfo of Nothing -> text "Connecting..." Just info -> div [] [ text "Connected to " , text info.url ] ] stringMsgControls : Model -> Html Msg stringMsgControls model = div [] [ div [] [ button [ onClick SendString ] [ text "Send" ] , input [ onInput UpdateInput, value model.toSend ] [] ] , div [] [ div [ class "sent" ] (div [] [ text "Sent" ] :: List.map messageInfo model.sentMessages ) , div [] (div [] [ text "Received" ] :: List.map messageInfo model.receivedMessages ) ] ] messageInfo : String -> Html Msg messageInfo message = div [] [ text message ]
elm
[ { "context": "h\"\n [ \"query\" => query\n , \"key\" => \"AIzaSyC-CzQ4NzurDdc9d7ItDLlUi--K0KDC9ZI\"\n , \"limit\" => \"10\"\n , \"indent\" => ", "end": 2299, "score": 0.9997600317, "start": 2260, "tag": "KEY", "value": "AIzaSyC-CzQ4NzurDdc9d7ItDLlUi--K0KDC9ZI" } ]
EntityTableSearchContainer.elm
justinsacbibit/elm-knowledge-graph
0
module EntityTableSearchContainer where import Effects exposing (Effects, batch, map) import Html exposing (..) import Http import Json.Decode as Json exposing ((:=)) import Task import SearchBox import EntityTable import EntityRow -- MODEL type alias Model = { search : SearchBox.Model , table : Maybe EntityTable.Model } init : (Model, Effects Action) init = let (search, fx) = SearchBox.init in ( Model search Nothing , map SearchBox fx ) -- UPDATE type Action = NoOp | SearchBox SearchBox.Action | Search String | NewEntities (Maybe EntityTable.Model) update : Action -> Model -> (Model, Effects Action) update action model = case action of NoOp -> ( model , Effects.none ) SearchBox searchAction -> let (searchBox, fx) = SearchBox.update searchAction model.search in ( { model | search = searchBox } , map SearchBox fx ) Search query -> let fx = searchKnowledgeGraph query in ( model , fx ) NewEntities maybeEntities -> ( { model | table = maybeEntities } , Effects.none ) -- VIEW view : Signal.Address Action -> Model -> Html view address model = let tableModel = case model.table of Just a -> a Nothing -> [] context = SearchBox.Context (Signal.forwardTo address SearchBox) (Signal.forwardTo address Search) in div [] [ SearchBox.view context model.search , EntityTable.view (Signal.forwardTo address (always NoOp)) tableModel ] -- EFFECTS searchKnowledgeGraph : String -> Effects Action searchKnowledgeGraph query = Http.get decodeData (queryUrl query) |> Task.toMaybe |> Task.map NewEntities |> Effects.task (=>) : a -> b -> ( a, b ) (=>) = (,) -- Black magic operator queryUrl : String -> String queryUrl query = Http.url "https://kgsearch.googleapis.com/v1/entities:search" [ "query" => query , "key" => "AIzaSyC-CzQ4NzurDdc9d7ItDLlUi--K0KDC9ZI" , "limit" => "10" , "indent" => "false" ] decoder : Json.Decoder EntityRow.Model decoder = Json.object6 EntityRow.Model (Json.at ["result", "name"] Json.string) (Json.at ["result", "@type"] (Json.list Json.string)) (Json.maybe (Json.at ["result", "description"] Json.string)) (Json.maybe (Json.at ["result", "image", "contentUrl"] Json.string)) (Json.maybe (Json.at ["result", "detailedDescription"] (Json.object2 EntityRow.DetailedDescription ("articleBody" := Json.string) ("url" := Json.string) ) ) ) (Json.at ["resultScore"] Json.float) decodeData : Json.Decoder (List EntityRow.Model) decodeData = Json.at ["itemListElement"] (Json.list decoder)
34516
module EntityTableSearchContainer where import Effects exposing (Effects, batch, map) import Html exposing (..) import Http import Json.Decode as Json exposing ((:=)) import Task import SearchBox import EntityTable import EntityRow -- MODEL type alias Model = { search : SearchBox.Model , table : Maybe EntityTable.Model } init : (Model, Effects Action) init = let (search, fx) = SearchBox.init in ( Model search Nothing , map SearchBox fx ) -- UPDATE type Action = NoOp | SearchBox SearchBox.Action | Search String | NewEntities (Maybe EntityTable.Model) update : Action -> Model -> (Model, Effects Action) update action model = case action of NoOp -> ( model , Effects.none ) SearchBox searchAction -> let (searchBox, fx) = SearchBox.update searchAction model.search in ( { model | search = searchBox } , map SearchBox fx ) Search query -> let fx = searchKnowledgeGraph query in ( model , fx ) NewEntities maybeEntities -> ( { model | table = maybeEntities } , Effects.none ) -- VIEW view : Signal.Address Action -> Model -> Html view address model = let tableModel = case model.table of Just a -> a Nothing -> [] context = SearchBox.Context (Signal.forwardTo address SearchBox) (Signal.forwardTo address Search) in div [] [ SearchBox.view context model.search , EntityTable.view (Signal.forwardTo address (always NoOp)) tableModel ] -- EFFECTS searchKnowledgeGraph : String -> Effects Action searchKnowledgeGraph query = Http.get decodeData (queryUrl query) |> Task.toMaybe |> Task.map NewEntities |> Effects.task (=>) : a -> b -> ( a, b ) (=>) = (,) -- Black magic operator queryUrl : String -> String queryUrl query = Http.url "https://kgsearch.googleapis.com/v1/entities:search" [ "query" => query , "key" => "<KEY>" , "limit" => "10" , "indent" => "false" ] decoder : Json.Decoder EntityRow.Model decoder = Json.object6 EntityRow.Model (Json.at ["result", "name"] Json.string) (Json.at ["result", "@type"] (Json.list Json.string)) (Json.maybe (Json.at ["result", "description"] Json.string)) (Json.maybe (Json.at ["result", "image", "contentUrl"] Json.string)) (Json.maybe (Json.at ["result", "detailedDescription"] (Json.object2 EntityRow.DetailedDescription ("articleBody" := Json.string) ("url" := Json.string) ) ) ) (Json.at ["resultScore"] Json.float) decodeData : Json.Decoder (List EntityRow.Model) decodeData = Json.at ["itemListElement"] (Json.list decoder)
true
module EntityTableSearchContainer where import Effects exposing (Effects, batch, map) import Html exposing (..) import Http import Json.Decode as Json exposing ((:=)) import Task import SearchBox import EntityTable import EntityRow -- MODEL type alias Model = { search : SearchBox.Model , table : Maybe EntityTable.Model } init : (Model, Effects Action) init = let (search, fx) = SearchBox.init in ( Model search Nothing , map SearchBox fx ) -- UPDATE type Action = NoOp | SearchBox SearchBox.Action | Search String | NewEntities (Maybe EntityTable.Model) update : Action -> Model -> (Model, Effects Action) update action model = case action of NoOp -> ( model , Effects.none ) SearchBox searchAction -> let (searchBox, fx) = SearchBox.update searchAction model.search in ( { model | search = searchBox } , map SearchBox fx ) Search query -> let fx = searchKnowledgeGraph query in ( model , fx ) NewEntities maybeEntities -> ( { model | table = maybeEntities } , Effects.none ) -- VIEW view : Signal.Address Action -> Model -> Html view address model = let tableModel = case model.table of Just a -> a Nothing -> [] context = SearchBox.Context (Signal.forwardTo address SearchBox) (Signal.forwardTo address Search) in div [] [ SearchBox.view context model.search , EntityTable.view (Signal.forwardTo address (always NoOp)) tableModel ] -- EFFECTS searchKnowledgeGraph : String -> Effects Action searchKnowledgeGraph query = Http.get decodeData (queryUrl query) |> Task.toMaybe |> Task.map NewEntities |> Effects.task (=>) : a -> b -> ( a, b ) (=>) = (,) -- Black magic operator queryUrl : String -> String queryUrl query = Http.url "https://kgsearch.googleapis.com/v1/entities:search" [ "query" => query , "key" => "PI:KEY:<KEY>END_PI" , "limit" => "10" , "indent" => "false" ] decoder : Json.Decoder EntityRow.Model decoder = Json.object6 EntityRow.Model (Json.at ["result", "name"] Json.string) (Json.at ["result", "@type"] (Json.list Json.string)) (Json.maybe (Json.at ["result", "description"] Json.string)) (Json.maybe (Json.at ["result", "image", "contentUrl"] Json.string)) (Json.maybe (Json.at ["result", "detailedDescription"] (Json.object2 EntityRow.DetailedDescription ("articleBody" := Json.string) ("url" := Json.string) ) ) ) (Json.at ["resultScore"] Json.float) decodeData : Json.Decoder (List EntityRow.Model) decodeData = Json.at ["itemListElement"] (Json.list decoder)
elm
[ { "context": "ey for style\n-}\nstyleKey : String\nstyleKey =\n \"a1\"\n\n\n{-| Internal key for 'on' events\n-}\neventKey :", "end": 325, "score": 0.9854941368, "start": 323, "tag": "KEY", "value": "a1" }, { "context": " 'on' events\n-}\neventKey : String\neventKey =\n \"a0\"\n\npropertyKey : String\npropertyKey =\n \"a2\"\n\n{-", "end": 401, "score": 0.9863597155, "start": 399, "tag": "KEY", "value": "a0" }, { "context": " \"a0\"\n\npropertyKey : String\npropertyKey =\n \"a2\"\n\n{-| Internal key for attributes\n-}\nattributeKey", "end": 446, "score": 0.9865555763, "start": 444, "tag": "KEY", "value": "a2" }, { "context": "utes\n-}\nattributeKey : String\nattributeKey =\n \"a3\"\n\n\n{-| Internal key for namespaced attributes\n-}\n", "end": 528, "score": 0.985809803, "start": 526, "tag": "KEY", "value": "a3" }, { "context": "amespaceKey : String\nattributeNamespaceKey =\n \"a4\"\n\n\n{-| Keys that we are aware of and should pay a", "end": 640, "score": 0.9122707844, "start": 638, "tag": "KEY", "value": "a4" } ]
src/ElmHtml/Constants.elm
ThinkAlexandria/elm-html-in-elm
2
module ElmHtml.Constants exposing (styleKey, eventKey, attributeKey, attributeNamespaceKey, knownKeys) {-| Constants for representing internal keys for Elm's vdom implementation @docs styleKey, eventKey, attributeKey, attributeNamespaceKey, knownKeys -} {-| Internal key for style -} styleKey : String styleKey = "a1" {-| Internal key for 'on' events -} eventKey : String eventKey = "a0" propertyKey : String propertyKey = "a2" {-| Internal key for attributes -} attributeKey : String attributeKey = "a3" {-| Internal key for namespaced attributes -} attributeNamespaceKey : String attributeNamespaceKey = "a4" {-| Keys that we are aware of and should pay attention to -} knownKeys : List String knownKeys = [ styleKey, eventKey, attributeKey, attributeNamespaceKey ]
11251
module ElmHtml.Constants exposing (styleKey, eventKey, attributeKey, attributeNamespaceKey, knownKeys) {-| Constants for representing internal keys for Elm's vdom implementation @docs styleKey, eventKey, attributeKey, attributeNamespaceKey, knownKeys -} {-| Internal key for style -} styleKey : String styleKey = "<KEY>" {-| Internal key for 'on' events -} eventKey : String eventKey = "<KEY>" propertyKey : String propertyKey = "<KEY>" {-| Internal key for attributes -} attributeKey : String attributeKey = "<KEY>" {-| Internal key for namespaced attributes -} attributeNamespaceKey : String attributeNamespaceKey = "<KEY>" {-| Keys that we are aware of and should pay attention to -} knownKeys : List String knownKeys = [ styleKey, eventKey, attributeKey, attributeNamespaceKey ]
true
module ElmHtml.Constants exposing (styleKey, eventKey, attributeKey, attributeNamespaceKey, knownKeys) {-| Constants for representing internal keys for Elm's vdom implementation @docs styleKey, eventKey, attributeKey, attributeNamespaceKey, knownKeys -} {-| Internal key for style -} styleKey : String styleKey = "PI:KEY:<KEY>END_PI" {-| Internal key for 'on' events -} eventKey : String eventKey = "PI:KEY:<KEY>END_PI" propertyKey : String propertyKey = "PI:KEY:<KEY>END_PI" {-| Internal key for attributes -} attributeKey : String attributeKey = "PI:KEY:<KEY>END_PI" {-| Internal key for namespaced attributes -} attributeNamespaceKey : String attributeNamespaceKey = "PI:KEY:<KEY>END_PI" {-| Keys that we are aware of and should pay attention to -} knownKeys : List String knownKeys = [ styleKey, eventKey, attributeKey, attributeNamespaceKey ]
elm
[ { "context": "=\n let\n paragraphText =\n \"Dr. Brené Brown, author of Daring Greatly, is a research professo", "end": 562, "score": 0.9998804331, "start": 551, "tag": "NAME", "value": "Brené Brown" }, { "context": "raphText =\n \"Dr. Brené Brown, author of Daring Greatly, is a research professor from the University of\"\n", "end": 588, "score": 0.9995896816, "start": 574, "tag": "NAME", "value": "Daring Greatly" } ]
draft-packages/loading-placeholder/ElmStories/LoadingPlaceholderStories.elm
ActuallyACat/kaizen-design-system
68
module ElmStories.LoadingPlaceholderStories exposing (main) import CssModules exposing (css) import ElmStorybook exposing (statelessStoryOf, storybook) import Html exposing (Html, div, text) import Html.Attributes exposing (style) import KaizenDraft.LoadingPlaceholder.LoadingPlaceholder as LoadingPlaceholder import Paragraph.Paragraph as Paragraph storyContainer : List (Html msg) -> Html msg storyContainer children = div [ class .storyContainer ] children paragraph : Html msg paragraph = let paragraphText = "Dr. Brené Brown, author of Daring Greatly, is a research professor from the University of" ++ " Houston who studies human emotions, including shame and vulnerability. In a March 2012 TED talk," ++ " she said, “Vulnerability is not weakness, and that myth is profoundly dangerous.” She went on to" ++ " say that after 12 years of research, she has actually determined that vulnerability is “our most" ++ " accurate measurement of courage.”" in Paragraph.view Paragraph.p [ text paragraphText ] defaultPlaceholder : Html msg defaultPlaceholder = LoadingPlaceholder.view LoadingPlaceholder.default inlinePlaceholder : Int -> Html msg inlinePlaceholder value = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inline |> LoadingPlaceholder.width value ) tallPlaceholder : Html msg tallPlaceholder = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.size LoadingPlaceholder.Tall ) variableWidthPlaceholder : Int -> Html msg variableWidthPlaceholder value = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.width value ) reversedDefaultPlaceholder : Html msg reversedDefaultPlaceholder = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.colorVariant LoadingPlaceholder.Reversed ) reversedOceanPlaceholder : Html msg reversedOceanPlaceholder = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.colorVariant LoadingPlaceholder.ReversedOcean ) main = storybook [ statelessStoryOf "Default, Multiple" <| storyContainer ([ paragraph ] ++ List.repeat 5 defaultPlaceholder ) , statelessStoryOf "Default, Multiple, Inline" <| storyContainer [ paragraph , div [] [ div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) ] ] , statelessStoryOf "Default, Multiple, Variable width" <| storyContainer [ paragraph , variableWidthPlaceholder 90 , defaultPlaceholder , variableWidthPlaceholder 95 , variableWidthPlaceholder 85 , variableWidthPlaceholder 80 ] , statelessStoryOf "Default, Multiple, Variable width, Centered" <| storyContainer [ div [ style "text-align" "center" ] [ paragraph ] , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 90 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 95 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 85 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 60 ) ] , statelessStoryOf "Default, Multiple, Combined block and inline" <| storyContainer [ paragraph , div [] [ div [] [ defaultPlaceholder , variableWidthPlaceholder 90 , variableWidthPlaceholder 60 ] ] , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) ] , statelessStoryOf "Default, Without bottom margin" <| storyContainer [ LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.noBottomMargin ) , Paragraph.view Paragraph.p [ text "These loading placeholders have no bottom margin." ] , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.noBottomMargin ) ] , statelessStoryOf "Default, Inherit baseline" <| storyContainer [ div [ class .flexbox ] [ Paragraph.view Paragraph.h2 [ text "Inheriting baseline" ] , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inheritBaseline ) ] ] , statelessStoryOf "Heading" <| storyContainer ([ paragraph ] ++ List.repeat 5 tallPlaceholder ) , statelessStoryOf "Reversed, Default" <| storyContainer [ div [ class .reversedDefault ] ([ paragraph ] ++ List.repeat 5 reversedDefaultPlaceholder ) ] , statelessStoryOf "In the wild" <| storyContainer [ div [] [ Paragraph.view Paragraph.h1 [ text "In the wild" ] , Paragraph.view Paragraph.p [ text ("This is an example of how you could use LoadingPlaceholder to " ++ "construct a loading state for a fictional tooltip component." ) ] , Paragraph.view Paragraph.h2 [ text "Tooltip component in a loaded state:" ] , div [ class .tooltip ] [ div [ class .tooltipHeader ] [ Paragraph.view (Paragraph.div |> Paragraph.variant Paragraph.IntroLede ) [ text "Hooli's Engagement Survey" ] , Paragraph.view Paragraph.div [ text "2019" ] ] , div [ class .tooltipBody ] [ div [ class .tooltipRow ] [ Paragraph.view Paragraph.div [ text "Favorable" ] , Paragraph.view Paragraph.div [ text "76%" ] ] , div [ class .tooltipRow ] [ Paragraph.view Paragraph.div [ text "Neutral" ] , Paragraph.view Paragraph.div [ text "21%" ] ] , div [ class .tooltipRow ] [ Paragraph.view Paragraph.div [ text "Unfavorable" ] , Paragraph.view Paragraph.div [ text "3%" ] ] ] ] , Paragraph.view Paragraph.h2 [ text "Tooltip component in a loading state:" ] , div [ class .tooltip ] [ div [ class .tooltipHeader ] [ LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inline |> LoadingPlaceholder.colorVariant LoadingPlaceholder.ReversedOcean |> LoadingPlaceholder.width 80 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inline |> LoadingPlaceholder.colorVariant LoadingPlaceholder.ReversedOcean |> LoadingPlaceholder.width 10 ) ] , div [ class .tooltipBody ] [ div [ class .tooltipRow ] [ inlinePlaceholder 10 , inlinePlaceholder 60 , inlinePlaceholder 10 ] , div [ class .tooltipRow ] [ inlinePlaceholder 10 , inlinePlaceholder 60 , inlinePlaceholder 10 ] , div [ class .tooltipRow ] [ inlinePlaceholder 10 , inlinePlaceholder 60 , inlinePlaceholder 10 ] ] ] ] ] ] class = styles.class styles = css "../docs/LoadingPlaceholder.stories.scss" { storyContainer = "storyContainer" , reversedDefault = "reversedDefault" , reversedOcean = "reversedOcean" , tooltip = "tooltip" , tooltipBody = "tooltipBody" , tooltipHeader = "tooltipHeader" , tooltipRow = "tooltipRow" , flexbox = "flexbox" }
50457
module ElmStories.LoadingPlaceholderStories exposing (main) import CssModules exposing (css) import ElmStorybook exposing (statelessStoryOf, storybook) import Html exposing (Html, div, text) import Html.Attributes exposing (style) import KaizenDraft.LoadingPlaceholder.LoadingPlaceholder as LoadingPlaceholder import Paragraph.Paragraph as Paragraph storyContainer : List (Html msg) -> Html msg storyContainer children = div [ class .storyContainer ] children paragraph : Html msg paragraph = let paragraphText = "Dr. <NAME>, author of <NAME>, is a research professor from the University of" ++ " Houston who studies human emotions, including shame and vulnerability. In a March 2012 TED talk," ++ " she said, “Vulnerability is not weakness, and that myth is profoundly dangerous.” She went on to" ++ " say that after 12 years of research, she has actually determined that vulnerability is “our most" ++ " accurate measurement of courage.”" in Paragraph.view Paragraph.p [ text paragraphText ] defaultPlaceholder : Html msg defaultPlaceholder = LoadingPlaceholder.view LoadingPlaceholder.default inlinePlaceholder : Int -> Html msg inlinePlaceholder value = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inline |> LoadingPlaceholder.width value ) tallPlaceholder : Html msg tallPlaceholder = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.size LoadingPlaceholder.Tall ) variableWidthPlaceholder : Int -> Html msg variableWidthPlaceholder value = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.width value ) reversedDefaultPlaceholder : Html msg reversedDefaultPlaceholder = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.colorVariant LoadingPlaceholder.Reversed ) reversedOceanPlaceholder : Html msg reversedOceanPlaceholder = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.colorVariant LoadingPlaceholder.ReversedOcean ) main = storybook [ statelessStoryOf "Default, Multiple" <| storyContainer ([ paragraph ] ++ List.repeat 5 defaultPlaceholder ) , statelessStoryOf "Default, Multiple, Inline" <| storyContainer [ paragraph , div [] [ div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) ] ] , statelessStoryOf "Default, Multiple, Variable width" <| storyContainer [ paragraph , variableWidthPlaceholder 90 , defaultPlaceholder , variableWidthPlaceholder 95 , variableWidthPlaceholder 85 , variableWidthPlaceholder 80 ] , statelessStoryOf "Default, Multiple, Variable width, Centered" <| storyContainer [ div [ style "text-align" "center" ] [ paragraph ] , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 90 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 95 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 85 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 60 ) ] , statelessStoryOf "Default, Multiple, Combined block and inline" <| storyContainer [ paragraph , div [] [ div [] [ defaultPlaceholder , variableWidthPlaceholder 90 , variableWidthPlaceholder 60 ] ] , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) ] , statelessStoryOf "Default, Without bottom margin" <| storyContainer [ LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.noBottomMargin ) , Paragraph.view Paragraph.p [ text "These loading placeholders have no bottom margin." ] , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.noBottomMargin ) ] , statelessStoryOf "Default, Inherit baseline" <| storyContainer [ div [ class .flexbox ] [ Paragraph.view Paragraph.h2 [ text "Inheriting baseline" ] , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inheritBaseline ) ] ] , statelessStoryOf "Heading" <| storyContainer ([ paragraph ] ++ List.repeat 5 tallPlaceholder ) , statelessStoryOf "Reversed, Default" <| storyContainer [ div [ class .reversedDefault ] ([ paragraph ] ++ List.repeat 5 reversedDefaultPlaceholder ) ] , statelessStoryOf "In the wild" <| storyContainer [ div [] [ Paragraph.view Paragraph.h1 [ text "In the wild" ] , Paragraph.view Paragraph.p [ text ("This is an example of how you could use LoadingPlaceholder to " ++ "construct a loading state for a fictional tooltip component." ) ] , Paragraph.view Paragraph.h2 [ text "Tooltip component in a loaded state:" ] , div [ class .tooltip ] [ div [ class .tooltipHeader ] [ Paragraph.view (Paragraph.div |> Paragraph.variant Paragraph.IntroLede ) [ text "Hooli's Engagement Survey" ] , Paragraph.view Paragraph.div [ text "2019" ] ] , div [ class .tooltipBody ] [ div [ class .tooltipRow ] [ Paragraph.view Paragraph.div [ text "Favorable" ] , Paragraph.view Paragraph.div [ text "76%" ] ] , div [ class .tooltipRow ] [ Paragraph.view Paragraph.div [ text "Neutral" ] , Paragraph.view Paragraph.div [ text "21%" ] ] , div [ class .tooltipRow ] [ Paragraph.view Paragraph.div [ text "Unfavorable" ] , Paragraph.view Paragraph.div [ text "3%" ] ] ] ] , Paragraph.view Paragraph.h2 [ text "Tooltip component in a loading state:" ] , div [ class .tooltip ] [ div [ class .tooltipHeader ] [ LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inline |> LoadingPlaceholder.colorVariant LoadingPlaceholder.ReversedOcean |> LoadingPlaceholder.width 80 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inline |> LoadingPlaceholder.colorVariant LoadingPlaceholder.ReversedOcean |> LoadingPlaceholder.width 10 ) ] , div [ class .tooltipBody ] [ div [ class .tooltipRow ] [ inlinePlaceholder 10 , inlinePlaceholder 60 , inlinePlaceholder 10 ] , div [ class .tooltipRow ] [ inlinePlaceholder 10 , inlinePlaceholder 60 , inlinePlaceholder 10 ] , div [ class .tooltipRow ] [ inlinePlaceholder 10 , inlinePlaceholder 60 , inlinePlaceholder 10 ] ] ] ] ] ] class = styles.class styles = css "../docs/LoadingPlaceholder.stories.scss" { storyContainer = "storyContainer" , reversedDefault = "reversedDefault" , reversedOcean = "reversedOcean" , tooltip = "tooltip" , tooltipBody = "tooltipBody" , tooltipHeader = "tooltipHeader" , tooltipRow = "tooltipRow" , flexbox = "flexbox" }
true
module ElmStories.LoadingPlaceholderStories exposing (main) import CssModules exposing (css) import ElmStorybook exposing (statelessStoryOf, storybook) import Html exposing (Html, div, text) import Html.Attributes exposing (style) import KaizenDraft.LoadingPlaceholder.LoadingPlaceholder as LoadingPlaceholder import Paragraph.Paragraph as Paragraph storyContainer : List (Html msg) -> Html msg storyContainer children = div [ class .storyContainer ] children paragraph : Html msg paragraph = let paragraphText = "Dr. PI:NAME:<NAME>END_PI, author of PI:NAME:<NAME>END_PI, is a research professor from the University of" ++ " Houston who studies human emotions, including shame and vulnerability. In a March 2012 TED talk," ++ " she said, “Vulnerability is not weakness, and that myth is profoundly dangerous.” She went on to" ++ " say that after 12 years of research, she has actually determined that vulnerability is “our most" ++ " accurate measurement of courage.”" in Paragraph.view Paragraph.p [ text paragraphText ] defaultPlaceholder : Html msg defaultPlaceholder = LoadingPlaceholder.view LoadingPlaceholder.default inlinePlaceholder : Int -> Html msg inlinePlaceholder value = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inline |> LoadingPlaceholder.width value ) tallPlaceholder : Html msg tallPlaceholder = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.size LoadingPlaceholder.Tall ) variableWidthPlaceholder : Int -> Html msg variableWidthPlaceholder value = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.width value ) reversedDefaultPlaceholder : Html msg reversedDefaultPlaceholder = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.colorVariant LoadingPlaceholder.Reversed ) reversedOceanPlaceholder : Html msg reversedOceanPlaceholder = LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.colorVariant LoadingPlaceholder.ReversedOcean ) main = storybook [ statelessStoryOf "Default, Multiple" <| storyContainer ([ paragraph ] ++ List.repeat 5 defaultPlaceholder ) , statelessStoryOf "Default, Multiple, Inline" <| storyContainer [ paragraph , div [] [ div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) ] ] , statelessStoryOf "Default, Multiple, Variable width" <| storyContainer [ paragraph , variableWidthPlaceholder 90 , defaultPlaceholder , variableWidthPlaceholder 95 , variableWidthPlaceholder 85 , variableWidthPlaceholder 80 ] , statelessStoryOf "Default, Multiple, Variable width, Centered" <| storyContainer [ div [ style "text-align" "center" ] [ paragraph ] , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 90 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 95 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 85 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.centered |> LoadingPlaceholder.width 60 ) ] , statelessStoryOf "Default, Multiple, Combined block and inline" <| storyContainer [ paragraph , div [] [ div [] [ defaultPlaceholder , variableWidthPlaceholder 90 , variableWidthPlaceholder 60 ] ] , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) , div [] (List.repeat 3 (inlinePlaceholder 30)) ] , statelessStoryOf "Default, Without bottom margin" <| storyContainer [ LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.noBottomMargin ) , Paragraph.view Paragraph.p [ text "These loading placeholders have no bottom margin." ] , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.noBottomMargin ) ] , statelessStoryOf "Default, Inherit baseline" <| storyContainer [ div [ class .flexbox ] [ Paragraph.view Paragraph.h2 [ text "Inheriting baseline" ] , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inheritBaseline ) ] ] , statelessStoryOf "Heading" <| storyContainer ([ paragraph ] ++ List.repeat 5 tallPlaceholder ) , statelessStoryOf "Reversed, Default" <| storyContainer [ div [ class .reversedDefault ] ([ paragraph ] ++ List.repeat 5 reversedDefaultPlaceholder ) ] , statelessStoryOf "In the wild" <| storyContainer [ div [] [ Paragraph.view Paragraph.h1 [ text "In the wild" ] , Paragraph.view Paragraph.p [ text ("This is an example of how you could use LoadingPlaceholder to " ++ "construct a loading state for a fictional tooltip component." ) ] , Paragraph.view Paragraph.h2 [ text "Tooltip component in a loaded state:" ] , div [ class .tooltip ] [ div [ class .tooltipHeader ] [ Paragraph.view (Paragraph.div |> Paragraph.variant Paragraph.IntroLede ) [ text "Hooli's Engagement Survey" ] , Paragraph.view Paragraph.div [ text "2019" ] ] , div [ class .tooltipBody ] [ div [ class .tooltipRow ] [ Paragraph.view Paragraph.div [ text "Favorable" ] , Paragraph.view Paragraph.div [ text "76%" ] ] , div [ class .tooltipRow ] [ Paragraph.view Paragraph.div [ text "Neutral" ] , Paragraph.view Paragraph.div [ text "21%" ] ] , div [ class .tooltipRow ] [ Paragraph.view Paragraph.div [ text "Unfavorable" ] , Paragraph.view Paragraph.div [ text "3%" ] ] ] ] , Paragraph.view Paragraph.h2 [ text "Tooltip component in a loading state:" ] , div [ class .tooltip ] [ div [ class .tooltipHeader ] [ LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inline |> LoadingPlaceholder.colorVariant LoadingPlaceholder.ReversedOcean |> LoadingPlaceholder.width 80 ) , LoadingPlaceholder.view (LoadingPlaceholder.default |> LoadingPlaceholder.inline |> LoadingPlaceholder.colorVariant LoadingPlaceholder.ReversedOcean |> LoadingPlaceholder.width 10 ) ] , div [ class .tooltipBody ] [ div [ class .tooltipRow ] [ inlinePlaceholder 10 , inlinePlaceholder 60 , inlinePlaceholder 10 ] , div [ class .tooltipRow ] [ inlinePlaceholder 10 , inlinePlaceholder 60 , inlinePlaceholder 10 ] , div [ class .tooltipRow ] [ inlinePlaceholder 10 , inlinePlaceholder 60 , inlinePlaceholder 10 ] ] ] ] ] ] class = styles.class styles = css "../docs/LoadingPlaceholder.stories.scss" { storyContainer = "storyContainer" , reversedDefault = "reversedDefault" , reversedOcean = "reversedOcean" , tooltip = "tooltip" , tooltipBody = "tooltipBody" , tooltipHeader = "tooltipHeader" , tooltipRow = "tooltipRow" , flexbox = "flexbox" }
elm
[ { "context": "efExists\n@docs buildOrderIndex\n\nCopyright (c) 2016 Robin Luiten\n\n-}\n\nimport Dict exposing (Dict)\nimport Index.Mod", "end": 437, "score": 0.9998137355, "start": 425, "tag": "NAME", "value": "Robin Luiten" } ]
src/Index/Utils.elm
eniac314/elm-text-search
0
module Index.Utils exposing ( createFuncCreator , getTokens , getTokensList , processTokens , applyTransform , applyFilter , idf , refExists , buildOrderIndex ) {-| Index Utilities ## Functions @docs createFuncCreator @docs getTokens @docs getTokensList @docs processTokens @docs applyTransform @docs applyFilter @docs idf @docs refExists @docs buildOrderIndex Copyright (c) 2016 Robin Luiten -} import Dict exposing (Dict) import Index.Model exposing (FilterFactory, FuncFactory, Index(..)) import Maybe exposing (andThen, withDefault) import Set exposing (Set) import TokenProcessors import Trie exposing (Trie) {-| Create a function creator (FuncFactory) given the simple Function to start with -} createFuncCreator : func -> FuncFactory doc func createFuncCreator func index = ( index, func ) {-| Extract tokens from string, and process them. -} getTokens : Index doc -> String -> ( Index doc, List String ) getTokens index string = processTokens index (TokenProcessors.tokenizer string) getTokensList : Index doc -> List String -> ( Index doc, List String ) getTokensList index listString = processTokens index (TokenProcessors.tokenizerList listString) {-| Transform list of words into tokens for index and search. Applies filters and transformers configured in index. Applies filters first then tokenizers. So filtesr applie to untokenized words from document. -} processTokens : Index doc -> List String -> ( Index doc, List String ) processTokens index tokens = let ( u1index, initialTransformTokens ) = applyInitialTransform index tokens ( u2index, filterTokens ) = applyFilter u1index initialTransformTokens in applyTransform u2index filterTokens {-| Apply the transforms to tokens. If any transform converts a token to an empty string no further transforms are applied and the empty string is removed from the set of tokens. -} applyTransform : Index doc -> List String -> ( Index doc, List String ) applyTransform index strings = let ( u1index, transformList ) = getOrSetTransformList index in ( u1index , List.filter (\val -> val /= "") (List.map (applyTransformList transformList) strings) ) {-| Would prefer to past just accessors (eg .transforms) to getOrSetIndexFuncList but so far the types are beating me. -} getOrSetTransformList : Index doc -> ( Index doc, List (String -> String) ) getOrSetTransformList index = getOrSetIndexFuncList (\(Index irec) -> irec.transforms) (\(Index irec) -> irec.transformFactories) setIndexTransforms index {-| set Index transforms func field -} setIndexTransforms : Index doc -> List (String -> String) -> Index doc setIndexTransforms (Index irec) listFuncs = Index { irec | transforms = Just listFuncs } applyInitialTransform : Index doc -> List String -> ( Index doc, List String ) applyInitialTransform index strings = let ( u1index, intitialTransformList ) = getOrSetInitialTransformList index in ( u1index , List.filter (\val -> val /= "") (List.map (applyTransformList intitialTransformList) strings) ) getOrSetInitialTransformList : Index doc -> ( Index doc, List (String -> String) ) getOrSetInitialTransformList index = getOrSetIndexFuncList (\(Index irec) -> irec.initialTransforms) (\(Index irec) -> irec.initialTransformFactories) setIndexInitialTransforms index setIndexInitialTransforms : Index doc -> List (String -> String) -> Index doc setIndexInitialTransforms (Index irec) listFuncs = Index { irec | initialTransforms = Just listFuncs } {-| Apply all transforms in sequence to input token. If any transform returns an empty string then this will return the empty string without running further transforms. -} applyTransformList : List (String -> String) -> String -> String applyTransformList transforms token = case transforms of [] -> token transform :: restTransforms -> let newToken = transform token in case newToken of "" -> "" _ -> applyTransformList restTransforms newToken {-| Apply index filters to tokens. If any token is an empty string it will be filtered out as well. -} applyFilter : Index doc -> List String -> ( Index doc, List String ) applyFilter index strings = let ( u1index, filterList ) = getOrSetFilterList index in ( u1index, List.filter (applyFilterList filterList) strings ) getOrSetFilterList : Index doc -> ( Index doc, List (String -> Bool) ) getOrSetFilterList index = getOrSetIndexFuncList (\(Index irec) -> irec.filters) (\(Index irec) -> irec.filterFactories) setIndexFilters index {-| set Index filters func field -} setIndexFilters : Index doc -> List (String -> Bool) -> Index doc setIndexFilters (Index irec) listFuncs = Index { irec | filters = Just listFuncs } {-| If any filter returns False then return False. Place more descriminant filters as early as possible in filters list as they are run in order. -} applyFilterList : List (String -> Bool) -> String -> Bool applyFilterList filters token = case filters of [] -> True filterFunc :: restFilters -> case token of "" -> False _ -> case filterFunc token of False -> False True -> applyFilterList restFilters token {-| Get a list of functions from Index, if they have not been created they are created and set on Index. -} getOrSetIndexFuncList : (Index doc -> Maybe (List func)) -> (Index doc -> List (FuncFactory doc func)) -> (Index doc -> List func -> Index doc) -> Index doc -> ( Index doc, List func ) getOrSetIndexFuncList getFuncs getFactoryFuncs setFuncs index = case getFuncs index of Just funcList -> ( index, funcList ) Nothing -> let ( u1index, newFuncList ) = runFactories (getFactoryFuncs index) index u2index = setFuncs u1index newFuncList in ( u2index, newFuncList ) {-| Run each of the function factories returning the list of functions. -} runFactories : List (FuncFactory doc func) -> Index doc -> ( Index doc, List func ) runFactories factoryList index = List.foldr (\factory ( u1index, funcList ) -> let ( u2index, newFunc ) = factory u1index in ( u2index, newFunc :: funcList ) ) ( index, [] ) factoryList {-| Calculate the inverse document frequency for a token in the Index. Model will update if token has no cached value for idf. -} idf : Index doc -> String -> ( Index doc, Float ) idf ((Index irec) as index) token = case Dict.get token irec.idfCache of Nothing -> calcIdf index token Just idfValue -> ( index, idfValue ) calcIdf : Index doc -> String -> ( Index doc, Float ) calcIdf (Index irec) token = let -- _ = Debug.log("calcIdf") (token) docFrequency = toFloat (Trie.valueCount token irec.tokenStore) idfLocal = if docFrequency > 0 then 1 + logBase 10 (toFloat (Dict.size irec.documentStore) / docFrequency) else toFloat 1 updatedIdfCache = Dict.insert token idfLocal irec.idfCache u1index = Index { irec | idfCache = updatedIdfCache } in ( u1index, idfLocal ) {-| Return True if document reference is indexed. -} refExists : String -> Index doc -> Bool refExists docRef (Index irec) = Dict.member docRef irec.documentStore {-| Build an index of string to index from Set where key is Set word and value is ordered index of word in Set. -} buildOrderIndex : Set String -> Dict String Int buildOrderIndex tokenSet = let withIndex = List.indexedMap Tuple.pair (Set.toList tokenSet) in List.foldr (\( i, v ) d -> Dict.insert v i d) Dict.empty withIndex
10043
module Index.Utils exposing ( createFuncCreator , getTokens , getTokensList , processTokens , applyTransform , applyFilter , idf , refExists , buildOrderIndex ) {-| Index Utilities ## Functions @docs createFuncCreator @docs getTokens @docs getTokensList @docs processTokens @docs applyTransform @docs applyFilter @docs idf @docs refExists @docs buildOrderIndex Copyright (c) 2016 <NAME> -} import Dict exposing (Dict) import Index.Model exposing (FilterFactory, FuncFactory, Index(..)) import Maybe exposing (andThen, withDefault) import Set exposing (Set) import TokenProcessors import Trie exposing (Trie) {-| Create a function creator (FuncFactory) given the simple Function to start with -} createFuncCreator : func -> FuncFactory doc func createFuncCreator func index = ( index, func ) {-| Extract tokens from string, and process them. -} getTokens : Index doc -> String -> ( Index doc, List String ) getTokens index string = processTokens index (TokenProcessors.tokenizer string) getTokensList : Index doc -> List String -> ( Index doc, List String ) getTokensList index listString = processTokens index (TokenProcessors.tokenizerList listString) {-| Transform list of words into tokens for index and search. Applies filters and transformers configured in index. Applies filters first then tokenizers. So filtesr applie to untokenized words from document. -} processTokens : Index doc -> List String -> ( Index doc, List String ) processTokens index tokens = let ( u1index, initialTransformTokens ) = applyInitialTransform index tokens ( u2index, filterTokens ) = applyFilter u1index initialTransformTokens in applyTransform u2index filterTokens {-| Apply the transforms to tokens. If any transform converts a token to an empty string no further transforms are applied and the empty string is removed from the set of tokens. -} applyTransform : Index doc -> List String -> ( Index doc, List String ) applyTransform index strings = let ( u1index, transformList ) = getOrSetTransformList index in ( u1index , List.filter (\val -> val /= "") (List.map (applyTransformList transformList) strings) ) {-| Would prefer to past just accessors (eg .transforms) to getOrSetIndexFuncList but so far the types are beating me. -} getOrSetTransformList : Index doc -> ( Index doc, List (String -> String) ) getOrSetTransformList index = getOrSetIndexFuncList (\(Index irec) -> irec.transforms) (\(Index irec) -> irec.transformFactories) setIndexTransforms index {-| set Index transforms func field -} setIndexTransforms : Index doc -> List (String -> String) -> Index doc setIndexTransforms (Index irec) listFuncs = Index { irec | transforms = Just listFuncs } applyInitialTransform : Index doc -> List String -> ( Index doc, List String ) applyInitialTransform index strings = let ( u1index, intitialTransformList ) = getOrSetInitialTransformList index in ( u1index , List.filter (\val -> val /= "") (List.map (applyTransformList intitialTransformList) strings) ) getOrSetInitialTransformList : Index doc -> ( Index doc, List (String -> String) ) getOrSetInitialTransformList index = getOrSetIndexFuncList (\(Index irec) -> irec.initialTransforms) (\(Index irec) -> irec.initialTransformFactories) setIndexInitialTransforms index setIndexInitialTransforms : Index doc -> List (String -> String) -> Index doc setIndexInitialTransforms (Index irec) listFuncs = Index { irec | initialTransforms = Just listFuncs } {-| Apply all transforms in sequence to input token. If any transform returns an empty string then this will return the empty string without running further transforms. -} applyTransformList : List (String -> String) -> String -> String applyTransformList transforms token = case transforms of [] -> token transform :: restTransforms -> let newToken = transform token in case newToken of "" -> "" _ -> applyTransformList restTransforms newToken {-| Apply index filters to tokens. If any token is an empty string it will be filtered out as well. -} applyFilter : Index doc -> List String -> ( Index doc, List String ) applyFilter index strings = let ( u1index, filterList ) = getOrSetFilterList index in ( u1index, List.filter (applyFilterList filterList) strings ) getOrSetFilterList : Index doc -> ( Index doc, List (String -> Bool) ) getOrSetFilterList index = getOrSetIndexFuncList (\(Index irec) -> irec.filters) (\(Index irec) -> irec.filterFactories) setIndexFilters index {-| set Index filters func field -} setIndexFilters : Index doc -> List (String -> Bool) -> Index doc setIndexFilters (Index irec) listFuncs = Index { irec | filters = Just listFuncs } {-| If any filter returns False then return False. Place more descriminant filters as early as possible in filters list as they are run in order. -} applyFilterList : List (String -> Bool) -> String -> Bool applyFilterList filters token = case filters of [] -> True filterFunc :: restFilters -> case token of "" -> False _ -> case filterFunc token of False -> False True -> applyFilterList restFilters token {-| Get a list of functions from Index, if they have not been created they are created and set on Index. -} getOrSetIndexFuncList : (Index doc -> Maybe (List func)) -> (Index doc -> List (FuncFactory doc func)) -> (Index doc -> List func -> Index doc) -> Index doc -> ( Index doc, List func ) getOrSetIndexFuncList getFuncs getFactoryFuncs setFuncs index = case getFuncs index of Just funcList -> ( index, funcList ) Nothing -> let ( u1index, newFuncList ) = runFactories (getFactoryFuncs index) index u2index = setFuncs u1index newFuncList in ( u2index, newFuncList ) {-| Run each of the function factories returning the list of functions. -} runFactories : List (FuncFactory doc func) -> Index doc -> ( Index doc, List func ) runFactories factoryList index = List.foldr (\factory ( u1index, funcList ) -> let ( u2index, newFunc ) = factory u1index in ( u2index, newFunc :: funcList ) ) ( index, [] ) factoryList {-| Calculate the inverse document frequency for a token in the Index. Model will update if token has no cached value for idf. -} idf : Index doc -> String -> ( Index doc, Float ) idf ((Index irec) as index) token = case Dict.get token irec.idfCache of Nothing -> calcIdf index token Just idfValue -> ( index, idfValue ) calcIdf : Index doc -> String -> ( Index doc, Float ) calcIdf (Index irec) token = let -- _ = Debug.log("calcIdf") (token) docFrequency = toFloat (Trie.valueCount token irec.tokenStore) idfLocal = if docFrequency > 0 then 1 + logBase 10 (toFloat (Dict.size irec.documentStore) / docFrequency) else toFloat 1 updatedIdfCache = Dict.insert token idfLocal irec.idfCache u1index = Index { irec | idfCache = updatedIdfCache } in ( u1index, idfLocal ) {-| Return True if document reference is indexed. -} refExists : String -> Index doc -> Bool refExists docRef (Index irec) = Dict.member docRef irec.documentStore {-| Build an index of string to index from Set where key is Set word and value is ordered index of word in Set. -} buildOrderIndex : Set String -> Dict String Int buildOrderIndex tokenSet = let withIndex = List.indexedMap Tuple.pair (Set.toList tokenSet) in List.foldr (\( i, v ) d -> Dict.insert v i d) Dict.empty withIndex
true
module Index.Utils exposing ( createFuncCreator , getTokens , getTokensList , processTokens , applyTransform , applyFilter , idf , refExists , buildOrderIndex ) {-| Index Utilities ## Functions @docs createFuncCreator @docs getTokens @docs getTokensList @docs processTokens @docs applyTransform @docs applyFilter @docs idf @docs refExists @docs buildOrderIndex Copyright (c) 2016 PI:NAME:<NAME>END_PI -} import Dict exposing (Dict) import Index.Model exposing (FilterFactory, FuncFactory, Index(..)) import Maybe exposing (andThen, withDefault) import Set exposing (Set) import TokenProcessors import Trie exposing (Trie) {-| Create a function creator (FuncFactory) given the simple Function to start with -} createFuncCreator : func -> FuncFactory doc func createFuncCreator func index = ( index, func ) {-| Extract tokens from string, and process them. -} getTokens : Index doc -> String -> ( Index doc, List String ) getTokens index string = processTokens index (TokenProcessors.tokenizer string) getTokensList : Index doc -> List String -> ( Index doc, List String ) getTokensList index listString = processTokens index (TokenProcessors.tokenizerList listString) {-| Transform list of words into tokens for index and search. Applies filters and transformers configured in index. Applies filters first then tokenizers. So filtesr applie to untokenized words from document. -} processTokens : Index doc -> List String -> ( Index doc, List String ) processTokens index tokens = let ( u1index, initialTransformTokens ) = applyInitialTransform index tokens ( u2index, filterTokens ) = applyFilter u1index initialTransformTokens in applyTransform u2index filterTokens {-| Apply the transforms to tokens. If any transform converts a token to an empty string no further transforms are applied and the empty string is removed from the set of tokens. -} applyTransform : Index doc -> List String -> ( Index doc, List String ) applyTransform index strings = let ( u1index, transformList ) = getOrSetTransformList index in ( u1index , List.filter (\val -> val /= "") (List.map (applyTransformList transformList) strings) ) {-| Would prefer to past just accessors (eg .transforms) to getOrSetIndexFuncList but so far the types are beating me. -} getOrSetTransformList : Index doc -> ( Index doc, List (String -> String) ) getOrSetTransformList index = getOrSetIndexFuncList (\(Index irec) -> irec.transforms) (\(Index irec) -> irec.transformFactories) setIndexTransforms index {-| set Index transforms func field -} setIndexTransforms : Index doc -> List (String -> String) -> Index doc setIndexTransforms (Index irec) listFuncs = Index { irec | transforms = Just listFuncs } applyInitialTransform : Index doc -> List String -> ( Index doc, List String ) applyInitialTransform index strings = let ( u1index, intitialTransformList ) = getOrSetInitialTransformList index in ( u1index , List.filter (\val -> val /= "") (List.map (applyTransformList intitialTransformList) strings) ) getOrSetInitialTransformList : Index doc -> ( Index doc, List (String -> String) ) getOrSetInitialTransformList index = getOrSetIndexFuncList (\(Index irec) -> irec.initialTransforms) (\(Index irec) -> irec.initialTransformFactories) setIndexInitialTransforms index setIndexInitialTransforms : Index doc -> List (String -> String) -> Index doc setIndexInitialTransforms (Index irec) listFuncs = Index { irec | initialTransforms = Just listFuncs } {-| Apply all transforms in sequence to input token. If any transform returns an empty string then this will return the empty string without running further transforms. -} applyTransformList : List (String -> String) -> String -> String applyTransformList transforms token = case transforms of [] -> token transform :: restTransforms -> let newToken = transform token in case newToken of "" -> "" _ -> applyTransformList restTransforms newToken {-| Apply index filters to tokens. If any token is an empty string it will be filtered out as well. -} applyFilter : Index doc -> List String -> ( Index doc, List String ) applyFilter index strings = let ( u1index, filterList ) = getOrSetFilterList index in ( u1index, List.filter (applyFilterList filterList) strings ) getOrSetFilterList : Index doc -> ( Index doc, List (String -> Bool) ) getOrSetFilterList index = getOrSetIndexFuncList (\(Index irec) -> irec.filters) (\(Index irec) -> irec.filterFactories) setIndexFilters index {-| set Index filters func field -} setIndexFilters : Index doc -> List (String -> Bool) -> Index doc setIndexFilters (Index irec) listFuncs = Index { irec | filters = Just listFuncs } {-| If any filter returns False then return False. Place more descriminant filters as early as possible in filters list as they are run in order. -} applyFilterList : List (String -> Bool) -> String -> Bool applyFilterList filters token = case filters of [] -> True filterFunc :: restFilters -> case token of "" -> False _ -> case filterFunc token of False -> False True -> applyFilterList restFilters token {-| Get a list of functions from Index, if they have not been created they are created and set on Index. -} getOrSetIndexFuncList : (Index doc -> Maybe (List func)) -> (Index doc -> List (FuncFactory doc func)) -> (Index doc -> List func -> Index doc) -> Index doc -> ( Index doc, List func ) getOrSetIndexFuncList getFuncs getFactoryFuncs setFuncs index = case getFuncs index of Just funcList -> ( index, funcList ) Nothing -> let ( u1index, newFuncList ) = runFactories (getFactoryFuncs index) index u2index = setFuncs u1index newFuncList in ( u2index, newFuncList ) {-| Run each of the function factories returning the list of functions. -} runFactories : List (FuncFactory doc func) -> Index doc -> ( Index doc, List func ) runFactories factoryList index = List.foldr (\factory ( u1index, funcList ) -> let ( u2index, newFunc ) = factory u1index in ( u2index, newFunc :: funcList ) ) ( index, [] ) factoryList {-| Calculate the inverse document frequency for a token in the Index. Model will update if token has no cached value for idf. -} idf : Index doc -> String -> ( Index doc, Float ) idf ((Index irec) as index) token = case Dict.get token irec.idfCache of Nothing -> calcIdf index token Just idfValue -> ( index, idfValue ) calcIdf : Index doc -> String -> ( Index doc, Float ) calcIdf (Index irec) token = let -- _ = Debug.log("calcIdf") (token) docFrequency = toFloat (Trie.valueCount token irec.tokenStore) idfLocal = if docFrequency > 0 then 1 + logBase 10 (toFloat (Dict.size irec.documentStore) / docFrequency) else toFloat 1 updatedIdfCache = Dict.insert token idfLocal irec.idfCache u1index = Index { irec | idfCache = updatedIdfCache } in ( u1index, idfLocal ) {-| Return True if document reference is indexed. -} refExists : String -> Index doc -> Bool refExists docRef (Index irec) = Dict.member docRef irec.documentStore {-| Build an index of string to index from Set where key is Set word and value is ordered index of word in Set. -} buildOrderIndex : Set String -> Dict String Int buildOrderIndex tokenSet = let withIndex = List.indexedMap Tuple.pair (Set.toList tokenSet) in List.foldr (\( i, v ) d -> Dict.insert v i d) Dict.empty withIndex
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.9999222159, "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.9996038079, "start": 289, "tag": "USERNAME", "value": "openapitools" } ]
clients/elm/generated/src/Data/InstallStatus.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 Data.InstallStatus exposing (InstallStatus, installStatusDecoder, installStatusEncoder) import Data.InstallStatusStatus exposing (InstallStatusStatus, installStatusStatusDecoder, installStatusStatusEncoder) 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 InstallStatus = { status : Maybe InstallStatusStatus } installStatusDecoder : Decoder InstallStatus installStatusDecoder = decode InstallStatus |> optional "status" (Decode.nullable installStatusStatusDecoder) Nothing installStatusEncoder : InstallStatus -> Encode.Value installStatusEncoder model = Encode.object [ ( "status", withDefault Encode.null (map installStatusStatusEncoder model.status) ) ]
38053
{- 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 Data.InstallStatus exposing (InstallStatus, installStatusDecoder, installStatusEncoder) import Data.InstallStatusStatus exposing (InstallStatusStatus, installStatusStatusDecoder, installStatusStatusEncoder) 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 InstallStatus = { status : Maybe InstallStatusStatus } installStatusDecoder : Decoder InstallStatus installStatusDecoder = decode InstallStatus |> optional "status" (Decode.nullable installStatusStatusDecoder) Nothing installStatusEncoder : InstallStatus -> Encode.Value installStatusEncoder model = Encode.object [ ( "status", withDefault Encode.null (map installStatusStatusEncoder model.status) ) ]
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 Data.InstallStatus exposing (InstallStatus, installStatusDecoder, installStatusEncoder) import Data.InstallStatusStatus exposing (InstallStatusStatus, installStatusStatusDecoder, installStatusStatusEncoder) 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 InstallStatus = { status : Maybe InstallStatusStatus } installStatusDecoder : Decoder InstallStatus installStatusDecoder = decode InstallStatus |> optional "status" (Decode.nullable installStatusStatusDecoder) Nothing installStatusEncoder : InstallStatus -> Encode.Value installStatusEncoder model = Encode.object [ ( "status", withDefault Encode.null (map installStatusStatusEncoder model.status) ) ]
elm
[ { "context": "{-\n Swaggy Jenkins\n Jenkins API clients generated from Swagger / O", "end": 20, "score": 0.9991167188, "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.9999137521, "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.9996459484, "start": 240, "tag": "USERNAME", "value": "openapitools" } ]
clients/elm/generated/src/Data/ScmOrganisations.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.ScmOrganisations exposing (ScmOrganisations, scmOrganisationsDecoder, scmOrganisationsEncoder) import Data.GithubOrganization exposing (GithubOrganization, githubOrganizationDecoder, githubOrganizationEncoder) 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 ScmOrganisations = List GithubOrganization scmOrganisationsDecoder : Decoder ScmOrganisations scmOrganisationsDecoder = Decode.list githubOrganizationDecoder scmOrganisationsEncoder : ScmOrganisations -> Encode.Value scmOrganisationsEncoder model = Encode.list (List.map githubOrganizationEncoder model)
21927
{- <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.ScmOrganisations exposing (ScmOrganisations, scmOrganisationsDecoder, scmOrganisationsEncoder) import Data.GithubOrganization exposing (GithubOrganization, githubOrganizationDecoder, githubOrganizationEncoder) 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 ScmOrganisations = List GithubOrganization scmOrganisationsDecoder : Decoder ScmOrganisations scmOrganisationsDecoder = Decode.list githubOrganizationDecoder scmOrganisationsEncoder : ScmOrganisations -> Encode.Value scmOrganisationsEncoder model = Encode.list (List.map githubOrganizationEncoder model)
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.ScmOrganisations exposing (ScmOrganisations, scmOrganisationsDecoder, scmOrganisationsEncoder) import Data.GithubOrganization exposing (GithubOrganization, githubOrganizationDecoder, githubOrganizationEncoder) 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 ScmOrganisations = List GithubOrganization scmOrganisationsDecoder : Decoder ScmOrganisations scmOrganisationsDecoder = Decode.list githubOrganizationDecoder scmOrganisationsEncoder : ScmOrganisations -> Encode.Value scmOrganisationsEncoder model = Encode.list (List.map githubOrganizationEncoder model)
elm
[ { "context": "ch = \"fake\"\n , hash = \"fake\"\n , username = \"fake\"\n , password = \"fake\"\n }\n", "end": 2199, "score": 0.9988760352, "start": 2195, "tag": "USERNAME", "value": "fake" }, { "context": " \"fake\"\n , username = \"fake\"\n , password = \"fake\"\n }\n", "end": 2223, "score": 0.9992015958, "start": 2219, "tag": "PASSWORD", "value": "fake" } ]
tests/Test/Routes.elm
sdenier/elm-blog-tutorial
0
module Test.Routes exposing (..) import Test exposing (..) import Expect import Models exposing (Route(..)) import Navigation import Routes exposing (..) tests : Test tests = describe "Routing" [ pathTests , routerTests ] pathTests : Test pathTests = describe "#pathFor" [ test "HomeRoute should translate to '/'" <| \() -> Expect.equal "/" (pathFor HomeRoute) , test "NotFound should translate to '/'" <| \() -> Expect.equal "/" (pathFor NotFound) , test "NewPostRoute should translate to '/posts/new'" <| \() -> Expect.equal "/posts/new" (pathFor NewPostRoute) , test "PostRoute should translate to '/posts/:postId'" <| \() -> Expect.equal "/posts/89" (pathFor (PostRoute 89)) ] routerTests : Test routerTests = describe "#router" [ test "HomeRoute should match root path" <| \() -> Expect.equal (Just HomeRoute) (router rootLocation) , test "NewPostRoute should match '/posts/new'" <| \() -> Expect.equal (Just NewPostRoute) (router newPostLocation) , test "PostRoute should match /posts/:id" <| \() -> Expect.equal (Just <| PostRoute 89) (router postLocation) , test "PostRoute should not match another PostId" <| \() -> Expect.notEqual (Just <| PostRoute 123) (router postLocation) , test "NotFound should match unknown path" <| \() -> Expect.equal Nothing (router unknownLocation) ] rootLocation : Navigation.Location rootLocation = { mockLocation | pathname = "/" } newPostLocation : Navigation.Location newPostLocation = { mockLocation | pathname = "/posts/new" } postLocation : Navigation.Location postLocation = { mockLocation | pathname = "/posts/89" } unknownLocation : Navigation.Location unknownLocation = { mockLocation | pathname = "/unknownPath" } mockLocation : Navigation.Location mockLocation = { href = "fake" , host = "fake" , hostname = "fake" , protocol = "fake" , origin = "fake" , port_ = "fake" , pathname = "fake" , search = "fake" , hash = "fake" , username = "fake" , password = "fake" }
23156
module Test.Routes exposing (..) import Test exposing (..) import Expect import Models exposing (Route(..)) import Navigation import Routes exposing (..) tests : Test tests = describe "Routing" [ pathTests , routerTests ] pathTests : Test pathTests = describe "#pathFor" [ test "HomeRoute should translate to '/'" <| \() -> Expect.equal "/" (pathFor HomeRoute) , test "NotFound should translate to '/'" <| \() -> Expect.equal "/" (pathFor NotFound) , test "NewPostRoute should translate to '/posts/new'" <| \() -> Expect.equal "/posts/new" (pathFor NewPostRoute) , test "PostRoute should translate to '/posts/:postId'" <| \() -> Expect.equal "/posts/89" (pathFor (PostRoute 89)) ] routerTests : Test routerTests = describe "#router" [ test "HomeRoute should match root path" <| \() -> Expect.equal (Just HomeRoute) (router rootLocation) , test "NewPostRoute should match '/posts/new'" <| \() -> Expect.equal (Just NewPostRoute) (router newPostLocation) , test "PostRoute should match /posts/:id" <| \() -> Expect.equal (Just <| PostRoute 89) (router postLocation) , test "PostRoute should not match another PostId" <| \() -> Expect.notEqual (Just <| PostRoute 123) (router postLocation) , test "NotFound should match unknown path" <| \() -> Expect.equal Nothing (router unknownLocation) ] rootLocation : Navigation.Location rootLocation = { mockLocation | pathname = "/" } newPostLocation : Navigation.Location newPostLocation = { mockLocation | pathname = "/posts/new" } postLocation : Navigation.Location postLocation = { mockLocation | pathname = "/posts/89" } unknownLocation : Navigation.Location unknownLocation = { mockLocation | pathname = "/unknownPath" } mockLocation : Navigation.Location mockLocation = { href = "fake" , host = "fake" , hostname = "fake" , protocol = "fake" , origin = "fake" , port_ = "fake" , pathname = "fake" , search = "fake" , hash = "fake" , username = "fake" , password = "<PASSWORD>" }
true
module Test.Routes exposing (..) import Test exposing (..) import Expect import Models exposing (Route(..)) import Navigation import Routes exposing (..) tests : Test tests = describe "Routing" [ pathTests , routerTests ] pathTests : Test pathTests = describe "#pathFor" [ test "HomeRoute should translate to '/'" <| \() -> Expect.equal "/" (pathFor HomeRoute) , test "NotFound should translate to '/'" <| \() -> Expect.equal "/" (pathFor NotFound) , test "NewPostRoute should translate to '/posts/new'" <| \() -> Expect.equal "/posts/new" (pathFor NewPostRoute) , test "PostRoute should translate to '/posts/:postId'" <| \() -> Expect.equal "/posts/89" (pathFor (PostRoute 89)) ] routerTests : Test routerTests = describe "#router" [ test "HomeRoute should match root path" <| \() -> Expect.equal (Just HomeRoute) (router rootLocation) , test "NewPostRoute should match '/posts/new'" <| \() -> Expect.equal (Just NewPostRoute) (router newPostLocation) , test "PostRoute should match /posts/:id" <| \() -> Expect.equal (Just <| PostRoute 89) (router postLocation) , test "PostRoute should not match another PostId" <| \() -> Expect.notEqual (Just <| PostRoute 123) (router postLocation) , test "NotFound should match unknown path" <| \() -> Expect.equal Nothing (router unknownLocation) ] rootLocation : Navigation.Location rootLocation = { mockLocation | pathname = "/" } newPostLocation : Navigation.Location newPostLocation = { mockLocation | pathname = "/posts/new" } postLocation : Navigation.Location postLocation = { mockLocation | pathname = "/posts/89" } unknownLocation : Navigation.Location unknownLocation = { mockLocation | pathname = "/unknownPath" } mockLocation : Navigation.Location mockLocation = { href = "fake" , host = "fake" , hostname = "fake" , protocol = "fake" , origin = "fake" , port_ = "fake" , pathname = "fake" , search = "fake" , hash = "fake" , username = "fake" , password = "PI:PASSWORD:<PASSWORD>END_PI" }
elm
[ { "context": " , name \"email\"\n , placeholder \"you@example.com\"\n , value model.email\n ", "end": 4028, "score": 0.9999200702, "start": 4013, "tag": "EMAIL", "value": "you@example.com" } ]
assets/elm/src/App/Modals/SigninModal.elm
reallinfo/cotoami
0
module App.Modals.SigninModal exposing ( Model , initModel , update , view , setSignupEnabled ) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onClick, onInput) import Http import Json.Decode as Decode import Util.StringUtil exposing (validateEmail) import Util.UpdateUtil exposing (withCmd, withoutCmd, addCmd) import Util.Modal as Modal import App.Messages as AppMsg exposing (Msg(CloseModal)) import App.Modals.SigninModalMsg as SigninModalMsg exposing (Msg(..)) type alias Model = { signupEnabled : Bool , email : String , requestProcessing : Bool , requestStatus : RequestStatus } type RequestStatus = None | Approved | Rejected initModel : Bool -> Model initModel signupEnabled = { signupEnabled = signupEnabled , email = "" , requestProcessing = False , requestStatus = None } setSignupEnabled : Bool -> Model -> Model setSignupEnabled signupEnabled model = { model | signupEnabled = signupEnabled } update : SigninModalMsg.Msg -> Model -> ( Model, Cmd AppMsg.Msg ) update msg model = case msg of EmailInput content -> { model | email = content } |> withoutCmd RequestClick -> { model | requestProcessing = True } |> withCmd (\model -> requestSignin model.email) RequestDone (Ok _) -> { model | email = "" , requestProcessing = False , requestStatus = Approved } |> withoutCmd RequestDone (Err _) -> { model | requestProcessing = False , requestStatus = Rejected } |> withoutCmd requestSignin : String -> Cmd AppMsg.Msg requestSignin email = let url = "/api/public/signin/request/" ++ email in Http.send (AppMsg.SigninModalMsg << RequestDone) (Http.get url Decode.string) view : Model -> Html AppMsg.Msg view model = modalConfig model |> Just |> Modal.view "signin-modal" modalConfig : Model -> Modal.Config AppMsg.Msg modalConfig model = if model.requestStatus == Approved then { closeMessage = CloseModal , title = text "Check your inbox!" , content = div [ id "signin-modal-content" ] [ p [] [ text "We just sent you an email with a link to access (or create) your Cotoami account." ] ] , buttons = [ button [ class "button", onClick CloseModal ] [ text "OK" ] ] } else if model.signupEnabled then modalConfigWithSignupEnabled model else modalConfigOnlyForSignin model modalConfigWithSignupEnabled : Model -> Modal.Config AppMsg.Msg modalConfigWithSignupEnabled model = { closeMessage = CloseModal , title = text "Sign in/up with your email" , content = div [] [ p [] [ text "Welcome to Cotoami!" ] , p [] [ text "Cotoami doesn't use passwords. Just enter your email address and we'll send you a sign-in (or sign-up) link." ] , signinForm model ] , buttons = [ signinButton "Sign in/up" model ] } modalConfigOnlyForSignin : Model -> Modal.Config AppMsg.Msg modalConfigOnlyForSignin model = { closeMessage = CloseModal , title = text "Sign in with your email" , content = div [] [ p [] [ text "Welcome to Cotoami!" ] , p [] [ text "Just enter your email address and we'll send you a sign-in link." ] , signinForm model ] , buttons = [ signinButton "Sign in" model ] } signinForm : Model -> Html AppMsg.Msg signinForm model = Html.form [ name "signin" ] [ div [] [ input [ type_ "email" , class "email u-full-width" , name "email" , placeholder "you@example.com" , value model.email , onInput (AppMsg.SigninModalMsg << EmailInput) ] [] ] , if model.requestStatus == Rejected then div [ class "error" ] [ span [ class "message" ] [ text "The email is not allowed to sign in." ] ] else div [] [] ] signinButton : String -> Model -> Html AppMsg.Msg signinButton label model = button [ class "button button-primary" , disabled (not (validateEmail model.email) || model.requestProcessing) , onClick (AppMsg.SigninModalMsg RequestClick) ] [ if model.requestProcessing then text "Sending..." else text label ]
49667
module App.Modals.SigninModal exposing ( Model , initModel , update , view , setSignupEnabled ) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onClick, onInput) import Http import Json.Decode as Decode import Util.StringUtil exposing (validateEmail) import Util.UpdateUtil exposing (withCmd, withoutCmd, addCmd) import Util.Modal as Modal import App.Messages as AppMsg exposing (Msg(CloseModal)) import App.Modals.SigninModalMsg as SigninModalMsg exposing (Msg(..)) type alias Model = { signupEnabled : Bool , email : String , requestProcessing : Bool , requestStatus : RequestStatus } type RequestStatus = None | Approved | Rejected initModel : Bool -> Model initModel signupEnabled = { signupEnabled = signupEnabled , email = "" , requestProcessing = False , requestStatus = None } setSignupEnabled : Bool -> Model -> Model setSignupEnabled signupEnabled model = { model | signupEnabled = signupEnabled } update : SigninModalMsg.Msg -> Model -> ( Model, Cmd AppMsg.Msg ) update msg model = case msg of EmailInput content -> { model | email = content } |> withoutCmd RequestClick -> { model | requestProcessing = True } |> withCmd (\model -> requestSignin model.email) RequestDone (Ok _) -> { model | email = "" , requestProcessing = False , requestStatus = Approved } |> withoutCmd RequestDone (Err _) -> { model | requestProcessing = False , requestStatus = Rejected } |> withoutCmd requestSignin : String -> Cmd AppMsg.Msg requestSignin email = let url = "/api/public/signin/request/" ++ email in Http.send (AppMsg.SigninModalMsg << RequestDone) (Http.get url Decode.string) view : Model -> Html AppMsg.Msg view model = modalConfig model |> Just |> Modal.view "signin-modal" modalConfig : Model -> Modal.Config AppMsg.Msg modalConfig model = if model.requestStatus == Approved then { closeMessage = CloseModal , title = text "Check your inbox!" , content = div [ id "signin-modal-content" ] [ p [] [ text "We just sent you an email with a link to access (or create) your Cotoami account." ] ] , buttons = [ button [ class "button", onClick CloseModal ] [ text "OK" ] ] } else if model.signupEnabled then modalConfigWithSignupEnabled model else modalConfigOnlyForSignin model modalConfigWithSignupEnabled : Model -> Modal.Config AppMsg.Msg modalConfigWithSignupEnabled model = { closeMessage = CloseModal , title = text "Sign in/up with your email" , content = div [] [ p [] [ text "Welcome to Cotoami!" ] , p [] [ text "Cotoami doesn't use passwords. Just enter your email address and we'll send you a sign-in (or sign-up) link." ] , signinForm model ] , buttons = [ signinButton "Sign in/up" model ] } modalConfigOnlyForSignin : Model -> Modal.Config AppMsg.Msg modalConfigOnlyForSignin model = { closeMessage = CloseModal , title = text "Sign in with your email" , content = div [] [ p [] [ text "Welcome to Cotoami!" ] , p [] [ text "Just enter your email address and we'll send you a sign-in link." ] , signinForm model ] , buttons = [ signinButton "Sign in" model ] } signinForm : Model -> Html AppMsg.Msg signinForm model = Html.form [ name "signin" ] [ div [] [ input [ type_ "email" , class "email u-full-width" , name "email" , placeholder "<EMAIL>" , value model.email , onInput (AppMsg.SigninModalMsg << EmailInput) ] [] ] , if model.requestStatus == Rejected then div [ class "error" ] [ span [ class "message" ] [ text "The email is not allowed to sign in." ] ] else div [] [] ] signinButton : String -> Model -> Html AppMsg.Msg signinButton label model = button [ class "button button-primary" , disabled (not (validateEmail model.email) || model.requestProcessing) , onClick (AppMsg.SigninModalMsg RequestClick) ] [ if model.requestProcessing then text "Sending..." else text label ]
true
module App.Modals.SigninModal exposing ( Model , initModel , update , view , setSignupEnabled ) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (onClick, onInput) import Http import Json.Decode as Decode import Util.StringUtil exposing (validateEmail) import Util.UpdateUtil exposing (withCmd, withoutCmd, addCmd) import Util.Modal as Modal import App.Messages as AppMsg exposing (Msg(CloseModal)) import App.Modals.SigninModalMsg as SigninModalMsg exposing (Msg(..)) type alias Model = { signupEnabled : Bool , email : String , requestProcessing : Bool , requestStatus : RequestStatus } type RequestStatus = None | Approved | Rejected initModel : Bool -> Model initModel signupEnabled = { signupEnabled = signupEnabled , email = "" , requestProcessing = False , requestStatus = None } setSignupEnabled : Bool -> Model -> Model setSignupEnabled signupEnabled model = { model | signupEnabled = signupEnabled } update : SigninModalMsg.Msg -> Model -> ( Model, Cmd AppMsg.Msg ) update msg model = case msg of EmailInput content -> { model | email = content } |> withoutCmd RequestClick -> { model | requestProcessing = True } |> withCmd (\model -> requestSignin model.email) RequestDone (Ok _) -> { model | email = "" , requestProcessing = False , requestStatus = Approved } |> withoutCmd RequestDone (Err _) -> { model | requestProcessing = False , requestStatus = Rejected } |> withoutCmd requestSignin : String -> Cmd AppMsg.Msg requestSignin email = let url = "/api/public/signin/request/" ++ email in Http.send (AppMsg.SigninModalMsg << RequestDone) (Http.get url Decode.string) view : Model -> Html AppMsg.Msg view model = modalConfig model |> Just |> Modal.view "signin-modal" modalConfig : Model -> Modal.Config AppMsg.Msg modalConfig model = if model.requestStatus == Approved then { closeMessage = CloseModal , title = text "Check your inbox!" , content = div [ id "signin-modal-content" ] [ p [] [ text "We just sent you an email with a link to access (or create) your Cotoami account." ] ] , buttons = [ button [ class "button", onClick CloseModal ] [ text "OK" ] ] } else if model.signupEnabled then modalConfigWithSignupEnabled model else modalConfigOnlyForSignin model modalConfigWithSignupEnabled : Model -> Modal.Config AppMsg.Msg modalConfigWithSignupEnabled model = { closeMessage = CloseModal , title = text "Sign in/up with your email" , content = div [] [ p [] [ text "Welcome to Cotoami!" ] , p [] [ text "Cotoami doesn't use passwords. Just enter your email address and we'll send you a sign-in (or sign-up) link." ] , signinForm model ] , buttons = [ signinButton "Sign in/up" model ] } modalConfigOnlyForSignin : Model -> Modal.Config AppMsg.Msg modalConfigOnlyForSignin model = { closeMessage = CloseModal , title = text "Sign in with your email" , content = div [] [ p [] [ text "Welcome to Cotoami!" ] , p [] [ text "Just enter your email address and we'll send you a sign-in link." ] , signinForm model ] , buttons = [ signinButton "Sign in" model ] } signinForm : Model -> Html AppMsg.Msg signinForm model = Html.form [ name "signin" ] [ div [] [ input [ type_ "email" , class "email u-full-width" , name "email" , placeholder "PI:EMAIL:<EMAIL>END_PI" , value model.email , onInput (AppMsg.SigninModalMsg << EmailInput) ] [] ] , if model.requestStatus == Rejected then div [ class "error" ] [ span [ class "message" ] [ text "The email is not allowed to sign in." ] ] else div [] [] ] signinButton : String -> Model -> Html AppMsg.Msg signinButton label model = button [ class "button button-primary" , disabled (not (validateEmail model.email) || model.requestProcessing) , onClick (AppMsg.SigninModalMsg RequestClick) ] [ if model.requestProcessing then text "Sending..." else text label ]
elm
[ { "context": " = \"The QA-Developer Relationship\"\n , guests = [\"Coilynn Buford\"]\n , summary = summary\n , identifier = \"qa-dev-", "end": 210, "score": 0.9998738766, "start": 196, "tag": "NAME", "value": "Coilynn Buford" }, { "context": "\"\n - There are websites for freelance QA work\n - [Rich Hickey on programmer meta-culture](https://www.youtube.c", "end": 1563, "score": 0.9989653826, "start": 1552, "tag": "NAME", "value": "Rich Hickey" } ]
src/Data/Episodes/TheQaDeveloperRelationship.elm
const-podcast/site
3
module Data.Episodes.TheQaDeveloperRelationship (episode) where import Models.Episode exposing (Episode) episode : Episode episode = { title = "The QA-Developer Relationship" , guests = ["Coilynn Buford"] , summary = summary , identifier = "qa-dev-relationship" , season = 1 , episodeOfSeason = 3 , url = "https://s3-us-west-2.amazonaws.com/constpodcast/const.s01e03.dev.qa.relationship.mp3" , icon = "magnify-bug-icon.png" } summary : String summary = """ The relationship between QAs and developers can truly make or break a product. Join us as we discuss ways developers can help make this relationship flourish. #### Show Notes - **Do not** put up a "do not disturb sign" - **Do** be open - [The programmer as a professional problem-solver](http://blog.codinghorror.com/can-your-team-pass-the-elevator-test/) - Recent movement to "automate everything" in last 5-6 years - We need both manual and automated testers - It makes sense for [Load Testing](https://en.wikipedia.org/wiki/Load_testing) to be automated - Some products are inherently difficult to write automated tests for (e.g. audio/visual) - If you are a manual tester, try to learn a language; If automated, try manual - [Bug Bash](https://en.wikipedia.org/wiki/Bug_bash) - Quality assurance happens before delivery and quality control comes after - [HP ALM](http://www8.hp.com/us/en/software-solutions/application-lifecycle-management.html) - "Don't become complacent to how they taught you in school" - There are websites for freelance QA work - [Rich Hickey on programmer meta-culture](https://www.youtube.com/watch?v=rI8tNMsozo0&feature=youtu.be&t=13m10s) - "QA is not needed" is a myth """
38541
module Data.Episodes.TheQaDeveloperRelationship (episode) where import Models.Episode exposing (Episode) episode : Episode episode = { title = "The QA-Developer Relationship" , guests = ["<NAME>"] , summary = summary , identifier = "qa-dev-relationship" , season = 1 , episodeOfSeason = 3 , url = "https://s3-us-west-2.amazonaws.com/constpodcast/const.s01e03.dev.qa.relationship.mp3" , icon = "magnify-bug-icon.png" } summary : String summary = """ The relationship between QAs and developers can truly make or break a product. Join us as we discuss ways developers can help make this relationship flourish. #### Show Notes - **Do not** put up a "do not disturb sign" - **Do** be open - [The programmer as a professional problem-solver](http://blog.codinghorror.com/can-your-team-pass-the-elevator-test/) - Recent movement to "automate everything" in last 5-6 years - We need both manual and automated testers - It makes sense for [Load Testing](https://en.wikipedia.org/wiki/Load_testing) to be automated - Some products are inherently difficult to write automated tests for (e.g. audio/visual) - If you are a manual tester, try to learn a language; If automated, try manual - [Bug Bash](https://en.wikipedia.org/wiki/Bug_bash) - Quality assurance happens before delivery and quality control comes after - [HP ALM](http://www8.hp.com/us/en/software-solutions/application-lifecycle-management.html) - "Don't become complacent to how they taught you in school" - There are websites for freelance QA work - [<NAME> on programmer meta-culture](https://www.youtube.com/watch?v=rI8tNMsozo0&feature=youtu.be&t=13m10s) - "QA is not needed" is a myth """
true
module Data.Episodes.TheQaDeveloperRelationship (episode) where import Models.Episode exposing (Episode) episode : Episode episode = { title = "The QA-Developer Relationship" , guests = ["PI:NAME:<NAME>END_PI"] , summary = summary , identifier = "qa-dev-relationship" , season = 1 , episodeOfSeason = 3 , url = "https://s3-us-west-2.amazonaws.com/constpodcast/const.s01e03.dev.qa.relationship.mp3" , icon = "magnify-bug-icon.png" } summary : String summary = """ The relationship between QAs and developers can truly make or break a product. Join us as we discuss ways developers can help make this relationship flourish. #### Show Notes - **Do not** put up a "do not disturb sign" - **Do** be open - [The programmer as a professional problem-solver](http://blog.codinghorror.com/can-your-team-pass-the-elevator-test/) - Recent movement to "automate everything" in last 5-6 years - We need both manual and automated testers - It makes sense for [Load Testing](https://en.wikipedia.org/wiki/Load_testing) to be automated - Some products are inherently difficult to write automated tests for (e.g. audio/visual) - If you are a manual tester, try to learn a language; If automated, try manual - [Bug Bash](https://en.wikipedia.org/wiki/Bug_bash) - Quality assurance happens before delivery and quality control comes after - [HP ALM](http://www8.hp.com/us/en/software-solutions/application-lifecycle-management.html) - "Don't become complacent to how they taught you in school" - There are websites for freelance QA work - [PI:NAME:<NAME>END_PI on programmer meta-culture](https://www.youtube.com/watch?v=rI8tNMsozo0&feature=youtu.be&t=13m10s) - "QA is not needed" is a myth """
elm
[ { "context": "ve |> App.Model.Game.moves) \n [ {player = White, location = (4,4)}\n , {player = White, l", "end": 7198, "score": 0.5910419822, "start": 7193, "tag": "NAME", "value": "White" }, { "context": "r = White, location = (4,6)}\n , {player = White, location = (5,6)}\n , {player = White, l", "end": 7480, "score": 0.710262537, "start": 7475, "tag": "NAME", "value": "White" }, { "context": "r = White, location = (5,6)}\n , {player = White, location = (6,6)}\n ]\n\n --, test \"Pos", "end": 7527, "score": 0.7101300955, "start": 7522, "tag": "NAME", "value": "White" }, { "context": "MovesFunc testGameMatrix3)\n -- [ {player = White, location = (2,2)}\n -- , {player = White,", "end": 7741, "score": 0.7960709333, "start": 7736, "tag": "NAME", "value": "White" }, { "context": "= White, location = (2,2)}\n -- , {player = White, location = (3,2)}\n -- , {player = White,", "end": 7790, "score": 0.8821561933, "start": 7785, "tag": "NAME", "value": "White" }, { "context": "= White, location = (3,2)}\n -- , {player = White, location = (4,2)}\n -- , {player = White,", "end": 7839, "score": 0.7039881945, "start": 7834, "tag": "NAME", "value": "White" }, { "context": "= White, location = (4,2)}\n -- , {player = White, location = (2,3)}\n -- , {player = White,", "end": 7888, "score": 0.5760453939, "start": 7883, "tag": "NAME", "value": "White" }, { "context": "= White, location = (5,2)}\n -- , {player = White, location = (5,3)}\n -- ]\n\n , test \"Aft", "end": 8476, "score": 0.9648106694, "start": 8471, "tag": "NAME", "value": "White" } ]
tests/AppModelGame.elm
jirichmiel/fiveinarow
0
module AppModelGame exposing (..) import Matrix exposing (..) import App.Model.Game exposing (..) import Expect exposing (Expectation) import Dict exposing (..) --import Fuzz exposing (Fuzzer, int, list, string) import Test exposing (..) -- filter for parsing logs cat /home/jiri/Downloads/test.txt | grep -Eo '(FORWARD|LEAF|WINNER|move = [^,]+,[^,]+,[^,]+|value = [^,]+|alpha = [^,]+|beta = [^,]+)' suite : Test suite = describe "App/Model/Game.elm" [ test "Function fivesInALine must generate a five correctly." <| \() -> Expect.equal (App.Model.Game.fivesInALine (3,2) (1,-1)) [((-1,6),(1,-1)),((0,5),(1,-1)),((1,4),(1,-1)),((2,3),(1,-1)),((3,2),(1,-1))] , test "Function affectedFives must generata all affected fives correctly." <| \() -> Expect.equal (App.Model.Game.affectedFives (3,3)) [ (( 3,-1),(0, 1)),((3,0),(0, 1)),((3,1),(0, 1)),((3,2),(0, 1)),((3,3),(0, 1)) , ((-1, 3),(1, 0)),((0,3),(1, 0)),((1,3),(1, 0)),((2,3),(1, 0)),((3,3),(1, 0)) , ((-1,-1),(1, 1)),((0,0),(1, 1)),((1,1),(1, 1)),((2,2),(1, 1)),((3,3),(1, 1)) , ((-1, 7),(1,-1)),((0,6),(1,-1)),((1,5),(1,-1)),((2,4),(1,-1)),((3,3),(1,-1)) ] --, test "Function updateCounter for black's stone." <| -- \() -> -- Expect.equal (App.Model.Game.updateCounter Black (4,6)) (5,6) --, test "Function updateCounter for white's stone." <| -- \() -> -- Expect.equal (App.Model.Game.updateCounter White (4,6)) (4,7) , test "Function updateCounterFunc for a counter and black's stone." <| \() -> Expect.equal (App.Model.Game.updateCounterFunc Black (Just (4,6))) (Just (5,6)) , test "Function updateCounterFunc for Nothing." <| \() -> Expect.equal (App.Model.Game.updateCounterFunc Black Nothing) Nothing , test "Function updateCounters for empty fives." <| \() -> Expect.equal (App.Model.Game.updateCounters (Dict.fromList [(((3,3),(0,1)), (4,6))]) [] (App.Model.Game.updateCounterFunc Black)) (Dict.fromList [(((3,3),(0,1)), (4,6))]) , test "Function updateCounters for not existed five." <| \() -> Expect.equal (App.Model.Game.updateCounters (Dict.fromList [(((3,3),(0,1)), (4,6))]) [((4,3),(0,1))] (App.Model.Game.updateCounterFunc Black)) (Dict.fromList [(((3,3),(0,1)), (4,6))]) , test "Function updateCounters for correct five." <| \() -> Expect.equal (App.Model.Game.updateCounters (Dict.fromList [(((3,3),(0,1)), (4,6))]) [((3,3),(0,1))] (App.Model.Game.updateCounterFunc Black)) (Dict.fromList [(((3,3),(0,1)), (5,6))]) , test "Function sumDeltaValueCounters." <| \() -> Expect.equal (App.Model.Game.sumDeltaValueCounters Black (Dict.fromList [(((3,3),(0,1)), (3,0))]) [((3,3),(0,1))]) ((0,0,-1,1,0),(0,0,0,0,0)) , test "Function sumDeltaValueCounters not existed five." <| \() -> Expect.equal (App.Model.Game.sumDeltaValueCounters Black (Dict.fromList [(((3,3),(0,1)), (3,0))]) [((-1,3),(0,1))]) ((0,0,0,0,0),(0,0,0,0,0)) , test "Test generate matrix." <| \() -> Expect.equal (List.range 0 5 |> List.map (\x -> List.map2 (,) (List.repeat 6 x) (List.range 0 5) ) |> List.concat) ( [ (0,0),(0,1),(0,2),(0,3),(0,4),(0,5), (1,0),(1,1),(1,2),(1,3),(1,4),(1,5), (2,0),(2,1),(2,2),(2,3),(2,4),(2,5), (3,0),(3,1),(3,2),(3,3),(3,4),(3,5), (4,0),(4,1),(4,2),(4,3),(4,4),(4,5), (5,0),(5,1),(5,2),(5,3),(5,4),(5,5) ] ) --, test "Function isInRange_ 5 (0,1),(0,1)." <| -- \() -> -- Expect.equal (App.Model.Game.isInRange_ 5 (0,1) (0,1)) True --, test "Function createEmptyCountersForDirection_ 5 1,1" <| -- \() -> -- Expect.equal (App.Model.Game.createEmptyCountersForDirection_ 5 (0,1)) ( -- [ -- (((0,0),(0,1)),(0,0)), (((0,1),(0,1)),(0,0)), (((1,0),(0,1)),(0,0)), (((1,1),(0,1)),(0,0)), (((2,0),(0,1)),(0,0)), (((2,1),(0,1)),(0,0)), -- (((3,0),(0,1)),(0,0)), (((3,1),(0,1)),(0,0)), (((4,0),(0,1)),(0,0)), (((4,1),(0,1)),(0,0)), (((5,0),(0,1)),(0,0)), (((5,1),(0,1)),(0,0)) -- ] -- ) , test "Function createEmptyCounters." <| \() -> Expect.equal (App.Model.Game.createEmptyCounters 5) (Dict.fromList [ (((0,0),(0,1)),(0,0)), (((0,0),(1,0)),(0,0)), (((0,0),(1,1)),(0,0)), (((0,1),(0,1)),(0,0)), (((0,1),(1,0)),(0,0)), (((0,1),(1,1)),(0,0)), (((0,2),(1,0)),(0,0)), (((0,3),(1,0)),(0,0)), (((0,4),(1,0)),(0,0)), (((0,4),(1,-1)),(0,0)), (((0,5),(1,0)),(0,0)), (((0,5),(1,-1)),(0,0)), (((1,0),(0,1)),(0,0)), (((1,0),(1,0)),(0,0)), (((1,0),(1,1)),(0,0)), (((1,1),(0,1)),(0,0)), (((1,1),(1,0)),(0,0)), (((1,1),(1,1)),(0,0)), (((1,2),(1,0)),(0,0)), (((1,3),(1,0)),(0,0)), (((1,4),(1,0)),(0,0)), (((1,4),(1,-1)),(0,0)), (((1,5),(1,0)),(0,0)), (((1,5),(1,-1)),(0,0)), (((2,0),(0,1)),(0,0)), (((2,1),(0,1)),(0,0)), (((3,0),(0,1)),(0,0)), (((3,1),(0,1)),(0,0)), (((4,0),(0,1)),(0,0)), (((4,1),(0,1)),(0,0)), (((5,0),(0,1)),(0,0)), (((5,1),(0,1)),(0,0)) ]) , test "Function locationsForFive." <| \() -> Expect.equal (App.Model.Game.locationsForFive ((12,13),(1,-1))) [ (12,13), (13,12), (14,11), (15,10), (16,9) ] , test "Function createGame creates a matrix with correct number of rows." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.board |> Matrix.rowCount) 10 , test "Function createGame creates a matrix with correct number of cols." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.board |> Matrix.colCount) 10 , test "Function createGame creates a matrix with all empty fields." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.board |> Matrix.flatten |> List.filter (\x -> x /= Empty) |> List.length) 0 , test "Function createGame creates a matrix with zero vector values." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.value) ((0,0,0,0,0),(0,0,0,0,0)) , test "Function createGame creates a matrix with one possible move." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.moves) [({player = Black, location = (5,5)})] , test "Function createGame creates a matrix with correct numbers of counters." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.counters |> Dict.size) 192 , test "After first move there must be only one non-empty field." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.board |> Matrix.flatten |> List.filter (\x -> x /= Empty) |> List.length) 1 , test "After first move field 5,5 must be Black." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.board |> Matrix.get (5,5)) (Just (Stone Black)) , test "After first move there must be 8 possible moves for White." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.moves) [ {player = White, location = (4,4)} , {player = White, location = (5,4)} , {player = White, location = (6,4)} , {player = White, location = (4,5)} , {player = White, location = (6,5)} , {player = White, location = (4,6)} , {player = White, location = (5,6)} , {player = White, location = (6,6)} ] --, test "Possible moves function for a few moves." <| -- \() -> -- Expect.equal (App.Model.Game.possibleMovesFunc testGameMatrix3) -- [ {player = White, location = (2,2)} -- , {player = White, location = (3,2)} -- , {player = White, location = (4,2)} -- , {player = White, location = (2,3)} -- , {player = White, location = (2,4)} -- , {player = White, location = (2,5)} -- , {player = White, location = (3,5)} -- , {player = White, location = (4,5)} -- , {player = White, location = (5,4)} -- , {player = White, location = (6,4)} -- , {player = White, location = (6,5)} -- , {player = White, location = (4,6)} -- , {player = White, location = (5,6)} -- , {player = White, location = (6,6)} -- , {player = White, location = (5,2)} -- , {player = White, location = (5,3)} -- ] , test "After first move there must be 20 affected counters around 5,5." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.counters |> Dict.foldl ( \(loc,dic) counter bool -> case bool of False -> False True -> if ( (dic == (0,1) && (List.member loc [(5,5),(5,4),(5,3),(5,2),(5,1)])) || (dic == (1,0) && (List.member loc [(5,5),(4,5),(3,5),(2,5),(1,5)])) || (dic == (1,1) && (List.member loc [(5,5),(4,4),(3,3),(2,2),(1,1)])) || (dic == (1,-1) && (List.member loc [(5,5),(4,6),(3,7),(2,8),(1,9)])) ) then counter == (1,0) -- there is count up black stone on affected fives else counter == (0,0) -- nothing is count up on other fives ) True) True , test "Test that there is no stone counter for five ((0,-1),(1,1))" <| \() -> Expect.equal (Dict.get ((0,-1),(1,1)) (testGame1FirstMove |> App.Model.Game.counters)) Nothing , test "Test that there is properly counter for five ((4,4),(1,1))" <| \() -> Expect.equal (Dict.get ((4,4),(1,1)) (testGame1FirstMove |> App.Model.Game.counters)) (Just (1,0)) , test "Test sumDeltaValueCounters after second move." <| \() -> Expect.equal (sumDeltaValueCounters White (testGame1FirstMove |> App.Model.Game.counters) (App.Model.Game.affectedFives (4,4))) ((-4,0,0,0,0),(16,0,0,0,0)) , test "After first move game value must be 20 1xstone fives for black and nothing for white." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.value) ((20,0,0,0,0),(0,0,0,0,0)) , test "After second move game value must be 16 1xstone fives for black and 16 1xstone for white." <| \() -> Expect.equal (testGame1SecondMove |> App.Model.Game.value) ((16,0,0,0,0),(16,0,0,0,0)) , test "After first move game no. 2 value must be 20 1xstone fives for black and nothing for white." <| \() -> Expect.equal (testGame2FirstMove |> App.Model.Game.value) ((20,0,0,0,0),(0,0,0,0,0)) , test "After second move game no. 2 value must be 16 1xstone fives for black and 13 1xstones for white." <| \() -> Expect.equal (testGame2SecondMove |> App.Model.Game.value) ((16,0,0,0,0),(13,0,0,0,0)) , test "After third move game no. 2 value must be 25 1xstone and 4 2xstones fives for black and 13 1xstones for white." <| \() -> Expect.equal (testGame2ThirdMove |> App.Model.Game.value) ((23,4,0,0,0),(13,0,0,0,0)) --, test "After third move game no. 2, total game value for black must be 11." <| -- \() -> -- Expect.equal (App.Model.Game.valueFunc App.Model.Game.basic Black testGame2ThirdMove (Just { player = Black, location = (0,0)})) 9 -- location is not important --, test "After third move game no. 2, total game value for white must be -117." <| -- \() -> -- Expect.equal (App.Model.Game.valueFunc App.Model.Game.basic Black testGame2ThirdMove (Just { player = White, location = (0,0)})) -113 -- location is not important --, test "Where move CPU after third move game no. 2." <| -- \() -> -- Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGame2ThirdMove) (Just (3,3)) , test "Test Game Matrix 1" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix1) (Just (0,8)) , test "Test Game Matrix 2" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix2) (Just (1,3)) , test "Test Game Matrix 2b" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix2) (Just (1,3)) , test "Test Game Matrix 3" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix3) (Just (2,2)) ] testCreateGame : Int -> GameBoardEx testCreateGame n = App.Model.Game.createGame n testGame1FirstMove : GameBoardEx testGame1FirstMove = testCreateGame 10 |> testMove {player = Black, location = (5,5) } testGame1SecondMove : GameBoardEx testGame1SecondMove = testGame1FirstMove |> testMove {player = White, location = (4,4) } testGame2FirstMove : GameBoardEx testGame2FirstMove = testCreateGame 9 |> testMove {player = Black, location = (4,4) } testGame2SecondMove : GameBoardEx testGame2SecondMove = testGame2FirstMove |> testMove {player = White, location = (3,4) } testGame2ThirdMove : GameBoardEx testGame2ThirdMove = testGame2SecondMove |> testMove {player = Black, location = (5,5) } {- MATRIX 1 -----------------------------------} {- 0 1 2 3 4 5 6 7 8 0 _ _ _ _ _ _ _ _ _ 1 _ _ _ _ _ _ _ x _ 2 _ _ _ _ _ _ x _ _ 3 _ _ o o x x x x o 4 _ _ _ o x o _ _ _ 5 _ _ _ o o _ _ _ _ 6 _ _ _ _ _ x _ _ _ 7 _ _ _ _ _ _ _ _ _ 8 _ _ _ _ _ _ _ _ _ -} testGameMatrix1 : GameBoardEx testGameMatrix1 = App.Model.Game.createGame 9 |> testMove { player = Black, location = (1,7) } |> testMove { player = White, location = (3,2) } |> testMove { player = Black, location = (2,6) } |> testMove { player = White, location = (3,3) } |> testMove { player = Black, location = (3,4) } |> testMove { player = White, location = (3,8) } |> testMove { player = Black, location = (3,5) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (3,6) } |> testMove { player = White, location = (4,5) } |> testMove { player = Black, location = (3,7) } |> testMove { player = White, location = (5,3) } |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (5,4) } |> testMove { player = Black, location = (6,5) } {- MATRIX 2 -----------------------------------} {- 0 1 2 3 4 5 6 7 8 0 _ _ _ _ _ _ _ _ _ 1 _ _ _ _ _ _ _ _ _ 2 _ _ _ o _ x _ _ _ 3 _ _ _ o o o x _ _ 4 _ _ _ o x _ x _ _ 5 _ _ o x _ x _ _ _ 6 _ o _ _ x _ _ _ _ 7 x _ _ _ _ _ _ _ _ 8 _ _ _ _ _ _ _ _ _ -} testGameMatrix2 : GameBoardEx testGameMatrix2 = App.Model.Game.createGame 9 |> testMove { player = Black, location = (2,5) } |> testMove { player = White, location = (2,3) } |> testMove { player = Black, location = (3,6) } |> testMove { player = White, location = (3,3) } |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (3,4) } |> testMove { player = Black, location = (4,6) } |> testMove { player = White, location = (3,5) } |> testMove { player = Black, location = (5,3) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (5,6) } |> testMove { player = White, location = (5,2) } |> testMove { player = Black, location = (6,4) } |> testMove { player = White, location = (6,1) } |> testMove { player = Black, location = (7,0) } testGameMatrix2b : GameBoardEx testGameMatrix2b = App.Model.Game.createGame 9 |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (5,5) } |> testMove { player = White, location = (3,3) } |> testMove { player = Black, location = (5,3) } |> testMove { player = White, location = (5,2) } |> testMove { player = Black, location = (6,4) } |> testMove { player = White, location = (6,1) } |> testMove { player = Black, location = (7,0) } |> testMove { player = White, location = (3,4) } |> testMove { player = Black, location = (2,5) } |> testMove { player = White, location = (3,5) } |> testMove { player = Black, location = (3,6) } |> testMove { player = White, location = (2,3) } |> testMove { player = Black, location = (4,6) } {- MATRIX 3 -----------------------------------} {- 0 1 2 3 4 5 6 7 8 0 _ _ _ _ _ _ _ _ _ 1 _ _ _ _ _ _ _ _ _ 2 _ _ _ _ _ _ _ _ _ 3 _ _ _ x o _ _ _ _ 4 _ _ _ o x _ _ _ _ 5 _ _ _ _ _ x _ _ _ 6 _ _ _ _ _ _ _ _ _ 7 _ _ _ _ _ _ _ _ _ 8 _ _ _ _ _ _ _ _ _ -} testGameMatrix3 : GameBoardEx testGameMatrix3 = App.Model.Game.createGame 9 |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (5,5) } |> testMove { player = White, location = (3,4) } |> testMove { player = Black, location = (3,3) } testMove : GameMove -> GameBoardEx -> GameBoardEx testMove move boardEx = App.Model.Game.moveFuncEx boardEx move.location
32913
module AppModelGame exposing (..) import Matrix exposing (..) import App.Model.Game exposing (..) import Expect exposing (Expectation) import Dict exposing (..) --import Fuzz exposing (Fuzzer, int, list, string) import Test exposing (..) -- filter for parsing logs cat /home/jiri/Downloads/test.txt | grep -Eo '(FORWARD|LEAF|WINNER|move = [^,]+,[^,]+,[^,]+|value = [^,]+|alpha = [^,]+|beta = [^,]+)' suite : Test suite = describe "App/Model/Game.elm" [ test "Function fivesInALine must generate a five correctly." <| \() -> Expect.equal (App.Model.Game.fivesInALine (3,2) (1,-1)) [((-1,6),(1,-1)),((0,5),(1,-1)),((1,4),(1,-1)),((2,3),(1,-1)),((3,2),(1,-1))] , test "Function affectedFives must generata all affected fives correctly." <| \() -> Expect.equal (App.Model.Game.affectedFives (3,3)) [ (( 3,-1),(0, 1)),((3,0),(0, 1)),((3,1),(0, 1)),((3,2),(0, 1)),((3,3),(0, 1)) , ((-1, 3),(1, 0)),((0,3),(1, 0)),((1,3),(1, 0)),((2,3),(1, 0)),((3,3),(1, 0)) , ((-1,-1),(1, 1)),((0,0),(1, 1)),((1,1),(1, 1)),((2,2),(1, 1)),((3,3),(1, 1)) , ((-1, 7),(1,-1)),((0,6),(1,-1)),((1,5),(1,-1)),((2,4),(1,-1)),((3,3),(1,-1)) ] --, test "Function updateCounter for black's stone." <| -- \() -> -- Expect.equal (App.Model.Game.updateCounter Black (4,6)) (5,6) --, test "Function updateCounter for white's stone." <| -- \() -> -- Expect.equal (App.Model.Game.updateCounter White (4,6)) (4,7) , test "Function updateCounterFunc for a counter and black's stone." <| \() -> Expect.equal (App.Model.Game.updateCounterFunc Black (Just (4,6))) (Just (5,6)) , test "Function updateCounterFunc for Nothing." <| \() -> Expect.equal (App.Model.Game.updateCounterFunc Black Nothing) Nothing , test "Function updateCounters for empty fives." <| \() -> Expect.equal (App.Model.Game.updateCounters (Dict.fromList [(((3,3),(0,1)), (4,6))]) [] (App.Model.Game.updateCounterFunc Black)) (Dict.fromList [(((3,3),(0,1)), (4,6))]) , test "Function updateCounters for not existed five." <| \() -> Expect.equal (App.Model.Game.updateCounters (Dict.fromList [(((3,3),(0,1)), (4,6))]) [((4,3),(0,1))] (App.Model.Game.updateCounterFunc Black)) (Dict.fromList [(((3,3),(0,1)), (4,6))]) , test "Function updateCounters for correct five." <| \() -> Expect.equal (App.Model.Game.updateCounters (Dict.fromList [(((3,3),(0,1)), (4,6))]) [((3,3),(0,1))] (App.Model.Game.updateCounterFunc Black)) (Dict.fromList [(((3,3),(0,1)), (5,6))]) , test "Function sumDeltaValueCounters." <| \() -> Expect.equal (App.Model.Game.sumDeltaValueCounters Black (Dict.fromList [(((3,3),(0,1)), (3,0))]) [((3,3),(0,1))]) ((0,0,-1,1,0),(0,0,0,0,0)) , test "Function sumDeltaValueCounters not existed five." <| \() -> Expect.equal (App.Model.Game.sumDeltaValueCounters Black (Dict.fromList [(((3,3),(0,1)), (3,0))]) [((-1,3),(0,1))]) ((0,0,0,0,0),(0,0,0,0,0)) , test "Test generate matrix." <| \() -> Expect.equal (List.range 0 5 |> List.map (\x -> List.map2 (,) (List.repeat 6 x) (List.range 0 5) ) |> List.concat) ( [ (0,0),(0,1),(0,2),(0,3),(0,4),(0,5), (1,0),(1,1),(1,2),(1,3),(1,4),(1,5), (2,0),(2,1),(2,2),(2,3),(2,4),(2,5), (3,0),(3,1),(3,2),(3,3),(3,4),(3,5), (4,0),(4,1),(4,2),(4,3),(4,4),(4,5), (5,0),(5,1),(5,2),(5,3),(5,4),(5,5) ] ) --, test "Function isInRange_ 5 (0,1),(0,1)." <| -- \() -> -- Expect.equal (App.Model.Game.isInRange_ 5 (0,1) (0,1)) True --, test "Function createEmptyCountersForDirection_ 5 1,1" <| -- \() -> -- Expect.equal (App.Model.Game.createEmptyCountersForDirection_ 5 (0,1)) ( -- [ -- (((0,0),(0,1)),(0,0)), (((0,1),(0,1)),(0,0)), (((1,0),(0,1)),(0,0)), (((1,1),(0,1)),(0,0)), (((2,0),(0,1)),(0,0)), (((2,1),(0,1)),(0,0)), -- (((3,0),(0,1)),(0,0)), (((3,1),(0,1)),(0,0)), (((4,0),(0,1)),(0,0)), (((4,1),(0,1)),(0,0)), (((5,0),(0,1)),(0,0)), (((5,1),(0,1)),(0,0)) -- ] -- ) , test "Function createEmptyCounters." <| \() -> Expect.equal (App.Model.Game.createEmptyCounters 5) (Dict.fromList [ (((0,0),(0,1)),(0,0)), (((0,0),(1,0)),(0,0)), (((0,0),(1,1)),(0,0)), (((0,1),(0,1)),(0,0)), (((0,1),(1,0)),(0,0)), (((0,1),(1,1)),(0,0)), (((0,2),(1,0)),(0,0)), (((0,3),(1,0)),(0,0)), (((0,4),(1,0)),(0,0)), (((0,4),(1,-1)),(0,0)), (((0,5),(1,0)),(0,0)), (((0,5),(1,-1)),(0,0)), (((1,0),(0,1)),(0,0)), (((1,0),(1,0)),(0,0)), (((1,0),(1,1)),(0,0)), (((1,1),(0,1)),(0,0)), (((1,1),(1,0)),(0,0)), (((1,1),(1,1)),(0,0)), (((1,2),(1,0)),(0,0)), (((1,3),(1,0)),(0,0)), (((1,4),(1,0)),(0,0)), (((1,4),(1,-1)),(0,0)), (((1,5),(1,0)),(0,0)), (((1,5),(1,-1)),(0,0)), (((2,0),(0,1)),(0,0)), (((2,1),(0,1)),(0,0)), (((3,0),(0,1)),(0,0)), (((3,1),(0,1)),(0,0)), (((4,0),(0,1)),(0,0)), (((4,1),(0,1)),(0,0)), (((5,0),(0,1)),(0,0)), (((5,1),(0,1)),(0,0)) ]) , test "Function locationsForFive." <| \() -> Expect.equal (App.Model.Game.locationsForFive ((12,13),(1,-1))) [ (12,13), (13,12), (14,11), (15,10), (16,9) ] , test "Function createGame creates a matrix with correct number of rows." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.board |> Matrix.rowCount) 10 , test "Function createGame creates a matrix with correct number of cols." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.board |> Matrix.colCount) 10 , test "Function createGame creates a matrix with all empty fields." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.board |> Matrix.flatten |> List.filter (\x -> x /= Empty) |> List.length) 0 , test "Function createGame creates a matrix with zero vector values." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.value) ((0,0,0,0,0),(0,0,0,0,0)) , test "Function createGame creates a matrix with one possible move." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.moves) [({player = Black, location = (5,5)})] , test "Function createGame creates a matrix with correct numbers of counters." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.counters |> Dict.size) 192 , test "After first move there must be only one non-empty field." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.board |> Matrix.flatten |> List.filter (\x -> x /= Empty) |> List.length) 1 , test "After first move field 5,5 must be Black." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.board |> Matrix.get (5,5)) (Just (Stone Black)) , test "After first move there must be 8 possible moves for White." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.moves) [ {player = <NAME>, location = (4,4)} , {player = White, location = (5,4)} , {player = White, location = (6,4)} , {player = White, location = (4,5)} , {player = White, location = (6,5)} , {player = White, location = (4,6)} , {player = <NAME>, location = (5,6)} , {player = <NAME>, location = (6,6)} ] --, test "Possible moves function for a few moves." <| -- \() -> -- Expect.equal (App.Model.Game.possibleMovesFunc testGameMatrix3) -- [ {player = <NAME>, location = (2,2)} -- , {player = <NAME>, location = (3,2)} -- , {player = <NAME>, location = (4,2)} -- , {player = <NAME>, location = (2,3)} -- , {player = White, location = (2,4)} -- , {player = White, location = (2,5)} -- , {player = White, location = (3,5)} -- , {player = White, location = (4,5)} -- , {player = White, location = (5,4)} -- , {player = White, location = (6,4)} -- , {player = White, location = (6,5)} -- , {player = White, location = (4,6)} -- , {player = White, location = (5,6)} -- , {player = White, location = (6,6)} -- , {player = White, location = (5,2)} -- , {player = <NAME>, location = (5,3)} -- ] , test "After first move there must be 20 affected counters around 5,5." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.counters |> Dict.foldl ( \(loc,dic) counter bool -> case bool of False -> False True -> if ( (dic == (0,1) && (List.member loc [(5,5),(5,4),(5,3),(5,2),(5,1)])) || (dic == (1,0) && (List.member loc [(5,5),(4,5),(3,5),(2,5),(1,5)])) || (dic == (1,1) && (List.member loc [(5,5),(4,4),(3,3),(2,2),(1,1)])) || (dic == (1,-1) && (List.member loc [(5,5),(4,6),(3,7),(2,8),(1,9)])) ) then counter == (1,0) -- there is count up black stone on affected fives else counter == (0,0) -- nothing is count up on other fives ) True) True , test "Test that there is no stone counter for five ((0,-1),(1,1))" <| \() -> Expect.equal (Dict.get ((0,-1),(1,1)) (testGame1FirstMove |> App.Model.Game.counters)) Nothing , test "Test that there is properly counter for five ((4,4),(1,1))" <| \() -> Expect.equal (Dict.get ((4,4),(1,1)) (testGame1FirstMove |> App.Model.Game.counters)) (Just (1,0)) , test "Test sumDeltaValueCounters after second move." <| \() -> Expect.equal (sumDeltaValueCounters White (testGame1FirstMove |> App.Model.Game.counters) (App.Model.Game.affectedFives (4,4))) ((-4,0,0,0,0),(16,0,0,0,0)) , test "After first move game value must be 20 1xstone fives for black and nothing for white." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.value) ((20,0,0,0,0),(0,0,0,0,0)) , test "After second move game value must be 16 1xstone fives for black and 16 1xstone for white." <| \() -> Expect.equal (testGame1SecondMove |> App.Model.Game.value) ((16,0,0,0,0),(16,0,0,0,0)) , test "After first move game no. 2 value must be 20 1xstone fives for black and nothing for white." <| \() -> Expect.equal (testGame2FirstMove |> App.Model.Game.value) ((20,0,0,0,0),(0,0,0,0,0)) , test "After second move game no. 2 value must be 16 1xstone fives for black and 13 1xstones for white." <| \() -> Expect.equal (testGame2SecondMove |> App.Model.Game.value) ((16,0,0,0,0),(13,0,0,0,0)) , test "After third move game no. 2 value must be 25 1xstone and 4 2xstones fives for black and 13 1xstones for white." <| \() -> Expect.equal (testGame2ThirdMove |> App.Model.Game.value) ((23,4,0,0,0),(13,0,0,0,0)) --, test "After third move game no. 2, total game value for black must be 11." <| -- \() -> -- Expect.equal (App.Model.Game.valueFunc App.Model.Game.basic Black testGame2ThirdMove (Just { player = Black, location = (0,0)})) 9 -- location is not important --, test "After third move game no. 2, total game value for white must be -117." <| -- \() -> -- Expect.equal (App.Model.Game.valueFunc App.Model.Game.basic Black testGame2ThirdMove (Just { player = White, location = (0,0)})) -113 -- location is not important --, test "Where move CPU after third move game no. 2." <| -- \() -> -- Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGame2ThirdMove) (Just (3,3)) , test "Test Game Matrix 1" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix1) (Just (0,8)) , test "Test Game Matrix 2" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix2) (Just (1,3)) , test "Test Game Matrix 2b" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix2) (Just (1,3)) , test "Test Game Matrix 3" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix3) (Just (2,2)) ] testCreateGame : Int -> GameBoardEx testCreateGame n = App.Model.Game.createGame n testGame1FirstMove : GameBoardEx testGame1FirstMove = testCreateGame 10 |> testMove {player = Black, location = (5,5) } testGame1SecondMove : GameBoardEx testGame1SecondMove = testGame1FirstMove |> testMove {player = White, location = (4,4) } testGame2FirstMove : GameBoardEx testGame2FirstMove = testCreateGame 9 |> testMove {player = Black, location = (4,4) } testGame2SecondMove : GameBoardEx testGame2SecondMove = testGame2FirstMove |> testMove {player = White, location = (3,4) } testGame2ThirdMove : GameBoardEx testGame2ThirdMove = testGame2SecondMove |> testMove {player = Black, location = (5,5) } {- MATRIX 1 -----------------------------------} {- 0 1 2 3 4 5 6 7 8 0 _ _ _ _ _ _ _ _ _ 1 _ _ _ _ _ _ _ x _ 2 _ _ _ _ _ _ x _ _ 3 _ _ o o x x x x o 4 _ _ _ o x o _ _ _ 5 _ _ _ o o _ _ _ _ 6 _ _ _ _ _ x _ _ _ 7 _ _ _ _ _ _ _ _ _ 8 _ _ _ _ _ _ _ _ _ -} testGameMatrix1 : GameBoardEx testGameMatrix1 = App.Model.Game.createGame 9 |> testMove { player = Black, location = (1,7) } |> testMove { player = White, location = (3,2) } |> testMove { player = Black, location = (2,6) } |> testMove { player = White, location = (3,3) } |> testMove { player = Black, location = (3,4) } |> testMove { player = White, location = (3,8) } |> testMove { player = Black, location = (3,5) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (3,6) } |> testMove { player = White, location = (4,5) } |> testMove { player = Black, location = (3,7) } |> testMove { player = White, location = (5,3) } |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (5,4) } |> testMove { player = Black, location = (6,5) } {- MATRIX 2 -----------------------------------} {- 0 1 2 3 4 5 6 7 8 0 _ _ _ _ _ _ _ _ _ 1 _ _ _ _ _ _ _ _ _ 2 _ _ _ o _ x _ _ _ 3 _ _ _ o o o x _ _ 4 _ _ _ o x _ x _ _ 5 _ _ o x _ x _ _ _ 6 _ o _ _ x _ _ _ _ 7 x _ _ _ _ _ _ _ _ 8 _ _ _ _ _ _ _ _ _ -} testGameMatrix2 : GameBoardEx testGameMatrix2 = App.Model.Game.createGame 9 |> testMove { player = Black, location = (2,5) } |> testMove { player = White, location = (2,3) } |> testMove { player = Black, location = (3,6) } |> testMove { player = White, location = (3,3) } |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (3,4) } |> testMove { player = Black, location = (4,6) } |> testMove { player = White, location = (3,5) } |> testMove { player = Black, location = (5,3) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (5,6) } |> testMove { player = White, location = (5,2) } |> testMove { player = Black, location = (6,4) } |> testMove { player = White, location = (6,1) } |> testMove { player = Black, location = (7,0) } testGameMatrix2b : GameBoardEx testGameMatrix2b = App.Model.Game.createGame 9 |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (5,5) } |> testMove { player = White, location = (3,3) } |> testMove { player = Black, location = (5,3) } |> testMove { player = White, location = (5,2) } |> testMove { player = Black, location = (6,4) } |> testMove { player = White, location = (6,1) } |> testMove { player = Black, location = (7,0) } |> testMove { player = White, location = (3,4) } |> testMove { player = Black, location = (2,5) } |> testMove { player = White, location = (3,5) } |> testMove { player = Black, location = (3,6) } |> testMove { player = White, location = (2,3) } |> testMove { player = Black, location = (4,6) } {- MATRIX 3 -----------------------------------} {- 0 1 2 3 4 5 6 7 8 0 _ _ _ _ _ _ _ _ _ 1 _ _ _ _ _ _ _ _ _ 2 _ _ _ _ _ _ _ _ _ 3 _ _ _ x o _ _ _ _ 4 _ _ _ o x _ _ _ _ 5 _ _ _ _ _ x _ _ _ 6 _ _ _ _ _ _ _ _ _ 7 _ _ _ _ _ _ _ _ _ 8 _ _ _ _ _ _ _ _ _ -} testGameMatrix3 : GameBoardEx testGameMatrix3 = App.Model.Game.createGame 9 |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (5,5) } |> testMove { player = White, location = (3,4) } |> testMove { player = Black, location = (3,3) } testMove : GameMove -> GameBoardEx -> GameBoardEx testMove move boardEx = App.Model.Game.moveFuncEx boardEx move.location
true
module AppModelGame exposing (..) import Matrix exposing (..) import App.Model.Game exposing (..) import Expect exposing (Expectation) import Dict exposing (..) --import Fuzz exposing (Fuzzer, int, list, string) import Test exposing (..) -- filter for parsing logs cat /home/jiri/Downloads/test.txt | grep -Eo '(FORWARD|LEAF|WINNER|move = [^,]+,[^,]+,[^,]+|value = [^,]+|alpha = [^,]+|beta = [^,]+)' suite : Test suite = describe "App/Model/Game.elm" [ test "Function fivesInALine must generate a five correctly." <| \() -> Expect.equal (App.Model.Game.fivesInALine (3,2) (1,-1)) [((-1,6),(1,-1)),((0,5),(1,-1)),((1,4),(1,-1)),((2,3),(1,-1)),((3,2),(1,-1))] , test "Function affectedFives must generata all affected fives correctly." <| \() -> Expect.equal (App.Model.Game.affectedFives (3,3)) [ (( 3,-1),(0, 1)),((3,0),(0, 1)),((3,1),(0, 1)),((3,2),(0, 1)),((3,3),(0, 1)) , ((-1, 3),(1, 0)),((0,3),(1, 0)),((1,3),(1, 0)),((2,3),(1, 0)),((3,3),(1, 0)) , ((-1,-1),(1, 1)),((0,0),(1, 1)),((1,1),(1, 1)),((2,2),(1, 1)),((3,3),(1, 1)) , ((-1, 7),(1,-1)),((0,6),(1,-1)),((1,5),(1,-1)),((2,4),(1,-1)),((3,3),(1,-1)) ] --, test "Function updateCounter for black's stone." <| -- \() -> -- Expect.equal (App.Model.Game.updateCounter Black (4,6)) (5,6) --, test "Function updateCounter for white's stone." <| -- \() -> -- Expect.equal (App.Model.Game.updateCounter White (4,6)) (4,7) , test "Function updateCounterFunc for a counter and black's stone." <| \() -> Expect.equal (App.Model.Game.updateCounterFunc Black (Just (4,6))) (Just (5,6)) , test "Function updateCounterFunc for Nothing." <| \() -> Expect.equal (App.Model.Game.updateCounterFunc Black Nothing) Nothing , test "Function updateCounters for empty fives." <| \() -> Expect.equal (App.Model.Game.updateCounters (Dict.fromList [(((3,3),(0,1)), (4,6))]) [] (App.Model.Game.updateCounterFunc Black)) (Dict.fromList [(((3,3),(0,1)), (4,6))]) , test "Function updateCounters for not existed five." <| \() -> Expect.equal (App.Model.Game.updateCounters (Dict.fromList [(((3,3),(0,1)), (4,6))]) [((4,3),(0,1))] (App.Model.Game.updateCounterFunc Black)) (Dict.fromList [(((3,3),(0,1)), (4,6))]) , test "Function updateCounters for correct five." <| \() -> Expect.equal (App.Model.Game.updateCounters (Dict.fromList [(((3,3),(0,1)), (4,6))]) [((3,3),(0,1))] (App.Model.Game.updateCounterFunc Black)) (Dict.fromList [(((3,3),(0,1)), (5,6))]) , test "Function sumDeltaValueCounters." <| \() -> Expect.equal (App.Model.Game.sumDeltaValueCounters Black (Dict.fromList [(((3,3),(0,1)), (3,0))]) [((3,3),(0,1))]) ((0,0,-1,1,0),(0,0,0,0,0)) , test "Function sumDeltaValueCounters not existed five." <| \() -> Expect.equal (App.Model.Game.sumDeltaValueCounters Black (Dict.fromList [(((3,3),(0,1)), (3,0))]) [((-1,3),(0,1))]) ((0,0,0,0,0),(0,0,0,0,0)) , test "Test generate matrix." <| \() -> Expect.equal (List.range 0 5 |> List.map (\x -> List.map2 (,) (List.repeat 6 x) (List.range 0 5) ) |> List.concat) ( [ (0,0),(0,1),(0,2),(0,3),(0,4),(0,5), (1,0),(1,1),(1,2),(1,3),(1,4),(1,5), (2,0),(2,1),(2,2),(2,3),(2,4),(2,5), (3,0),(3,1),(3,2),(3,3),(3,4),(3,5), (4,0),(4,1),(4,2),(4,3),(4,4),(4,5), (5,0),(5,1),(5,2),(5,3),(5,4),(5,5) ] ) --, test "Function isInRange_ 5 (0,1),(0,1)." <| -- \() -> -- Expect.equal (App.Model.Game.isInRange_ 5 (0,1) (0,1)) True --, test "Function createEmptyCountersForDirection_ 5 1,1" <| -- \() -> -- Expect.equal (App.Model.Game.createEmptyCountersForDirection_ 5 (0,1)) ( -- [ -- (((0,0),(0,1)),(0,0)), (((0,1),(0,1)),(0,0)), (((1,0),(0,1)),(0,0)), (((1,1),(0,1)),(0,0)), (((2,0),(0,1)),(0,0)), (((2,1),(0,1)),(0,0)), -- (((3,0),(0,1)),(0,0)), (((3,1),(0,1)),(0,0)), (((4,0),(0,1)),(0,0)), (((4,1),(0,1)),(0,0)), (((5,0),(0,1)),(0,0)), (((5,1),(0,1)),(0,0)) -- ] -- ) , test "Function createEmptyCounters." <| \() -> Expect.equal (App.Model.Game.createEmptyCounters 5) (Dict.fromList [ (((0,0),(0,1)),(0,0)), (((0,0),(1,0)),(0,0)), (((0,0),(1,1)),(0,0)), (((0,1),(0,1)),(0,0)), (((0,1),(1,0)),(0,0)), (((0,1),(1,1)),(0,0)), (((0,2),(1,0)),(0,0)), (((0,3),(1,0)),(0,0)), (((0,4),(1,0)),(0,0)), (((0,4),(1,-1)),(0,0)), (((0,5),(1,0)),(0,0)), (((0,5),(1,-1)),(0,0)), (((1,0),(0,1)),(0,0)), (((1,0),(1,0)),(0,0)), (((1,0),(1,1)),(0,0)), (((1,1),(0,1)),(0,0)), (((1,1),(1,0)),(0,0)), (((1,1),(1,1)),(0,0)), (((1,2),(1,0)),(0,0)), (((1,3),(1,0)),(0,0)), (((1,4),(1,0)),(0,0)), (((1,4),(1,-1)),(0,0)), (((1,5),(1,0)),(0,0)), (((1,5),(1,-1)),(0,0)), (((2,0),(0,1)),(0,0)), (((2,1),(0,1)),(0,0)), (((3,0),(0,1)),(0,0)), (((3,1),(0,1)),(0,0)), (((4,0),(0,1)),(0,0)), (((4,1),(0,1)),(0,0)), (((5,0),(0,1)),(0,0)), (((5,1),(0,1)),(0,0)) ]) , test "Function locationsForFive." <| \() -> Expect.equal (App.Model.Game.locationsForFive ((12,13),(1,-1))) [ (12,13), (13,12), (14,11), (15,10), (16,9) ] , test "Function createGame creates a matrix with correct number of rows." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.board |> Matrix.rowCount) 10 , test "Function createGame creates a matrix with correct number of cols." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.board |> Matrix.colCount) 10 , test "Function createGame creates a matrix with all empty fields." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.board |> Matrix.flatten |> List.filter (\x -> x /= Empty) |> List.length) 0 , test "Function createGame creates a matrix with zero vector values." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.value) ((0,0,0,0,0),(0,0,0,0,0)) , test "Function createGame creates a matrix with one possible move." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.moves) [({player = Black, location = (5,5)})] , test "Function createGame creates a matrix with correct numbers of counters." <| \() -> Expect.equal (testCreateGame 10 |> App.Model.Game.counters |> Dict.size) 192 , test "After first move there must be only one non-empty field." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.board |> Matrix.flatten |> List.filter (\x -> x /= Empty) |> List.length) 1 , test "After first move field 5,5 must be Black." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.board |> Matrix.get (5,5)) (Just (Stone Black)) , test "After first move there must be 8 possible moves for White." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.moves) [ {player = PI:NAME:<NAME>END_PI, location = (4,4)} , {player = White, location = (5,4)} , {player = White, location = (6,4)} , {player = White, location = (4,5)} , {player = White, location = (6,5)} , {player = White, location = (4,6)} , {player = PI:NAME:<NAME>END_PI, location = (5,6)} , {player = PI:NAME:<NAME>END_PI, location = (6,6)} ] --, test "Possible moves function for a few moves." <| -- \() -> -- Expect.equal (App.Model.Game.possibleMovesFunc testGameMatrix3) -- [ {player = PI:NAME:<NAME>END_PI, location = (2,2)} -- , {player = PI:NAME:<NAME>END_PI, location = (3,2)} -- , {player = PI:NAME:<NAME>END_PI, location = (4,2)} -- , {player = PI:NAME:<NAME>END_PI, location = (2,3)} -- , {player = White, location = (2,4)} -- , {player = White, location = (2,5)} -- , {player = White, location = (3,5)} -- , {player = White, location = (4,5)} -- , {player = White, location = (5,4)} -- , {player = White, location = (6,4)} -- , {player = White, location = (6,5)} -- , {player = White, location = (4,6)} -- , {player = White, location = (5,6)} -- , {player = White, location = (6,6)} -- , {player = White, location = (5,2)} -- , {player = PI:NAME:<NAME>END_PI, location = (5,3)} -- ] , test "After first move there must be 20 affected counters around 5,5." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.counters |> Dict.foldl ( \(loc,dic) counter bool -> case bool of False -> False True -> if ( (dic == (0,1) && (List.member loc [(5,5),(5,4),(5,3),(5,2),(5,1)])) || (dic == (1,0) && (List.member loc [(5,5),(4,5),(3,5),(2,5),(1,5)])) || (dic == (1,1) && (List.member loc [(5,5),(4,4),(3,3),(2,2),(1,1)])) || (dic == (1,-1) && (List.member loc [(5,5),(4,6),(3,7),(2,8),(1,9)])) ) then counter == (1,0) -- there is count up black stone on affected fives else counter == (0,0) -- nothing is count up on other fives ) True) True , test "Test that there is no stone counter for five ((0,-1),(1,1))" <| \() -> Expect.equal (Dict.get ((0,-1),(1,1)) (testGame1FirstMove |> App.Model.Game.counters)) Nothing , test "Test that there is properly counter for five ((4,4),(1,1))" <| \() -> Expect.equal (Dict.get ((4,4),(1,1)) (testGame1FirstMove |> App.Model.Game.counters)) (Just (1,0)) , test "Test sumDeltaValueCounters after second move." <| \() -> Expect.equal (sumDeltaValueCounters White (testGame1FirstMove |> App.Model.Game.counters) (App.Model.Game.affectedFives (4,4))) ((-4,0,0,0,0),(16,0,0,0,0)) , test "After first move game value must be 20 1xstone fives for black and nothing for white." <| \() -> Expect.equal (testGame1FirstMove |> App.Model.Game.value) ((20,0,0,0,0),(0,0,0,0,0)) , test "After second move game value must be 16 1xstone fives for black and 16 1xstone for white." <| \() -> Expect.equal (testGame1SecondMove |> App.Model.Game.value) ((16,0,0,0,0),(16,0,0,0,0)) , test "After first move game no. 2 value must be 20 1xstone fives for black and nothing for white." <| \() -> Expect.equal (testGame2FirstMove |> App.Model.Game.value) ((20,0,0,0,0),(0,0,0,0,0)) , test "After second move game no. 2 value must be 16 1xstone fives for black and 13 1xstones for white." <| \() -> Expect.equal (testGame2SecondMove |> App.Model.Game.value) ((16,0,0,0,0),(13,0,0,0,0)) , test "After third move game no. 2 value must be 25 1xstone and 4 2xstones fives for black and 13 1xstones for white." <| \() -> Expect.equal (testGame2ThirdMove |> App.Model.Game.value) ((23,4,0,0,0),(13,0,0,0,0)) --, test "After third move game no. 2, total game value for black must be 11." <| -- \() -> -- Expect.equal (App.Model.Game.valueFunc App.Model.Game.basic Black testGame2ThirdMove (Just { player = Black, location = (0,0)})) 9 -- location is not important --, test "After third move game no. 2, total game value for white must be -117." <| -- \() -> -- Expect.equal (App.Model.Game.valueFunc App.Model.Game.basic Black testGame2ThirdMove (Just { player = White, location = (0,0)})) -113 -- location is not important --, test "Where move CPU after third move game no. 2." <| -- \() -> -- Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGame2ThirdMove) (Just (3,3)) , test "Test Game Matrix 1" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix1) (Just (0,8)) , test "Test Game Matrix 2" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix2) (Just (1,3)) , test "Test Game Matrix 2b" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix2) (Just (1,3)) , test "Test Game Matrix 3" <| \() -> Expect.equal (App.Model.Game.cpuMove App.Model.Game.expert testGameMatrix3) (Just (2,2)) ] testCreateGame : Int -> GameBoardEx testCreateGame n = App.Model.Game.createGame n testGame1FirstMove : GameBoardEx testGame1FirstMove = testCreateGame 10 |> testMove {player = Black, location = (5,5) } testGame1SecondMove : GameBoardEx testGame1SecondMove = testGame1FirstMove |> testMove {player = White, location = (4,4) } testGame2FirstMove : GameBoardEx testGame2FirstMove = testCreateGame 9 |> testMove {player = Black, location = (4,4) } testGame2SecondMove : GameBoardEx testGame2SecondMove = testGame2FirstMove |> testMove {player = White, location = (3,4) } testGame2ThirdMove : GameBoardEx testGame2ThirdMove = testGame2SecondMove |> testMove {player = Black, location = (5,5) } {- MATRIX 1 -----------------------------------} {- 0 1 2 3 4 5 6 7 8 0 _ _ _ _ _ _ _ _ _ 1 _ _ _ _ _ _ _ x _ 2 _ _ _ _ _ _ x _ _ 3 _ _ o o x x x x o 4 _ _ _ o x o _ _ _ 5 _ _ _ o o _ _ _ _ 6 _ _ _ _ _ x _ _ _ 7 _ _ _ _ _ _ _ _ _ 8 _ _ _ _ _ _ _ _ _ -} testGameMatrix1 : GameBoardEx testGameMatrix1 = App.Model.Game.createGame 9 |> testMove { player = Black, location = (1,7) } |> testMove { player = White, location = (3,2) } |> testMove { player = Black, location = (2,6) } |> testMove { player = White, location = (3,3) } |> testMove { player = Black, location = (3,4) } |> testMove { player = White, location = (3,8) } |> testMove { player = Black, location = (3,5) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (3,6) } |> testMove { player = White, location = (4,5) } |> testMove { player = Black, location = (3,7) } |> testMove { player = White, location = (5,3) } |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (5,4) } |> testMove { player = Black, location = (6,5) } {- MATRIX 2 -----------------------------------} {- 0 1 2 3 4 5 6 7 8 0 _ _ _ _ _ _ _ _ _ 1 _ _ _ _ _ _ _ _ _ 2 _ _ _ o _ x _ _ _ 3 _ _ _ o o o x _ _ 4 _ _ _ o x _ x _ _ 5 _ _ o x _ x _ _ _ 6 _ o _ _ x _ _ _ _ 7 x _ _ _ _ _ _ _ _ 8 _ _ _ _ _ _ _ _ _ -} testGameMatrix2 : GameBoardEx testGameMatrix2 = App.Model.Game.createGame 9 |> testMove { player = Black, location = (2,5) } |> testMove { player = White, location = (2,3) } |> testMove { player = Black, location = (3,6) } |> testMove { player = White, location = (3,3) } |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (3,4) } |> testMove { player = Black, location = (4,6) } |> testMove { player = White, location = (3,5) } |> testMove { player = Black, location = (5,3) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (5,6) } |> testMove { player = White, location = (5,2) } |> testMove { player = Black, location = (6,4) } |> testMove { player = White, location = (6,1) } |> testMove { player = Black, location = (7,0) } testGameMatrix2b : GameBoardEx testGameMatrix2b = App.Model.Game.createGame 9 |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (5,5) } |> testMove { player = White, location = (3,3) } |> testMove { player = Black, location = (5,3) } |> testMove { player = White, location = (5,2) } |> testMove { player = Black, location = (6,4) } |> testMove { player = White, location = (6,1) } |> testMove { player = Black, location = (7,0) } |> testMove { player = White, location = (3,4) } |> testMove { player = Black, location = (2,5) } |> testMove { player = White, location = (3,5) } |> testMove { player = Black, location = (3,6) } |> testMove { player = White, location = (2,3) } |> testMove { player = Black, location = (4,6) } {- MATRIX 3 -----------------------------------} {- 0 1 2 3 4 5 6 7 8 0 _ _ _ _ _ _ _ _ _ 1 _ _ _ _ _ _ _ _ _ 2 _ _ _ _ _ _ _ _ _ 3 _ _ _ x o _ _ _ _ 4 _ _ _ o x _ _ _ _ 5 _ _ _ _ _ x _ _ _ 6 _ _ _ _ _ _ _ _ _ 7 _ _ _ _ _ _ _ _ _ 8 _ _ _ _ _ _ _ _ _ -} testGameMatrix3 : GameBoardEx testGameMatrix3 = App.Model.Game.createGame 9 |> testMove { player = Black, location = (4,4) } |> testMove { player = White, location = (4,3) } |> testMove { player = Black, location = (5,5) } |> testMove { player = White, location = (3,4) } |> testMove { player = Black, location = (3,3) } testMove : GameMove -> GameBoardEx -> GameBoardEx testMove move boardEx = App.Model.Game.moveFuncEx boardEx move.location
elm
[ { "context": "e ->\n \"я\"\n\n You ->\n \"ты\"\n\n She ->\n \"она\"\n\n We ->", "end": 6329, "score": 0.8216874599, "start": 6327, "tag": "NAME", "value": "ты" }, { "context": " ->\n \"ты\"\n\n She ->\n \"она\"\n\n We ->\n \"мы\"\n\n YouGrou", "end": 6363, "score": 0.9809961319, "start": 6360, "tag": "NAME", "value": "она" } ]
src/Main.elm
roSievers/ru-conjugate
0
module Main exposing (..) {-| https://en.wiktionary.org/wiki/Appendix:Russian_verbs -} import Return import Html exposing (Html, div, text, input, button, br, img) import Html.Attributes exposing (value, style, src, alt) import Html.Events exposing (onInput, onClick) import Random exposing (Generator) import Random.Extra as Random main : Program Never Model Msg main = Html.program { init = init , update = update , subscriptions = subscriptions , view = view } type alias Model = { userInput : String , word : Word , state : State } type State = Correct | Wrong | StillTyping type Msg = SetUserInput String | AppendLetter Char | DeleteLetter | SetTarget Word | GenerateTargetWord | CheckInput type Stem = Class1 String | Class4b String type Use = Me | You | She | We | YouGroup | They type alias Word = { stem : Stem , use : Use } init : ( Model, Cmd Msg ) init = ( { userInput = "" , word = defaultWord , state = StillTyping } , Random.generate SetTarget randomWord ) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of SetUserInput newText -> Return.singleton { model | userInput = newText , state = StillTyping } AppendLetter char -> { model | userInput = model.userInput ++ String.fromChar char , state = StillTyping } |> Return.singleton DeleteLetter -> { model | userInput = String.dropRight 1 model.userInput , state = StillTyping } |> Return.singleton SetTarget word -> { model | word = word , userInput = questionPhrase word , state = StillTyping } |> Return.singleton GenerateTargetWord -> ( model, Random.generate SetTarget randomWord ) CheckInput -> let newState = if model.userInput == targetPhrase model.word then Correct else Wrong in { model | state = newState } |> Return.singleton subscriptions : Model -> Sub Msg subscriptions _ = Sub.none view : Model -> Html Msg view model = div [ style [ ( "text-align", "center" ) ] ] [ textInput model , br [] [] , colorblindCorrect model , br [] [] , text (infinitive model.word) , text " " , button [ onClick CheckInput ] [ text "Prüfen" ] , button [ onClick GenerateTargetWord ] [ text "Neues Wort" ] , keyboard , br [] [ ] , img [ src "qrcode.png", alt "QR-Code for the Website" ] [] , br [] [] , text "http://rosievers.github.io/ru-conjugate/" ] colorblindCorrect : Model -> Html Msg colorblindCorrect model = case model.state of Correct -> text "Richtig" Wrong -> text "Falsch" StillTyping -> text "" textInput : Model -> Html Msg textInput model = let color = case model.state of Correct -> Just "#009900" Wrong -> Just "#990000" StillTyping -> Nothing inputStyles = [ Just ( "width", "30em" ) , Just ( "margin", "1em" ) , Maybe.map (\c -> ("color", c)) color ] |> List.filterMap identity |> style in input [ value model.userInput , onInput SetUserInput , inputStyles ] [] -- Russian keyboard keyboard : Html Msg keyboard = let row1 = div [] (List.map charButton (String.toList "йцукеёнгшщзхъ") ++ [ backspaceButton ]) row2 = div [] (List.map charButton (String.toList "фывапролджэ")) row3 = div [] (List.map charButton (String.toList "ячсмитьбю")) in div [ style [ ("margin-top", "0.5em")]] [ row1 , br [] [] , row2 , br [] [] , row3 , br [] [] , spacebar ] charButton : Char -> Html Msg charButton char = button [ onClick (AppendLetter char) ] [ text (String.fromChar char) ] backspaceButton : Html Msg backspaceButton = button [ onClick (DeleteLetter) ] [ text "бекспейс" ] spacebar : Html Msg spacebar = button [ onClick (AppendLetter ' ') , style [ ( "width", "30em" ) ] ] [ text "Пробел" ] -- Random Word Generation randomUse : Generator Use randomUse = Random.sample [ Me, You, She, We, YouGroup, They ] |> Random.map (Maybe.withDefault Me) defaultStem : Stem defaultStem = Class1 "де́ла" randomClass1 : Generator (Maybe Stem) randomClass1 = Random.sample [ "де́ла", "работа", "зна", "понима", "чита"] |> Random.map (Maybe.map Class1) randomClass4b : Generator (Maybe Stem) randomClass4b = Random.sample [ "говор" ] |> Random.map (Maybe.map Class4b) randomStem : Generator Stem randomStem = Random.choices [ randomClass1, randomClass4b ] |> Random.map (Maybe.withDefault defaultStem) randomWord : Generator Word randomWord = Random.map2 Word randomStem randomUse defaultWord : Word defaultWord = Word defaultStem Me -- Conjugation infinitive : Word -> String infinitive word = case word.stem of Class1 stem -> stem ++ "ть" Class4b stem -> stem ++ "ить" targetPhrase : Word -> String targetPhrase word = person word.use ++ " " ++ conjugate word questionPhrase : Word -> String questionPhrase word = person word.use ++ " " ++ stem word person : Use -> String person use = case use of Me -> "я" You -> "ты" She -> "она" We -> "мы" YouGroup -> "вы" They -> "они" conjugate : Word -> String conjugate word = case word.stem of Class1 stem -> conjugateClass1 stem word.use Class4b stem -> conjugateClass4b stem word.use stem : Word -> String stem word = case word.stem of Class1 stem -> stem Class4b stem -> stem conjugateClass1 : String -> Use -> String conjugateClass1 stem use = case use of Me -> stem ++ "ю" You -> stem ++ "ешь" She -> stem ++ "ет" We -> stem ++ "ем" YouGroup -> stem ++ "ете" They -> stem ++ "ют" conjugateClass4b : String -> Use -> String conjugateClass4b stem use = case use of Me -> stem ++ "ю" You -> stem ++ "ишь" She -> stem ++ "ит" We -> stem ++ "им" YouGroup -> stem ++ "ите" They -> stem ++ "ят"
3831
module Main exposing (..) {-| https://en.wiktionary.org/wiki/Appendix:Russian_verbs -} import Return import Html exposing (Html, div, text, input, button, br, img) import Html.Attributes exposing (value, style, src, alt) import Html.Events exposing (onInput, onClick) import Random exposing (Generator) import Random.Extra as Random main : Program Never Model Msg main = Html.program { init = init , update = update , subscriptions = subscriptions , view = view } type alias Model = { userInput : String , word : Word , state : State } type State = Correct | Wrong | StillTyping type Msg = SetUserInput String | AppendLetter Char | DeleteLetter | SetTarget Word | GenerateTargetWord | CheckInput type Stem = Class1 String | Class4b String type Use = Me | You | She | We | YouGroup | They type alias Word = { stem : Stem , use : Use } init : ( Model, Cmd Msg ) init = ( { userInput = "" , word = defaultWord , state = StillTyping } , Random.generate SetTarget randomWord ) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of SetUserInput newText -> Return.singleton { model | userInput = newText , state = StillTyping } AppendLetter char -> { model | userInput = model.userInput ++ String.fromChar char , state = StillTyping } |> Return.singleton DeleteLetter -> { model | userInput = String.dropRight 1 model.userInput , state = StillTyping } |> Return.singleton SetTarget word -> { model | word = word , userInput = questionPhrase word , state = StillTyping } |> Return.singleton GenerateTargetWord -> ( model, Random.generate SetTarget randomWord ) CheckInput -> let newState = if model.userInput == targetPhrase model.word then Correct else Wrong in { model | state = newState } |> Return.singleton subscriptions : Model -> Sub Msg subscriptions _ = Sub.none view : Model -> Html Msg view model = div [ style [ ( "text-align", "center" ) ] ] [ textInput model , br [] [] , colorblindCorrect model , br [] [] , text (infinitive model.word) , text " " , button [ onClick CheckInput ] [ text "Prüfen" ] , button [ onClick GenerateTargetWord ] [ text "Neues Wort" ] , keyboard , br [] [ ] , img [ src "qrcode.png", alt "QR-Code for the Website" ] [] , br [] [] , text "http://rosievers.github.io/ru-conjugate/" ] colorblindCorrect : Model -> Html Msg colorblindCorrect model = case model.state of Correct -> text "Richtig" Wrong -> text "Falsch" StillTyping -> text "" textInput : Model -> Html Msg textInput model = let color = case model.state of Correct -> Just "#009900" Wrong -> Just "#990000" StillTyping -> Nothing inputStyles = [ Just ( "width", "30em" ) , Just ( "margin", "1em" ) , Maybe.map (\c -> ("color", c)) color ] |> List.filterMap identity |> style in input [ value model.userInput , onInput SetUserInput , inputStyles ] [] -- Russian keyboard keyboard : Html Msg keyboard = let row1 = div [] (List.map charButton (String.toList "йцукеёнгшщзхъ") ++ [ backspaceButton ]) row2 = div [] (List.map charButton (String.toList "фывапролджэ")) row3 = div [] (List.map charButton (String.toList "ячсмитьбю")) in div [ style [ ("margin-top", "0.5em")]] [ row1 , br [] [] , row2 , br [] [] , row3 , br [] [] , spacebar ] charButton : Char -> Html Msg charButton char = button [ onClick (AppendLetter char) ] [ text (String.fromChar char) ] backspaceButton : Html Msg backspaceButton = button [ onClick (DeleteLetter) ] [ text "бекспейс" ] spacebar : Html Msg spacebar = button [ onClick (AppendLetter ' ') , style [ ( "width", "30em" ) ] ] [ text "Пробел" ] -- Random Word Generation randomUse : Generator Use randomUse = Random.sample [ Me, You, She, We, YouGroup, They ] |> Random.map (Maybe.withDefault Me) defaultStem : Stem defaultStem = Class1 "де́ла" randomClass1 : Generator (Maybe Stem) randomClass1 = Random.sample [ "де́ла", "работа", "зна", "понима", "чита"] |> Random.map (Maybe.map Class1) randomClass4b : Generator (Maybe Stem) randomClass4b = Random.sample [ "говор" ] |> Random.map (Maybe.map Class4b) randomStem : Generator Stem randomStem = Random.choices [ randomClass1, randomClass4b ] |> Random.map (Maybe.withDefault defaultStem) randomWord : Generator Word randomWord = Random.map2 Word randomStem randomUse defaultWord : Word defaultWord = Word defaultStem Me -- Conjugation infinitive : Word -> String infinitive word = case word.stem of Class1 stem -> stem ++ "ть" Class4b stem -> stem ++ "ить" targetPhrase : Word -> String targetPhrase word = person word.use ++ " " ++ conjugate word questionPhrase : Word -> String questionPhrase word = person word.use ++ " " ++ stem word person : Use -> String person use = case use of Me -> "я" You -> "<NAME>" She -> "<NAME>" We -> "мы" YouGroup -> "вы" They -> "они" conjugate : Word -> String conjugate word = case word.stem of Class1 stem -> conjugateClass1 stem word.use Class4b stem -> conjugateClass4b stem word.use stem : Word -> String stem word = case word.stem of Class1 stem -> stem Class4b stem -> stem conjugateClass1 : String -> Use -> String conjugateClass1 stem use = case use of Me -> stem ++ "ю" You -> stem ++ "ешь" She -> stem ++ "ет" We -> stem ++ "ем" YouGroup -> stem ++ "ете" They -> stem ++ "ют" conjugateClass4b : String -> Use -> String conjugateClass4b stem use = case use of Me -> stem ++ "ю" You -> stem ++ "ишь" She -> stem ++ "ит" We -> stem ++ "им" YouGroup -> stem ++ "ите" They -> stem ++ "ят"
true
module Main exposing (..) {-| https://en.wiktionary.org/wiki/Appendix:Russian_verbs -} import Return import Html exposing (Html, div, text, input, button, br, img) import Html.Attributes exposing (value, style, src, alt) import Html.Events exposing (onInput, onClick) import Random exposing (Generator) import Random.Extra as Random main : Program Never Model Msg main = Html.program { init = init , update = update , subscriptions = subscriptions , view = view } type alias Model = { userInput : String , word : Word , state : State } type State = Correct | Wrong | StillTyping type Msg = SetUserInput String | AppendLetter Char | DeleteLetter | SetTarget Word | GenerateTargetWord | CheckInput type Stem = Class1 String | Class4b String type Use = Me | You | She | We | YouGroup | They type alias Word = { stem : Stem , use : Use } init : ( Model, Cmd Msg ) init = ( { userInput = "" , word = defaultWord , state = StillTyping } , Random.generate SetTarget randomWord ) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of SetUserInput newText -> Return.singleton { model | userInput = newText , state = StillTyping } AppendLetter char -> { model | userInput = model.userInput ++ String.fromChar char , state = StillTyping } |> Return.singleton DeleteLetter -> { model | userInput = String.dropRight 1 model.userInput , state = StillTyping } |> Return.singleton SetTarget word -> { model | word = word , userInput = questionPhrase word , state = StillTyping } |> Return.singleton GenerateTargetWord -> ( model, Random.generate SetTarget randomWord ) CheckInput -> let newState = if model.userInput == targetPhrase model.word then Correct else Wrong in { model | state = newState } |> Return.singleton subscriptions : Model -> Sub Msg subscriptions _ = Sub.none view : Model -> Html Msg view model = div [ style [ ( "text-align", "center" ) ] ] [ textInput model , br [] [] , colorblindCorrect model , br [] [] , text (infinitive model.word) , text " " , button [ onClick CheckInput ] [ text "Prüfen" ] , button [ onClick GenerateTargetWord ] [ text "Neues Wort" ] , keyboard , br [] [ ] , img [ src "qrcode.png", alt "QR-Code for the Website" ] [] , br [] [] , text "http://rosievers.github.io/ru-conjugate/" ] colorblindCorrect : Model -> Html Msg colorblindCorrect model = case model.state of Correct -> text "Richtig" Wrong -> text "Falsch" StillTyping -> text "" textInput : Model -> Html Msg textInput model = let color = case model.state of Correct -> Just "#009900" Wrong -> Just "#990000" StillTyping -> Nothing inputStyles = [ Just ( "width", "30em" ) , Just ( "margin", "1em" ) , Maybe.map (\c -> ("color", c)) color ] |> List.filterMap identity |> style in input [ value model.userInput , onInput SetUserInput , inputStyles ] [] -- Russian keyboard keyboard : Html Msg keyboard = let row1 = div [] (List.map charButton (String.toList "йцукеёнгшщзхъ") ++ [ backspaceButton ]) row2 = div [] (List.map charButton (String.toList "фывапролджэ")) row3 = div [] (List.map charButton (String.toList "ячсмитьбю")) in div [ style [ ("margin-top", "0.5em")]] [ row1 , br [] [] , row2 , br [] [] , row3 , br [] [] , spacebar ] charButton : Char -> Html Msg charButton char = button [ onClick (AppendLetter char) ] [ text (String.fromChar char) ] backspaceButton : Html Msg backspaceButton = button [ onClick (DeleteLetter) ] [ text "бекспейс" ] spacebar : Html Msg spacebar = button [ onClick (AppendLetter ' ') , style [ ( "width", "30em" ) ] ] [ text "Пробел" ] -- Random Word Generation randomUse : Generator Use randomUse = Random.sample [ Me, You, She, We, YouGroup, They ] |> Random.map (Maybe.withDefault Me) defaultStem : Stem defaultStem = Class1 "де́ла" randomClass1 : Generator (Maybe Stem) randomClass1 = Random.sample [ "де́ла", "работа", "зна", "понима", "чита"] |> Random.map (Maybe.map Class1) randomClass4b : Generator (Maybe Stem) randomClass4b = Random.sample [ "говор" ] |> Random.map (Maybe.map Class4b) randomStem : Generator Stem randomStem = Random.choices [ randomClass1, randomClass4b ] |> Random.map (Maybe.withDefault defaultStem) randomWord : Generator Word randomWord = Random.map2 Word randomStem randomUse defaultWord : Word defaultWord = Word defaultStem Me -- Conjugation infinitive : Word -> String infinitive word = case word.stem of Class1 stem -> stem ++ "ть" Class4b stem -> stem ++ "ить" targetPhrase : Word -> String targetPhrase word = person word.use ++ " " ++ conjugate word questionPhrase : Word -> String questionPhrase word = person word.use ++ " " ++ stem word person : Use -> String person use = case use of Me -> "я" You -> "PI:NAME:<NAME>END_PI" She -> "PI:NAME:<NAME>END_PI" We -> "мы" YouGroup -> "вы" They -> "они" conjugate : Word -> String conjugate word = case word.stem of Class1 stem -> conjugateClass1 stem word.use Class4b stem -> conjugateClass4b stem word.use stem : Word -> String stem word = case word.stem of Class1 stem -> stem Class4b stem -> stem conjugateClass1 : String -> Use -> String conjugateClass1 stem use = case use of Me -> stem ++ "ю" You -> stem ++ "ешь" She -> stem ++ "ет" We -> stem ++ "ем" YouGroup -> stem ++ "ете" They -> stem ++ "ют" conjugateClass4b : String -> Use -> String conjugateClass4b stem use = case use of Me -> stem ++ "ю" You -> stem ++ "ишь" She -> stem ++ "ит" We -> stem ++ "им" YouGroup -> stem ++ "ите" They -> stem ++ "ят"
elm
[ { "context": "le = R10.Form.style.outlined\n , key = \"field1\"\n , palette = palette\n , co", "end": 1808, "score": 0.6020228863, "start": 1802, "tag": "KEY", "value": "field1" }, { "context": "tyle = R10.Form.style.filled\n , key = \"field2\"\n , palette = palette\n , co", "end": 2253, "score": 0.7277693748, "start": 2247, "tag": "KEY", "value": "field2" } ]
examples/pwa/src/Pages/Form_Example_PhoneSelector.elm
rakutentech/rakuten-ui
61
module Pages.Form_Example_PhoneSelector exposing ( Model , Msg , init , update , view ) import Element exposing (..) import R10.Form import R10.FormTypes import R10.Theme type alias Model = { phone1 : R10.Form.PhoneModel , phone2 : R10.Form.PhoneModel , disabled : Bool , messages : List String , valid : Maybe Bool } init : Model init = { phone1 = R10.Form.phoneInit , phone2 = R10.Form.phoneInit , disabled = False , messages = [] , valid = Nothing } type Msg = OnPhoneMsg1 R10.Form.PhoneMsg | OnPhoneMsg2 R10.Form.PhoneMsg update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of OnPhoneMsg1 singleMsg -> let ( selectState, selectCmd ) = R10.Form.phoneUpdate singleMsg model.phone1 in ( { model | phone1 = selectState }, Cmd.map OnPhoneMsg1 selectCmd ) OnPhoneMsg2 singleMsg -> let ( selectState, selectCmd ) = R10.Form.phoneUpdate singleMsg model.phone2 in ( { model | phone2 = selectState }, Cmd.map OnPhoneMsg2 selectCmd ) view : Model -> R10.Theme.Theme -> List (Element Msg) view model theme = let palette : R10.FormTypes.Palette palette = R10.Form.themeToPalette theme in [ row [ spacing 40, width fill, padding 40 ] [ R10.Form.phoneView [] model.phone1 { valid = model.valid , toMsg = OnPhoneMsg1 , label = "Phone number" , helperText = Nothing , disabled = model.disabled , requiredLabel = Nothing , style = R10.Form.style.outlined , key = "field1" , palette = palette , countryOptions = Nothing } , R10.Form.phoneView [] model.phone2 { valid = model.valid , toMsg = OnPhoneMsg2 , label = "Phone number" , helperText = Nothing , disabled = model.disabled , requiredLabel = Nothing , style = R10.Form.style.filled , key = "field2" , palette = palette , countryOptions = Nothing } ] ]
55199
module Pages.Form_Example_PhoneSelector exposing ( Model , Msg , init , update , view ) import Element exposing (..) import R10.Form import R10.FormTypes import R10.Theme type alias Model = { phone1 : R10.Form.PhoneModel , phone2 : R10.Form.PhoneModel , disabled : Bool , messages : List String , valid : Maybe Bool } init : Model init = { phone1 = R10.Form.phoneInit , phone2 = R10.Form.phoneInit , disabled = False , messages = [] , valid = Nothing } type Msg = OnPhoneMsg1 R10.Form.PhoneMsg | OnPhoneMsg2 R10.Form.PhoneMsg update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of OnPhoneMsg1 singleMsg -> let ( selectState, selectCmd ) = R10.Form.phoneUpdate singleMsg model.phone1 in ( { model | phone1 = selectState }, Cmd.map OnPhoneMsg1 selectCmd ) OnPhoneMsg2 singleMsg -> let ( selectState, selectCmd ) = R10.Form.phoneUpdate singleMsg model.phone2 in ( { model | phone2 = selectState }, Cmd.map OnPhoneMsg2 selectCmd ) view : Model -> R10.Theme.Theme -> List (Element Msg) view model theme = let palette : R10.FormTypes.Palette palette = R10.Form.themeToPalette theme in [ row [ spacing 40, width fill, padding 40 ] [ R10.Form.phoneView [] model.phone1 { valid = model.valid , toMsg = OnPhoneMsg1 , label = "Phone number" , helperText = Nothing , disabled = model.disabled , requiredLabel = Nothing , style = R10.Form.style.outlined , key = "<KEY>" , palette = palette , countryOptions = Nothing } , R10.Form.phoneView [] model.phone2 { valid = model.valid , toMsg = OnPhoneMsg2 , label = "Phone number" , helperText = Nothing , disabled = model.disabled , requiredLabel = Nothing , style = R10.Form.style.filled , key = "<KEY>" , palette = palette , countryOptions = Nothing } ] ]
true
module Pages.Form_Example_PhoneSelector exposing ( Model , Msg , init , update , view ) import Element exposing (..) import R10.Form import R10.FormTypes import R10.Theme type alias Model = { phone1 : R10.Form.PhoneModel , phone2 : R10.Form.PhoneModel , disabled : Bool , messages : List String , valid : Maybe Bool } init : Model init = { phone1 = R10.Form.phoneInit , phone2 = R10.Form.phoneInit , disabled = False , messages = [] , valid = Nothing } type Msg = OnPhoneMsg1 R10.Form.PhoneMsg | OnPhoneMsg2 R10.Form.PhoneMsg update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of OnPhoneMsg1 singleMsg -> let ( selectState, selectCmd ) = R10.Form.phoneUpdate singleMsg model.phone1 in ( { model | phone1 = selectState }, Cmd.map OnPhoneMsg1 selectCmd ) OnPhoneMsg2 singleMsg -> let ( selectState, selectCmd ) = R10.Form.phoneUpdate singleMsg model.phone2 in ( { model | phone2 = selectState }, Cmd.map OnPhoneMsg2 selectCmd ) view : Model -> R10.Theme.Theme -> List (Element Msg) view model theme = let palette : R10.FormTypes.Palette palette = R10.Form.themeToPalette theme in [ row [ spacing 40, width fill, padding 40 ] [ R10.Form.phoneView [] model.phone1 { valid = model.valid , toMsg = OnPhoneMsg1 , label = "Phone number" , helperText = Nothing , disabled = model.disabled , requiredLabel = Nothing , style = R10.Form.style.outlined , key = "PI:KEY:<KEY>END_PI" , palette = palette , countryOptions = Nothing } , R10.Form.phoneView [] model.phone2 { valid = model.valid , toMsg = OnPhoneMsg2 , label = "Phone number" , helperText = Nothing , disabled = model.disabled , requiredLabel = Nothing , style = R10.Form.style.filled , key = "PI:KEY:<KEY>END_PI" , palette = palette , countryOptions = Nothing } ] ]
elm
[ { "context": "sword password ->\n { model | password = password }\n\n PasswordAgain password ->\n ", "end": 1015, "score": 0.9434382915, "start": 1007, "tag": "PASSWORD", "value": "password" } ]
session1/src/Passwords.elm
kngwyu/mini-course-elm
1
module Passwords exposing (..) {- Exercises: Try to add the following features to the viewValidation helper function: * Check that the password is longer than 8 characters. * Make sure the password contains upper case, lower case, and numeric characters. Use the functions from the String module for these exercises! (https://package.elm-lang.org) -} import Browser import Html exposing (Html) import Html.Attributes as Attr import Html.Events -- MAIN main : Program () Model Msg main = Browser.sandbox { init = init, update = update, view = view } -- MODEL type alias Model = { name : String , password : String , passwordAgain : String } init : Model init = Model "" "" "" -- UPDATE type Msg = Name String | Password String | PasswordAgain String update : Msg -> Model -> Model update msg model = case msg of Name name -> { model | name = name } Password password -> { model | password = password } PasswordAgain password -> { model | passwordAgain = password } -- VIEW view : Model -> Html Msg view model = Html.div [] [ viewInput "text" "Name" model.name Name , viewInput "password" "Password" model.password Password , viewInput "password" "Re-enter Password" model.passwordAgain PasswordAgain , viewValidation model ] viewInput : String -> String -> String -> (String -> msg) -> Html msg viewInput t p v toMsg = Html.input [ Attr.type_ t, Attr.placeholder p, Attr.value v, Html.Events.onInput toMsg ] [] viewValidation : Model -> Html msg viewValidation model = if model.password == model.passwordAgain then Html.div [ Attr.style "color" "green" ] [ Html.text "OK" ] else Html.div [ Attr.style "color" "red" ] [ Html.text "Passwords do not match!" ]
39149
module Passwords exposing (..) {- Exercises: Try to add the following features to the viewValidation helper function: * Check that the password is longer than 8 characters. * Make sure the password contains upper case, lower case, and numeric characters. Use the functions from the String module for these exercises! (https://package.elm-lang.org) -} import Browser import Html exposing (Html) import Html.Attributes as Attr import Html.Events -- MAIN main : Program () Model Msg main = Browser.sandbox { init = init, update = update, view = view } -- MODEL type alias Model = { name : String , password : String , passwordAgain : String } init : Model init = Model "" "" "" -- UPDATE type Msg = Name String | Password String | PasswordAgain String update : Msg -> Model -> Model update msg model = case msg of Name name -> { model | name = name } Password password -> { model | password = <PASSWORD> } PasswordAgain password -> { model | passwordAgain = password } -- VIEW view : Model -> Html Msg view model = Html.div [] [ viewInput "text" "Name" model.name Name , viewInput "password" "Password" model.password Password , viewInput "password" "Re-enter Password" model.passwordAgain PasswordAgain , viewValidation model ] viewInput : String -> String -> String -> (String -> msg) -> Html msg viewInput t p v toMsg = Html.input [ Attr.type_ t, Attr.placeholder p, Attr.value v, Html.Events.onInput toMsg ] [] viewValidation : Model -> Html msg viewValidation model = if model.password == model.passwordAgain then Html.div [ Attr.style "color" "green" ] [ Html.text "OK" ] else Html.div [ Attr.style "color" "red" ] [ Html.text "Passwords do not match!" ]
true
module Passwords exposing (..) {- Exercises: Try to add the following features to the viewValidation helper function: * Check that the password is longer than 8 characters. * Make sure the password contains upper case, lower case, and numeric characters. Use the functions from the String module for these exercises! (https://package.elm-lang.org) -} import Browser import Html exposing (Html) import Html.Attributes as Attr import Html.Events -- MAIN main : Program () Model Msg main = Browser.sandbox { init = init, update = update, view = view } -- MODEL type alias Model = { name : String , password : String , passwordAgain : String } init : Model init = Model "" "" "" -- UPDATE type Msg = Name String | Password String | PasswordAgain String update : Msg -> Model -> Model update msg model = case msg of Name name -> { model | name = name } Password password -> { model | password = PI:PASSWORD:<PASSWORD>END_PI } PasswordAgain password -> { model | passwordAgain = password } -- VIEW view : Model -> Html Msg view model = Html.div [] [ viewInput "text" "Name" model.name Name , viewInput "password" "Password" model.password Password , viewInput "password" "Re-enter Password" model.passwordAgain PasswordAgain , viewValidation model ] viewInput : String -> String -> String -> (String -> msg) -> Html msg viewInput t p v toMsg = Html.input [ Attr.type_ t, Attr.placeholder p, Attr.value v, Html.Events.onInput toMsg ] [] viewValidation : Model -> Html msg viewValidation model = if model.password == model.passwordAgain then Html.div [ Attr.style "color" "green" ] [ Html.text "OK" ] else Html.div [ Attr.style "color" "red" ] [ Html.text "Passwords do not match!" ]
elm
[ { "context": "st Login\nfictiveLogins zone now =\n [ { user = \"Jane doe\", date = now, os = Linux, place = \"Home\" }\n , ", "end": 636, "score": 0.9996955991, "start": 628, "tag": "NAME", "value": "Jane doe" }, { "context": "now, os = Linux, place = \"Home\" }\n , { user = \"Jane doe\", date = Time.Extra.add Time.Extra.Hour -2 zone n", "end": 704, "score": 0.9997169375, "start": 696, "tag": "NAME", "value": "Jane doe" }, { "context": "now, os = Linux, place = \"Home\" }\n , { user = \"Jane doe\", date = Time.Extra.add Time.Extra.Week -2 zone n", "end": 811, "score": 0.999745369, "start": 803, "tag": "NAME", "value": "Jane doe" }, { "context": "now, os = Linux, place = \"Home\" }\n , { user = \"Jane doe\", date = Time.Extra.add Time.Extra.Day -2 zone no", "end": 918, "score": 0.9997153878, "start": 910, "tag": "NAME", "value": "Jane doe" }, { "context": "w, os = Linux, place = \"Office\" }\n , { user = \"Jane doe\"\n , date = Time.Extra.add Time.Extra.Hour -3", "end": 1026, "score": 0.9996033907, "start": 1018, "tag": "NAME", "value": "Jane doe" }, { "context": "\n , place = \"Office\"\n }\n , { user = \"Jon doe\", date = Time.Extra.add Time.Extra.Hour 3 zone <|", "end": 1202, "score": 0.9995372295, "start": 1195, "tag": "NAME", "value": "Jon doe" }, { "context": "w, os = Linux, place = \"Office\" }\n , { user = \"Jon doe\", date = Time.Extra.add Time.Extra.Hour 3 zone <|", "end": 1350, "score": 0.9996094704, "start": 1343, "tag": "NAME", "value": "Jon doe" }, { "context": "os = Linux, place = \"Commuting\" }\n , { user = \"Jon doe\", date = Time.Extra.add Time.Extra.Hour 3 zone <|", "end": 1501, "score": 0.9994578958, "start": 1494, "tag": "NAME", "value": "Jon doe" }, { "context": "os = Linux, place = \"Commuting\" }\n , { user = \"Jon doe\", date = Time.Extra.add Time.Extra.Hour 3 zone <|", "end": 1652, "score": 0.9562897086, "start": 1645, "tag": "NAME", "value": "Jon doe" }, { "context": "now, os = Linux, place = \"Home\" }\n , { user = \"Jon doe\", date = Time.Extra.add Time.Extra.Hour 3 zone <|", "end": 1798, "score": 0.9812138081, "start": 1791, "tag": "NAME", "value": "Jon doe" } ]
example/src/Main.elm
leojpod/elm-apex-charts-link
3
port module Main exposing (main) import Apex import Browser import Charts.Bar as Bar import Charts.Plot as Plot import Charts.RoundChart as RoundChart import FakeData import Html exposing (Html, div, h1, text) import Html.Attributes exposing (class, id) import Json.Encode import List.Extra import Platform exposing (Program) import Task import Time import Time.Extra type alias Login = { user : String , date : Time.Posix , os : OS , place : String } type OS = Linux | MacOS | BSD | Other fictiveLogins : Time.Zone -> Time.Posix -> List Login fictiveLogins zone now = [ { user = "Jane doe", date = now, os = Linux, place = "Home" } , { user = "Jane doe", date = Time.Extra.add Time.Extra.Hour -2 zone now, os = Linux, place = "Home" } , { user = "Jane doe", date = Time.Extra.add Time.Extra.Week -2 zone now, os = Linux, place = "Home" } , { user = "Jane doe", date = Time.Extra.add Time.Extra.Day -2 zone now, os = Linux, place = "Office" } , { user = "Jane doe" , date = Time.Extra.add Time.Extra.Hour -3 zone <| Time.Extra.add Time.Extra.Day -6 zone now , os = Linux , place = "Office" } , { user = "Jon doe", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -3 zone now, os = Linux, place = "Office" } , { user = "Jon doe", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -2 zone now, os = Linux, place = "Commuting" } , { user = "Jon doe", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -9 zone now, os = Linux, place = "Commuting" } , { user = "Jon doe", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -9 zone now, os = Linux, place = "Home" } , { user = "Jon doe", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -3 zone now, os = Linux, place = "Home" } ] type alias Model = { logins : List Login , yearlyUsage : List FakeData.Usage , stateReport : FakeData.StateReport } type Msg = LoadFakeLogins Time.Posix | UpdateNow Time.Posix | LoadYearlyUsage (List FakeData.Usage) | LoadStateReport FakeData.StateReport main : Program () Model Msg main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions } init : () -> ( Model, Cmd Msg ) init () = ( { logins = [] , yearlyUsage = [] , stateReport = FakeData.StateReport 0 0 0 } , Cmd.batch [ Time.now |> Task.perform LoadFakeLogins , Time.now |> Task.perform UpdateNow , FakeData.fakeStateReport LoadStateReport ] ) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of LoadFakeLogins now -> let logins = fictiveLogins Time.utc now in ( { model | logins = logins } , Cmd.none ) UpdateNow now -> ( model, FakeData.fakeYearlyUsage Time.utc now LoadYearlyUsage ) LoadYearlyUsage usages -> ( { model | yearlyUsage = usages } , updateChart <| Apex.encodeChart <| (Plot.plot |> Plot.addColumnSeries "Time used" (usagesByMonth usages) |> Plot.withXAxisType Plot.DateTime |> Apex.fromPlotChart |> Apex.withColors [ "#5C4742" ] ) ) LoadStateReport stateReport -> ( { model | stateReport = stateReport }, Cmd.none ) connectionsByWeek : List Login -> List Plot.Point connectionsByWeek = List.Extra.gatherEqualsBy (.date >> Time.Extra.floor Time.Extra.Week Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.Extra.floor Time.Extra.Week Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.length |> toFloat } ) >> List.sortBy .x usagesByMonth : List FakeData.Usage -> List Plot.Point usagesByMonth = List.Extra.gatherEqualsBy (Time.Extra.floor Time.Extra.Month Time.utc) >> List.map (\( head, list ) -> { x = head |> Time.Extra.floor Time.Extra.Month Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.length |> toFloat } ) >> List.sortBy .x dayTimeConnectionByWeek : List Login -> List Plot.Point dayTimeConnectionByWeek = List.Extra.gatherEqualsBy (.date >> Time.Extra.floor Time.Extra.Week Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.Extra.floor Time.Extra.Week Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.filter (.date >> Time.toHour Time.utc >> (\h -> h >= 8 && h < 18)) |> List.length |> toFloat } ) >> List.sortBy .x outsideOfficeHourConnectionByWeek : List Login -> List Plot.Point outsideOfficeHourConnectionByWeek = List.Extra.gatherEqualsBy (.date >> Time.Extra.floor Time.Extra.Week Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.Extra.floor Time.Extra.Week Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.filter (.date >> Time.toHour Time.utc >> (\h -> h < 8 && h >= 18)) |> List.length |> toFloat } ) >> List.sortBy .x connectionsByHourOfTheDay : List Login -> List Plot.Point connectionsByHourOfTheDay = List.Extra.gatherEqualsBy (.date >> Time.toHour Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.toHour Time.utc |> toFloat , y = (head :: list) |> List.length |> toFloat } ) >> List.sortBy .x subscriptions : Model -> Sub Msg subscriptions _ = Sub.none port updateChart : Json.Encode.Value -> Cmd msg view : Model -> Html Msg view { logins, stateReport } = let defaultChart = Plot.plot |> Plot.addLineSeries "Connections by week" (connectionsByWeek logins) |> Plot.addColumnSeries "Connections within office hour for that week" (dayTimeConnectionByWeek logins) |> Plot.addColumnSeries "Connections outside office hour for that week" (outsideOfficeHourConnectionByWeek logins) |> Plot.withXAxisType Plot.DateTime |> Apex.fromPlotChart |> Apex.withColors [ "#ff2E9B", "#3f51b5", "#7700D0" ] in div [ class "min-h-screen bg-gray-100" ] [ div [ class "max-w-3xl p-1 p-12 mx-auto bg-white shadow-2xl rounded-xl grid grid-cols-1 gap-4 md:grid-cols-3" ] [ div [ id "chart1", class "col-span-1 md:col-span-3" ] [ div [] [] ] , Apex.apexChart [ class "col-span-1 md:col-span-2" ] (RoundChart.pieChart "State" [ ( "working", stateReport.working |> toFloat ) , ( "meeh", stateReport.meeh |> toFloat ) , ( "not working", stateReport.notWorking |> toFloat ) ] |> Apex.fromRoundChart |> Apex.withColors [ "#1B998B", "#E2C044", "#D7263D" ] ) , div [ class "flex flex-col items-center" ] [ div [ class "flex flex-col items-center justify-center w-56 h-56 bg-red-400 rounded-full" ] [ h1 [ class "text-xl font-bold text-white" ] [ text "56 " ] , h1 [ class "font-bold text-gray-50 text-l" ] [ text "incidents" ] ] , Apex.apexChart [ class "col-span-1" ] (RoundChart.radialBar "Time boooked" [ ( "room 1", 80 ) ] |> RoundChart.withCustomAngles -90 90 |> Apex.fromRoundChart |> Apex.withColors [ "#A300D6" ] ) ] , Apex.apexChart [ class "col-span-1" ] (Bar.bar |> Bar.addSeries "day time" [ ( "abc", 10 ), ( "def", 30 ), ( "ghi", 2 ), ( "jkl", 12 ) ] |> Bar.addSeries "night time" [ ( "abc", 1 ), ( "def", 2.5 ), ( "ghi", 20 ), ( "jkl", 22 ) ] |> Bar.isHorizontal |> Bar.isStacked |> Apex.fromBarChart |> Apex.withColors [ "#00B1F2", "#546E7A", "#F86624", "#E2C044" ] ) , Apex.apexChart [ class "col-span-2" ] defaultChart ] ]
13433
port module Main exposing (main) import Apex import Browser import Charts.Bar as Bar import Charts.Plot as Plot import Charts.RoundChart as RoundChart import FakeData import Html exposing (Html, div, h1, text) import Html.Attributes exposing (class, id) import Json.Encode import List.Extra import Platform exposing (Program) import Task import Time import Time.Extra type alias Login = { user : String , date : Time.Posix , os : OS , place : String } type OS = Linux | MacOS | BSD | Other fictiveLogins : Time.Zone -> Time.Posix -> List Login fictiveLogins zone now = [ { user = "<NAME>", date = now, os = Linux, place = "Home" } , { user = "<NAME>", date = Time.Extra.add Time.Extra.Hour -2 zone now, os = Linux, place = "Home" } , { user = "<NAME>", date = Time.Extra.add Time.Extra.Week -2 zone now, os = Linux, place = "Home" } , { user = "<NAME>", date = Time.Extra.add Time.Extra.Day -2 zone now, os = Linux, place = "Office" } , { user = "<NAME>" , date = Time.Extra.add Time.Extra.Hour -3 zone <| Time.Extra.add Time.Extra.Day -6 zone now , os = Linux , place = "Office" } , { user = "<NAME>", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -3 zone now, os = Linux, place = "Office" } , { user = "<NAME>", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -2 zone now, os = Linux, place = "Commuting" } , { user = "<NAME>", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -9 zone now, os = Linux, place = "Commuting" } , { user = "<NAME>", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -9 zone now, os = Linux, place = "Home" } , { user = "<NAME>", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -3 zone now, os = Linux, place = "Home" } ] type alias Model = { logins : List Login , yearlyUsage : List FakeData.Usage , stateReport : FakeData.StateReport } type Msg = LoadFakeLogins Time.Posix | UpdateNow Time.Posix | LoadYearlyUsage (List FakeData.Usage) | LoadStateReport FakeData.StateReport main : Program () Model Msg main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions } init : () -> ( Model, Cmd Msg ) init () = ( { logins = [] , yearlyUsage = [] , stateReport = FakeData.StateReport 0 0 0 } , Cmd.batch [ Time.now |> Task.perform LoadFakeLogins , Time.now |> Task.perform UpdateNow , FakeData.fakeStateReport LoadStateReport ] ) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of LoadFakeLogins now -> let logins = fictiveLogins Time.utc now in ( { model | logins = logins } , Cmd.none ) UpdateNow now -> ( model, FakeData.fakeYearlyUsage Time.utc now LoadYearlyUsage ) LoadYearlyUsage usages -> ( { model | yearlyUsage = usages } , updateChart <| Apex.encodeChart <| (Plot.plot |> Plot.addColumnSeries "Time used" (usagesByMonth usages) |> Plot.withXAxisType Plot.DateTime |> Apex.fromPlotChart |> Apex.withColors [ "#5C4742" ] ) ) LoadStateReport stateReport -> ( { model | stateReport = stateReport }, Cmd.none ) connectionsByWeek : List Login -> List Plot.Point connectionsByWeek = List.Extra.gatherEqualsBy (.date >> Time.Extra.floor Time.Extra.Week Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.Extra.floor Time.Extra.Week Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.length |> toFloat } ) >> List.sortBy .x usagesByMonth : List FakeData.Usage -> List Plot.Point usagesByMonth = List.Extra.gatherEqualsBy (Time.Extra.floor Time.Extra.Month Time.utc) >> List.map (\( head, list ) -> { x = head |> Time.Extra.floor Time.Extra.Month Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.length |> toFloat } ) >> List.sortBy .x dayTimeConnectionByWeek : List Login -> List Plot.Point dayTimeConnectionByWeek = List.Extra.gatherEqualsBy (.date >> Time.Extra.floor Time.Extra.Week Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.Extra.floor Time.Extra.Week Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.filter (.date >> Time.toHour Time.utc >> (\h -> h >= 8 && h < 18)) |> List.length |> toFloat } ) >> List.sortBy .x outsideOfficeHourConnectionByWeek : List Login -> List Plot.Point outsideOfficeHourConnectionByWeek = List.Extra.gatherEqualsBy (.date >> Time.Extra.floor Time.Extra.Week Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.Extra.floor Time.Extra.Week Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.filter (.date >> Time.toHour Time.utc >> (\h -> h < 8 && h >= 18)) |> List.length |> toFloat } ) >> List.sortBy .x connectionsByHourOfTheDay : List Login -> List Plot.Point connectionsByHourOfTheDay = List.Extra.gatherEqualsBy (.date >> Time.toHour Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.toHour Time.utc |> toFloat , y = (head :: list) |> List.length |> toFloat } ) >> List.sortBy .x subscriptions : Model -> Sub Msg subscriptions _ = Sub.none port updateChart : Json.Encode.Value -> Cmd msg view : Model -> Html Msg view { logins, stateReport } = let defaultChart = Plot.plot |> Plot.addLineSeries "Connections by week" (connectionsByWeek logins) |> Plot.addColumnSeries "Connections within office hour for that week" (dayTimeConnectionByWeek logins) |> Plot.addColumnSeries "Connections outside office hour for that week" (outsideOfficeHourConnectionByWeek logins) |> Plot.withXAxisType Plot.DateTime |> Apex.fromPlotChart |> Apex.withColors [ "#ff2E9B", "#3f51b5", "#7700D0" ] in div [ class "min-h-screen bg-gray-100" ] [ div [ class "max-w-3xl p-1 p-12 mx-auto bg-white shadow-2xl rounded-xl grid grid-cols-1 gap-4 md:grid-cols-3" ] [ div [ id "chart1", class "col-span-1 md:col-span-3" ] [ div [] [] ] , Apex.apexChart [ class "col-span-1 md:col-span-2" ] (RoundChart.pieChart "State" [ ( "working", stateReport.working |> toFloat ) , ( "meeh", stateReport.meeh |> toFloat ) , ( "not working", stateReport.notWorking |> toFloat ) ] |> Apex.fromRoundChart |> Apex.withColors [ "#1B998B", "#E2C044", "#D7263D" ] ) , div [ class "flex flex-col items-center" ] [ div [ class "flex flex-col items-center justify-center w-56 h-56 bg-red-400 rounded-full" ] [ h1 [ class "text-xl font-bold text-white" ] [ text "56 " ] , h1 [ class "font-bold text-gray-50 text-l" ] [ text "incidents" ] ] , Apex.apexChart [ class "col-span-1" ] (RoundChart.radialBar "Time boooked" [ ( "room 1", 80 ) ] |> RoundChart.withCustomAngles -90 90 |> Apex.fromRoundChart |> Apex.withColors [ "#A300D6" ] ) ] , Apex.apexChart [ class "col-span-1" ] (Bar.bar |> Bar.addSeries "day time" [ ( "abc", 10 ), ( "def", 30 ), ( "ghi", 2 ), ( "jkl", 12 ) ] |> Bar.addSeries "night time" [ ( "abc", 1 ), ( "def", 2.5 ), ( "ghi", 20 ), ( "jkl", 22 ) ] |> Bar.isHorizontal |> Bar.isStacked |> Apex.fromBarChart |> Apex.withColors [ "#00B1F2", "#546E7A", "#F86624", "#E2C044" ] ) , Apex.apexChart [ class "col-span-2" ] defaultChart ] ]
true
port module Main exposing (main) import Apex import Browser import Charts.Bar as Bar import Charts.Plot as Plot import Charts.RoundChart as RoundChart import FakeData import Html exposing (Html, div, h1, text) import Html.Attributes exposing (class, id) import Json.Encode import List.Extra import Platform exposing (Program) import Task import Time import Time.Extra type alias Login = { user : String , date : Time.Posix , os : OS , place : String } type OS = Linux | MacOS | BSD | Other fictiveLogins : Time.Zone -> Time.Posix -> List Login fictiveLogins zone now = [ { user = "PI:NAME:<NAME>END_PI", date = now, os = Linux, place = "Home" } , { user = "PI:NAME:<NAME>END_PI", date = Time.Extra.add Time.Extra.Hour -2 zone now, os = Linux, place = "Home" } , { user = "PI:NAME:<NAME>END_PI", date = Time.Extra.add Time.Extra.Week -2 zone now, os = Linux, place = "Home" } , { user = "PI:NAME:<NAME>END_PI", date = Time.Extra.add Time.Extra.Day -2 zone now, os = Linux, place = "Office" } , { user = "PI:NAME:<NAME>END_PI" , date = Time.Extra.add Time.Extra.Hour -3 zone <| Time.Extra.add Time.Extra.Day -6 zone now , os = Linux , place = "Office" } , { user = "PI:NAME:<NAME>END_PI", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -3 zone now, os = Linux, place = "Office" } , { user = "PI:NAME:<NAME>END_PI", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -2 zone now, os = Linux, place = "Commuting" } , { user = "PI:NAME:<NAME>END_PI", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -9 zone now, os = Linux, place = "Commuting" } , { user = "PI:NAME:<NAME>END_PI", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -9 zone now, os = Linux, place = "Home" } , { user = "PI:NAME:<NAME>END_PI", date = Time.Extra.add Time.Extra.Hour 3 zone <| Time.Extra.add Time.Extra.Day -3 zone now, os = Linux, place = "Home" } ] type alias Model = { logins : List Login , yearlyUsage : List FakeData.Usage , stateReport : FakeData.StateReport } type Msg = LoadFakeLogins Time.Posix | UpdateNow Time.Posix | LoadYearlyUsage (List FakeData.Usage) | LoadStateReport FakeData.StateReport main : Program () Model Msg main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions } init : () -> ( Model, Cmd Msg ) init () = ( { logins = [] , yearlyUsage = [] , stateReport = FakeData.StateReport 0 0 0 } , Cmd.batch [ Time.now |> Task.perform LoadFakeLogins , Time.now |> Task.perform UpdateNow , FakeData.fakeStateReport LoadStateReport ] ) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of LoadFakeLogins now -> let logins = fictiveLogins Time.utc now in ( { model | logins = logins } , Cmd.none ) UpdateNow now -> ( model, FakeData.fakeYearlyUsage Time.utc now LoadYearlyUsage ) LoadYearlyUsage usages -> ( { model | yearlyUsage = usages } , updateChart <| Apex.encodeChart <| (Plot.plot |> Plot.addColumnSeries "Time used" (usagesByMonth usages) |> Plot.withXAxisType Plot.DateTime |> Apex.fromPlotChart |> Apex.withColors [ "#5C4742" ] ) ) LoadStateReport stateReport -> ( { model | stateReport = stateReport }, Cmd.none ) connectionsByWeek : List Login -> List Plot.Point connectionsByWeek = List.Extra.gatherEqualsBy (.date >> Time.Extra.floor Time.Extra.Week Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.Extra.floor Time.Extra.Week Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.length |> toFloat } ) >> List.sortBy .x usagesByMonth : List FakeData.Usage -> List Plot.Point usagesByMonth = List.Extra.gatherEqualsBy (Time.Extra.floor Time.Extra.Month Time.utc) >> List.map (\( head, list ) -> { x = head |> Time.Extra.floor Time.Extra.Month Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.length |> toFloat } ) >> List.sortBy .x dayTimeConnectionByWeek : List Login -> List Plot.Point dayTimeConnectionByWeek = List.Extra.gatherEqualsBy (.date >> Time.Extra.floor Time.Extra.Week Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.Extra.floor Time.Extra.Week Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.filter (.date >> Time.toHour Time.utc >> (\h -> h >= 8 && h < 18)) |> List.length |> toFloat } ) >> List.sortBy .x outsideOfficeHourConnectionByWeek : List Login -> List Plot.Point outsideOfficeHourConnectionByWeek = List.Extra.gatherEqualsBy (.date >> Time.Extra.floor Time.Extra.Week Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.Extra.floor Time.Extra.Week Time.utc |> Time.posixToMillis |> toFloat , y = (head :: list) |> List.filter (.date >> Time.toHour Time.utc >> (\h -> h < 8 && h >= 18)) |> List.length |> toFloat } ) >> List.sortBy .x connectionsByHourOfTheDay : List Login -> List Plot.Point connectionsByHourOfTheDay = List.Extra.gatherEqualsBy (.date >> Time.toHour Time.utc) >> List.map (\( head, list ) -> { x = head.date |> Time.toHour Time.utc |> toFloat , y = (head :: list) |> List.length |> toFloat } ) >> List.sortBy .x subscriptions : Model -> Sub Msg subscriptions _ = Sub.none port updateChart : Json.Encode.Value -> Cmd msg view : Model -> Html Msg view { logins, stateReport } = let defaultChart = Plot.plot |> Plot.addLineSeries "Connections by week" (connectionsByWeek logins) |> Plot.addColumnSeries "Connections within office hour for that week" (dayTimeConnectionByWeek logins) |> Plot.addColumnSeries "Connections outside office hour for that week" (outsideOfficeHourConnectionByWeek logins) |> Plot.withXAxisType Plot.DateTime |> Apex.fromPlotChart |> Apex.withColors [ "#ff2E9B", "#3f51b5", "#7700D0" ] in div [ class "min-h-screen bg-gray-100" ] [ div [ class "max-w-3xl p-1 p-12 mx-auto bg-white shadow-2xl rounded-xl grid grid-cols-1 gap-4 md:grid-cols-3" ] [ div [ id "chart1", class "col-span-1 md:col-span-3" ] [ div [] [] ] , Apex.apexChart [ class "col-span-1 md:col-span-2" ] (RoundChart.pieChart "State" [ ( "working", stateReport.working |> toFloat ) , ( "meeh", stateReport.meeh |> toFloat ) , ( "not working", stateReport.notWorking |> toFloat ) ] |> Apex.fromRoundChart |> Apex.withColors [ "#1B998B", "#E2C044", "#D7263D" ] ) , div [ class "flex flex-col items-center" ] [ div [ class "flex flex-col items-center justify-center w-56 h-56 bg-red-400 rounded-full" ] [ h1 [ class "text-xl font-bold text-white" ] [ text "56 " ] , h1 [ class "font-bold text-gray-50 text-l" ] [ text "incidents" ] ] , Apex.apexChart [ class "col-span-1" ] (RoundChart.radialBar "Time boooked" [ ( "room 1", 80 ) ] |> RoundChart.withCustomAngles -90 90 |> Apex.fromRoundChart |> Apex.withColors [ "#A300D6" ] ) ] , Apex.apexChart [ class "col-span-1" ] (Bar.bar |> Bar.addSeries "day time" [ ( "abc", 10 ), ( "def", 30 ), ( "ghi", 2 ), ( "jkl", 12 ) ] |> Bar.addSeries "night time" [ ( "abc", 1 ), ( "def", 2.5 ), ( "ghi", 20 ), ( "jkl", 22 ) ] |> Bar.isHorizontal |> Bar.isStacked |> Apex.fromBarChart |> Apex.withColors [ "#00B1F2", "#546E7A", "#F86624", "#E2C044" ] ) , Apex.apexChart [ class "col-span-2" ] defaultChart ] ]
elm
[ { "context": "l\n [ correctColor \"green\" \"Gabi\"\n , correctColor \"blue\" \"A", "end": 699, "score": 0.9995826483, "start": 695, "tag": "NAME", "value": "Gabi" }, { "context": "i\"\n , correctColor \"blue\" \"Andrew\"\n , correctColor \"red\" \"Ka", "end": 754, "score": 0.9992794991, "start": 748, "tag": "NAME", "value": "Andrew" }, { "context": "ew\"\n , correctColor \"red\" \"Katerina\"\n , correctColor \"green\" \"", "end": 810, "score": 0.9996387959, "start": 802, "tag": "NAME", "value": "Katerina" }, { "context": "\"\n , correctColor \"green\" \"Laurent\"\n ]\n ", "end": 867, "score": 0.9996711612, "start": 860, "tag": "NAME", "value": "Laurent" }, { "context": " Expect.equal \"blue\" (getAuthorColor colors \"Andrew\")\n , test \"it returns an empty string ", "end": 1254, "score": 0.9948377609, "start": 1248, "tag": "NAME", "value": "Andrew" }, { "context": "\n\nauthors : List Author\nauthors =\n [ { name = \"Gabi\", posts = [] }\n , { name = \"Andrew\", posts = [", "end": 1623, "score": 0.9997701645, "start": 1619, "tag": "NAME", "value": "Gabi" }, { "context": " [ { name = \"Gabi\", posts = [] }\n , { name = \"Andrew\", posts = [] }\n , { name = \"Katerina\", posts =", "end": 1661, "score": 0.9995913506, "start": 1655, "tag": "NAME", "value": "Andrew" }, { "context": ", { name = \"Andrew\", posts = [] }\n , { name = \"Katerina\", posts = [] }\n , { name = \"Laurent\", posts = ", "end": 1701, "score": 0.9997601509, "start": 1693, "tag": "NAME", "value": "Katerina" }, { "context": "{ name = \"Katerina\", posts = [] }\n , { name = \"Laurent\", posts = [] }\n ]\n", "end": 1740, "score": 0.9996070266, "start": 1733, "tag": "NAME", "value": "Laurent" } ]
frontend/tests/ViewTests/ColorsTest.elm
Gabbendorf/spindle
1
module ViewTests.ColorsTest exposing (..) import Data.Author exposing (Author) import Dict exposing (Dict) import Expect import Test exposing (..) import View exposing (..) suite : Test suite = describe "colors functions" [ describe "authorColors" [ test "it assigns colors in order" <| \_ -> let colors = authorColors authors correctColor expectedColor name colors = Expect.equal (Dict.get name colors) (Just expectedColor) in Expect.all [ correctColor "green" "Gabi" , correctColor "blue" "Andrew" , correctColor "red" "Katerina" , correctColor "green" "Laurent" ] colors ] , describe "getAuthorColor" [ test "it gets correct color for author" <| \_ -> let colors = authorColors authors in Expect.equal "blue" (getAuthorColor colors "Andrew") , test "it returns an empty string for unknown author" <| \_ -> let colors = authorColors authors in Expect.equal "" (getAuthorColor colors "wut?") ] ] authors : List Author authors = [ { name = "Gabi", posts = [] } , { name = "Andrew", posts = [] } , { name = "Katerina", posts = [] } , { name = "Laurent", posts = [] } ]
33429
module ViewTests.ColorsTest exposing (..) import Data.Author exposing (Author) import Dict exposing (Dict) import Expect import Test exposing (..) import View exposing (..) suite : Test suite = describe "colors functions" [ describe "authorColors" [ test "it assigns colors in order" <| \_ -> let colors = authorColors authors correctColor expectedColor name colors = Expect.equal (Dict.get name colors) (Just expectedColor) in Expect.all [ correctColor "green" "<NAME>" , correctColor "blue" "<NAME>" , correctColor "red" "<NAME>" , correctColor "green" "<NAME>" ] colors ] , describe "getAuthorColor" [ test "it gets correct color for author" <| \_ -> let colors = authorColors authors in Expect.equal "blue" (getAuthorColor colors "<NAME>") , test "it returns an empty string for unknown author" <| \_ -> let colors = authorColors authors in Expect.equal "" (getAuthorColor colors "wut?") ] ] authors : List Author authors = [ { name = "<NAME>", posts = [] } , { name = "<NAME>", posts = [] } , { name = "<NAME>", posts = [] } , { name = "<NAME>", posts = [] } ]
true
module ViewTests.ColorsTest exposing (..) import Data.Author exposing (Author) import Dict exposing (Dict) import Expect import Test exposing (..) import View exposing (..) suite : Test suite = describe "colors functions" [ describe "authorColors" [ test "it assigns colors in order" <| \_ -> let colors = authorColors authors correctColor expectedColor name colors = Expect.equal (Dict.get name colors) (Just expectedColor) in Expect.all [ correctColor "green" "PI:NAME:<NAME>END_PI" , correctColor "blue" "PI:NAME:<NAME>END_PI" , correctColor "red" "PI:NAME:<NAME>END_PI" , correctColor "green" "PI:NAME:<NAME>END_PI" ] colors ] , describe "getAuthorColor" [ test "it gets correct color for author" <| \_ -> let colors = authorColors authors in Expect.equal "blue" (getAuthorColor colors "PI:NAME:<NAME>END_PI") , test "it returns an empty string for unknown author" <| \_ -> let colors = authorColors authors in Expect.equal "" (getAuthorColor colors "wut?") ] ] authors : List Author authors = [ { name = "PI:NAME:<NAME>END_PI", posts = [] } , { name = "PI:NAME:<NAME>END_PI", posts = [] } , { name = "PI:NAME:<NAME>END_PI", posts = [] } , { name = "PI:NAME:<NAME>END_PI", posts = [] } ]
elm
[ { "context": " String.join \" \" middleNamesList\n in \n lastName ++ \", \" ++ firstName ++ \" \" ++ middleNames\n\ngetC", "end": 4093, "score": 0.9492840767, "start": 4085, "tag": "NAME", "value": "lastName" }, { "context": "iddleNamesList\n in \n lastName ++ \", \" ++ firstName ++ \" \" ++ middleNames\n\ngetCompleteExcerciseWeigh", "end": 4114, "score": 0.9934387803, "start": 4105, "tag": "NAME", "value": "firstName" } ]
Elm/src/DataProcessing.elm
maxhenze/exam-information-visualization
0
module DataProcessing exposing (..) import Csv.Decode import List.Extra import Maybe.Extra import Debug exposing (toString) import Dict import Dict.Extra as DiEx import Json.Encode as JsEn import Html exposing (Html) import TreeDiagram.Svg as TrSv import TreeDiagram exposing (defaultTreeLayout) import Json.Decode as JsDe import Color import TypedSvg.Core as TyCo import TypedSvg import TypedSvg.Attributes.InPx as TyAtIn import TypedSvg.Attributes as TyAt import TypedSvg.Types exposing (AnchorAlignment(..), CoordinateSystem(..), Length(..), Opacity(..), Paint(..), Transform(..), px) import Model as MO -- ein Decoder, welcher an die Elemente des Records und die CSV-Spalten-Namen angepasst ist openPowerliftingDataDecoder : Csv.Decode.Decoder MO.OpenPowerliftingData openPowerliftingDataDecoder = Csv.Decode.into MO.OpenPowerliftingData |> Csv.Decode.pipeline (Csv.Decode.field "Name" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "Sex" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "Squat1Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Squat2Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Squat3Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Bench1Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Bench2Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Bench3Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Deadlift1Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Deadlift2Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Deadlift3Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Federation" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "Date" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "MeetCountry" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "MeetName" Csv.Decode.string) csvString_to_openPowerliftingData : String -> List MO.OpenPowerliftingData csvString_to_openPowerliftingData csvRaw = let result = Csv.Decode.decodeCsv Csv.Decode.FieldNamesFromFirstRow openPowerliftingDataDecoder csvRaw in case result of Ok value -> value Err error -> [] csvString_to_openPowerliftingDataVisA : String -> List MO.OpenPowerliftingData csvString_to_openPowerliftingDataVisA csvRaw = let result = Csv.Decode.decodeCsv Csv.Decode.FieldNamesFromFirstRow openPowerliftingDataDecoder csvRaw in case result of Ok value -> List.filter (\x -> discipline_filter x) value Err error -> [] discipline_filter : MO.OpenPowerliftingData -> Bool discipline_filter dataEntry = if dataEntry.squat1Kg == Nothing || dataEntry.squat2Kg == Nothing || dataEntry.squat3Kg == Nothing || dataEntry.bench1Kg == Nothing || dataEntry.bench2Kg == Nothing || dataEntry.bench3Kg == Nothing || dataEntry.dead1Kg == Nothing || dataEntry.dead2Kg == Nothing || dataEntry.dead3Kg == Nothing then False else True bringNamesIntoRightOrder : String -> String bringNamesIntoRightOrder name = let splittedName = String.split " " name firstName = Maybe.withDefault "" <| List.head <| splittedName lastName = Maybe.withDefault "" <| List.head <| List.reverse splittedName middleNamesList = Maybe.withDefault [] <| List.tail <| List.reverse <| Maybe.withDefault [] <| List.tail splittedName middleNames = String.join " " middleNamesList in lastName ++ ", " ++ firstName ++ " " ++ middleNames getCompleteExcerciseWeightsList : List MO.OpenPowerliftingData -> List Float getCompleteExcerciseWeightsList dataList = let squatOneList = List.filterMap .squat1Kg dataList benchOneList = List.filterMap .bench1Kg dataList deadOneList = List.filterMap .dead1Kg dataList squatTwoList = List.filterMap .squat2Kg dataList benchTwoList = List.filterMap .bench2Kg dataList deadTwoList = List.filterMap .dead2Kg dataList squatThreeList = List.filterMap .squat3Kg dataList benchThreeList = List.filterMap .bench3Kg dataList deadThreeList = List.filterMap .dead3Kg dataList in squatOneList ++ squatTwoList ++ squatThreeList ++ benchOneList ++ benchTwoList ++ benchThreeList ++ deadOneList ++ deadTwoList ++ deadThreeList
33459
module DataProcessing exposing (..) import Csv.Decode import List.Extra import Maybe.Extra import Debug exposing (toString) import Dict import Dict.Extra as DiEx import Json.Encode as JsEn import Html exposing (Html) import TreeDiagram.Svg as TrSv import TreeDiagram exposing (defaultTreeLayout) import Json.Decode as JsDe import Color import TypedSvg.Core as TyCo import TypedSvg import TypedSvg.Attributes.InPx as TyAtIn import TypedSvg.Attributes as TyAt import TypedSvg.Types exposing (AnchorAlignment(..), CoordinateSystem(..), Length(..), Opacity(..), Paint(..), Transform(..), px) import Model as MO -- ein Decoder, welcher an die Elemente des Records und die CSV-Spalten-Namen angepasst ist openPowerliftingDataDecoder : Csv.Decode.Decoder MO.OpenPowerliftingData openPowerliftingDataDecoder = Csv.Decode.into MO.OpenPowerliftingData |> Csv.Decode.pipeline (Csv.Decode.field "Name" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "Sex" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "Squat1Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Squat2Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Squat3Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Bench1Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Bench2Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Bench3Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Deadlift1Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Deadlift2Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Deadlift3Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Federation" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "Date" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "MeetCountry" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "MeetName" Csv.Decode.string) csvString_to_openPowerliftingData : String -> List MO.OpenPowerliftingData csvString_to_openPowerliftingData csvRaw = let result = Csv.Decode.decodeCsv Csv.Decode.FieldNamesFromFirstRow openPowerliftingDataDecoder csvRaw in case result of Ok value -> value Err error -> [] csvString_to_openPowerliftingDataVisA : String -> List MO.OpenPowerliftingData csvString_to_openPowerliftingDataVisA csvRaw = let result = Csv.Decode.decodeCsv Csv.Decode.FieldNamesFromFirstRow openPowerliftingDataDecoder csvRaw in case result of Ok value -> List.filter (\x -> discipline_filter x) value Err error -> [] discipline_filter : MO.OpenPowerliftingData -> Bool discipline_filter dataEntry = if dataEntry.squat1Kg == Nothing || dataEntry.squat2Kg == Nothing || dataEntry.squat3Kg == Nothing || dataEntry.bench1Kg == Nothing || dataEntry.bench2Kg == Nothing || dataEntry.bench3Kg == Nothing || dataEntry.dead1Kg == Nothing || dataEntry.dead2Kg == Nothing || dataEntry.dead3Kg == Nothing then False else True bringNamesIntoRightOrder : String -> String bringNamesIntoRightOrder name = let splittedName = String.split " " name firstName = Maybe.withDefault "" <| List.head <| splittedName lastName = Maybe.withDefault "" <| List.head <| List.reverse splittedName middleNamesList = Maybe.withDefault [] <| List.tail <| List.reverse <| Maybe.withDefault [] <| List.tail splittedName middleNames = String.join " " middleNamesList in <NAME> ++ ", " ++ <NAME> ++ " " ++ middleNames getCompleteExcerciseWeightsList : List MO.OpenPowerliftingData -> List Float getCompleteExcerciseWeightsList dataList = let squatOneList = List.filterMap .squat1Kg dataList benchOneList = List.filterMap .bench1Kg dataList deadOneList = List.filterMap .dead1Kg dataList squatTwoList = List.filterMap .squat2Kg dataList benchTwoList = List.filterMap .bench2Kg dataList deadTwoList = List.filterMap .dead2Kg dataList squatThreeList = List.filterMap .squat3Kg dataList benchThreeList = List.filterMap .bench3Kg dataList deadThreeList = List.filterMap .dead3Kg dataList in squatOneList ++ squatTwoList ++ squatThreeList ++ benchOneList ++ benchTwoList ++ benchThreeList ++ deadOneList ++ deadTwoList ++ deadThreeList
true
module DataProcessing exposing (..) import Csv.Decode import List.Extra import Maybe.Extra import Debug exposing (toString) import Dict import Dict.Extra as DiEx import Json.Encode as JsEn import Html exposing (Html) import TreeDiagram.Svg as TrSv import TreeDiagram exposing (defaultTreeLayout) import Json.Decode as JsDe import Color import TypedSvg.Core as TyCo import TypedSvg import TypedSvg.Attributes.InPx as TyAtIn import TypedSvg.Attributes as TyAt import TypedSvg.Types exposing (AnchorAlignment(..), CoordinateSystem(..), Length(..), Opacity(..), Paint(..), Transform(..), px) import Model as MO -- ein Decoder, welcher an die Elemente des Records und die CSV-Spalten-Namen angepasst ist openPowerliftingDataDecoder : Csv.Decode.Decoder MO.OpenPowerliftingData openPowerliftingDataDecoder = Csv.Decode.into MO.OpenPowerliftingData |> Csv.Decode.pipeline (Csv.Decode.field "Name" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "Sex" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "Squat1Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Squat2Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Squat3Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Bench1Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Bench2Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Bench3Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Deadlift1Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Deadlift2Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Deadlift3Kg" (Csv.Decode.blank Csv.Decode.float)) |> Csv.Decode.pipeline (Csv.Decode.field "Federation" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "Date" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "MeetCountry" Csv.Decode.string) |> Csv.Decode.pipeline (Csv.Decode.field "MeetName" Csv.Decode.string) csvString_to_openPowerliftingData : String -> List MO.OpenPowerliftingData csvString_to_openPowerliftingData csvRaw = let result = Csv.Decode.decodeCsv Csv.Decode.FieldNamesFromFirstRow openPowerliftingDataDecoder csvRaw in case result of Ok value -> value Err error -> [] csvString_to_openPowerliftingDataVisA : String -> List MO.OpenPowerliftingData csvString_to_openPowerliftingDataVisA csvRaw = let result = Csv.Decode.decodeCsv Csv.Decode.FieldNamesFromFirstRow openPowerliftingDataDecoder csvRaw in case result of Ok value -> List.filter (\x -> discipline_filter x) value Err error -> [] discipline_filter : MO.OpenPowerliftingData -> Bool discipline_filter dataEntry = if dataEntry.squat1Kg == Nothing || dataEntry.squat2Kg == Nothing || dataEntry.squat3Kg == Nothing || dataEntry.bench1Kg == Nothing || dataEntry.bench2Kg == Nothing || dataEntry.bench3Kg == Nothing || dataEntry.dead1Kg == Nothing || dataEntry.dead2Kg == Nothing || dataEntry.dead3Kg == Nothing then False else True bringNamesIntoRightOrder : String -> String bringNamesIntoRightOrder name = let splittedName = String.split " " name firstName = Maybe.withDefault "" <| List.head <| splittedName lastName = Maybe.withDefault "" <| List.head <| List.reverse splittedName middleNamesList = Maybe.withDefault [] <| List.tail <| List.reverse <| Maybe.withDefault [] <| List.tail splittedName middleNames = String.join " " middleNamesList in PI:NAME:<NAME>END_PI ++ ", " ++ PI:NAME:<NAME>END_PI ++ " " ++ middleNames getCompleteExcerciseWeightsList : List MO.OpenPowerliftingData -> List Float getCompleteExcerciseWeightsList dataList = let squatOneList = List.filterMap .squat1Kg dataList benchOneList = List.filterMap .bench1Kg dataList deadOneList = List.filterMap .dead1Kg dataList squatTwoList = List.filterMap .squat2Kg dataList benchTwoList = List.filterMap .bench2Kg dataList deadTwoList = List.filterMap .dead2Kg dataList squatThreeList = List.filterMap .squat3Kg dataList benchThreeList = List.filterMap .bench3Kg dataList deadThreeList = List.filterMap .dead3Kg dataList in squatOneList ++ squatTwoList ++ squatThreeList ++ benchOneList ++ benchTwoList ++ benchThreeList ++ deadOneList ++ deadTwoList ++ deadThreeList
elm
[ { "context": " {\n \"id\": 123,\n \"email\": \"sam@example.com\",\n \"profile\": {\"name\": \"Sam\"}\n ", "end": 2417, "score": 0.9999251366, "start": 2402, "tag": "EMAIL", "value": "sam@example.com" }, { "context": "am@example.com\",\n \"profile\": {\"name\": \"Sam\"}\n }\n \\\"\\\"\\\"\n\n\n -- Ok { id = 1", "end": 2456, "score": 0.9991703033, "start": 2453, "tag": "NAME", "value": "Sam" }, { "context": " }\n \\\"\\\"\\\"\n\n\n -- Ok { id = 123, name = \"Sam\", email = \"sam@example.com\" }\n\n\"\"\"\n ", "end": 2521, "score": 0.9993966222, "start": 2518, "tag": "NAME", "value": "Sam" }, { "context": "\\\"\n\n\n -- Ok { id = 123, name = \"Sam\", email = \"sam@example.com\" }\n\n\"\"\"\n , tipe = Lambda (Type \"Json", "end": 2548, "score": 0.9999252558, "start": 2533, "tag": "EMAIL", "value": "sam@example.com" }, { "context": " \\\"\\\"\\\"\n {\"id\": 123, \"email\": \"sam@example.com\"}\n \\\"\\\"\\\"\n\n\n -- Ok { id = 123, email = ", "end": 3510, "score": 0.9999240041, "start": 3495, "tag": "EMAIL", "value": "sam@example.com" }, { "context": "}\n \\\"\\\"\\\"\n\n\n -- Ok { id = 123, email = \"sam@example.com\", followers = 0 }\n\n\"\"\"\n , tipe = Lam", "end": 3576, "score": 0.9999254346, "start": 3561, "tag": "EMAIL", "value": "sam@example.com" }, { "context": " \\\"\\\"\\\"\n {\"id\": 123, \"email\": \"sam@example.com\" }\n \\\"\\\"\\\"\n\n\n -- Ok { id = 123, name = ", "end": 4734, "score": 0.999920547, "start": 4719, "tag": "EMAIL", "value": "sam@example.com" }, { "context": " }\n \\\"\\\"\\\"\n\n\n -- Ok { id = 123, name = \"blah\", email = \"sam@example.com\" }\n\nBecause `valDecode", "end": 4789, "score": 0.8007021546, "start": 4785, "tag": "NAME", "value": "blah" }, { "context": "\"\n\n\n -- Ok { id = 123, name = \"blah\", email = \"sam@example.com\" }\n\nBecause `valDecoder` is given an opportunity ", "end": 4816, "score": 0.9999216795, "start": 4801, "tag": "EMAIL", "value": "sam@example.com" }, { "context": " \\\"\\\"\\\"\n {\"id\": 123, \"email\": \"sam@example.com\", \"name\": \"Sam\"}\n \\\"\\\"\\\"\n\n\n -- Ok { id ", "end": 6480, "score": 0.9999217987, "start": 6465, "tag": "EMAIL", "value": "sam@example.com" }, { "context": " {\"id\": 123, \"email\": \"sam@example.com\", \"name\": \"Sam\"}\n \\\"\\\"\\\"\n\n\n -- Ok { id = 123, name = \"", "end": 6495, "score": 0.9982128143, "start": 6492, "tag": "NAME", "value": "Sam" }, { "context": "\"}\n \\\"\\\"\\\"\n\n\n -- Ok { id = 123, name = \"Sam\", email = \"sam@example.com\" }\n\n\"\"\"\n ", "end": 6548, "score": 0.9993984699, "start": 6545, "tag": "NAME", "value": "Sam" }, { "context": "\\\"\n\n\n -- Ok { id = 123, name = \"Sam\", email = \"sam@example.com\" }\n\n\"\"\"\n , tipe = Lambda (Type \"Stri", "end": 6575, "score": 0.9999238253, "start": 6560, "tag": "EMAIL", "value": "sam@example.com" }, { "context": " \\\"\\\"\\\"\n {\"id\": 123, \"email\": \"sam@example.com\", \"version\": 1}\n \\\"\\\"\\\"\n\n\n -- Err \"This", "end": 8477, "score": 0.9999206662, "start": 8462, "tag": "EMAIL", "value": "sam@example.com" } ]
tests/Review/Test/Dependencies/NoRedInkElmJsonDecodePipeline.elm
sparksp/elm-review-ports
3
module Review.Test.Dependencies.NoRedInkElmJsonDecodePipeline exposing (dependency) import Elm.Constraint import Elm.Docs import Elm.License import Elm.Module import Elm.Package import Elm.Project import Elm.Type exposing (Type(..)) import Elm.Version import Review.Project.Dependency as Dependency exposing (Dependency) dependency : Dependency dependency = Dependency.create "NoRedInk/elm-json-decode-pipeline" elmJson dependencyModules elmJson : Elm.Project.Project elmJson = Elm.Project.Package { elm = unsafeConstraint "0.19.0 <= v < 0.20.0" , exposed = Elm.Project.ExposedList [ unsafeModuleName "Json.Decode.Pipeline" ] , license = Elm.License.fromString "BSD-3-Clause" |> Maybe.withDefault Elm.License.bsd3 , name = unsafePackageName "NoRedInk/elm-json-decode-pipeline" , summary = "Use pipelines to build JSON Decoders." , deps = [ ( unsafePackageName "elm/core", unsafeConstraint "1.0.0 <= v < 2.0.0" ) , ( unsafePackageName "elm/json", unsafeConstraint "1.0.0 <= v < 2.0.0" ) ] , testDeps = [] , version = Elm.Version.fromString "1.0.0" |> Maybe.withDefault Elm.Version.one } dependencyModules : List Elm.Docs.Module dependencyModules = [ { name = "Json.Decode.Pipeline" , comment = """ # Json.Decode.Pipeline Use the `(|>)` operator to build JSON decoders. ## Decoding fields @docs required, requiredAt, optional, optionalAt, hardcoded, custom ## Ending pipelines @docs resolve """ , aliases = [] , unions = [] , binops = [] , values = [ { name = "custom" , comment = """ Run the given decoder and feed its result into the pipeline at this point. Consider this example. import Json.Decode as Decode exposing (Decoder, at, int, string) import Json.Decode.Pipeline exposing (custom, required) type alias User = { id : Int , name : String , email : String } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> custom (at [ "profile", "name" ] string) |> required "email" string result : Result String User result = Decode.decodeString userDecoder \"\"\" { "id": 123, "email": "sam@example.com", "profile": {"name": "Sam"} } \"\"\" -- Ok { id = 123, name = "Sam", email = "sam@example.com" } """ , tipe = Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])) } , { name = "hardcoded" , comment = """ Rather than decoding anything, use a fixed value for the next step in the pipeline. `harcoded` does not look at the JSON at all. import Json.Decode as Decode exposing (Decoder, int, string) import Json.Decode.Pipeline exposing (required) type alias User = { id : Int , email : String , followers : Int } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> required "email" string |> hardcoded 0 result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "sam@example.com"} \"\"\" -- Ok { id = 123, email = "sam@example.com", followers = 0 } """ , tipe = Lambda (Var "a") (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])) } , { name = "optional" , comment = """ Decode a field that may be missing or have a null value. If the field is missing, then it decodes as the `fallback` value. If the field is present, then `valDecoder` is used to decode its value. If `valDecoder` fails on a `null` value, then the `fallback` is used as if the field were missing entirely. import Json.Decode as Decode exposing (Decoder, int, null, oneOf, string) import Json.Decode.Pipeline exposing (optional, required) type alias User = { id : Int , name : String , email : String } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> optional "name" string "blah" |> required "email" string result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "sam@example.com" } \"\"\" -- Ok { id = 123, name = "blah", email = "sam@example.com" } Because `valDecoder` is given an opportunity to decode `null` values before resorting to the `fallback`, you can distinguish between missing and `null` values if you need to: userDecoder2 = Decode.succeed User |> required "id" int |> optional "name" (oneOf [ string, null "NULL" ]) "MISSING" |> required "email" string """ , tipe = Lambda (Type "String.String" []) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Var "a") (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])))) } , { name = "optionalAt" , comment = """ Decode an optional nested field. """ , tipe = Lambda (Type "List.List" [ Type "String.String" [] ]) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Var "a") (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])))) } , { name = "required" , comment = """ Decode a required field. import Json.Decode as Decode exposing (Decoder, int, string) import Json.Decode.Pipeline exposing (required) type alias User = { id : Int , name : String , email : String } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> required "name" string |> required "email" string result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "sam@example.com", "name": "Sam"} \"\"\" -- Ok { id = 123, name = "Sam", email = "sam@example.com" } """ , tipe = Lambda (Type "String.String" []) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ]))) } , { name = "requiredAt" , comment = """ Decode a required nested field. """ , tipe = Lambda (Type "List.List" [ Type "String.String" [] ]) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ]))) } , { name = "resolve" , comment = """ Convert a `Decoder (Result x a)` into a `Decoder a`. Useful when you want to perform some custom processing just before completing the decoding operation. import Json.Decode as Decode exposing (Decoder, float, int, string) import Json.Decode.Pipeline exposing (required, resolve) type alias User = { id : Int , email : String } userDecoder : Decoder User userDecoder = let -- toDecoder gets run *after* all the -- (|> required ...) steps are done. toDecoder : Int -> String -> Int -> Decoder User toDecoder id email version = if version > 2 then Decode.succeed (User id email) else fail "This JSON is from a deprecated source. Please upgrade!" in Decode.succeed toDecoder |> required "id" int |> required "email" string |> required "version" int -- version is part of toDecoder, |> resolve -- but it is not a part of User result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "sam@example.com", "version": 1} \"\"\" -- Err "This JSON is from a deprecated source. Please upgrade!" """ , tipe = Lambda (Type "Json.Decode.Decoder" [ Type "Json.Decode.Decoder" [ Var "a" ] ]) (Type "Json.Decode.Decoder" [ Var "a" ]) } ] } ] unsafePackageName : String -> Elm.Package.Name unsafePackageName packageName = case Elm.Package.fromString packageName of Just name -> name Nothing -> -- unsafe, but if the generation went well, it should all be good. unsafePackageName packageName -- Disables the tail-call optimization, so that the test crashes if we enter this case |> identity unsafeModuleName : String -> Elm.Module.Name unsafeModuleName moduleName = case Elm.Module.fromString moduleName of Just name -> name Nothing -> -- unsafe, but if the generation went well, it should all be good. unsafeModuleName moduleName -- Disables the tail-call optimization, so that the test crashes if we enter this case |> identity unsafeConstraint : String -> Elm.Constraint.Constraint unsafeConstraint constraint = case Elm.Constraint.fromString constraint of Just constr -> constr Nothing -> -- unsafe, but if the generation went well, it should all be good. unsafeConstraint constraint -- Disables the tail-call optimization, so that the test crashes if we enter this case |> identity
47412
module Review.Test.Dependencies.NoRedInkElmJsonDecodePipeline exposing (dependency) import Elm.Constraint import Elm.Docs import Elm.License import Elm.Module import Elm.Package import Elm.Project import Elm.Type exposing (Type(..)) import Elm.Version import Review.Project.Dependency as Dependency exposing (Dependency) dependency : Dependency dependency = Dependency.create "NoRedInk/elm-json-decode-pipeline" elmJson dependencyModules elmJson : Elm.Project.Project elmJson = Elm.Project.Package { elm = unsafeConstraint "0.19.0 <= v < 0.20.0" , exposed = Elm.Project.ExposedList [ unsafeModuleName "Json.Decode.Pipeline" ] , license = Elm.License.fromString "BSD-3-Clause" |> Maybe.withDefault Elm.License.bsd3 , name = unsafePackageName "NoRedInk/elm-json-decode-pipeline" , summary = "Use pipelines to build JSON Decoders." , deps = [ ( unsafePackageName "elm/core", unsafeConstraint "1.0.0 <= v < 2.0.0" ) , ( unsafePackageName "elm/json", unsafeConstraint "1.0.0 <= v < 2.0.0" ) ] , testDeps = [] , version = Elm.Version.fromString "1.0.0" |> Maybe.withDefault Elm.Version.one } dependencyModules : List Elm.Docs.Module dependencyModules = [ { name = "Json.Decode.Pipeline" , comment = """ # Json.Decode.Pipeline Use the `(|>)` operator to build JSON decoders. ## Decoding fields @docs required, requiredAt, optional, optionalAt, hardcoded, custom ## Ending pipelines @docs resolve """ , aliases = [] , unions = [] , binops = [] , values = [ { name = "custom" , comment = """ Run the given decoder and feed its result into the pipeline at this point. Consider this example. import Json.Decode as Decode exposing (Decoder, at, int, string) import Json.Decode.Pipeline exposing (custom, required) type alias User = { id : Int , name : String , email : String } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> custom (at [ "profile", "name" ] string) |> required "email" string result : Result String User result = Decode.decodeString userDecoder \"\"\" { "id": 123, "email": "<EMAIL>", "profile": {"name": "<NAME>"} } \"\"\" -- Ok { id = 123, name = "<NAME>", email = "<EMAIL>" } """ , tipe = Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])) } , { name = "hardcoded" , comment = """ Rather than decoding anything, use a fixed value for the next step in the pipeline. `harcoded` does not look at the JSON at all. import Json.Decode as Decode exposing (Decoder, int, string) import Json.Decode.Pipeline exposing (required) type alias User = { id : Int , email : String , followers : Int } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> required "email" string |> hardcoded 0 result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "<EMAIL>"} \"\"\" -- Ok { id = 123, email = "<EMAIL>", followers = 0 } """ , tipe = Lambda (Var "a") (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])) } , { name = "optional" , comment = """ Decode a field that may be missing or have a null value. If the field is missing, then it decodes as the `fallback` value. If the field is present, then `valDecoder` is used to decode its value. If `valDecoder` fails on a `null` value, then the `fallback` is used as if the field were missing entirely. import Json.Decode as Decode exposing (Decoder, int, null, oneOf, string) import Json.Decode.Pipeline exposing (optional, required) type alias User = { id : Int , name : String , email : String } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> optional "name" string "blah" |> required "email" string result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "<EMAIL>" } \"\"\" -- Ok { id = 123, name = "<NAME>", email = "<EMAIL>" } Because `valDecoder` is given an opportunity to decode `null` values before resorting to the `fallback`, you can distinguish between missing and `null` values if you need to: userDecoder2 = Decode.succeed User |> required "id" int |> optional "name" (oneOf [ string, null "NULL" ]) "MISSING" |> required "email" string """ , tipe = Lambda (Type "String.String" []) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Var "a") (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])))) } , { name = "optionalAt" , comment = """ Decode an optional nested field. """ , tipe = Lambda (Type "List.List" [ Type "String.String" [] ]) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Var "a") (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])))) } , { name = "required" , comment = """ Decode a required field. import Json.Decode as Decode exposing (Decoder, int, string) import Json.Decode.Pipeline exposing (required) type alias User = { id : Int , name : String , email : String } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> required "name" string |> required "email" string result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "<EMAIL>", "name": "<NAME>"} \"\"\" -- Ok { id = 123, name = "<NAME>", email = "<EMAIL>" } """ , tipe = Lambda (Type "String.String" []) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ]))) } , { name = "requiredAt" , comment = """ Decode a required nested field. """ , tipe = Lambda (Type "List.List" [ Type "String.String" [] ]) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ]))) } , { name = "resolve" , comment = """ Convert a `Decoder (Result x a)` into a `Decoder a`. Useful when you want to perform some custom processing just before completing the decoding operation. import Json.Decode as Decode exposing (Decoder, float, int, string) import Json.Decode.Pipeline exposing (required, resolve) type alias User = { id : Int , email : String } userDecoder : Decoder User userDecoder = let -- toDecoder gets run *after* all the -- (|> required ...) steps are done. toDecoder : Int -> String -> Int -> Decoder User toDecoder id email version = if version > 2 then Decode.succeed (User id email) else fail "This JSON is from a deprecated source. Please upgrade!" in Decode.succeed toDecoder |> required "id" int |> required "email" string |> required "version" int -- version is part of toDecoder, |> resolve -- but it is not a part of User result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "<EMAIL>", "version": 1} \"\"\" -- Err "This JSON is from a deprecated source. Please upgrade!" """ , tipe = Lambda (Type "Json.Decode.Decoder" [ Type "Json.Decode.Decoder" [ Var "a" ] ]) (Type "Json.Decode.Decoder" [ Var "a" ]) } ] } ] unsafePackageName : String -> Elm.Package.Name unsafePackageName packageName = case Elm.Package.fromString packageName of Just name -> name Nothing -> -- unsafe, but if the generation went well, it should all be good. unsafePackageName packageName -- Disables the tail-call optimization, so that the test crashes if we enter this case |> identity unsafeModuleName : String -> Elm.Module.Name unsafeModuleName moduleName = case Elm.Module.fromString moduleName of Just name -> name Nothing -> -- unsafe, but if the generation went well, it should all be good. unsafeModuleName moduleName -- Disables the tail-call optimization, so that the test crashes if we enter this case |> identity unsafeConstraint : String -> Elm.Constraint.Constraint unsafeConstraint constraint = case Elm.Constraint.fromString constraint of Just constr -> constr Nothing -> -- unsafe, but if the generation went well, it should all be good. unsafeConstraint constraint -- Disables the tail-call optimization, so that the test crashes if we enter this case |> identity
true
module Review.Test.Dependencies.NoRedInkElmJsonDecodePipeline exposing (dependency) import Elm.Constraint import Elm.Docs import Elm.License import Elm.Module import Elm.Package import Elm.Project import Elm.Type exposing (Type(..)) import Elm.Version import Review.Project.Dependency as Dependency exposing (Dependency) dependency : Dependency dependency = Dependency.create "NoRedInk/elm-json-decode-pipeline" elmJson dependencyModules elmJson : Elm.Project.Project elmJson = Elm.Project.Package { elm = unsafeConstraint "0.19.0 <= v < 0.20.0" , exposed = Elm.Project.ExposedList [ unsafeModuleName "Json.Decode.Pipeline" ] , license = Elm.License.fromString "BSD-3-Clause" |> Maybe.withDefault Elm.License.bsd3 , name = unsafePackageName "NoRedInk/elm-json-decode-pipeline" , summary = "Use pipelines to build JSON Decoders." , deps = [ ( unsafePackageName "elm/core", unsafeConstraint "1.0.0 <= v < 2.0.0" ) , ( unsafePackageName "elm/json", unsafeConstraint "1.0.0 <= v < 2.0.0" ) ] , testDeps = [] , version = Elm.Version.fromString "1.0.0" |> Maybe.withDefault Elm.Version.one } dependencyModules : List Elm.Docs.Module dependencyModules = [ { name = "Json.Decode.Pipeline" , comment = """ # Json.Decode.Pipeline Use the `(|>)` operator to build JSON decoders. ## Decoding fields @docs required, requiredAt, optional, optionalAt, hardcoded, custom ## Ending pipelines @docs resolve """ , aliases = [] , unions = [] , binops = [] , values = [ { name = "custom" , comment = """ Run the given decoder and feed its result into the pipeline at this point. Consider this example. import Json.Decode as Decode exposing (Decoder, at, int, string) import Json.Decode.Pipeline exposing (custom, required) type alias User = { id : Int , name : String , email : String } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> custom (at [ "profile", "name" ] string) |> required "email" string result : Result String User result = Decode.decodeString userDecoder \"\"\" { "id": 123, "email": "PI:EMAIL:<EMAIL>END_PI", "profile": {"name": "PI:NAME:<NAME>END_PI"} } \"\"\" -- Ok { id = 123, name = "PI:NAME:<NAME>END_PI", email = "PI:EMAIL:<EMAIL>END_PI" } """ , tipe = Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])) } , { name = "hardcoded" , comment = """ Rather than decoding anything, use a fixed value for the next step in the pipeline. `harcoded` does not look at the JSON at all. import Json.Decode as Decode exposing (Decoder, int, string) import Json.Decode.Pipeline exposing (required) type alias User = { id : Int , email : String , followers : Int } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> required "email" string |> hardcoded 0 result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "PI:EMAIL:<EMAIL>END_PI"} \"\"\" -- Ok { id = 123, email = "PI:EMAIL:<EMAIL>END_PI", followers = 0 } """ , tipe = Lambda (Var "a") (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])) } , { name = "optional" , comment = """ Decode a field that may be missing or have a null value. If the field is missing, then it decodes as the `fallback` value. If the field is present, then `valDecoder` is used to decode its value. If `valDecoder` fails on a `null` value, then the `fallback` is used as if the field were missing entirely. import Json.Decode as Decode exposing (Decoder, int, null, oneOf, string) import Json.Decode.Pipeline exposing (optional, required) type alias User = { id : Int , name : String , email : String } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> optional "name" string "blah" |> required "email" string result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "PI:EMAIL:<EMAIL>END_PI" } \"\"\" -- Ok { id = 123, name = "PI:NAME:<NAME>END_PI", email = "PI:EMAIL:<EMAIL>END_PI" } Because `valDecoder` is given an opportunity to decode `null` values before resorting to the `fallback`, you can distinguish between missing and `null` values if you need to: userDecoder2 = Decode.succeed User |> required "id" int |> optional "name" (oneOf [ string, null "NULL" ]) "MISSING" |> required "email" string """ , tipe = Lambda (Type "String.String" []) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Var "a") (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])))) } , { name = "optionalAt" , comment = """ Decode an optional nested field. """ , tipe = Lambda (Type "List.List" [ Type "String.String" [] ]) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Var "a") (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ])))) } , { name = "required" , comment = """ Decode a required field. import Json.Decode as Decode exposing (Decoder, int, string) import Json.Decode.Pipeline exposing (required) type alias User = { id : Int , name : String , email : String } userDecoder : Decoder User userDecoder = Decode.succeed User |> required "id" int |> required "name" string |> required "email" string result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "PI:EMAIL:<EMAIL>END_PI", "name": "PI:NAME:<NAME>END_PI"} \"\"\" -- Ok { id = 123, name = "PI:NAME:<NAME>END_PI", email = "PI:EMAIL:<EMAIL>END_PI" } """ , tipe = Lambda (Type "String.String" []) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ]))) } , { name = "requiredAt" , comment = """ Decode a required nested field. """ , tipe = Lambda (Type "List.List" [ Type "String.String" [] ]) (Lambda (Type "Json.Decode.Decoder" [ Var "a" ]) (Lambda (Type "Json.Decode.Decoder" [ Lambda (Var "a") (Var "b") ]) (Type "Json.Decode.Decoder" [ Var "b" ]))) } , { name = "resolve" , comment = """ Convert a `Decoder (Result x a)` into a `Decoder a`. Useful when you want to perform some custom processing just before completing the decoding operation. import Json.Decode as Decode exposing (Decoder, float, int, string) import Json.Decode.Pipeline exposing (required, resolve) type alias User = { id : Int , email : String } userDecoder : Decoder User userDecoder = let -- toDecoder gets run *after* all the -- (|> required ...) steps are done. toDecoder : Int -> String -> Int -> Decoder User toDecoder id email version = if version > 2 then Decode.succeed (User id email) else fail "This JSON is from a deprecated source. Please upgrade!" in Decode.succeed toDecoder |> required "id" int |> required "email" string |> required "version" int -- version is part of toDecoder, |> resolve -- but it is not a part of User result : Result String User result = Decode.decodeString userDecoder \"\"\" {"id": 123, "email": "PI:EMAIL:<EMAIL>END_PI", "version": 1} \"\"\" -- Err "This JSON is from a deprecated source. Please upgrade!" """ , tipe = Lambda (Type "Json.Decode.Decoder" [ Type "Json.Decode.Decoder" [ Var "a" ] ]) (Type "Json.Decode.Decoder" [ Var "a" ]) } ] } ] unsafePackageName : String -> Elm.Package.Name unsafePackageName packageName = case Elm.Package.fromString packageName of Just name -> name Nothing -> -- unsafe, but if the generation went well, it should all be good. unsafePackageName packageName -- Disables the tail-call optimization, so that the test crashes if we enter this case |> identity unsafeModuleName : String -> Elm.Module.Name unsafeModuleName moduleName = case Elm.Module.fromString moduleName of Just name -> name Nothing -> -- unsafe, but if the generation went well, it should all be good. unsafeModuleName moduleName -- Disables the tail-call optimization, so that the test crashes if we enter this case |> identity unsafeConstraint : String -> Elm.Constraint.Constraint unsafeConstraint constraint = case Elm.Constraint.fromString constraint of Just constr -> constr Nothing -> -- unsafe, but if the generation went well, it should all be good. unsafeConstraint constraint -- Disables the tail-call optimization, so that the test crashes if we enter this case |> identity
elm
[ { "context": " anology than &ldquo;arrow&rdquo;). Huge thanks to Joey Adams for suggesting this library\nand working through t", "end": 1894, "score": 0.9998758435, "start": 1884, "tag": "NAME", "value": "Joey Adams" }, { "context": "ntribute]!\n\n [contribute]: https://github.com/elm-lang/elm-compiler/blob/master/CONTRIBUTING.md \"how to ", "end": 5134, "score": 0.8677175045, "start": 5130, "tag": "USERNAME", "value": "lang" }, { "context": "cuss \"Elm-Discuss\"\n [github]: https://github.com/evancz \"Elm on GitHub\"\n [irc]: http://webchat.freenode.", "end": 5320, "score": 0.9994962215, "start": 5314, "tag": "USERNAME", "value": "evancz" } ]
src/pages/blog/announce/0.5.elm
kacperj/elm-lang.org
0
import Skeleton import Center main = Skeleton.blog "Elm 0.5" "The Libraries you Need" Skeleton.evan (Skeleton.Date 2012 10 25) [ Center.markdown "600px" content ] content = """ This release focuses on growing [Elm](/)'s standard libraries to make sure you always have the tools you need. For a full listing of Elm's current libraries, see [this page][docs]. [docs]: /docs "docs" ### Dictionaries and Sets Elm now has [dictionaries][Dict] and [sets][Set]! [Dict]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Dict "Dictionary library" [Set]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Set "Set library" The Dict and Set libraries could be used from JavaScript. I can make this easier if people are interested. Let me know! ### Automatons This version also introduces the [Automaton][auto] library. This library will make it easier to create dynamic components that can be switched in and out of a program. [auto]: http://package.elm-lang.org/packages/evancz/automaton/1.0.0/ "Automaton Library" &ldquo;But what is an automaton?&rdquo; you might be asking. An automaton is like a little robot that takes inputs and produces outputs. Without input, an automaton just sits quietly, waiting for something to do. Automatons can have a &ldquo;memory&rdquo; so their output may depend on their past experiences. All automatons are interchangeable, so they are easy to switch in and out of programs. This library is based on the very clever ideas introduced by [Arrowized FRP][afrp]. I have made an effort to make it easier to understand and use for people unfamiliar with &ldquo;Arrows&rdquo; and other concepts that are largely orthogonal to doing-things-in-real-life. I am hoping that the term [&ldquo;automaton&rdquo;][wiki] is somewhat familiar (or at least a better anology than &ldquo;arrow&rdquo;). Huge thanks to Joey Adams for suggesting this library and working through the details with me! I plan on writing some blog posts on automatons, so hopefully that will make it clearer why they are totally rad. [wiki]: http://en.wikipedia.org/wiki/Automata_theory#Informal_description "automaton wiki" [afrp]: http://haskell.cs.yale.edu/wp-content/uploads/2011/02/workshop-02.pdf "Arrowized FRP" ### Escape from &ldquo;Callback Hell&rdquo; (new HTTP library) You can now make pretty much any kind of request you want ([docs][http]). You can specify verb, url, payload, and custom headers. This library makes it possible to escape &ldquo;callback hell&rdquo;. The [`send`][send] function takes in a signal of HTTP requests and produces a signal of responses. The responses only update when they are ready. You can use it just like any other signal, but it updates asynchronously, so you can write nice code that is both readable and efficient. No callbacks! No nested-callbacks! ... See this library in action with the [Zip Code fetcher][zips]. I will be writing more about this library fairly soon because I think it is an important and novel part of Elm. JS developers struggle with &ldquo;callback hell&rdquo; on a daily basis, and now they do not have to! [send]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Http#send "send" [http]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Http "HTTP docs" [zips]: /examples/zip-codes ### New Functions and Syntax - Abbreviated notation for tuple functions: * `(,) === (\\x y -> (x,y))` * `(,,) === (\\x y z -> (x,y,z))` * etc. - New functions for converting strings to numbers. Great for text input boxes: * `readInt : String -> Maybe Int` * `readFloat : String -> Maybe Float` - [`(complement : Color -> Color)`][color] which computes complementary colors! Surprisingly difficult to do! [color]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Color "Color library" ### Fewer Library Prefixes The library prefixes have pretty much all been removed. `Data.List` is now `List`, `Signal.Mouse` is now `Mouse`, etc. The prefixes end up being more confusing than helpful. `Data.List` makes it sound like some special version for no reason. This is a breaking change, but one that I think makes Elm a nicer language. The fix is just a matter of taking some words out of your `import` statements, but please email [the list][list] if you want assistance with this (e.g. a script or some advice). ### Bug fixes, Optimizations, and Error Messages - Generated JS is more readable. - Pattern matching is smaller and faster in generated JS. - Fix a bug with pattern parsing. `Four _ _ B _` was parsed as `Four _ _ (B _)`. - `String` is now treated as an alias of `[Char]`. - Better type error reporting for ambiguous uses of variables and for variables in aliased modules. ## Other News I recently started an [`#elm` IRC channel at freenode][irc], so feel free to come hang out and chat. Big thank you to `tac` for helping get the channel set up! In other cool news, Elm just got its 100th star on [github][github]! Yay growth! If you want to help out, there are [tons of ways to contribute][contribute]! [contribute]: https://github.com/elm-lang/elm-compiler/blob/master/CONTRIBUTING.md "how to contribute" [list]: https://groups.google.com/forum/?fromgroups#!forum/elm-discuss "Elm-Discuss" [github]: https://github.com/evancz "Elm on GitHub" [irc]: http://webchat.freenode.net/ "IRC" """
19261
import Skeleton import Center main = Skeleton.blog "Elm 0.5" "The Libraries you Need" Skeleton.evan (Skeleton.Date 2012 10 25) [ Center.markdown "600px" content ] content = """ This release focuses on growing [Elm](/)'s standard libraries to make sure you always have the tools you need. For a full listing of Elm's current libraries, see [this page][docs]. [docs]: /docs "docs" ### Dictionaries and Sets Elm now has [dictionaries][Dict] and [sets][Set]! [Dict]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Dict "Dictionary library" [Set]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Set "Set library" The Dict and Set libraries could be used from JavaScript. I can make this easier if people are interested. Let me know! ### Automatons This version also introduces the [Automaton][auto] library. This library will make it easier to create dynamic components that can be switched in and out of a program. [auto]: http://package.elm-lang.org/packages/evancz/automaton/1.0.0/ "Automaton Library" &ldquo;But what is an automaton?&rdquo; you might be asking. An automaton is like a little robot that takes inputs and produces outputs. Without input, an automaton just sits quietly, waiting for something to do. Automatons can have a &ldquo;memory&rdquo; so their output may depend on their past experiences. All automatons are interchangeable, so they are easy to switch in and out of programs. This library is based on the very clever ideas introduced by [Arrowized FRP][afrp]. I have made an effort to make it easier to understand and use for people unfamiliar with &ldquo;Arrows&rdquo; and other concepts that are largely orthogonal to doing-things-in-real-life. I am hoping that the term [&ldquo;automaton&rdquo;][wiki] is somewhat familiar (or at least a better anology than &ldquo;arrow&rdquo;). Huge thanks to <NAME> for suggesting this library and working through the details with me! I plan on writing some blog posts on automatons, so hopefully that will make it clearer why they are totally rad. [wiki]: http://en.wikipedia.org/wiki/Automata_theory#Informal_description "automaton wiki" [afrp]: http://haskell.cs.yale.edu/wp-content/uploads/2011/02/workshop-02.pdf "Arrowized FRP" ### Escape from &ldquo;Callback Hell&rdquo; (new HTTP library) You can now make pretty much any kind of request you want ([docs][http]). You can specify verb, url, payload, and custom headers. This library makes it possible to escape &ldquo;callback hell&rdquo;. The [`send`][send] function takes in a signal of HTTP requests and produces a signal of responses. The responses only update when they are ready. You can use it just like any other signal, but it updates asynchronously, so you can write nice code that is both readable and efficient. No callbacks! No nested-callbacks! ... See this library in action with the [Zip Code fetcher][zips]. I will be writing more about this library fairly soon because I think it is an important and novel part of Elm. JS developers struggle with &ldquo;callback hell&rdquo; on a daily basis, and now they do not have to! [send]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Http#send "send" [http]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Http "HTTP docs" [zips]: /examples/zip-codes ### New Functions and Syntax - Abbreviated notation for tuple functions: * `(,) === (\\x y -> (x,y))` * `(,,) === (\\x y z -> (x,y,z))` * etc. - New functions for converting strings to numbers. Great for text input boxes: * `readInt : String -> Maybe Int` * `readFloat : String -> Maybe Float` - [`(complement : Color -> Color)`][color] which computes complementary colors! Surprisingly difficult to do! [color]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Color "Color library" ### Fewer Library Prefixes The library prefixes have pretty much all been removed. `Data.List` is now `List`, `Signal.Mouse` is now `Mouse`, etc. The prefixes end up being more confusing than helpful. `Data.List` makes it sound like some special version for no reason. This is a breaking change, but one that I think makes Elm a nicer language. The fix is just a matter of taking some words out of your `import` statements, but please email [the list][list] if you want assistance with this (e.g. a script or some advice). ### Bug fixes, Optimizations, and Error Messages - Generated JS is more readable. - Pattern matching is smaller and faster in generated JS. - Fix a bug with pattern parsing. `Four _ _ B _` was parsed as `Four _ _ (B _)`. - `String` is now treated as an alias of `[Char]`. - Better type error reporting for ambiguous uses of variables and for variables in aliased modules. ## Other News I recently started an [`#elm` IRC channel at freenode][irc], so feel free to come hang out and chat. Big thank you to `tac` for helping get the channel set up! In other cool news, Elm just got its 100th star on [github][github]! Yay growth! If you want to help out, there are [tons of ways to contribute][contribute]! [contribute]: https://github.com/elm-lang/elm-compiler/blob/master/CONTRIBUTING.md "how to contribute" [list]: https://groups.google.com/forum/?fromgroups#!forum/elm-discuss "Elm-Discuss" [github]: https://github.com/evancz "Elm on GitHub" [irc]: http://webchat.freenode.net/ "IRC" """
true
import Skeleton import Center main = Skeleton.blog "Elm 0.5" "The Libraries you Need" Skeleton.evan (Skeleton.Date 2012 10 25) [ Center.markdown "600px" content ] content = """ This release focuses on growing [Elm](/)'s standard libraries to make sure you always have the tools you need. For a full listing of Elm's current libraries, see [this page][docs]. [docs]: /docs "docs" ### Dictionaries and Sets Elm now has [dictionaries][Dict] and [sets][Set]! [Dict]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Dict "Dictionary library" [Set]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Set "Set library" The Dict and Set libraries could be used from JavaScript. I can make this easier if people are interested. Let me know! ### Automatons This version also introduces the [Automaton][auto] library. This library will make it easier to create dynamic components that can be switched in and out of a program. [auto]: http://package.elm-lang.org/packages/evancz/automaton/1.0.0/ "Automaton Library" &ldquo;But what is an automaton?&rdquo; you might be asking. An automaton is like a little robot that takes inputs and produces outputs. Without input, an automaton just sits quietly, waiting for something to do. Automatons can have a &ldquo;memory&rdquo; so their output may depend on their past experiences. All automatons are interchangeable, so they are easy to switch in and out of programs. This library is based on the very clever ideas introduced by [Arrowized FRP][afrp]. I have made an effort to make it easier to understand and use for people unfamiliar with &ldquo;Arrows&rdquo; and other concepts that are largely orthogonal to doing-things-in-real-life. I am hoping that the term [&ldquo;automaton&rdquo;][wiki] is somewhat familiar (or at least a better anology than &ldquo;arrow&rdquo;). Huge thanks to PI:NAME:<NAME>END_PI for suggesting this library and working through the details with me! I plan on writing some blog posts on automatons, so hopefully that will make it clearer why they are totally rad. [wiki]: http://en.wikipedia.org/wiki/Automata_theory#Informal_description "automaton wiki" [afrp]: http://haskell.cs.yale.edu/wp-content/uploads/2011/02/workshop-02.pdf "Arrowized FRP" ### Escape from &ldquo;Callback Hell&rdquo; (new HTTP library) You can now make pretty much any kind of request you want ([docs][http]). You can specify verb, url, payload, and custom headers. This library makes it possible to escape &ldquo;callback hell&rdquo;. The [`send`][send] function takes in a signal of HTTP requests and produces a signal of responses. The responses only update when they are ready. You can use it just like any other signal, but it updates asynchronously, so you can write nice code that is both readable and efficient. No callbacks! No nested-callbacks! ... See this library in action with the [Zip Code fetcher][zips]. I will be writing more about this library fairly soon because I think it is an important and novel part of Elm. JS developers struggle with &ldquo;callback hell&rdquo; on a daily basis, and now they do not have to! [send]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Http#send "send" [http]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Http "HTTP docs" [zips]: /examples/zip-codes ### New Functions and Syntax - Abbreviated notation for tuple functions: * `(,) === (\\x y -> (x,y))` * `(,,) === (\\x y z -> (x,y,z))` * etc. - New functions for converting strings to numbers. Great for text input boxes: * `readInt : String -> Maybe Int` * `readFloat : String -> Maybe Float` - [`(complement : Color -> Color)`][color] which computes complementary colors! Surprisingly difficult to do! [color]: http://package.elm-lang.org/packages/elm-lang/core/1.0.0/Color "Color library" ### Fewer Library Prefixes The library prefixes have pretty much all been removed. `Data.List` is now `List`, `Signal.Mouse` is now `Mouse`, etc. The prefixes end up being more confusing than helpful. `Data.List` makes it sound like some special version for no reason. This is a breaking change, but one that I think makes Elm a nicer language. The fix is just a matter of taking some words out of your `import` statements, but please email [the list][list] if you want assistance with this (e.g. a script or some advice). ### Bug fixes, Optimizations, and Error Messages - Generated JS is more readable. - Pattern matching is smaller and faster in generated JS. - Fix a bug with pattern parsing. `Four _ _ B _` was parsed as `Four _ _ (B _)`. - `String` is now treated as an alias of `[Char]`. - Better type error reporting for ambiguous uses of variables and for variables in aliased modules. ## Other News I recently started an [`#elm` IRC channel at freenode][irc], so feel free to come hang out and chat. Big thank you to `tac` for helping get the channel set up! In other cool news, Elm just got its 100th star on [github][github]! Yay growth! If you want to help out, there are [tons of ways to contribute][contribute]! [contribute]: https://github.com/elm-lang/elm-compiler/blob/master/CONTRIBUTING.md "how to contribute" [list]: https://groups.google.com/forum/?fromgroups#!forum/elm-discuss "Elm-Discuss" [github]: https://github.com/evancz "Elm on GitHub" [irc]: http://webchat.freenode.net/ "IRC" """
elm
[ { "context": "String\ngodName god =\n case god of\n Charon -> \"Charon\"\n Nyx -> \"Nyx\"\n Hades -> \"Hades\"\n Hermes", "end": 2549, "score": 0.8046115637, "start": 2543, "tag": "NAME", "value": "Charon" }, { "context": "ng\"\n , trait = \"HadesShoutTrait\"\n , name = \"Hades Aid\"\n , description = \"Your {$Keywords.WrathHades}", "end": 10504, "score": 0.8967548013, "start": 10495, "tag": "NAME", "value": "Hades Aid" } ]
src/Traits.elm
JustinLove/hades-boons
1
module Traits exposing ( TraitId , SlotId , Traits , makeTraits , loadPreprocessedGodsAndDuoBoons , empty , God(..) , BoonType(..) , Frame(..) , GodData , GodDataRecord , godData , Trait , Requirements(..) , BoonStatus(..) , linkableGods , allGods , dataGod , dataName , dataLootColor , dataLayout , godName , godIcon , godColor , godTraits , duoBoons , duoBoonsOf , miscBoons , boonsForSlot , isSlot , slots , iconForSlot , nameForSlot , boonsOf , basicBoons , dataBoon , allTraits , findBoon , boonStatus , traitStatus , addLayout , calculateActiveLayoutGroups , calculateActiveDuoSets , calculateActiveSlots ) import Layout exposing (Layout) import Color exposing (Color) import Dict exposing (Dict) import Set exposing (Set) type alias TraitId = String type alias SlotId = String type Traits = Traits { gods : List GodData , duos : List Trait , misc : List Trait } empty : Traits empty = Traits {gods = [], duos = [], misc = []} type God = Hades | Charon | Nyx | Hermes | Aphrodite | Ares | Demeter | Dionysus | Poseidon | Athena | Artemis | Zeus type BoonType = BasicBoon God | DuoBoon God God | Keepsake type Frame = CommonFrame | DuoFrame | KeepsakeFrame | LegendaryFrame type GodData = GodData GodDataRecord type alias GodDataRecord = { god : God , traits : List Trait , layout : Layout } type alias Trait = { icon : String , trait : TraitId , name : String , description : String , tooltipData : Dict String Float , slot : Maybe SlotId , requiredSlottedTrait : Maybe SlotId , requiredMetaUpgradeSelected : Maybe TraitId , requiredFalseTraits : Set TraitId , requirements : Requirements , boonType : BoonType , frame : Frame } type Requirements = None | OneOf (Set TraitId) | OneFromEachSet (List (Set TraitId)) type BoonStatus = Active | Available | Excluded | Unavailable linkableGods : Traits -> List GodData linkableGods (Traits {gods}) = List.drop 1 gods allGods : Traits -> List GodData allGods (Traits {gods}) = gods godData : GodDataRecord -> GodData godData = GodData dataGod : GodData -> God dataGod (GodData data) = data.god dataName : GodData -> String dataName (GodData data) = godName data.god dataLootColor : GodData -> Color dataLootColor (GodData data) = godColor data.god dataLayout : GodData -> Layout dataLayout (GodData data) = data.layout godName : God -> String godName god = case god of Charon -> "Charon" Nyx -> "Nyx" Hades -> "Hades" Hermes -> "Hermes" Aphrodite -> "Aphrodite" Ares -> "Ares" Demeter -> "Demeter" Dionysus -> "Dionysus" Poseidon -> "Poseidon" Athena -> "Athena" Artemis -> "Artemis" Zeus -> "Zeus" godColor : God -> Color godColor god = case god of Charon -> Color.fromRgba { red = 0.4 , green = 0 , blue = 0.706 , alpha = 1 } Nyx -> Color.fromRgba { red = 0.4 , green = 0 , blue = 0.706 , alpha = 1 } Hades -> Color.fromRgba { red = 0.776 , green = 0 , blue = 0 , alpha = 1 } Hermes -> Color.fromRgba { red = 1 , green = 0.35294117647058826 , blue = 0 , alpha = 1 } Aphrodite -> Color.fromRgba { red = 1 , green = 0.19607843137254902 , blue = 0.9411764705882353 , alpha = 1 } Ares -> Color.fromRgba { red = 1, green = 0.0784313725490196, blue = 0, alpha = 1 } Demeter -> Color.fromRgba { red = 0.631 , green = 0.702 , blue = 1 , alpha = 1 } Dionysus -> Color.fromRgba { red = 0.7843137254901961, green = 0, blue = 1, alpha = 1 } Poseidon -> Color.fromRgba { red = 0, green = 0.7843137254901961, blue = 1, alpha = 1 } Athena -> Color.fromRgba { red = 0.733 , green = 0.69 , blue = 0.373 , alpha = 1 } Artemis -> Color.fromRgba { red = 0.43137254901960786 , green = 1 , blue = 0 , alpha = 1 } Zeus -> Color.fromRgba { red = 1 , green = 1 , blue = 0.25098039215686274 , alpha = 1 } godIcon : God -> String godIcon god = "GUI/Screens/BoonSelectSymbols/" ++ (godName god) ++ ".png" basicBoons : GodData -> List Trait basicBoons data = data |> godTraits |> List.filter isBasicBoon dataBoon : GodData -> TraitId -> Maybe Trait dataBoon data id = data |> godTraits |> List.filter (hasId id) |> List.head boonsForSlot : SlotId -> Traits -> List Trait boonsForSlot slot (Traits {gods}) = gods |> List.concatMap basicBoons |> List.append miscBoons |> List.filter (isSlot slot) isSlot : SlotId -> Trait -> Bool isSlot target {slot} = slot == Just target slots : List SlotId slots = [ "Melee" , "Secondary" , "Ranged" , "Rush" , "Shout" ] iconForSlot : SlotId -> String iconForSlot slot = case slot of "Melee" -> "GUI/HUD/PrimaryBoons/SlotIcon_Attack_White.png" "Secondary" -> "GUI/HUD/PrimaryBoons/SlotIcon_Secondary_White.png" "Ranged" -> "GUI/HUD/PrimaryBoons/SlotIcon_Ranged_White.png" "Rush" -> "GUI/HUD/PrimaryBoons/SlotIcon_Dash_White.png" "Shout" -> "GUI/HUD/PrimaryBoons/SlotIcon_Wrath_White.png" _ -> "GUI/LockIcon/LockIcon0001.png" nameForSlot : SlotId -> String nameForSlot slot = case slot of "Melee" -> "Any Attack" "Secondary" -> "Any Secondary" "Ranged" -> "Any Ranged" "Rush" -> "Any Dash" "Shout" -> "Any Call" _ -> "Unknown Slot" metaUpgrades : List String metaUpgrades = [ "AmmoMetaUpgrade" , "ReloadAmmoMetaUpgrade" ] boonsOf : God -> Traits -> List Trait boonsOf target (Traits {gods}) = gods |> List.filter (\data -> dataGod data == target) |> List.concatMap basicBoons duoBoons : Traits -> List Trait duoBoons (Traits {duos}) = duos duoBoonsOf : God -> Traits -> List Trait duoBoonsOf target (Traits {duos}) = duos |> List.filter (\{boonType} -> case boonType of BasicBoon _ -> False DuoBoon a b -> a == target || b == target Keepsake -> False ) singleBoons : Traits -> List Trait singleBoons (Traits {gods}) = gods |> List.concatMap godTraits isBasicBoon : Trait -> Bool isBasicBoon {boonType} = case boonType of BasicBoon _ -> True DuoBoon _ _ -> False Keepsake -> True isDuoBoon : Trait -> Bool isDuoBoon {boonType} = case boonType of BasicBoon _ -> False DuoBoon _ _ -> True Keepsake -> False makeTraits : List GodData -> Traits makeTraits gods = gods |> tagLinkedBoons -- propagate to duos |> separateDuos loadPreprocessedGodsAndDuoBoons : List GodData -> List Trait -> Traits loadPreprocessedGodsAndDuoBoons basicGods duos = Traits { gods = basicGods , duos = duos , misc = miscBoons } -- see also: Traits.Decode.trinkets miscBoons : List Trait miscBoons = [ { icon = "GUI/Screens/WeaponEnchantmentIcons/bow_echantment_2.png" , trait = "BowLoadAmmoTrait" , name = "Aspect of Hera" , description = "Your {$Keywords.Cast} loads {!Icons.Ammo} into your next {$Keywords.Attack}, firing on impact." , tooltipData = Dict.empty , slot = Just "Weapon" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Charon , frame = CommonFrame } , { icon = "GUI/Screens/WeaponEnchantmentIcons/shield_enchantment_3.png" , trait = "ShieldLoadAmmoTrait" , name = "Aspect of Beowulf" , description = "You have {$Keywords.BeowulfAspect}, but take {#AltPenaltyFormat}{$TooltipData.TooltipDamageTaken:P} {#PreviousFormat}damage." , tooltipData = Dict.fromList [("TooltipDamageTaken",10)] , slot = Just "Weapon" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Charon , frame = CommonFrame } , { icon = "GUI/Screens/MirrorIcons/infernal soul.png" , trait = "AmmoMetaUpgrade" , name = "Infernal Soul" , description = "Raise your supply of {!Icons.Ammo} for your {#BoldFormatGraft}Cast{#PreviousFormat}, {#TooltipUpgradeFormat}+1 {#PreviousFormat}per rank." , tooltipData = Dict.empty , slot = Just "Soul" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Nyx , frame = KeepsakeFrame } , { icon = "GUI/Screens/MirrorBIcons/Stygian_Soul.png" , trait = "ReloadAmmoMetaUpgrade" , name = "Stygian Soul" , description = "Regenerate your {!Icons.Ammo} for your {#BoldFormatGraft}Cast {#PreviousFormat}{#ItalicFormat}(rather than pick it up){#PreviousFormat}, faster by {#TooltipUpgradeFormat}{$TempTextData.BaseValue} Sec. {#PreviousFormat}per rank." , tooltipData = Dict.fromList [("BaseValue",1)] , slot = Just "Soul" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Nyx , frame = KeepsakeFrame } , { icon = "GUI/Screens/AwardMenu/badge_23.png" , trait = "HadesShoutKeepsake" , name = "Sigil of the Dead" , description = "Your {$Keywords.WrathHades} becomes {#BoldFormatGraft}Hades' Aid{#PreviousFormat}, which briefly makes you {#BoldFormatGraft}{$Keywords.Invisible}{#PreviousFormat}; your {$Keywords.WrathGauge} starts {#UpgradeFormat}{$TooltipData.TooltipSuperGain}% {#PreviousFormat} full." , tooltipData = Dict.fromList [("TooltipSuperGain",15)] , slot = Just "Keepsake" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.fromList [ "AphroditeShoutTrait" , "AresShoutTrait" , "DemeterShoutTrait" , "DionysusShoutTrait" , "PoseidonShoutTrait" , "AthenaShoutTrait" , "ArtemisShoutTrait" , "ZeusShoutTrait" ] , requirements = None , boonType = BasicBoon Hades , frame = CommonFrame } , { icon = "GUI/Screens/BoonIcons/Hades_01_Large.png" , trait = "HadesShoutTrait" , name = "Hades Aid" , description = "Your {$Keywords.WrathHades} briefly makes you turn {$Keywords.Invisible}." , tooltipData = Dict.empty , slot = Just "Shout" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = Keepsake , frame = KeepsakeFrame } ] tagLinkedBoons : List GodData -> List GodData tagLinkedBoons gods = gods |> List.map (tagLinkedGodBoons gods) tagLinkedGodBoons : List GodData -> GodData -> GodData tagLinkedGodBoons gods (GodData god) = GodData { god | traits = god.traits |> List.map (tagLinkedBoon gods god.god) } tagLinkedBoon : List GodData -> God -> Trait -> Trait tagLinkedBoon gods god trait = case trait.boonType of Keepsake -> trait _ -> let boonType = boonTypeFromRequirements gods god trait.requirements in { trait | boonType = boonType , frame = case boonType of BasicBoon _ -> frameFromRequirements gods trait.requirements DuoBoon _ _ -> DuoFrame Keepsake -> KeepsakeFrame } boonTypeFromRequirements : List GodData -> God -> Requirements -> BoonType boonTypeFromRequirements gods god requirements = case requirements of None -> BasicBoon god OneOf set -> boonTypeFromGroup god (godOfSet gods set) OneFromEachSet list -> list |> List.map (godOfSet gods) |> List.foldr oneFromEachSetAccumulator (BasicBoon god) frameFromRequirements : List GodData -> Requirements -> Frame frameFromRequirements gods requirements = if legendaryRequirements gods requirements then LegendaryFrame else CommonFrame legendaryRequirements : List GodData -> Requirements -> Bool legendaryRequirements gods requirements = case requirements of None -> False OneOf set -> (setHasRequirements gods set) || (Set.member "FastClearDodgeBonusTrait" set) OneFromEachSet list -> True setHasRequirements : List GodData -> Set TraitId -> Bool setHasRequirements gods set = set |> Set.toList |> List.map (findBoonRequirements gods) |> List.any (\req -> req /= None && req /= OneOf (Set.singleton "ShieldLoadAmmoTrait") && req /= OneOf (Set.fromList ["BowLoadAmmoTrait", "ShieldLoadAmmoTrait"]) ) type GodsInGroup = Empty | One God | Many boonTypeFromGroup : God -> GodsInGroup -> BoonType boonTypeFromGroup default group = case group of Empty -> BasicBoon default One god -> BasicBoon god Many -> BasicBoon default oneFromEachSetAccumulator : GodsInGroup -> BoonType -> BoonType oneFromEachSetAccumulator group boonType = case (boonType, group) of (_, Many) -> boonType (_, Empty) -> boonType (BasicBoon a, One g) -> if a == g then BasicBoon a else DuoBoon a g (DuoBoon a b, One g) -> if a == g || b == g then DuoBoon a b else -- Debug.todo "too many gods" -- no way to punt boonType (Keepsake, _) -> boonType godOfSet : List GodData -> Set TraitId -> GodsInGroup godOfSet gods set = set |> Set.foldr (godAccumulator gods) Empty godAccumulator : List GodData -> TraitId -> GodsInGroup -> GodsInGroup godAccumulator gods id group = case (findBoonType gods id, group) of (_, Many) -> Many (Nothing, _) -> group (Just (Keepsake), _) -> group (Just (BasicBoon a), Empty) -> One a (Just (BasicBoon a), One b) -> if a == b then One a else Many (Just (DuoBoon _ _), _) -> Many findBoonType : List GodData -> TraitId -> Maybe BoonType findBoonType gods id = findGodBoon gods id |> Maybe.map .boonType findBoonRequirements : List GodData -> TraitId -> Requirements findBoonRequirements gods id = findGodBoon gods id |> Maybe.map .requirements |> Maybe.withDefault None findGodBoon : List GodData -> TraitId -> Maybe Trait findGodBoon gods id = gods |> List.concatMap godTraits |> List.filter (hasId id) |> List.head separateDuos : List GodData -> Traits separateDuos gods = let (basicGods, listOfDuos) = gods |> List.map extractDuos |> List.unzip duos = List.concat listOfDuos in loadPreprocessedGodsAndDuoBoons basicGods duos extractDuos : GodData -> (GodData, List Trait) extractDuos (GodData data) = let (duos, basic) = List.partition isDuoBoon data.traits in (GodData {data | traits = basic}, duos) godTraits : GodData -> List Trait godTraits (GodData data) = data.traits hasId : TraitId -> Trait -> Bool hasId id trait = trait.trait == id allTraits : Traits -> List Trait allTraits traits = traits |> allGods |> List.concatMap godTraits |> List.append (duoBoons traits) findBoon : Traits -> TraitId -> Maybe Trait findBoon traits id = traits |> allTraits |> List.append miscBoons |> List.filter (hasId id) |> List.head boonStatus : Set TraitId -> Set SlotId -> Set TraitId -> Trait -> BoonStatus boonStatus activeTraits activeSlots excludedTraits trait = if Set.member trait.trait activeTraits then Active else if Set.member trait.trait excludedTraits then Excluded else if boonHasRequiredSlottedTrait activeSlots trait && boonMeetsRequirements activeTraits trait then Available else Unavailable slotFilled : Set SlotId -> Trait -> Bool slotFilled activeSlots trait = case trait.slot of Just slot -> if Set.member slot activeSlots then True else False Nothing -> False boonHasRequiredSlottedTrait : Set SlotId -> Trait -> Bool boonHasRequiredSlottedTrait activeSlots trait = case trait.requiredSlottedTrait of Just slot -> if Set.member slot activeSlots then True else False Nothing -> True boonMeetsRequirements : Set TraitId -> Trait -> Bool boonMeetsRequirements activeTraits trait = case trait.requirements of None -> True OneOf set -> if Set.intersect activeTraits set |> Set.isEmpty |> not then True else False OneFromEachSet list -> if list |> List.all (Set.intersect activeTraits >> Set.isEmpty >> not) then True else False boonExcludedByRequirements : Set TraitId -> Trait -> Bool boonExcludedByRequirements excludedTraits trait = case trait.requirements of None -> False OneOf set -> if Set.diff set excludedTraits |> Set.isEmpty then True else False OneFromEachSet list -> if list |> List.any (\set -> Set.diff set excludedTraits |> Set.isEmpty) then True else False traitStatus : Set TraitId -> String -> Traits -> Dict TraitId BoonStatus traitStatus activeTraits metaUpgrade traits = let activeSlots = calculateActiveSlots activeTraits traits excludedTraits = calculateExcludedTraits activeTraits activeSlots metaUpgrade traits statusOfTraits = allTraits traits |> List.map (\trait -> (trait.trait, boonStatus activeTraits activeSlots excludedTraits trait)) statusOfSlots = slots |> List.map (\slot -> let id = "Any"++slot in ( id , if Set.member slot activeSlots then Active else Available ) ) statusOfMeta = metaUpgrades |> List.map (\id -> ( id , if id == metaUpgrade then Active else Excluded ) ) in statusOfTraits |> List.append statusOfSlots |> List.append statusOfMeta |> Dict.fromList addLayout : God -> Layout -> Traits -> Traits addLayout god layout (Traits traits) = Traits { traits | gods = List.map (\goddata -> case goddata of GodData data -> if data.god == god then GodData { data | layout = layout } else goddata ) traits.gods } calculateActiveLayoutGroups : Set TraitId -> List GodData -> List (Set Layout.GroupId) calculateActiveLayoutGroups activeTraits gods = gods |> List.map (\(GodData {layout}) -> Layout.calculateActiveGroups activeTraits layout) calculateActiveDuoSets : List GodData -> Set TraitId -> List Trait -> Set Layout.GroupId calculateActiveDuoSets gods activeTraits duos = duos |> List.foldl (\trait active -> calculateActiveSets gods activeTraits trait |> Set.union active) Set.empty calculateActiveSets : List GodData -> Set TraitId -> Trait -> Set Layout.GroupId calculateActiveSets gods activeTraits trait = case trait.requirements of None -> Set.empty OneOf set -> if Set.intersect activeTraits set |> Set.isEmpty |> not then activeRequirementSet gods trait set |> Maybe.map Set.singleton |> Maybe.withDefault Set.empty else Set.empty OneFromEachSet list -> list |> List.filter (Set.intersect activeTraits >> Set.isEmpty >> not) |> List.filterMap (activeRequirementSet gods trait) |> Set.fromList activeRequirementSet : List GodData -> Trait -> Set TraitId -> Maybe Layout.GroupId activeRequirementSet gods {trait} set = case godOfSet gods set of Empty -> Nothing One god -> Just ((godName god) ++ trait) Many -> Nothing calculateActiveSlots : Set TraitId -> Traits -> Set SlotId calculateActiveSlots activeTraits (Traits {gods}) = gods |> List.concatMap godTraits |> List.append miscBoons |> List.filter (\{trait} -> Set.member trait activeTraits) |> List.filterMap .slot |> Set.fromList calculateExcludedTraits : Set TraitId -> Set SlotId -> String -> Traits -> Set TraitId calculateExcludedTraits activeTraits activeSlots metaUpgrade (Traits {gods, duos} as traits) = let basics = gods |> List.concatMap godTraits all = allTraits traits in (Set.diff (Set.fromList ["ShieldLoadAmmoTrait", "BowLoadAmmoTrait"]) activeTraits) |> Set.union (calculateExcludedSlotTraits activeTraits activeSlots gods) |> Set.union (calculateExcludedIncompatibleTraits activeTraits all) |> Set.union (calculateExcludedMetaUpgradeTraits metaUpgrade all) |> calculateExcludedDerivedTraits basics -- first requirments |> calculateExcludedDerivedTraits basics -- legendary |> calculateExcludedDerivedTraits duos -- duos calculateExcludedSlotTraits : Set TraitId -> Set SlotId -> List GodData -> Set TraitId calculateExcludedSlotTraits activeTraits activeSlots gods = gods |> List.concatMap godTraits |> List.filter (\{trait} -> not <| Set.member trait activeTraits) |> List.filter (\trait -> slotFilled activeSlots trait) |> List.map .trait |> Set.fromList calculateExcludedIncompatibleTraits : Set TraitId -> List Trait -> Set TraitId calculateExcludedIncompatibleTraits activeTraits traits = traits |> List.filter (\{trait} -> not <| Set.member trait activeTraits) |> List.filter (\{requiredFalseTraits} -> Set.intersect activeTraits requiredFalseTraits |> Set.isEmpty |> not) |> List.map .trait |> Set.fromList calculateExcludedMetaUpgradeTraits : String -> List Trait -> Set TraitId calculateExcludedMetaUpgradeTraits metaUpgrade traits = traits |> List.filter (\{requiredMetaUpgradeSelected} -> case requiredMetaUpgradeSelected of Just req -> metaUpgrade /= req Nothing -> False ) |> List.map .trait |> Set.fromList calculateExcludedDerivedTraits : List Trait -> Set TraitId -> Set TraitId calculateExcludedDerivedTraits traits excludedTraits = traits |> List.filter (\trait -> boonExcludedByRequirements excludedTraits trait) |> List.map .trait |> Set.fromList |> Set.union excludedTraits
2286
module Traits exposing ( TraitId , SlotId , Traits , makeTraits , loadPreprocessedGodsAndDuoBoons , empty , God(..) , BoonType(..) , Frame(..) , GodData , GodDataRecord , godData , Trait , Requirements(..) , BoonStatus(..) , linkableGods , allGods , dataGod , dataName , dataLootColor , dataLayout , godName , godIcon , godColor , godTraits , duoBoons , duoBoonsOf , miscBoons , boonsForSlot , isSlot , slots , iconForSlot , nameForSlot , boonsOf , basicBoons , dataBoon , allTraits , findBoon , boonStatus , traitStatus , addLayout , calculateActiveLayoutGroups , calculateActiveDuoSets , calculateActiveSlots ) import Layout exposing (Layout) import Color exposing (Color) import Dict exposing (Dict) import Set exposing (Set) type alias TraitId = String type alias SlotId = String type Traits = Traits { gods : List GodData , duos : List Trait , misc : List Trait } empty : Traits empty = Traits {gods = [], duos = [], misc = []} type God = Hades | Charon | Nyx | Hermes | Aphrodite | Ares | Demeter | Dionysus | Poseidon | Athena | Artemis | Zeus type BoonType = BasicBoon God | DuoBoon God God | Keepsake type Frame = CommonFrame | DuoFrame | KeepsakeFrame | LegendaryFrame type GodData = GodData GodDataRecord type alias GodDataRecord = { god : God , traits : List Trait , layout : Layout } type alias Trait = { icon : String , trait : TraitId , name : String , description : String , tooltipData : Dict String Float , slot : Maybe SlotId , requiredSlottedTrait : Maybe SlotId , requiredMetaUpgradeSelected : Maybe TraitId , requiredFalseTraits : Set TraitId , requirements : Requirements , boonType : BoonType , frame : Frame } type Requirements = None | OneOf (Set TraitId) | OneFromEachSet (List (Set TraitId)) type BoonStatus = Active | Available | Excluded | Unavailable linkableGods : Traits -> List GodData linkableGods (Traits {gods}) = List.drop 1 gods allGods : Traits -> List GodData allGods (Traits {gods}) = gods godData : GodDataRecord -> GodData godData = GodData dataGod : GodData -> God dataGod (GodData data) = data.god dataName : GodData -> String dataName (GodData data) = godName data.god dataLootColor : GodData -> Color dataLootColor (GodData data) = godColor data.god dataLayout : GodData -> Layout dataLayout (GodData data) = data.layout godName : God -> String godName god = case god of Charon -> "<NAME>" Nyx -> "Nyx" Hades -> "Hades" Hermes -> "Hermes" Aphrodite -> "Aphrodite" Ares -> "Ares" Demeter -> "Demeter" Dionysus -> "Dionysus" Poseidon -> "Poseidon" Athena -> "Athena" Artemis -> "Artemis" Zeus -> "Zeus" godColor : God -> Color godColor god = case god of Charon -> Color.fromRgba { red = 0.4 , green = 0 , blue = 0.706 , alpha = 1 } Nyx -> Color.fromRgba { red = 0.4 , green = 0 , blue = 0.706 , alpha = 1 } Hades -> Color.fromRgba { red = 0.776 , green = 0 , blue = 0 , alpha = 1 } Hermes -> Color.fromRgba { red = 1 , green = 0.35294117647058826 , blue = 0 , alpha = 1 } Aphrodite -> Color.fromRgba { red = 1 , green = 0.19607843137254902 , blue = 0.9411764705882353 , alpha = 1 } Ares -> Color.fromRgba { red = 1, green = 0.0784313725490196, blue = 0, alpha = 1 } Demeter -> Color.fromRgba { red = 0.631 , green = 0.702 , blue = 1 , alpha = 1 } Dionysus -> Color.fromRgba { red = 0.7843137254901961, green = 0, blue = 1, alpha = 1 } Poseidon -> Color.fromRgba { red = 0, green = 0.7843137254901961, blue = 1, alpha = 1 } Athena -> Color.fromRgba { red = 0.733 , green = 0.69 , blue = 0.373 , alpha = 1 } Artemis -> Color.fromRgba { red = 0.43137254901960786 , green = 1 , blue = 0 , alpha = 1 } Zeus -> Color.fromRgba { red = 1 , green = 1 , blue = 0.25098039215686274 , alpha = 1 } godIcon : God -> String godIcon god = "GUI/Screens/BoonSelectSymbols/" ++ (godName god) ++ ".png" basicBoons : GodData -> List Trait basicBoons data = data |> godTraits |> List.filter isBasicBoon dataBoon : GodData -> TraitId -> Maybe Trait dataBoon data id = data |> godTraits |> List.filter (hasId id) |> List.head boonsForSlot : SlotId -> Traits -> List Trait boonsForSlot slot (Traits {gods}) = gods |> List.concatMap basicBoons |> List.append miscBoons |> List.filter (isSlot slot) isSlot : SlotId -> Trait -> Bool isSlot target {slot} = slot == Just target slots : List SlotId slots = [ "Melee" , "Secondary" , "Ranged" , "Rush" , "Shout" ] iconForSlot : SlotId -> String iconForSlot slot = case slot of "Melee" -> "GUI/HUD/PrimaryBoons/SlotIcon_Attack_White.png" "Secondary" -> "GUI/HUD/PrimaryBoons/SlotIcon_Secondary_White.png" "Ranged" -> "GUI/HUD/PrimaryBoons/SlotIcon_Ranged_White.png" "Rush" -> "GUI/HUD/PrimaryBoons/SlotIcon_Dash_White.png" "Shout" -> "GUI/HUD/PrimaryBoons/SlotIcon_Wrath_White.png" _ -> "GUI/LockIcon/LockIcon0001.png" nameForSlot : SlotId -> String nameForSlot slot = case slot of "Melee" -> "Any Attack" "Secondary" -> "Any Secondary" "Ranged" -> "Any Ranged" "Rush" -> "Any Dash" "Shout" -> "Any Call" _ -> "Unknown Slot" metaUpgrades : List String metaUpgrades = [ "AmmoMetaUpgrade" , "ReloadAmmoMetaUpgrade" ] boonsOf : God -> Traits -> List Trait boonsOf target (Traits {gods}) = gods |> List.filter (\data -> dataGod data == target) |> List.concatMap basicBoons duoBoons : Traits -> List Trait duoBoons (Traits {duos}) = duos duoBoonsOf : God -> Traits -> List Trait duoBoonsOf target (Traits {duos}) = duos |> List.filter (\{boonType} -> case boonType of BasicBoon _ -> False DuoBoon a b -> a == target || b == target Keepsake -> False ) singleBoons : Traits -> List Trait singleBoons (Traits {gods}) = gods |> List.concatMap godTraits isBasicBoon : Trait -> Bool isBasicBoon {boonType} = case boonType of BasicBoon _ -> True DuoBoon _ _ -> False Keepsake -> True isDuoBoon : Trait -> Bool isDuoBoon {boonType} = case boonType of BasicBoon _ -> False DuoBoon _ _ -> True Keepsake -> False makeTraits : List GodData -> Traits makeTraits gods = gods |> tagLinkedBoons -- propagate to duos |> separateDuos loadPreprocessedGodsAndDuoBoons : List GodData -> List Trait -> Traits loadPreprocessedGodsAndDuoBoons basicGods duos = Traits { gods = basicGods , duos = duos , misc = miscBoons } -- see also: Traits.Decode.trinkets miscBoons : List Trait miscBoons = [ { icon = "GUI/Screens/WeaponEnchantmentIcons/bow_echantment_2.png" , trait = "BowLoadAmmoTrait" , name = "Aspect of Hera" , description = "Your {$Keywords.Cast} loads {!Icons.Ammo} into your next {$Keywords.Attack}, firing on impact." , tooltipData = Dict.empty , slot = Just "Weapon" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Charon , frame = CommonFrame } , { icon = "GUI/Screens/WeaponEnchantmentIcons/shield_enchantment_3.png" , trait = "ShieldLoadAmmoTrait" , name = "Aspect of Beowulf" , description = "You have {$Keywords.BeowulfAspect}, but take {#AltPenaltyFormat}{$TooltipData.TooltipDamageTaken:P} {#PreviousFormat}damage." , tooltipData = Dict.fromList [("TooltipDamageTaken",10)] , slot = Just "Weapon" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Charon , frame = CommonFrame } , { icon = "GUI/Screens/MirrorIcons/infernal soul.png" , trait = "AmmoMetaUpgrade" , name = "Infernal Soul" , description = "Raise your supply of {!Icons.Ammo} for your {#BoldFormatGraft}Cast{#PreviousFormat}, {#TooltipUpgradeFormat}+1 {#PreviousFormat}per rank." , tooltipData = Dict.empty , slot = Just "Soul" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Nyx , frame = KeepsakeFrame } , { icon = "GUI/Screens/MirrorBIcons/Stygian_Soul.png" , trait = "ReloadAmmoMetaUpgrade" , name = "Stygian Soul" , description = "Regenerate your {!Icons.Ammo} for your {#BoldFormatGraft}Cast {#PreviousFormat}{#ItalicFormat}(rather than pick it up){#PreviousFormat}, faster by {#TooltipUpgradeFormat}{$TempTextData.BaseValue} Sec. {#PreviousFormat}per rank." , tooltipData = Dict.fromList [("BaseValue",1)] , slot = Just "Soul" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Nyx , frame = KeepsakeFrame } , { icon = "GUI/Screens/AwardMenu/badge_23.png" , trait = "HadesShoutKeepsake" , name = "Sigil of the Dead" , description = "Your {$Keywords.WrathHades} becomes {#BoldFormatGraft}Hades' Aid{#PreviousFormat}, which briefly makes you {#BoldFormatGraft}{$Keywords.Invisible}{#PreviousFormat}; your {$Keywords.WrathGauge} starts {#UpgradeFormat}{$TooltipData.TooltipSuperGain}% {#PreviousFormat} full." , tooltipData = Dict.fromList [("TooltipSuperGain",15)] , slot = Just "Keepsake" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.fromList [ "AphroditeShoutTrait" , "AresShoutTrait" , "DemeterShoutTrait" , "DionysusShoutTrait" , "PoseidonShoutTrait" , "AthenaShoutTrait" , "ArtemisShoutTrait" , "ZeusShoutTrait" ] , requirements = None , boonType = BasicBoon Hades , frame = CommonFrame } , { icon = "GUI/Screens/BoonIcons/Hades_01_Large.png" , trait = "HadesShoutTrait" , name = "<NAME>" , description = "Your {$Keywords.WrathHades} briefly makes you turn {$Keywords.Invisible}." , tooltipData = Dict.empty , slot = Just "Shout" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = Keepsake , frame = KeepsakeFrame } ] tagLinkedBoons : List GodData -> List GodData tagLinkedBoons gods = gods |> List.map (tagLinkedGodBoons gods) tagLinkedGodBoons : List GodData -> GodData -> GodData tagLinkedGodBoons gods (GodData god) = GodData { god | traits = god.traits |> List.map (tagLinkedBoon gods god.god) } tagLinkedBoon : List GodData -> God -> Trait -> Trait tagLinkedBoon gods god trait = case trait.boonType of Keepsake -> trait _ -> let boonType = boonTypeFromRequirements gods god trait.requirements in { trait | boonType = boonType , frame = case boonType of BasicBoon _ -> frameFromRequirements gods trait.requirements DuoBoon _ _ -> DuoFrame Keepsake -> KeepsakeFrame } boonTypeFromRequirements : List GodData -> God -> Requirements -> BoonType boonTypeFromRequirements gods god requirements = case requirements of None -> BasicBoon god OneOf set -> boonTypeFromGroup god (godOfSet gods set) OneFromEachSet list -> list |> List.map (godOfSet gods) |> List.foldr oneFromEachSetAccumulator (BasicBoon god) frameFromRequirements : List GodData -> Requirements -> Frame frameFromRequirements gods requirements = if legendaryRequirements gods requirements then LegendaryFrame else CommonFrame legendaryRequirements : List GodData -> Requirements -> Bool legendaryRequirements gods requirements = case requirements of None -> False OneOf set -> (setHasRequirements gods set) || (Set.member "FastClearDodgeBonusTrait" set) OneFromEachSet list -> True setHasRequirements : List GodData -> Set TraitId -> Bool setHasRequirements gods set = set |> Set.toList |> List.map (findBoonRequirements gods) |> List.any (\req -> req /= None && req /= OneOf (Set.singleton "ShieldLoadAmmoTrait") && req /= OneOf (Set.fromList ["BowLoadAmmoTrait", "ShieldLoadAmmoTrait"]) ) type GodsInGroup = Empty | One God | Many boonTypeFromGroup : God -> GodsInGroup -> BoonType boonTypeFromGroup default group = case group of Empty -> BasicBoon default One god -> BasicBoon god Many -> BasicBoon default oneFromEachSetAccumulator : GodsInGroup -> BoonType -> BoonType oneFromEachSetAccumulator group boonType = case (boonType, group) of (_, Many) -> boonType (_, Empty) -> boonType (BasicBoon a, One g) -> if a == g then BasicBoon a else DuoBoon a g (DuoBoon a b, One g) -> if a == g || b == g then DuoBoon a b else -- Debug.todo "too many gods" -- no way to punt boonType (Keepsake, _) -> boonType godOfSet : List GodData -> Set TraitId -> GodsInGroup godOfSet gods set = set |> Set.foldr (godAccumulator gods) Empty godAccumulator : List GodData -> TraitId -> GodsInGroup -> GodsInGroup godAccumulator gods id group = case (findBoonType gods id, group) of (_, Many) -> Many (Nothing, _) -> group (Just (Keepsake), _) -> group (Just (BasicBoon a), Empty) -> One a (Just (BasicBoon a), One b) -> if a == b then One a else Many (Just (DuoBoon _ _), _) -> Many findBoonType : List GodData -> TraitId -> Maybe BoonType findBoonType gods id = findGodBoon gods id |> Maybe.map .boonType findBoonRequirements : List GodData -> TraitId -> Requirements findBoonRequirements gods id = findGodBoon gods id |> Maybe.map .requirements |> Maybe.withDefault None findGodBoon : List GodData -> TraitId -> Maybe Trait findGodBoon gods id = gods |> List.concatMap godTraits |> List.filter (hasId id) |> List.head separateDuos : List GodData -> Traits separateDuos gods = let (basicGods, listOfDuos) = gods |> List.map extractDuos |> List.unzip duos = List.concat listOfDuos in loadPreprocessedGodsAndDuoBoons basicGods duos extractDuos : GodData -> (GodData, List Trait) extractDuos (GodData data) = let (duos, basic) = List.partition isDuoBoon data.traits in (GodData {data | traits = basic}, duos) godTraits : GodData -> List Trait godTraits (GodData data) = data.traits hasId : TraitId -> Trait -> Bool hasId id trait = trait.trait == id allTraits : Traits -> List Trait allTraits traits = traits |> allGods |> List.concatMap godTraits |> List.append (duoBoons traits) findBoon : Traits -> TraitId -> Maybe Trait findBoon traits id = traits |> allTraits |> List.append miscBoons |> List.filter (hasId id) |> List.head boonStatus : Set TraitId -> Set SlotId -> Set TraitId -> Trait -> BoonStatus boonStatus activeTraits activeSlots excludedTraits trait = if Set.member trait.trait activeTraits then Active else if Set.member trait.trait excludedTraits then Excluded else if boonHasRequiredSlottedTrait activeSlots trait && boonMeetsRequirements activeTraits trait then Available else Unavailable slotFilled : Set SlotId -> Trait -> Bool slotFilled activeSlots trait = case trait.slot of Just slot -> if Set.member slot activeSlots then True else False Nothing -> False boonHasRequiredSlottedTrait : Set SlotId -> Trait -> Bool boonHasRequiredSlottedTrait activeSlots trait = case trait.requiredSlottedTrait of Just slot -> if Set.member slot activeSlots then True else False Nothing -> True boonMeetsRequirements : Set TraitId -> Trait -> Bool boonMeetsRequirements activeTraits trait = case trait.requirements of None -> True OneOf set -> if Set.intersect activeTraits set |> Set.isEmpty |> not then True else False OneFromEachSet list -> if list |> List.all (Set.intersect activeTraits >> Set.isEmpty >> not) then True else False boonExcludedByRequirements : Set TraitId -> Trait -> Bool boonExcludedByRequirements excludedTraits trait = case trait.requirements of None -> False OneOf set -> if Set.diff set excludedTraits |> Set.isEmpty then True else False OneFromEachSet list -> if list |> List.any (\set -> Set.diff set excludedTraits |> Set.isEmpty) then True else False traitStatus : Set TraitId -> String -> Traits -> Dict TraitId BoonStatus traitStatus activeTraits metaUpgrade traits = let activeSlots = calculateActiveSlots activeTraits traits excludedTraits = calculateExcludedTraits activeTraits activeSlots metaUpgrade traits statusOfTraits = allTraits traits |> List.map (\trait -> (trait.trait, boonStatus activeTraits activeSlots excludedTraits trait)) statusOfSlots = slots |> List.map (\slot -> let id = "Any"++slot in ( id , if Set.member slot activeSlots then Active else Available ) ) statusOfMeta = metaUpgrades |> List.map (\id -> ( id , if id == metaUpgrade then Active else Excluded ) ) in statusOfTraits |> List.append statusOfSlots |> List.append statusOfMeta |> Dict.fromList addLayout : God -> Layout -> Traits -> Traits addLayout god layout (Traits traits) = Traits { traits | gods = List.map (\goddata -> case goddata of GodData data -> if data.god == god then GodData { data | layout = layout } else goddata ) traits.gods } calculateActiveLayoutGroups : Set TraitId -> List GodData -> List (Set Layout.GroupId) calculateActiveLayoutGroups activeTraits gods = gods |> List.map (\(GodData {layout}) -> Layout.calculateActiveGroups activeTraits layout) calculateActiveDuoSets : List GodData -> Set TraitId -> List Trait -> Set Layout.GroupId calculateActiveDuoSets gods activeTraits duos = duos |> List.foldl (\trait active -> calculateActiveSets gods activeTraits trait |> Set.union active) Set.empty calculateActiveSets : List GodData -> Set TraitId -> Trait -> Set Layout.GroupId calculateActiveSets gods activeTraits trait = case trait.requirements of None -> Set.empty OneOf set -> if Set.intersect activeTraits set |> Set.isEmpty |> not then activeRequirementSet gods trait set |> Maybe.map Set.singleton |> Maybe.withDefault Set.empty else Set.empty OneFromEachSet list -> list |> List.filter (Set.intersect activeTraits >> Set.isEmpty >> not) |> List.filterMap (activeRequirementSet gods trait) |> Set.fromList activeRequirementSet : List GodData -> Trait -> Set TraitId -> Maybe Layout.GroupId activeRequirementSet gods {trait} set = case godOfSet gods set of Empty -> Nothing One god -> Just ((godName god) ++ trait) Many -> Nothing calculateActiveSlots : Set TraitId -> Traits -> Set SlotId calculateActiveSlots activeTraits (Traits {gods}) = gods |> List.concatMap godTraits |> List.append miscBoons |> List.filter (\{trait} -> Set.member trait activeTraits) |> List.filterMap .slot |> Set.fromList calculateExcludedTraits : Set TraitId -> Set SlotId -> String -> Traits -> Set TraitId calculateExcludedTraits activeTraits activeSlots metaUpgrade (Traits {gods, duos} as traits) = let basics = gods |> List.concatMap godTraits all = allTraits traits in (Set.diff (Set.fromList ["ShieldLoadAmmoTrait", "BowLoadAmmoTrait"]) activeTraits) |> Set.union (calculateExcludedSlotTraits activeTraits activeSlots gods) |> Set.union (calculateExcludedIncompatibleTraits activeTraits all) |> Set.union (calculateExcludedMetaUpgradeTraits metaUpgrade all) |> calculateExcludedDerivedTraits basics -- first requirments |> calculateExcludedDerivedTraits basics -- legendary |> calculateExcludedDerivedTraits duos -- duos calculateExcludedSlotTraits : Set TraitId -> Set SlotId -> List GodData -> Set TraitId calculateExcludedSlotTraits activeTraits activeSlots gods = gods |> List.concatMap godTraits |> List.filter (\{trait} -> not <| Set.member trait activeTraits) |> List.filter (\trait -> slotFilled activeSlots trait) |> List.map .trait |> Set.fromList calculateExcludedIncompatibleTraits : Set TraitId -> List Trait -> Set TraitId calculateExcludedIncompatibleTraits activeTraits traits = traits |> List.filter (\{trait} -> not <| Set.member trait activeTraits) |> List.filter (\{requiredFalseTraits} -> Set.intersect activeTraits requiredFalseTraits |> Set.isEmpty |> not) |> List.map .trait |> Set.fromList calculateExcludedMetaUpgradeTraits : String -> List Trait -> Set TraitId calculateExcludedMetaUpgradeTraits metaUpgrade traits = traits |> List.filter (\{requiredMetaUpgradeSelected} -> case requiredMetaUpgradeSelected of Just req -> metaUpgrade /= req Nothing -> False ) |> List.map .trait |> Set.fromList calculateExcludedDerivedTraits : List Trait -> Set TraitId -> Set TraitId calculateExcludedDerivedTraits traits excludedTraits = traits |> List.filter (\trait -> boonExcludedByRequirements excludedTraits trait) |> List.map .trait |> Set.fromList |> Set.union excludedTraits
true
module Traits exposing ( TraitId , SlotId , Traits , makeTraits , loadPreprocessedGodsAndDuoBoons , empty , God(..) , BoonType(..) , Frame(..) , GodData , GodDataRecord , godData , Trait , Requirements(..) , BoonStatus(..) , linkableGods , allGods , dataGod , dataName , dataLootColor , dataLayout , godName , godIcon , godColor , godTraits , duoBoons , duoBoonsOf , miscBoons , boonsForSlot , isSlot , slots , iconForSlot , nameForSlot , boonsOf , basicBoons , dataBoon , allTraits , findBoon , boonStatus , traitStatus , addLayout , calculateActiveLayoutGroups , calculateActiveDuoSets , calculateActiveSlots ) import Layout exposing (Layout) import Color exposing (Color) import Dict exposing (Dict) import Set exposing (Set) type alias TraitId = String type alias SlotId = String type Traits = Traits { gods : List GodData , duos : List Trait , misc : List Trait } empty : Traits empty = Traits {gods = [], duos = [], misc = []} type God = Hades | Charon | Nyx | Hermes | Aphrodite | Ares | Demeter | Dionysus | Poseidon | Athena | Artemis | Zeus type BoonType = BasicBoon God | DuoBoon God God | Keepsake type Frame = CommonFrame | DuoFrame | KeepsakeFrame | LegendaryFrame type GodData = GodData GodDataRecord type alias GodDataRecord = { god : God , traits : List Trait , layout : Layout } type alias Trait = { icon : String , trait : TraitId , name : String , description : String , tooltipData : Dict String Float , slot : Maybe SlotId , requiredSlottedTrait : Maybe SlotId , requiredMetaUpgradeSelected : Maybe TraitId , requiredFalseTraits : Set TraitId , requirements : Requirements , boonType : BoonType , frame : Frame } type Requirements = None | OneOf (Set TraitId) | OneFromEachSet (List (Set TraitId)) type BoonStatus = Active | Available | Excluded | Unavailable linkableGods : Traits -> List GodData linkableGods (Traits {gods}) = List.drop 1 gods allGods : Traits -> List GodData allGods (Traits {gods}) = gods godData : GodDataRecord -> GodData godData = GodData dataGod : GodData -> God dataGod (GodData data) = data.god dataName : GodData -> String dataName (GodData data) = godName data.god dataLootColor : GodData -> Color dataLootColor (GodData data) = godColor data.god dataLayout : GodData -> Layout dataLayout (GodData data) = data.layout godName : God -> String godName god = case god of Charon -> "PI:NAME:<NAME>END_PI" Nyx -> "Nyx" Hades -> "Hades" Hermes -> "Hermes" Aphrodite -> "Aphrodite" Ares -> "Ares" Demeter -> "Demeter" Dionysus -> "Dionysus" Poseidon -> "Poseidon" Athena -> "Athena" Artemis -> "Artemis" Zeus -> "Zeus" godColor : God -> Color godColor god = case god of Charon -> Color.fromRgba { red = 0.4 , green = 0 , blue = 0.706 , alpha = 1 } Nyx -> Color.fromRgba { red = 0.4 , green = 0 , blue = 0.706 , alpha = 1 } Hades -> Color.fromRgba { red = 0.776 , green = 0 , blue = 0 , alpha = 1 } Hermes -> Color.fromRgba { red = 1 , green = 0.35294117647058826 , blue = 0 , alpha = 1 } Aphrodite -> Color.fromRgba { red = 1 , green = 0.19607843137254902 , blue = 0.9411764705882353 , alpha = 1 } Ares -> Color.fromRgba { red = 1, green = 0.0784313725490196, blue = 0, alpha = 1 } Demeter -> Color.fromRgba { red = 0.631 , green = 0.702 , blue = 1 , alpha = 1 } Dionysus -> Color.fromRgba { red = 0.7843137254901961, green = 0, blue = 1, alpha = 1 } Poseidon -> Color.fromRgba { red = 0, green = 0.7843137254901961, blue = 1, alpha = 1 } Athena -> Color.fromRgba { red = 0.733 , green = 0.69 , blue = 0.373 , alpha = 1 } Artemis -> Color.fromRgba { red = 0.43137254901960786 , green = 1 , blue = 0 , alpha = 1 } Zeus -> Color.fromRgba { red = 1 , green = 1 , blue = 0.25098039215686274 , alpha = 1 } godIcon : God -> String godIcon god = "GUI/Screens/BoonSelectSymbols/" ++ (godName god) ++ ".png" basicBoons : GodData -> List Trait basicBoons data = data |> godTraits |> List.filter isBasicBoon dataBoon : GodData -> TraitId -> Maybe Trait dataBoon data id = data |> godTraits |> List.filter (hasId id) |> List.head boonsForSlot : SlotId -> Traits -> List Trait boonsForSlot slot (Traits {gods}) = gods |> List.concatMap basicBoons |> List.append miscBoons |> List.filter (isSlot slot) isSlot : SlotId -> Trait -> Bool isSlot target {slot} = slot == Just target slots : List SlotId slots = [ "Melee" , "Secondary" , "Ranged" , "Rush" , "Shout" ] iconForSlot : SlotId -> String iconForSlot slot = case slot of "Melee" -> "GUI/HUD/PrimaryBoons/SlotIcon_Attack_White.png" "Secondary" -> "GUI/HUD/PrimaryBoons/SlotIcon_Secondary_White.png" "Ranged" -> "GUI/HUD/PrimaryBoons/SlotIcon_Ranged_White.png" "Rush" -> "GUI/HUD/PrimaryBoons/SlotIcon_Dash_White.png" "Shout" -> "GUI/HUD/PrimaryBoons/SlotIcon_Wrath_White.png" _ -> "GUI/LockIcon/LockIcon0001.png" nameForSlot : SlotId -> String nameForSlot slot = case slot of "Melee" -> "Any Attack" "Secondary" -> "Any Secondary" "Ranged" -> "Any Ranged" "Rush" -> "Any Dash" "Shout" -> "Any Call" _ -> "Unknown Slot" metaUpgrades : List String metaUpgrades = [ "AmmoMetaUpgrade" , "ReloadAmmoMetaUpgrade" ] boonsOf : God -> Traits -> List Trait boonsOf target (Traits {gods}) = gods |> List.filter (\data -> dataGod data == target) |> List.concatMap basicBoons duoBoons : Traits -> List Trait duoBoons (Traits {duos}) = duos duoBoonsOf : God -> Traits -> List Trait duoBoonsOf target (Traits {duos}) = duos |> List.filter (\{boonType} -> case boonType of BasicBoon _ -> False DuoBoon a b -> a == target || b == target Keepsake -> False ) singleBoons : Traits -> List Trait singleBoons (Traits {gods}) = gods |> List.concatMap godTraits isBasicBoon : Trait -> Bool isBasicBoon {boonType} = case boonType of BasicBoon _ -> True DuoBoon _ _ -> False Keepsake -> True isDuoBoon : Trait -> Bool isDuoBoon {boonType} = case boonType of BasicBoon _ -> False DuoBoon _ _ -> True Keepsake -> False makeTraits : List GodData -> Traits makeTraits gods = gods |> tagLinkedBoons -- propagate to duos |> separateDuos loadPreprocessedGodsAndDuoBoons : List GodData -> List Trait -> Traits loadPreprocessedGodsAndDuoBoons basicGods duos = Traits { gods = basicGods , duos = duos , misc = miscBoons } -- see also: Traits.Decode.trinkets miscBoons : List Trait miscBoons = [ { icon = "GUI/Screens/WeaponEnchantmentIcons/bow_echantment_2.png" , trait = "BowLoadAmmoTrait" , name = "Aspect of Hera" , description = "Your {$Keywords.Cast} loads {!Icons.Ammo} into your next {$Keywords.Attack}, firing on impact." , tooltipData = Dict.empty , slot = Just "Weapon" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Charon , frame = CommonFrame } , { icon = "GUI/Screens/WeaponEnchantmentIcons/shield_enchantment_3.png" , trait = "ShieldLoadAmmoTrait" , name = "Aspect of Beowulf" , description = "You have {$Keywords.BeowulfAspect}, but take {#AltPenaltyFormat}{$TooltipData.TooltipDamageTaken:P} {#PreviousFormat}damage." , tooltipData = Dict.fromList [("TooltipDamageTaken",10)] , slot = Just "Weapon" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Charon , frame = CommonFrame } , { icon = "GUI/Screens/MirrorIcons/infernal soul.png" , trait = "AmmoMetaUpgrade" , name = "Infernal Soul" , description = "Raise your supply of {!Icons.Ammo} for your {#BoldFormatGraft}Cast{#PreviousFormat}, {#TooltipUpgradeFormat}+1 {#PreviousFormat}per rank." , tooltipData = Dict.empty , slot = Just "Soul" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Nyx , frame = KeepsakeFrame } , { icon = "GUI/Screens/MirrorBIcons/Stygian_Soul.png" , trait = "ReloadAmmoMetaUpgrade" , name = "Stygian Soul" , description = "Regenerate your {!Icons.Ammo} for your {#BoldFormatGraft}Cast {#PreviousFormat}{#ItalicFormat}(rather than pick it up){#PreviousFormat}, faster by {#TooltipUpgradeFormat}{$TempTextData.BaseValue} Sec. {#PreviousFormat}per rank." , tooltipData = Dict.fromList [("BaseValue",1)] , slot = Just "Soul" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = BasicBoon Nyx , frame = KeepsakeFrame } , { icon = "GUI/Screens/AwardMenu/badge_23.png" , trait = "HadesShoutKeepsake" , name = "Sigil of the Dead" , description = "Your {$Keywords.WrathHades} becomes {#BoldFormatGraft}Hades' Aid{#PreviousFormat}, which briefly makes you {#BoldFormatGraft}{$Keywords.Invisible}{#PreviousFormat}; your {$Keywords.WrathGauge} starts {#UpgradeFormat}{$TooltipData.TooltipSuperGain}% {#PreviousFormat} full." , tooltipData = Dict.fromList [("TooltipSuperGain",15)] , slot = Just "Keepsake" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.fromList [ "AphroditeShoutTrait" , "AresShoutTrait" , "DemeterShoutTrait" , "DionysusShoutTrait" , "PoseidonShoutTrait" , "AthenaShoutTrait" , "ArtemisShoutTrait" , "ZeusShoutTrait" ] , requirements = None , boonType = BasicBoon Hades , frame = CommonFrame } , { icon = "GUI/Screens/BoonIcons/Hades_01_Large.png" , trait = "HadesShoutTrait" , name = "PI:NAME:<NAME>END_PI" , description = "Your {$Keywords.WrathHades} briefly makes you turn {$Keywords.Invisible}." , tooltipData = Dict.empty , slot = Just "Shout" , requiredSlottedTrait = Nothing , requiredMetaUpgradeSelected = Nothing , requiredFalseTraits = Set.empty , requirements = None , boonType = Keepsake , frame = KeepsakeFrame } ] tagLinkedBoons : List GodData -> List GodData tagLinkedBoons gods = gods |> List.map (tagLinkedGodBoons gods) tagLinkedGodBoons : List GodData -> GodData -> GodData tagLinkedGodBoons gods (GodData god) = GodData { god | traits = god.traits |> List.map (tagLinkedBoon gods god.god) } tagLinkedBoon : List GodData -> God -> Trait -> Trait tagLinkedBoon gods god trait = case trait.boonType of Keepsake -> trait _ -> let boonType = boonTypeFromRequirements gods god trait.requirements in { trait | boonType = boonType , frame = case boonType of BasicBoon _ -> frameFromRequirements gods trait.requirements DuoBoon _ _ -> DuoFrame Keepsake -> KeepsakeFrame } boonTypeFromRequirements : List GodData -> God -> Requirements -> BoonType boonTypeFromRequirements gods god requirements = case requirements of None -> BasicBoon god OneOf set -> boonTypeFromGroup god (godOfSet gods set) OneFromEachSet list -> list |> List.map (godOfSet gods) |> List.foldr oneFromEachSetAccumulator (BasicBoon god) frameFromRequirements : List GodData -> Requirements -> Frame frameFromRequirements gods requirements = if legendaryRequirements gods requirements then LegendaryFrame else CommonFrame legendaryRequirements : List GodData -> Requirements -> Bool legendaryRequirements gods requirements = case requirements of None -> False OneOf set -> (setHasRequirements gods set) || (Set.member "FastClearDodgeBonusTrait" set) OneFromEachSet list -> True setHasRequirements : List GodData -> Set TraitId -> Bool setHasRequirements gods set = set |> Set.toList |> List.map (findBoonRequirements gods) |> List.any (\req -> req /= None && req /= OneOf (Set.singleton "ShieldLoadAmmoTrait") && req /= OneOf (Set.fromList ["BowLoadAmmoTrait", "ShieldLoadAmmoTrait"]) ) type GodsInGroup = Empty | One God | Many boonTypeFromGroup : God -> GodsInGroup -> BoonType boonTypeFromGroup default group = case group of Empty -> BasicBoon default One god -> BasicBoon god Many -> BasicBoon default oneFromEachSetAccumulator : GodsInGroup -> BoonType -> BoonType oneFromEachSetAccumulator group boonType = case (boonType, group) of (_, Many) -> boonType (_, Empty) -> boonType (BasicBoon a, One g) -> if a == g then BasicBoon a else DuoBoon a g (DuoBoon a b, One g) -> if a == g || b == g then DuoBoon a b else -- Debug.todo "too many gods" -- no way to punt boonType (Keepsake, _) -> boonType godOfSet : List GodData -> Set TraitId -> GodsInGroup godOfSet gods set = set |> Set.foldr (godAccumulator gods) Empty godAccumulator : List GodData -> TraitId -> GodsInGroup -> GodsInGroup godAccumulator gods id group = case (findBoonType gods id, group) of (_, Many) -> Many (Nothing, _) -> group (Just (Keepsake), _) -> group (Just (BasicBoon a), Empty) -> One a (Just (BasicBoon a), One b) -> if a == b then One a else Many (Just (DuoBoon _ _), _) -> Many findBoonType : List GodData -> TraitId -> Maybe BoonType findBoonType gods id = findGodBoon gods id |> Maybe.map .boonType findBoonRequirements : List GodData -> TraitId -> Requirements findBoonRequirements gods id = findGodBoon gods id |> Maybe.map .requirements |> Maybe.withDefault None findGodBoon : List GodData -> TraitId -> Maybe Trait findGodBoon gods id = gods |> List.concatMap godTraits |> List.filter (hasId id) |> List.head separateDuos : List GodData -> Traits separateDuos gods = let (basicGods, listOfDuos) = gods |> List.map extractDuos |> List.unzip duos = List.concat listOfDuos in loadPreprocessedGodsAndDuoBoons basicGods duos extractDuos : GodData -> (GodData, List Trait) extractDuos (GodData data) = let (duos, basic) = List.partition isDuoBoon data.traits in (GodData {data | traits = basic}, duos) godTraits : GodData -> List Trait godTraits (GodData data) = data.traits hasId : TraitId -> Trait -> Bool hasId id trait = trait.trait == id allTraits : Traits -> List Trait allTraits traits = traits |> allGods |> List.concatMap godTraits |> List.append (duoBoons traits) findBoon : Traits -> TraitId -> Maybe Trait findBoon traits id = traits |> allTraits |> List.append miscBoons |> List.filter (hasId id) |> List.head boonStatus : Set TraitId -> Set SlotId -> Set TraitId -> Trait -> BoonStatus boonStatus activeTraits activeSlots excludedTraits trait = if Set.member trait.trait activeTraits then Active else if Set.member trait.trait excludedTraits then Excluded else if boonHasRequiredSlottedTrait activeSlots trait && boonMeetsRequirements activeTraits trait then Available else Unavailable slotFilled : Set SlotId -> Trait -> Bool slotFilled activeSlots trait = case trait.slot of Just slot -> if Set.member slot activeSlots then True else False Nothing -> False boonHasRequiredSlottedTrait : Set SlotId -> Trait -> Bool boonHasRequiredSlottedTrait activeSlots trait = case trait.requiredSlottedTrait of Just slot -> if Set.member slot activeSlots then True else False Nothing -> True boonMeetsRequirements : Set TraitId -> Trait -> Bool boonMeetsRequirements activeTraits trait = case trait.requirements of None -> True OneOf set -> if Set.intersect activeTraits set |> Set.isEmpty |> not then True else False OneFromEachSet list -> if list |> List.all (Set.intersect activeTraits >> Set.isEmpty >> not) then True else False boonExcludedByRequirements : Set TraitId -> Trait -> Bool boonExcludedByRequirements excludedTraits trait = case trait.requirements of None -> False OneOf set -> if Set.diff set excludedTraits |> Set.isEmpty then True else False OneFromEachSet list -> if list |> List.any (\set -> Set.diff set excludedTraits |> Set.isEmpty) then True else False traitStatus : Set TraitId -> String -> Traits -> Dict TraitId BoonStatus traitStatus activeTraits metaUpgrade traits = let activeSlots = calculateActiveSlots activeTraits traits excludedTraits = calculateExcludedTraits activeTraits activeSlots metaUpgrade traits statusOfTraits = allTraits traits |> List.map (\trait -> (trait.trait, boonStatus activeTraits activeSlots excludedTraits trait)) statusOfSlots = slots |> List.map (\slot -> let id = "Any"++slot in ( id , if Set.member slot activeSlots then Active else Available ) ) statusOfMeta = metaUpgrades |> List.map (\id -> ( id , if id == metaUpgrade then Active else Excluded ) ) in statusOfTraits |> List.append statusOfSlots |> List.append statusOfMeta |> Dict.fromList addLayout : God -> Layout -> Traits -> Traits addLayout god layout (Traits traits) = Traits { traits | gods = List.map (\goddata -> case goddata of GodData data -> if data.god == god then GodData { data | layout = layout } else goddata ) traits.gods } calculateActiveLayoutGroups : Set TraitId -> List GodData -> List (Set Layout.GroupId) calculateActiveLayoutGroups activeTraits gods = gods |> List.map (\(GodData {layout}) -> Layout.calculateActiveGroups activeTraits layout) calculateActiveDuoSets : List GodData -> Set TraitId -> List Trait -> Set Layout.GroupId calculateActiveDuoSets gods activeTraits duos = duos |> List.foldl (\trait active -> calculateActiveSets gods activeTraits trait |> Set.union active) Set.empty calculateActiveSets : List GodData -> Set TraitId -> Trait -> Set Layout.GroupId calculateActiveSets gods activeTraits trait = case trait.requirements of None -> Set.empty OneOf set -> if Set.intersect activeTraits set |> Set.isEmpty |> not then activeRequirementSet gods trait set |> Maybe.map Set.singleton |> Maybe.withDefault Set.empty else Set.empty OneFromEachSet list -> list |> List.filter (Set.intersect activeTraits >> Set.isEmpty >> not) |> List.filterMap (activeRequirementSet gods trait) |> Set.fromList activeRequirementSet : List GodData -> Trait -> Set TraitId -> Maybe Layout.GroupId activeRequirementSet gods {trait} set = case godOfSet gods set of Empty -> Nothing One god -> Just ((godName god) ++ trait) Many -> Nothing calculateActiveSlots : Set TraitId -> Traits -> Set SlotId calculateActiveSlots activeTraits (Traits {gods}) = gods |> List.concatMap godTraits |> List.append miscBoons |> List.filter (\{trait} -> Set.member trait activeTraits) |> List.filterMap .slot |> Set.fromList calculateExcludedTraits : Set TraitId -> Set SlotId -> String -> Traits -> Set TraitId calculateExcludedTraits activeTraits activeSlots metaUpgrade (Traits {gods, duos} as traits) = let basics = gods |> List.concatMap godTraits all = allTraits traits in (Set.diff (Set.fromList ["ShieldLoadAmmoTrait", "BowLoadAmmoTrait"]) activeTraits) |> Set.union (calculateExcludedSlotTraits activeTraits activeSlots gods) |> Set.union (calculateExcludedIncompatibleTraits activeTraits all) |> Set.union (calculateExcludedMetaUpgradeTraits metaUpgrade all) |> calculateExcludedDerivedTraits basics -- first requirments |> calculateExcludedDerivedTraits basics -- legendary |> calculateExcludedDerivedTraits duos -- duos calculateExcludedSlotTraits : Set TraitId -> Set SlotId -> List GodData -> Set TraitId calculateExcludedSlotTraits activeTraits activeSlots gods = gods |> List.concatMap godTraits |> List.filter (\{trait} -> not <| Set.member trait activeTraits) |> List.filter (\trait -> slotFilled activeSlots trait) |> List.map .trait |> Set.fromList calculateExcludedIncompatibleTraits : Set TraitId -> List Trait -> Set TraitId calculateExcludedIncompatibleTraits activeTraits traits = traits |> List.filter (\{trait} -> not <| Set.member trait activeTraits) |> List.filter (\{requiredFalseTraits} -> Set.intersect activeTraits requiredFalseTraits |> Set.isEmpty |> not) |> List.map .trait |> Set.fromList calculateExcludedMetaUpgradeTraits : String -> List Trait -> Set TraitId calculateExcludedMetaUpgradeTraits metaUpgrade traits = traits |> List.filter (\{requiredMetaUpgradeSelected} -> case requiredMetaUpgradeSelected of Just req -> metaUpgrade /= req Nothing -> False ) |> List.map .trait |> Set.fromList calculateExcludedDerivedTraits : List Trait -> Set TraitId -> Set TraitId calculateExcludedDerivedTraits traits excludedTraits = traits |> List.filter (\trait -> boonExcludedByRequirements excludedTraits trait) |> List.map .trait |> Set.fromList |> Set.union excludedTraits
elm
[ { "context": "\"\"\n {\n viewer {\n id\n firstName\n lastName\n space {\n ", "end": 503, "score": 0.9958407879, "start": 494, "tag": "NAME", "value": "firstName" }, { "context": "iewer {\n id\n firstName\n lastName\n space {\n id\n name", "end": 522, "score": 0.9929008484, "start": 514, "tag": "NAME", "value": "lastName" }, { "context": " node {\n id\n firstName\n lastName\n }\n ", "end": 852, "score": 0.9986052513, "start": 843, "tag": "NAME", "value": "firstName" }, { "context": " id\n firstName\n lastName\n }\n cursor\n ", "end": 879, "score": 0.9959233999, "start": 871, "tag": "NAME", "value": "lastName" } ]
assets/elm/src/Query/AppState.elm
cas27/level
0
module Query.AppState exposing (request, Response) import Session exposing (Session) import Data.Space exposing (Space, spaceDecoder) import Data.User exposing (User, UserConnection, userDecoder, userConnectionDecoder) import Http import Json.Decode as Decode import Json.Decode.Pipeline as Pipeline import GraphQL type alias Response = { user : User , space : Space , users : UserConnection } query : String query = """ { viewer { id firstName lastName space { id name users(first: 10) { pageInfo { hasPreviousPage hasNextPage startCursor endCursor } edges { node { id firstName lastName } cursor } } } } } """ decoder : Decode.Decoder Response decoder = Decode.at [ "data", "viewer" ] <| (Pipeline.decode Response |> Pipeline.custom userDecoder |> Pipeline.custom (Decode.at [ "space" ] spaceDecoder) |> Pipeline.custom (Decode.at [ "space", "users" ] userConnectionDecoder) ) request : Session -> Http.Request Response request session = GraphQL.request session query Nothing decoder
10767
module Query.AppState exposing (request, Response) import Session exposing (Session) import Data.Space exposing (Space, spaceDecoder) import Data.User exposing (User, UserConnection, userDecoder, userConnectionDecoder) import Http import Json.Decode as Decode import Json.Decode.Pipeline as Pipeline import GraphQL type alias Response = { user : User , space : Space , users : UserConnection } query : String query = """ { viewer { id <NAME> <NAME> space { id name users(first: 10) { pageInfo { hasPreviousPage hasNextPage startCursor endCursor } edges { node { id <NAME> <NAME> } cursor } } } } } """ decoder : Decode.Decoder Response decoder = Decode.at [ "data", "viewer" ] <| (Pipeline.decode Response |> Pipeline.custom userDecoder |> Pipeline.custom (Decode.at [ "space" ] spaceDecoder) |> Pipeline.custom (Decode.at [ "space", "users" ] userConnectionDecoder) ) request : Session -> Http.Request Response request session = GraphQL.request session query Nothing decoder
true
module Query.AppState exposing (request, Response) import Session exposing (Session) import Data.Space exposing (Space, spaceDecoder) import Data.User exposing (User, UserConnection, userDecoder, userConnectionDecoder) import Http import Json.Decode as Decode import Json.Decode.Pipeline as Pipeline import GraphQL type alias Response = { user : User , space : Space , users : UserConnection } query : String query = """ { viewer { id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI space { id name users(first: 10) { pageInfo { hasPreviousPage hasNextPage startCursor endCursor } edges { node { id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI } cursor } } } } } """ decoder : Decode.Decoder Response decoder = Decode.at [ "data", "viewer" ] <| (Pipeline.decode Response |> Pipeline.custom userDecoder |> Pipeline.custom (Decode.at [ "space" ] spaceDecoder) |> Pipeline.custom (Decode.at [ "space", "users" ] userConnectionDecoder) ) request : Session -> Http.Request Response request session = GraphQL.request session query Nothing decoder
elm
[ { "context": "person : String\nperson = \"\"\"\n{\n\"id\":2,\"fullName\":\"Jason\",\"dob\":\"2014-02-10T00:00:00\",\"email\":\"jason@gmail", "end": 1598, "score": 0.9998068213, "start": 1593, "tag": "NAME", "value": "Jason" }, { "context": "ame\":\"Jason\",\"dob\":\"2014-02-10T00:00:00\",\"email\":\"jason@gmail.com\",\"mobilePhoneNumber\":\"98091234\",\"citizenship\":nul", "end": 1652, "score": 0.9999216199, "start": 1637, "tag": "EMAIL", "value": "jason@gmail.com" }, { "context": "metadata#Students\",\"value\":[\n{\n\"id\":2,\"fullName\":\"Jason\",\"dob\":\"2014-02-10T00:00:00\",\"email\":\"jason@gmail", "end": 1920, "score": 0.9997804165, "start": 1915, "tag": "NAME", "value": "Jason" }, { "context": "ame\":\"Jason\",\"dob\":\"2014-02-10T00:00:00\",\"email\":\"jason@gmail.com\",\"mobilePhoneNumber\":\"98091234\",\"citizenship\":nul", "end": 1974, "score": 0.9999265671, "start": 1959, "tag": "EMAIL", "value": "jason@gmail.com" }, { "context": "n\":null,\"salaryRange\":null\n},{\n\"id\":3,\"fullName\":\"Bob\",\"dob\":\"1997-12-25T00:00:00\",\"email\":\"bob@gmail.c", "end": 2125, "score": 0.999423027, "start": 2122, "tag": "NAME", "value": "Bob" }, { "context": "lName\":\"Bob\",\"dob\":\"1997-12-25T00:00:00\",\"email\":\"bob@gmail.com\",\"mobilePhoneNumber\":\"98088234\",\"citizenship\":nul", "end": 2177, "score": 0.9999281764, "start": 2164, "tag": "EMAIL", "value": "bob@gmail.com" }, { "context": "n\":null,\"salaryRange\":null\n},{\n\"id\":4,\"fullName\":\"John\",\"dob\":\"2001-02-10T00:00:00\",\"email\":\"john@gmail.", "end": 2329, "score": 0.999545455, "start": 2325, "tag": "NAME", "value": "John" }, { "context": "Name\":\"John\",\"dob\":\"2001-02-10T00:00:00\",\"email\":\"john@gmail.com\",\"mobilePhoneNumber\":\"89091234\",\"citizenship\":nul", "end": 2382, "score": 0.9999267459, "start": 2368, "tag": "EMAIL", "value": "john@gmail.com" } ]
OdataDecoder.elm
billstclair/elm-odata-decoder
1
module OdataDecoder exposing ( Odata, Person, decodePerson, decodeOdata , odata, person ) import Json.Decode as JD exposing ( Decoder, string, int, nullable ) import Json.Decode.Pipeline exposing ( decode, required, optional ) type alias Odata = { metadata : String , value : List Person } type alias Person = { id : Int , fullName : String , dob : String , email : String , mobilePhoneNumber : String , citizenship : Maybe String , idType : Maybe String , idNumber : Maybe String , highestEducation : Maybe String , salaryRange : Maybe String } decodeOdata : String -> Result String Odata decodeOdata string = JD.decodeString odataDecoder string odataDecoder : Decoder Odata odataDecoder = decode Odata |> required "odata.metadata" string |> required "value" (JD.list personDecoder) decodePerson : String -> Result String Person decodePerson string = JD.decodeString personDecoder string personDecoder : Decoder Person personDecoder = decode Person |> required "id" int |> required "fullName" string |> required "dob" string |> required "email" string |> required "mobilePhoneNumber" string |> required "citizenship" (nullable string) |> required "idType" (nullable string) |> required "idNumber" (nullable string) |> required "highestEducation" (nullable string) |> required "salaryRange" (nullable string) person : String person = """ { "id":2,"fullName":"Jason","dob":"2014-02-10T00:00:00","email":"jason@gmail.com","mobilePhoneNumber":"98091234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null } """ odata : String odata = """ { "odata.metadata":"http://localhost:52134/odata/$metadata#Students","value":[ { "id":2,"fullName":"Jason","dob":"2014-02-10T00:00:00","email":"jason@gmail.com","mobilePhoneNumber":"98091234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null },{ "id":3,"fullName":"Bob","dob":"1997-12-25T00:00:00","email":"bob@gmail.com","mobilePhoneNumber":"98088234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null },{ "id":4,"fullName":"John","dob":"2001-02-10T00:00:00","email":"john@gmail.com","mobilePhoneNumber":"89091234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null } ] } """
50798
module OdataDecoder exposing ( Odata, Person, decodePerson, decodeOdata , odata, person ) import Json.Decode as JD exposing ( Decoder, string, int, nullable ) import Json.Decode.Pipeline exposing ( decode, required, optional ) type alias Odata = { metadata : String , value : List Person } type alias Person = { id : Int , fullName : String , dob : String , email : String , mobilePhoneNumber : String , citizenship : Maybe String , idType : Maybe String , idNumber : Maybe String , highestEducation : Maybe String , salaryRange : Maybe String } decodeOdata : String -> Result String Odata decodeOdata string = JD.decodeString odataDecoder string odataDecoder : Decoder Odata odataDecoder = decode Odata |> required "odata.metadata" string |> required "value" (JD.list personDecoder) decodePerson : String -> Result String Person decodePerson string = JD.decodeString personDecoder string personDecoder : Decoder Person personDecoder = decode Person |> required "id" int |> required "fullName" string |> required "dob" string |> required "email" string |> required "mobilePhoneNumber" string |> required "citizenship" (nullable string) |> required "idType" (nullable string) |> required "idNumber" (nullable string) |> required "highestEducation" (nullable string) |> required "salaryRange" (nullable string) person : String person = """ { "id":2,"fullName":"<NAME>","dob":"2014-02-10T00:00:00","email":"<EMAIL>","mobilePhoneNumber":"98091234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null } """ odata : String odata = """ { "odata.metadata":"http://localhost:52134/odata/$metadata#Students","value":[ { "id":2,"fullName":"<NAME>","dob":"2014-02-10T00:00:00","email":"<EMAIL>","mobilePhoneNumber":"98091234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null },{ "id":3,"fullName":"<NAME>","dob":"1997-12-25T00:00:00","email":"<EMAIL>","mobilePhoneNumber":"98088234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null },{ "id":4,"fullName":"<NAME>","dob":"2001-02-10T00:00:00","email":"<EMAIL>","mobilePhoneNumber":"89091234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null } ] } """
true
module OdataDecoder exposing ( Odata, Person, decodePerson, decodeOdata , odata, person ) import Json.Decode as JD exposing ( Decoder, string, int, nullable ) import Json.Decode.Pipeline exposing ( decode, required, optional ) type alias Odata = { metadata : String , value : List Person } type alias Person = { id : Int , fullName : String , dob : String , email : String , mobilePhoneNumber : String , citizenship : Maybe String , idType : Maybe String , idNumber : Maybe String , highestEducation : Maybe String , salaryRange : Maybe String } decodeOdata : String -> Result String Odata decodeOdata string = JD.decodeString odataDecoder string odataDecoder : Decoder Odata odataDecoder = decode Odata |> required "odata.metadata" string |> required "value" (JD.list personDecoder) decodePerson : String -> Result String Person decodePerson string = JD.decodeString personDecoder string personDecoder : Decoder Person personDecoder = decode Person |> required "id" int |> required "fullName" string |> required "dob" string |> required "email" string |> required "mobilePhoneNumber" string |> required "citizenship" (nullable string) |> required "idType" (nullable string) |> required "idNumber" (nullable string) |> required "highestEducation" (nullable string) |> required "salaryRange" (nullable string) person : String person = """ { "id":2,"fullName":"PI:NAME:<NAME>END_PI","dob":"2014-02-10T00:00:00","email":"PI:EMAIL:<EMAIL>END_PI","mobilePhoneNumber":"98091234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null } """ odata : String odata = """ { "odata.metadata":"http://localhost:52134/odata/$metadata#Students","value":[ { "id":2,"fullName":"PI:NAME:<NAME>END_PI","dob":"2014-02-10T00:00:00","email":"PI:EMAIL:<EMAIL>END_PI","mobilePhoneNumber":"98091234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null },{ "id":3,"fullName":"PI:NAME:<NAME>END_PI","dob":"1997-12-25T00:00:00","email":"PI:EMAIL:<EMAIL>END_PI","mobilePhoneNumber":"98088234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null },{ "id":4,"fullName":"PI:NAME:<NAME>END_PI","dob":"2001-02-10T00:00:00","email":"PI:EMAIL:<EMAIL>END_PI","mobilePhoneNumber":"89091234","citizenship":null,"idType":null,"idNumber":null,"highestEducation":null,"salaryRange":null } ] } """
elm
[ { "context": "ameChange username ->\n ( { model | username = username }, Cmd.none )\n\n PasswordChange password ->\n ", "end": 315, "score": 0.9370974302, "start": 307, "tag": "USERNAME", "value": "username" }, { "context": "ordChange password ->\n ( { model | password = password }, Cmd.none )\n", "end": 399, "score": 0.9973256588, "start": 391, "tag": "PASSWORD", "value": "password" } ]
client/elm/Pages/Login/Update.elm
oamaok/kinko
1
module Pages.Login.Update exposing (update) import Pages.Login.Model exposing (Msg(..), Model, initialModel) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ClearCredentials -> ( initialModel, Cmd.none ) UsernameChange username -> ( { model | username = username }, Cmd.none ) PasswordChange password -> ( { model | password = password }, Cmd.none )
61219
module Pages.Login.Update exposing (update) import Pages.Login.Model exposing (Msg(..), Model, initialModel) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ClearCredentials -> ( initialModel, Cmd.none ) UsernameChange username -> ( { model | username = username }, Cmd.none ) PasswordChange password -> ( { model | password = <PASSWORD> }, Cmd.none )
true
module Pages.Login.Update exposing (update) import Pages.Login.Model exposing (Msg(..), Model, initialModel) update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of ClearCredentials -> ( initialModel, Cmd.none ) UsernameChange username -> ( { model | username = username }, Cmd.none ) PasswordChange password -> ( { model | password = PI:PASSWORD:<PASSWORD>END_PI }, Cmd.none )
elm
[ { "context": "y \"\n , a [ href \"https://twitter.com/irrwitz\"\n , class \"button\"\n ", "end": 5206, "score": 0.9996993542, "start": 5199, "tag": "USERNAME", "value": "irrwitz" }, { "context": "lank\"\n ]\n [ text \"@irrwitz\" ]\n ]\n , div [ style [(\"float", "end": 5333, "score": 0.9997388124, "start": 5324, "tag": "USERNAME", "value": "\"@irrwitz" }, { "context": "on \"\n , a [ href \"https://github.com/irrwitz/elm-css-color-guess-game\"\n , cla", "end": 5485, "score": 0.9996722341, "start": 5478, "tag": "USERNAME", "value": "irrwitz" }, { "context": "\"MistyRose\"\n , \"Moccasin\"\n , \"NavajoWhite\"\n , \"Navy\"\n , \"OldLace\"\n , \"Olive\"\n , \"OliveDrab\"\n , \"O", "end": 7488, "score": 0.7726182342, "start": 7484, "tag": "NAME", "value": "Navy" } ]
10-New-Game.elm
irrwitz/elm-css-color-game
1
import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Random import Array import String import Random.Array exposing (shuffle) port random : Int type Action = NoOp | GuessColor String | NewGame Int | DefaultNewGame type alias GameSize = Int gameSize = 80 type alias Model = { colors : List String , randomColor : (Random.Seed, String) , correctGuesses : Int , wrongGuesses : Int , wrongColor : String } initialModel : Model initialModel = let colors = filterColors allColors 40 random in { colors = colors , randomColor = nextRandomColor colors (Random.initialSeed random) , correctGuesses = 0 , wrongGuesses = 0 , wrongColor = "" } filterColors : List String -> Int -> Int -> List String filterColors colors gameSize randomInt = let colorArray = Array.fromList allColors shuffled = shuffle colorArray seed = Random.initialSeed randomInt listShuffled = Array.toList (fst <| Random.generate shuffled seed) listValues = List.take gameSize listShuffled in listValues update : Action -> Model -> Model update action model = case action of NoOp -> model DefaultNewGame -> { model | colors = filterColors allColors (List.length model.colors) random , randomColor = nextRandomColor model.colors (fst model.randomColor) , correctGuesses = 0 , wrongGuesses = 0 , wrongColor = "" } NewGame gameSize -> { model | colors = filterColors allColors gameSize random , randomColor = nextRandomColor model.colors (fst model.randomColor) , correctGuesses = 0 , wrongGuesses = 0 , wrongColor = "" } GuessColor color -> if color == snd model.randomColor then { model | randomColor = nextRandomColor model.colors (fst model.randomColor) , correctGuesses = model.correctGuesses + 1 , wrongColor = "" } else { model | wrongGuesses = model.wrongGuesses + 1 , wrongColor = color } guessInbox : Signal.Mailbox Action guessInbox = Signal.mailbox NoOp actions : Signal Action actions = guessInbox.signal nextRandomColor : List String -> Random.Seed -> (Random.Seed, String) nextRandomColor colors = nextRandom colors nextRandom : List String -> Random.Seed -> (Random.Seed, String) nextRandom colors seed = let r = Random.generate (Random.int 0 (List.length colors - 1)) seed array = Array.fromList colors result = Maybe.withDefault "" (Array.get (fst r) array) in (snd r, result) upperView : Model -> Html upperView model = div [ class "upperView" ] [ p [ class "firstRow" ] [ a [ href "#" , onClick guessInbox.address DefaultNewGame , class "newGame" ] [ text "New Game" ] , newGameSection ] , p [ ] [ text "Click color " , span [ class "randomColorStyle" ] [ text (snd model.randomColor) ] , text " " , span [ ] [ span [ ] [ text (toString model.correctGuesses) , text " / " ] , span [ ] [ span [ ] [ text (toString model.wrongGuesses) ] ] ] , if (String.length model.wrongColor > 0) then p [ ] [ text "No, was " , span [ style [ ("font-style", "italic") ] ] [ text model.wrongColor ] ] else p [ ] [ ] ] ] newGameSection : Html newGameSection = span [ style [("float", "left")] ] [ text "Colors: " , span [ class "gameSize" ] [ a [ href "#" , onClick guessInbox.address (NewGame 40) ] [ text " 40 " ] , a [ href "#" , onClick guessInbox.address (NewGame 80) ] [ text " 80 " ] , a [ href "#" , onClick guessInbox.address (NewGame 120) ] [ text " 120 " ] , a [ href "#" , onClick guessInbox.address (NewGame (List.length allColors)) ] [ text " All " ] ] ] singleColorView : String -> Html singleColorView color = li [ ] [ a [ href "#" , onClick guessInbox.address (GuessColor color) , style [ colorStyle color ] , class "colorStyle" ] [ text " " ] ] view : Signal.Address Action -> Model -> Html view act model = div [ id "mainDiv" ] [ upperView model , ul [ ] (List.map singleColorView model.colors) , div [ style [("padding-top", "15px")] ] [ div [ style [("float", "left")] ] [ text "Build by " , a [ href "https://twitter.com/irrwitz" , class "button" , target "_blank" ] [ text "@irrwitz" ] ] , div [ style [("float", "right")] ] [ text " Source on " , a [ href "https://github.com/irrwitz/elm-css-color-guess-game" , class "button" , target "_blank" ] [ text "Github"] ] ] ] colorStyle color = ("background-color", color) model : Signal Model model = Signal.foldp update initialModel actions main : Signal Html main = Signal.map (view guessInbox.address) model allColors : List String allColors = [ "AliceBlue" , "AntiqueWhite" , "Aqua" , "Aquamarine" , "Azure" , "Beige" , "Bisque" , "Black" , "BlanchedAlmond" , "Blue" , "BlueViolet" , "Brown" , "BurlyWood" , "CadetBlue" , "Chartreuse" , "Chocolate" , "Coral" , "CornflowerBlue" , "Cornsilk" , "Crimson" , "Cyan" , "DarkBlue" , "DarkCyan" , "DarkGoldenRod" , "DarkGray" , "DarkGreen" , "DarkKhaki" , "DarkMagenta" , "DarkOliveGreen" , "DarkOrange" , "DarkOrchid" , "DarkRed" , "DarkSalmon" , "DarkSeaGreen" , "DarkSlateBlue" , "DarkSlateGray" , "DarkTurquoise" , "DarkViolet" , "DeepPink" , "DeepSkyBlue" , "DimGray" , "DodgerBlue" , "FireBrick" , "FloralWhite" , "ForestGreen" , "Fuchsia" , "Gainsboro" , "GhostWhite" , "Gold" , "GoldenRod" , "Gray" , "Green" , "GreenYellow" , "HoneyDew" , "HotPink" , "IndianRed " , "Indigo " , "Ivory" , "Khaki" , "Lavender" , "LavenderBlush" , "LawnGreen" , "LemonChiffon" , "LightBlue" , "LightCoral" , "LightCyan" , "LightGoldenRodYellow" , "LightGray" , "LightGreen" , "LightPink" , "LightSalmon" , "LightSeaGreen" , "LightSkyBlue" , "LightSlateGray" , "LightSteelBlue" , "LightYellow" , "Lime" , "LimeGreen" , "Linen" , "Magenta" , "Maroon" , "MediumAquaMarine" , "MediumBlue" , "MediumOrchid" , "MediumPurple" , "MediumSeaGreen" , "MediumSlateBlue" , "MediumSpringGreen" , "MediumTurquoise" , "MediumVioletRed" , "MidnightBlue" , "MintCream" , "MistyRose" , "Moccasin" , "NavajoWhite" , "Navy" , "OldLace" , "Olive" , "OliveDrab" , "Orange" , "OrangeRed" , "Orchid" , "PaleGoldenRod" , "PaleGreen" , "PaleTurquoise" , "PaleVioletRed" , "PapayaWhip" , "PeachPuff" , "Peru" , "Pink" , "Plum" , "PowderBlue" , "Purple" , "RebeccaPurple" , "Red" , "RosyBrown" , "RoyalBlue" , "SaddleBrown" , "Salmon" , "SandyBrown" , "SeaGreen" , "SeaShell" , "Sienna" , "Silver" , "SkyBlue" , "SlateBlue" , "SlateGray" , "Snow" , "SpringGreen" , "SteelBlue" , "Tan" , "Teal" , "Thistle" , "Tomato" , "Turquoise" , "Violet" , "Wheat" , "White" , "WhiteSmoke" , "Yellow" , "YellowGreen" ]
46373
import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Random import Array import String import Random.Array exposing (shuffle) port random : Int type Action = NoOp | GuessColor String | NewGame Int | DefaultNewGame type alias GameSize = Int gameSize = 80 type alias Model = { colors : List String , randomColor : (Random.Seed, String) , correctGuesses : Int , wrongGuesses : Int , wrongColor : String } initialModel : Model initialModel = let colors = filterColors allColors 40 random in { colors = colors , randomColor = nextRandomColor colors (Random.initialSeed random) , correctGuesses = 0 , wrongGuesses = 0 , wrongColor = "" } filterColors : List String -> Int -> Int -> List String filterColors colors gameSize randomInt = let colorArray = Array.fromList allColors shuffled = shuffle colorArray seed = Random.initialSeed randomInt listShuffled = Array.toList (fst <| Random.generate shuffled seed) listValues = List.take gameSize listShuffled in listValues update : Action -> Model -> Model update action model = case action of NoOp -> model DefaultNewGame -> { model | colors = filterColors allColors (List.length model.colors) random , randomColor = nextRandomColor model.colors (fst model.randomColor) , correctGuesses = 0 , wrongGuesses = 0 , wrongColor = "" } NewGame gameSize -> { model | colors = filterColors allColors gameSize random , randomColor = nextRandomColor model.colors (fst model.randomColor) , correctGuesses = 0 , wrongGuesses = 0 , wrongColor = "" } GuessColor color -> if color == snd model.randomColor then { model | randomColor = nextRandomColor model.colors (fst model.randomColor) , correctGuesses = model.correctGuesses + 1 , wrongColor = "" } else { model | wrongGuesses = model.wrongGuesses + 1 , wrongColor = color } guessInbox : Signal.Mailbox Action guessInbox = Signal.mailbox NoOp actions : Signal Action actions = guessInbox.signal nextRandomColor : List String -> Random.Seed -> (Random.Seed, String) nextRandomColor colors = nextRandom colors nextRandom : List String -> Random.Seed -> (Random.Seed, String) nextRandom colors seed = let r = Random.generate (Random.int 0 (List.length colors - 1)) seed array = Array.fromList colors result = Maybe.withDefault "" (Array.get (fst r) array) in (snd r, result) upperView : Model -> Html upperView model = div [ class "upperView" ] [ p [ class "firstRow" ] [ a [ href "#" , onClick guessInbox.address DefaultNewGame , class "newGame" ] [ text "New Game" ] , newGameSection ] , p [ ] [ text "Click color " , span [ class "randomColorStyle" ] [ text (snd model.randomColor) ] , text " " , span [ ] [ span [ ] [ text (toString model.correctGuesses) , text " / " ] , span [ ] [ span [ ] [ text (toString model.wrongGuesses) ] ] ] , if (String.length model.wrongColor > 0) then p [ ] [ text "No, was " , span [ style [ ("font-style", "italic") ] ] [ text model.wrongColor ] ] else p [ ] [ ] ] ] newGameSection : Html newGameSection = span [ style [("float", "left")] ] [ text "Colors: " , span [ class "gameSize" ] [ a [ href "#" , onClick guessInbox.address (NewGame 40) ] [ text " 40 " ] , a [ href "#" , onClick guessInbox.address (NewGame 80) ] [ text " 80 " ] , a [ href "#" , onClick guessInbox.address (NewGame 120) ] [ text " 120 " ] , a [ href "#" , onClick guessInbox.address (NewGame (List.length allColors)) ] [ text " All " ] ] ] singleColorView : String -> Html singleColorView color = li [ ] [ a [ href "#" , onClick guessInbox.address (GuessColor color) , style [ colorStyle color ] , class "colorStyle" ] [ text " " ] ] view : Signal.Address Action -> Model -> Html view act model = div [ id "mainDiv" ] [ upperView model , ul [ ] (List.map singleColorView model.colors) , div [ style [("padding-top", "15px")] ] [ div [ style [("float", "left")] ] [ text "Build by " , a [ href "https://twitter.com/irrwitz" , class "button" , target "_blank" ] [ text "@irrwitz" ] ] , div [ style [("float", "right")] ] [ text " Source on " , a [ href "https://github.com/irrwitz/elm-css-color-guess-game" , class "button" , target "_blank" ] [ text "Github"] ] ] ] colorStyle color = ("background-color", color) model : Signal Model model = Signal.foldp update initialModel actions main : Signal Html main = Signal.map (view guessInbox.address) model allColors : List String allColors = [ "AliceBlue" , "AntiqueWhite" , "Aqua" , "Aquamarine" , "Azure" , "Beige" , "Bisque" , "Black" , "BlanchedAlmond" , "Blue" , "BlueViolet" , "Brown" , "BurlyWood" , "CadetBlue" , "Chartreuse" , "Chocolate" , "Coral" , "CornflowerBlue" , "Cornsilk" , "Crimson" , "Cyan" , "DarkBlue" , "DarkCyan" , "DarkGoldenRod" , "DarkGray" , "DarkGreen" , "DarkKhaki" , "DarkMagenta" , "DarkOliveGreen" , "DarkOrange" , "DarkOrchid" , "DarkRed" , "DarkSalmon" , "DarkSeaGreen" , "DarkSlateBlue" , "DarkSlateGray" , "DarkTurquoise" , "DarkViolet" , "DeepPink" , "DeepSkyBlue" , "DimGray" , "DodgerBlue" , "FireBrick" , "FloralWhite" , "ForestGreen" , "Fuchsia" , "Gainsboro" , "GhostWhite" , "Gold" , "GoldenRod" , "Gray" , "Green" , "GreenYellow" , "HoneyDew" , "HotPink" , "IndianRed " , "Indigo " , "Ivory" , "Khaki" , "Lavender" , "LavenderBlush" , "LawnGreen" , "LemonChiffon" , "LightBlue" , "LightCoral" , "LightCyan" , "LightGoldenRodYellow" , "LightGray" , "LightGreen" , "LightPink" , "LightSalmon" , "LightSeaGreen" , "LightSkyBlue" , "LightSlateGray" , "LightSteelBlue" , "LightYellow" , "Lime" , "LimeGreen" , "Linen" , "Magenta" , "Maroon" , "MediumAquaMarine" , "MediumBlue" , "MediumOrchid" , "MediumPurple" , "MediumSeaGreen" , "MediumSlateBlue" , "MediumSpringGreen" , "MediumTurquoise" , "MediumVioletRed" , "MidnightBlue" , "MintCream" , "MistyRose" , "Moccasin" , "NavajoWhite" , "<NAME>" , "OldLace" , "Olive" , "OliveDrab" , "Orange" , "OrangeRed" , "Orchid" , "PaleGoldenRod" , "PaleGreen" , "PaleTurquoise" , "PaleVioletRed" , "PapayaWhip" , "PeachPuff" , "Peru" , "Pink" , "Plum" , "PowderBlue" , "Purple" , "RebeccaPurple" , "Red" , "RosyBrown" , "RoyalBlue" , "SaddleBrown" , "Salmon" , "SandyBrown" , "SeaGreen" , "SeaShell" , "Sienna" , "Silver" , "SkyBlue" , "SlateBlue" , "SlateGray" , "Snow" , "SpringGreen" , "SteelBlue" , "Tan" , "Teal" , "Thistle" , "Tomato" , "Turquoise" , "Violet" , "Wheat" , "White" , "WhiteSmoke" , "Yellow" , "YellowGreen" ]
true
import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Random import Array import String import Random.Array exposing (shuffle) port random : Int type Action = NoOp | GuessColor String | NewGame Int | DefaultNewGame type alias GameSize = Int gameSize = 80 type alias Model = { colors : List String , randomColor : (Random.Seed, String) , correctGuesses : Int , wrongGuesses : Int , wrongColor : String } initialModel : Model initialModel = let colors = filterColors allColors 40 random in { colors = colors , randomColor = nextRandomColor colors (Random.initialSeed random) , correctGuesses = 0 , wrongGuesses = 0 , wrongColor = "" } filterColors : List String -> Int -> Int -> List String filterColors colors gameSize randomInt = let colorArray = Array.fromList allColors shuffled = shuffle colorArray seed = Random.initialSeed randomInt listShuffled = Array.toList (fst <| Random.generate shuffled seed) listValues = List.take gameSize listShuffled in listValues update : Action -> Model -> Model update action model = case action of NoOp -> model DefaultNewGame -> { model | colors = filterColors allColors (List.length model.colors) random , randomColor = nextRandomColor model.colors (fst model.randomColor) , correctGuesses = 0 , wrongGuesses = 0 , wrongColor = "" } NewGame gameSize -> { model | colors = filterColors allColors gameSize random , randomColor = nextRandomColor model.colors (fst model.randomColor) , correctGuesses = 0 , wrongGuesses = 0 , wrongColor = "" } GuessColor color -> if color == snd model.randomColor then { model | randomColor = nextRandomColor model.colors (fst model.randomColor) , correctGuesses = model.correctGuesses + 1 , wrongColor = "" } else { model | wrongGuesses = model.wrongGuesses + 1 , wrongColor = color } guessInbox : Signal.Mailbox Action guessInbox = Signal.mailbox NoOp actions : Signal Action actions = guessInbox.signal nextRandomColor : List String -> Random.Seed -> (Random.Seed, String) nextRandomColor colors = nextRandom colors nextRandom : List String -> Random.Seed -> (Random.Seed, String) nextRandom colors seed = let r = Random.generate (Random.int 0 (List.length colors - 1)) seed array = Array.fromList colors result = Maybe.withDefault "" (Array.get (fst r) array) in (snd r, result) upperView : Model -> Html upperView model = div [ class "upperView" ] [ p [ class "firstRow" ] [ a [ href "#" , onClick guessInbox.address DefaultNewGame , class "newGame" ] [ text "New Game" ] , newGameSection ] , p [ ] [ text "Click color " , span [ class "randomColorStyle" ] [ text (snd model.randomColor) ] , text " " , span [ ] [ span [ ] [ text (toString model.correctGuesses) , text " / " ] , span [ ] [ span [ ] [ text (toString model.wrongGuesses) ] ] ] , if (String.length model.wrongColor > 0) then p [ ] [ text "No, was " , span [ style [ ("font-style", "italic") ] ] [ text model.wrongColor ] ] else p [ ] [ ] ] ] newGameSection : Html newGameSection = span [ style [("float", "left")] ] [ text "Colors: " , span [ class "gameSize" ] [ a [ href "#" , onClick guessInbox.address (NewGame 40) ] [ text " 40 " ] , a [ href "#" , onClick guessInbox.address (NewGame 80) ] [ text " 80 " ] , a [ href "#" , onClick guessInbox.address (NewGame 120) ] [ text " 120 " ] , a [ href "#" , onClick guessInbox.address (NewGame (List.length allColors)) ] [ text " All " ] ] ] singleColorView : String -> Html singleColorView color = li [ ] [ a [ href "#" , onClick guessInbox.address (GuessColor color) , style [ colorStyle color ] , class "colorStyle" ] [ text " " ] ] view : Signal.Address Action -> Model -> Html view act model = div [ id "mainDiv" ] [ upperView model , ul [ ] (List.map singleColorView model.colors) , div [ style [("padding-top", "15px")] ] [ div [ style [("float", "left")] ] [ text "Build by " , a [ href "https://twitter.com/irrwitz" , class "button" , target "_blank" ] [ text "@irrwitz" ] ] , div [ style [("float", "right")] ] [ text " Source on " , a [ href "https://github.com/irrwitz/elm-css-color-guess-game" , class "button" , target "_blank" ] [ text "Github"] ] ] ] colorStyle color = ("background-color", color) model : Signal Model model = Signal.foldp update initialModel actions main : Signal Html main = Signal.map (view guessInbox.address) model allColors : List String allColors = [ "AliceBlue" , "AntiqueWhite" , "Aqua" , "Aquamarine" , "Azure" , "Beige" , "Bisque" , "Black" , "BlanchedAlmond" , "Blue" , "BlueViolet" , "Brown" , "BurlyWood" , "CadetBlue" , "Chartreuse" , "Chocolate" , "Coral" , "CornflowerBlue" , "Cornsilk" , "Crimson" , "Cyan" , "DarkBlue" , "DarkCyan" , "DarkGoldenRod" , "DarkGray" , "DarkGreen" , "DarkKhaki" , "DarkMagenta" , "DarkOliveGreen" , "DarkOrange" , "DarkOrchid" , "DarkRed" , "DarkSalmon" , "DarkSeaGreen" , "DarkSlateBlue" , "DarkSlateGray" , "DarkTurquoise" , "DarkViolet" , "DeepPink" , "DeepSkyBlue" , "DimGray" , "DodgerBlue" , "FireBrick" , "FloralWhite" , "ForestGreen" , "Fuchsia" , "Gainsboro" , "GhostWhite" , "Gold" , "GoldenRod" , "Gray" , "Green" , "GreenYellow" , "HoneyDew" , "HotPink" , "IndianRed " , "Indigo " , "Ivory" , "Khaki" , "Lavender" , "LavenderBlush" , "LawnGreen" , "LemonChiffon" , "LightBlue" , "LightCoral" , "LightCyan" , "LightGoldenRodYellow" , "LightGray" , "LightGreen" , "LightPink" , "LightSalmon" , "LightSeaGreen" , "LightSkyBlue" , "LightSlateGray" , "LightSteelBlue" , "LightYellow" , "Lime" , "LimeGreen" , "Linen" , "Magenta" , "Maroon" , "MediumAquaMarine" , "MediumBlue" , "MediumOrchid" , "MediumPurple" , "MediumSeaGreen" , "MediumSlateBlue" , "MediumSpringGreen" , "MediumTurquoise" , "MediumVioletRed" , "MidnightBlue" , "MintCream" , "MistyRose" , "Moccasin" , "NavajoWhite" , "PI:NAME:<NAME>END_PI" , "OldLace" , "Olive" , "OliveDrab" , "Orange" , "OrangeRed" , "Orchid" , "PaleGoldenRod" , "PaleGreen" , "PaleTurquoise" , "PaleVioletRed" , "PapayaWhip" , "PeachPuff" , "Peru" , "Pink" , "Plum" , "PowderBlue" , "Purple" , "RebeccaPurple" , "Red" , "RosyBrown" , "RoyalBlue" , "SaddleBrown" , "Salmon" , "SandyBrown" , "SeaGreen" , "SeaShell" , "Sienna" , "Silver" , "SkyBlue" , "SlateBlue" , "SlateGray" , "Snow" , "SpringGreen" , "SteelBlue" , "Tan" , "Teal" , "Thistle" , "Tomato" , "Turquoise" , "Violet" , "Wheat" , "White" , "WhiteSmoke" , "Yellow" , "YellowGreen" ]
elm
[ { "context": " [ a [ href \"https://twitter.com/startupC12\", class \"icon icon-twitter\" ]\n ", "end": 2656, "score": 0.9994210601, "start": 2646, "tag": "USERNAME", "value": "startupC12" }, { "context": " [ a [ href \"https://github.com/betagouv/ClasseA12\", class \"icon icon-github\" ]\n ", "end": 2901, "score": 0.9996035695, "start": 2893, "tag": "USERNAME", "value": "betagouv" }, { "context": " li []\n [ a [ href \"mailto:contact@classea12.beta.gouv.fr?subject=Classes à 12 sur beta.gouv.fr\", class \"ic", "end": 3164, "score": 0.9999219775, "start": 3134, "tag": "EMAIL", "value": "contact@classea12.beta.gouv.fr" } ]
src/Views/Page.elm
magopian/ClasseA12
3
module Views.Page exposing (ActivePage(..), Config, frame) import Browser exposing (Document) import Data.Session exposing (Session) import Html exposing (..) import Html.Attributes exposing (alt, class, classList, href, src, title) import Html.Events exposing (onClick) import Route type ActivePage = Home | About | Participate | Newsletter | CGU | Convention | PrivacyPolicy | Admin | Video | NotFound type alias Config = { session : Session , activePage : ActivePage } frame : Config -> ( String, List (Html.Html msg) ) -> Document msg frame config ( title, content ) = { title = title ++ " | Classe à 12" , body = [ viewHeader config ] ++ content ++ [ viewFooter ] } viewHeader : Config -> Html msg viewHeader { activePage } = let linkMaybeActive page route caption = li [ class "nav__item" ] [ a [ Route.href route , classList [ ( "active", page == activePage ) ] ] [ text caption ] ] in header [ class "navbar" ] [ div [ class "navbar__container" ] [ a [ class "navbar__home" , Route.href Route.Home ] [ img [ src "/logo.png" , alt "logo" , class "navbar__logo" ] [] , text "classea12.beta.gouv.fr" ] , nav [] [ ul [ class "nav__links" ] [ linkMaybeActive Home Route.Home "Nos vidéos" , linkMaybeActive About Route.About "Classe à 12 ?" , linkMaybeActive Participate Route.Participate "Je participe !" , linkMaybeActive Newsletter Route.Newsletter "Inscrivez-vous à notre infolettre" ] ] ] ] viewFooter : Html msg viewFooter = footer [ class "footer" ] [ div [ class "container" ] [ div [ class "footer__logo" ] [ img [ src "//res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_300,w_300,f_auto,q_auto/v1/1436014/r7mrgstb76x8onkugzno.jpg" , alt "Logo du Lab 110bis" ] [] , ul [ class "footer__social" ] [ li [] [ a [ href "https://twitter.com/startupC12", class "icon icon-twitter" ] [ i [ class "fa fa-twitter fa-2x" ] [] ] ] , li [] [ a [ href "https://github.com/betagouv/ClasseA12", class "icon icon-github" ] [ i [ class "fa fa-github fa-2x" ] [] ] ] , li [] [ a [ href "mailto:contact@classea12.beta.gouv.fr?subject=Classes à 12 sur beta.gouv.fr", class "icon icon-mail" ] [ i [ class "fa fa-envelope fa-2x" ] [] ] ] ] ] , ul [ class "footer__links" ] [ li [] [ h2 [] [ text "classea12.beta.gouv.fr" ] ] , li [] [ a [ Route.href Route.CGU ] [ text "Conditions générales d'utilisation" ] ] , li [] [ a [ Route.href Route.Convention ] [ text "Charte de bonne conduite" ] ] , li [] [ a [ Route.href Route.PrivacyPolicy ] [ text "Politique de confidentialité" ] ] ] ] ]
33639
module Views.Page exposing (ActivePage(..), Config, frame) import Browser exposing (Document) import Data.Session exposing (Session) import Html exposing (..) import Html.Attributes exposing (alt, class, classList, href, src, title) import Html.Events exposing (onClick) import Route type ActivePage = Home | About | Participate | Newsletter | CGU | Convention | PrivacyPolicy | Admin | Video | NotFound type alias Config = { session : Session , activePage : ActivePage } frame : Config -> ( String, List (Html.Html msg) ) -> Document msg frame config ( title, content ) = { title = title ++ " | Classe à 12" , body = [ viewHeader config ] ++ content ++ [ viewFooter ] } viewHeader : Config -> Html msg viewHeader { activePage } = let linkMaybeActive page route caption = li [ class "nav__item" ] [ a [ Route.href route , classList [ ( "active", page == activePage ) ] ] [ text caption ] ] in header [ class "navbar" ] [ div [ class "navbar__container" ] [ a [ class "navbar__home" , Route.href Route.Home ] [ img [ src "/logo.png" , alt "logo" , class "navbar__logo" ] [] , text "classea12.beta.gouv.fr" ] , nav [] [ ul [ class "nav__links" ] [ linkMaybeActive Home Route.Home "Nos vidéos" , linkMaybeActive About Route.About "Classe à 12 ?" , linkMaybeActive Participate Route.Participate "Je participe !" , linkMaybeActive Newsletter Route.Newsletter "Inscrivez-vous à notre infolettre" ] ] ] ] viewFooter : Html msg viewFooter = footer [ class "footer" ] [ div [ class "container" ] [ div [ class "footer__logo" ] [ img [ src "//res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_300,w_300,f_auto,q_auto/v1/1436014/r7mrgstb76x8onkugzno.jpg" , alt "Logo du Lab 110bis" ] [] , ul [ class "footer__social" ] [ li [] [ a [ href "https://twitter.com/startupC12", class "icon icon-twitter" ] [ i [ class "fa fa-twitter fa-2x" ] [] ] ] , li [] [ a [ href "https://github.com/betagouv/ClasseA12", class "icon icon-github" ] [ i [ class "fa fa-github fa-2x" ] [] ] ] , li [] [ a [ href "mailto:<EMAIL>?subject=Classes à 12 sur beta.gouv.fr", class "icon icon-mail" ] [ i [ class "fa fa-envelope fa-2x" ] [] ] ] ] ] , ul [ class "footer__links" ] [ li [] [ h2 [] [ text "classea12.beta.gouv.fr" ] ] , li [] [ a [ Route.href Route.CGU ] [ text "Conditions générales d'utilisation" ] ] , li [] [ a [ Route.href Route.Convention ] [ text "Charte de bonne conduite" ] ] , li [] [ a [ Route.href Route.PrivacyPolicy ] [ text "Politique de confidentialité" ] ] ] ] ]
true
module Views.Page exposing (ActivePage(..), Config, frame) import Browser exposing (Document) import Data.Session exposing (Session) import Html exposing (..) import Html.Attributes exposing (alt, class, classList, href, src, title) import Html.Events exposing (onClick) import Route type ActivePage = Home | About | Participate | Newsletter | CGU | Convention | PrivacyPolicy | Admin | Video | NotFound type alias Config = { session : Session , activePage : ActivePage } frame : Config -> ( String, List (Html.Html msg) ) -> Document msg frame config ( title, content ) = { title = title ++ " | Classe à 12" , body = [ viewHeader config ] ++ content ++ [ viewFooter ] } viewHeader : Config -> Html msg viewHeader { activePage } = let linkMaybeActive page route caption = li [ class "nav__item" ] [ a [ Route.href route , classList [ ( "active", page == activePage ) ] ] [ text caption ] ] in header [ class "navbar" ] [ div [ class "navbar__container" ] [ a [ class "navbar__home" , Route.href Route.Home ] [ img [ src "/logo.png" , alt "logo" , class "navbar__logo" ] [] , text "classea12.beta.gouv.fr" ] , nav [] [ ul [ class "nav__links" ] [ linkMaybeActive Home Route.Home "Nos vidéos" , linkMaybeActive About Route.About "Classe à 12 ?" , linkMaybeActive Participate Route.Participate "Je participe !" , linkMaybeActive Newsletter Route.Newsletter "Inscrivez-vous à notre infolettre" ] ] ] ] viewFooter : Html msg viewFooter = footer [ class "footer" ] [ div [ class "container" ] [ div [ class "footer__logo" ] [ img [ src "//res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_300,w_300,f_auto,q_auto/v1/1436014/r7mrgstb76x8onkugzno.jpg" , alt "Logo du Lab 110bis" ] [] , ul [ class "footer__social" ] [ li [] [ a [ href "https://twitter.com/startupC12", class "icon icon-twitter" ] [ i [ class "fa fa-twitter fa-2x" ] [] ] ] , li [] [ a [ href "https://github.com/betagouv/ClasseA12", class "icon icon-github" ] [ i [ class "fa fa-github fa-2x" ] [] ] ] , li [] [ a [ href "mailto:PI:EMAIL:<EMAIL>END_PI?subject=Classes à 12 sur beta.gouv.fr", class "icon icon-mail" ] [ i [ class "fa fa-envelope fa-2x" ] [] ] ] ] ] , ul [ class "footer__links" ] [ li [] [ h2 [] [ text "classea12.beta.gouv.fr" ] ] , li [] [ a [ Route.href Route.CGU ] [ text "Conditions générales d'utilisation" ] ] , li [] [ a [ Route.href Route.Convention ] [ text "Charte de bonne conduite" ] ] , li [] [ a [ Route.href Route.PrivacyPolicy ] [ text "Politique de confidentialité" ] ] ] ] ]
elm
[ { "context": " \"text\"\n\n Password ->\n \"password\"\n\n Email ->\n \"email\"\n\n ", "end": 9631, "score": 0.9991602302, "start": 9623, "tag": "PASSWORD", "value": "password" } ]
src/Prima/Pyxis/Form/Input.elm
primait/pyxis-components
10
module Prima.Pyxis.Form.Input exposing ( Input , text, password, date, number, email , render , withAttribute, withClass, withDefaultValue, withDisabled, withId, withName, withMediumSize, withSmallSize, withLargeSize, withPlaceholder, withOverridingClass, withIsSubmitted , withPrependGroup, withAppendGroup, withGroupClass , withOnBlur, withOnFocus , withValidation ) {-| ## Configuration @docs Input ## Configuration Methods @docs text, password, date, number, email ## Rendering @docs render ## Options @docs withAttribute, withClass, withDefaultValue, withDisabled, withId, withName, withMediumSize, withSmallSize, withLargeSize, withPlaceholder, withOverridingClass, withIsSubmitted ## Group Options @docs withPrependGroup, withAppendGroup, withGroupClass ## Event Options @docs withOnBlur, withOnFocus ## Validation @docs withValidation -} import Html exposing (Html) import Html.Attributes as Attrs import Html.Events as Events import Prima.Pyxis.Form.Validation as Validation import Prima.Pyxis.Helpers as H {-| Represent the opaque `Input` configuration. -} type Input model msg = Input (InputConfig model msg) {-| Internal. Represent the `Input` configuration. -} type alias InputConfig model msg = { options : List (InputOption model msg) , type_ : InputType , reader : model -> Maybe String , tagger : String -> msg } {-| Internal. Represent the `Input` type. -} type InputType = Text | Password | Date | Number | Email {-| Internal. Create the configuration. -} input : InputType -> (model -> Maybe String) -> (String -> msg) -> Input model msg input type_ reader tagger = Input <| InputConfig [] type_ reader tagger {-| Create an `input[type="text"]`. -} text : (model -> Maybe String) -> (String -> msg) -> Input model msg text reader tagger = input Text reader tagger {-| Create an `input[type="password"]`. -} password : (model -> Maybe String) -> (String -> msg) -> Input model msg password reader tagger = input Password reader tagger {-| Create an `input[type="date"]`. -} date : (model -> Maybe String) -> (String -> msg) -> Input model msg date reader tagger = input Date reader tagger {-| Create an `input[type="number"]`. -} number : (model -> Maybe String) -> (String -> msg) -> Input model msg number reader tagger = input Number reader tagger {-| Create an `input[type="email"]`. -} email : (model -> Maybe String) -> (String -> msg) -> Input model msg email reader tagger = input Email reader tagger {-| Internal. Represent the possible modifiers for an `Input`. -} type InputOption model msg = AppendGroup (List (Html msg)) | Attribute (Html.Attribute msg) | Class String | DefaultValue (Maybe String) | Disabled Bool | GroupClass String | Id String | IsSubmitted (model -> Bool) | Name String | OnBlur msg | OnFocus msg | OverridingClass String | Placeholder String | PrependGroup (List (Html msg)) | Size InputSize | Validation (model -> Maybe Validation.Type) type Default = Indeterminate | Value (Maybe String) {-| Internal. Represent the `Input` size. -} type InputSize = Small | Medium | Large {-| Appends an `InputGroup` with custom `Html`. -} withAppendGroup : List (Html msg) -> Input model msg -> Input model msg withAppendGroup html = addOption (AppendGroup html) {-| Adds a generic Html.Attribute to the `Input`. -} withAttribute : Html.Attribute msg -> Input model msg -> Input model msg withAttribute attribute = addOption (Attribute attribute) {-| Adds a `class` to the `Input`. -} withClass : String -> Input model msg -> Input model msg withClass class_ = addOption (Class class_) {-| Adds a default value to the `Input`. Useful to teach the component about it's `pristine/touched` state. -} withDefaultValue : Maybe String -> Input model msg -> Input model msg withDefaultValue value = addOption (DefaultValue value) {-| Adds a `disabled` Html.Attribute to the `Input`. -} withDisabled : Bool -> Input model msg -> Input model msg withDisabled disabled = addOption (Disabled disabled) {-| Adds a `class` to the `InputGroup` which wraps the `Input`. -} withGroupClass : String -> Input model msg -> Input model msg withGroupClass class = addOption (GroupClass class) {-| Adds an `id` Html.Attribute to the `Input`. -} withId : String -> Input model msg -> Input model msg withId id = addOption (Id id) {-| Adds an `isSubmitted` predicate to the `Input`. -} withIsSubmitted : (model -> Bool) -> Input model msg -> Input model msg withIsSubmitted isSubmitted = addOption (IsSubmitted isSubmitted) {-| Adds a `name` Html.Attribute to the `Input`. -} withName : String -> Input model msg -> Input model msg withName name = addOption (Name name) {-| Attaches the `onBlur` event to the `Input`. -} withOnBlur : msg -> Input model msg -> Input model msg withOnBlur tagger = addOption (OnBlur tagger) {-| Attaches the `onFocus` event to the `Input`. -} withOnFocus : msg -> Input model msg -> Input model msg withOnFocus tagger = addOption (OnFocus tagger) {-| Adds a `class` to the `Input` which overrides all the previous. -} withOverridingClass : String -> Input model msg -> Input model msg withOverridingClass class = addOption (OverridingClass class) {-| Adds a `placeholder` Html.Attribute to the `Input`. -} withPlaceholder : String -> Input model msg -> Input model msg withPlaceholder placeholder = addOption (Placeholder placeholder) {-| Prepends an `InputGroup` with custom `Html`. -} withPrependGroup : List (Html msg) -> Input model msg -> Input model msg withPrependGroup html = addOption (PrependGroup html) {-| Adds a `size` of `Large` to the `Input`. -} withLargeSize : Input model msg -> Input model msg withLargeSize = addOption (Size Large) {-| Adds a `size` of `Medium` to the `Input`. -} withMediumSize : Input model msg -> Input model msg withMediumSize = addOption (Size Medium) {-| Sets a `size` of `Small` to the `Input`. -} withSmallSize : Input model msg -> Input model msg withSmallSize = addOption (Size Small) {-| Adds a `Validation` rule to the `Input`. -} withValidation : (model -> Maybe Validation.Type) -> Input model msg -> Input model msg withValidation validation = addOption (Validation validation) {-| Internal. Adds a generic option to the `Input`. -} addOption : InputOption model msg -> Input model msg -> Input model msg addOption option (Input inputConfig) = Input { inputConfig | options = inputConfig.options ++ [ option ] } {-| Internal. Represent the list of customizations for the `Input` component. -} type alias Options model msg = { appendGroup : Maybe (List (Html msg)) , attributes : List (Html.Attribute msg) , defaultValue : Default , disabled : Maybe Bool , classes : List String , groupClasses : List String , id : Maybe String , isSubmitted : model -> Bool , name : Maybe String , onFocus : Maybe msg , onBlur : Maybe msg , placeholder : Maybe String , prependGroup : Maybe (List (Html msg)) , size : InputSize , validations : List (model -> Maybe Validation.Type) } {-| Internal. Represent the initial state of the list of customizations for the `Input` component. -} defaultOptions : Options model msg defaultOptions = { appendGroup = Nothing , attributes = [] , defaultValue = Indeterminate , disabled = Nothing , classes = [ "form-input" ] , groupClasses = [] , id = Nothing , isSubmitted = always True , name = Nothing , onFocus = Nothing , onBlur = Nothing , placeholder = Nothing , prependGroup = Nothing , size = Medium , validations = [] } {-| Internal. Applies the customizations made by end user to the `Input` component. -} applyOption : InputOption model msg -> Options model msg -> Options model msg applyOption modifier options = case modifier of AppendGroup html -> { options | appendGroup = Just html } Attribute attribute -> { options | attributes = attribute :: options.attributes } Class class -> { options | classes = class :: options.classes } OverridingClass class -> { options | classes = [ class ] } DefaultValue value -> { options | defaultValue = Value value } Disabled disabled -> { options | disabled = Just disabled } GroupClass class -> { options | groupClasses = class :: options.groupClasses } Id id -> { options | id = Just id } IsSubmitted predicate -> { options | isSubmitted = predicate } Name name -> { options | name = Just name } OnBlur onBlur -> { options | onBlur = Just onBlur } OnFocus onFocus -> { options | onFocus = Just onFocus } Placeholder placeholder -> { options | placeholder = Just placeholder } PrependGroup html -> { options | prependGroup = Just html } Size size -> { options | size = size } Validation validation -> { options | validations = validation :: options.validations } {-| Internal. Transforms an `InputType` into a valid Html.Attribute. -} typeAttribute : InputType -> Html.Attribute msg typeAttribute type_ = Attrs.type_ (case type_ of Text -> "text" Password -> "password" Email -> "email" Date -> "date" Number -> "number" ) {-| Internal. Transforms an `InputSize` into a valid Html.Attribute. -} sizeAttribute : InputSize -> Html.Attribute msg sizeAttribute size = Attrs.class (case size of Small -> "is-small" Medium -> "is-medium" Large -> "is-large" ) {-| Internal. Transforms the `reader` function into a valid Html.Attribute. -} readerAttribute : model -> Input model msg -> Html.Attribute msg readerAttribute model (Input config) = (Attrs.value << Maybe.withDefault "" << config.reader) model {-| Internal. Transforms the `tagger` function into a valid Html.Attribute. -} taggerAttribute : Input model msg -> Html.Attribute msg taggerAttribute (Input config) = Events.onInput config.tagger {-| Internal. Transforms the `Validation` status into an Html.Attribute `class`. -} validationAttribute : model -> Input model msg -> Html.Attribute msg validationAttribute model inputModel = let warnings = warningValidations model (computeOptions inputModel) errors = errorsValidations model (computeOptions inputModel) in case ( errors, warnings ) of ( [], [] ) -> Attrs.class "is-valid" ( [], _ ) -> Attrs.class "has-warning" ( _, _ ) -> Attrs.class "has-error" isPristine : model -> Input model msg -> Bool isPristine model ((Input config) as inputModel) = let options = computeOptions inputModel in case ( Value (config.reader model) == options.defaultValue, config.reader model ) of ( True, _ ) -> True ( False, Nothing ) -> True ( False, Just _ ) -> False {-| Internal. Applies the `pristine/touched` visual state to the component. -} pristineAttribute : model -> Input model msg -> Html.Attribute msg pristineAttribute model inputModel = if isPristine model inputModel then Attrs.class "is-pristine" else Attrs.class "is-touched" {-| Internal. Applies all the customizations and returns the internal `Options` type. -} computeOptions : Input model msg -> Options model msg computeOptions (Input config) = List.foldl applyOption defaultOptions config.options {-| Internal. Determines whether the field should be validated or not. -} shouldBeValidated : model -> Input model msg -> Options model msg -> Bool shouldBeValidated model inputModel options = (not <| isPristine model inputModel) || options.isSubmitted model {-| Internal. Transforms all the customizations into a list of valid Html.Attribute(s). -} buildAttributes : model -> Input model msg -> List (Html.Attribute msg) buildAttributes model ((Input config) as inputModel) = let options : Options model msg options = computeOptions inputModel in [ options.id |> Maybe.map Attrs.id , options.name |> Maybe.map Attrs.name , options.disabled |> Maybe.map Attrs.disabled , options.placeholder |> Maybe.map Attrs.placeholder , options.onBlur |> Maybe.map Events.onBlur , options.onFocus |> Maybe.map Events.onFocus ] |> List.filterMap identity |> (++) options.attributes |> (::) (H.classesAttribute options.classes) |> (::) (readerAttribute model inputModel) |> (::) (taggerAttribute inputModel) |> (::) (typeAttribute config.type_) |> (::) (sizeAttribute options.size) |> H.addIf (shouldBeValidated model inputModel options) (validationAttribute model inputModel) |> (::) (pristineAttribute model inputModel) {-| ## Renders the `Input`. import Html import Prima.Pyxis.Form.Input as Input import Prima.Pyxis.Form.Validation as Validation ... type Msg = OnInput String type alias Model = { username : Maybe String , isSubmitted : Bool } ... view : Html Msg view = Html.div [] (Input.email .username OnInput |> Input.withClass "my-custom-class" |> Input.withValidation (Maybe.andThen validate << .username) |> Input.withIsSubmitted .isSubmitted ) validate : String -> Validation.Type validate str = if String.isEmpty str then Just <| Validation.ErrorWithMessage "Username is empty". else Nothing -} render : model -> Input model msg -> List (Html msg) render model inputModel = let options = computeOptions inputModel hasValidations = shouldBeValidated model inputModel options in case ( options.prependGroup, options.appendGroup ) of ( Just html, _ ) -> [ renderGroup (renderPrependGroup inputModel html :: renderInput model inputModel :: renderValidationMessages model inputModel hasValidations ) ] ( _, Just html ) -> [ renderGroup (renderAppendGroup inputModel html :: renderInput model inputModel :: renderValidationMessages model inputModel hasValidations ) ] _ -> renderInput model inputModel :: renderValidationMessages model inputModel hasValidations {-| Internal. Renders the `Input` alone. -} renderInput : model -> Input model msg -> Html msg renderInput model inputModel = Html.input (buildAttributes model inputModel) [] {-| Internal. Renders the `InputGroup` which wraps the `Input`. -} renderGroup : List (Html msg) -> Html msg renderGroup = Html.div [ Attrs.class "form-input-group" ] {-| Internal. Renders the `InputGroup` which wraps the `Input`. -} renderAppendGroup : Input model msg -> List (Html msg) -> Html msg renderAppendGroup inputModel = let options = computeOptions inputModel in Html.div [ Attrs.class "form-input-group__append" , Attrs.class <| String.join " " options.groupClasses ] {-| Internal. Renders the `InputGroup` which wraps the `Input`. -} renderPrependGroup : Input model msg -> List (Html msg) -> Html msg renderPrependGroup inputModel = let options = computeOptions inputModel in Html.div [ Attrs.class "form-input-group__prepend" , Attrs.class <| String.join " " options.groupClasses ] {-| Internal. Renders the list of errors if present. Renders the list of warnings if not. -} renderValidationMessages : model -> Input model msg -> Bool -> List (Html msg) renderValidationMessages model inputModel showValidation = let warnings = warningValidations model (computeOptions inputModel) errors = errorsValidations model (computeOptions inputModel) in case ( showValidation, errors, warnings ) of ( True, [], _ ) -> List.map Validation.render warnings ( True, _, _ ) -> List.map Validation.render errors ( False, _, _ ) -> [] warningValidations : model -> Options model msg -> List Validation.Type warningValidations model options = options.validations |> List.filterMap (H.flip identity model) |> List.filter Validation.isWarning errorsValidations : model -> Options model msg -> List Validation.Type errorsValidations model options = options.validations |> List.filterMap (H.flip identity model) |> List.filter Validation.isError
11466
module Prima.Pyxis.Form.Input exposing ( Input , text, password, date, number, email , render , withAttribute, withClass, withDefaultValue, withDisabled, withId, withName, withMediumSize, withSmallSize, withLargeSize, withPlaceholder, withOverridingClass, withIsSubmitted , withPrependGroup, withAppendGroup, withGroupClass , withOnBlur, withOnFocus , withValidation ) {-| ## Configuration @docs Input ## Configuration Methods @docs text, password, date, number, email ## Rendering @docs render ## Options @docs withAttribute, withClass, withDefaultValue, withDisabled, withId, withName, withMediumSize, withSmallSize, withLargeSize, withPlaceholder, withOverridingClass, withIsSubmitted ## Group Options @docs withPrependGroup, withAppendGroup, withGroupClass ## Event Options @docs withOnBlur, withOnFocus ## Validation @docs withValidation -} import Html exposing (Html) import Html.Attributes as Attrs import Html.Events as Events import Prima.Pyxis.Form.Validation as Validation import Prima.Pyxis.Helpers as H {-| Represent the opaque `Input` configuration. -} type Input model msg = Input (InputConfig model msg) {-| Internal. Represent the `Input` configuration. -} type alias InputConfig model msg = { options : List (InputOption model msg) , type_ : InputType , reader : model -> Maybe String , tagger : String -> msg } {-| Internal. Represent the `Input` type. -} type InputType = Text | Password | Date | Number | Email {-| Internal. Create the configuration. -} input : InputType -> (model -> Maybe String) -> (String -> msg) -> Input model msg input type_ reader tagger = Input <| InputConfig [] type_ reader tagger {-| Create an `input[type="text"]`. -} text : (model -> Maybe String) -> (String -> msg) -> Input model msg text reader tagger = input Text reader tagger {-| Create an `input[type="password"]`. -} password : (model -> Maybe String) -> (String -> msg) -> Input model msg password reader tagger = input Password reader tagger {-| Create an `input[type="date"]`. -} date : (model -> Maybe String) -> (String -> msg) -> Input model msg date reader tagger = input Date reader tagger {-| Create an `input[type="number"]`. -} number : (model -> Maybe String) -> (String -> msg) -> Input model msg number reader tagger = input Number reader tagger {-| Create an `input[type="email"]`. -} email : (model -> Maybe String) -> (String -> msg) -> Input model msg email reader tagger = input Email reader tagger {-| Internal. Represent the possible modifiers for an `Input`. -} type InputOption model msg = AppendGroup (List (Html msg)) | Attribute (Html.Attribute msg) | Class String | DefaultValue (Maybe String) | Disabled Bool | GroupClass String | Id String | IsSubmitted (model -> Bool) | Name String | OnBlur msg | OnFocus msg | OverridingClass String | Placeholder String | PrependGroup (List (Html msg)) | Size InputSize | Validation (model -> Maybe Validation.Type) type Default = Indeterminate | Value (Maybe String) {-| Internal. Represent the `Input` size. -} type InputSize = Small | Medium | Large {-| Appends an `InputGroup` with custom `Html`. -} withAppendGroup : List (Html msg) -> Input model msg -> Input model msg withAppendGroup html = addOption (AppendGroup html) {-| Adds a generic Html.Attribute to the `Input`. -} withAttribute : Html.Attribute msg -> Input model msg -> Input model msg withAttribute attribute = addOption (Attribute attribute) {-| Adds a `class` to the `Input`. -} withClass : String -> Input model msg -> Input model msg withClass class_ = addOption (Class class_) {-| Adds a default value to the `Input`. Useful to teach the component about it's `pristine/touched` state. -} withDefaultValue : Maybe String -> Input model msg -> Input model msg withDefaultValue value = addOption (DefaultValue value) {-| Adds a `disabled` Html.Attribute to the `Input`. -} withDisabled : Bool -> Input model msg -> Input model msg withDisabled disabled = addOption (Disabled disabled) {-| Adds a `class` to the `InputGroup` which wraps the `Input`. -} withGroupClass : String -> Input model msg -> Input model msg withGroupClass class = addOption (GroupClass class) {-| Adds an `id` Html.Attribute to the `Input`. -} withId : String -> Input model msg -> Input model msg withId id = addOption (Id id) {-| Adds an `isSubmitted` predicate to the `Input`. -} withIsSubmitted : (model -> Bool) -> Input model msg -> Input model msg withIsSubmitted isSubmitted = addOption (IsSubmitted isSubmitted) {-| Adds a `name` Html.Attribute to the `Input`. -} withName : String -> Input model msg -> Input model msg withName name = addOption (Name name) {-| Attaches the `onBlur` event to the `Input`. -} withOnBlur : msg -> Input model msg -> Input model msg withOnBlur tagger = addOption (OnBlur tagger) {-| Attaches the `onFocus` event to the `Input`. -} withOnFocus : msg -> Input model msg -> Input model msg withOnFocus tagger = addOption (OnFocus tagger) {-| Adds a `class` to the `Input` which overrides all the previous. -} withOverridingClass : String -> Input model msg -> Input model msg withOverridingClass class = addOption (OverridingClass class) {-| Adds a `placeholder` Html.Attribute to the `Input`. -} withPlaceholder : String -> Input model msg -> Input model msg withPlaceholder placeholder = addOption (Placeholder placeholder) {-| Prepends an `InputGroup` with custom `Html`. -} withPrependGroup : List (Html msg) -> Input model msg -> Input model msg withPrependGroup html = addOption (PrependGroup html) {-| Adds a `size` of `Large` to the `Input`. -} withLargeSize : Input model msg -> Input model msg withLargeSize = addOption (Size Large) {-| Adds a `size` of `Medium` to the `Input`. -} withMediumSize : Input model msg -> Input model msg withMediumSize = addOption (Size Medium) {-| Sets a `size` of `Small` to the `Input`. -} withSmallSize : Input model msg -> Input model msg withSmallSize = addOption (Size Small) {-| Adds a `Validation` rule to the `Input`. -} withValidation : (model -> Maybe Validation.Type) -> Input model msg -> Input model msg withValidation validation = addOption (Validation validation) {-| Internal. Adds a generic option to the `Input`. -} addOption : InputOption model msg -> Input model msg -> Input model msg addOption option (Input inputConfig) = Input { inputConfig | options = inputConfig.options ++ [ option ] } {-| Internal. Represent the list of customizations for the `Input` component. -} type alias Options model msg = { appendGroup : Maybe (List (Html msg)) , attributes : List (Html.Attribute msg) , defaultValue : Default , disabled : Maybe Bool , classes : List String , groupClasses : List String , id : Maybe String , isSubmitted : model -> Bool , name : Maybe String , onFocus : Maybe msg , onBlur : Maybe msg , placeholder : Maybe String , prependGroup : Maybe (List (Html msg)) , size : InputSize , validations : List (model -> Maybe Validation.Type) } {-| Internal. Represent the initial state of the list of customizations for the `Input` component. -} defaultOptions : Options model msg defaultOptions = { appendGroup = Nothing , attributes = [] , defaultValue = Indeterminate , disabled = Nothing , classes = [ "form-input" ] , groupClasses = [] , id = Nothing , isSubmitted = always True , name = Nothing , onFocus = Nothing , onBlur = Nothing , placeholder = Nothing , prependGroup = Nothing , size = Medium , validations = [] } {-| Internal. Applies the customizations made by end user to the `Input` component. -} applyOption : InputOption model msg -> Options model msg -> Options model msg applyOption modifier options = case modifier of AppendGroup html -> { options | appendGroup = Just html } Attribute attribute -> { options | attributes = attribute :: options.attributes } Class class -> { options | classes = class :: options.classes } OverridingClass class -> { options | classes = [ class ] } DefaultValue value -> { options | defaultValue = Value value } Disabled disabled -> { options | disabled = Just disabled } GroupClass class -> { options | groupClasses = class :: options.groupClasses } Id id -> { options | id = Just id } IsSubmitted predicate -> { options | isSubmitted = predicate } Name name -> { options | name = Just name } OnBlur onBlur -> { options | onBlur = Just onBlur } OnFocus onFocus -> { options | onFocus = Just onFocus } Placeholder placeholder -> { options | placeholder = Just placeholder } PrependGroup html -> { options | prependGroup = Just html } Size size -> { options | size = size } Validation validation -> { options | validations = validation :: options.validations } {-| Internal. Transforms an `InputType` into a valid Html.Attribute. -} typeAttribute : InputType -> Html.Attribute msg typeAttribute type_ = Attrs.type_ (case type_ of Text -> "text" Password -> "<PASSWORD>" Email -> "email" Date -> "date" Number -> "number" ) {-| Internal. Transforms an `InputSize` into a valid Html.Attribute. -} sizeAttribute : InputSize -> Html.Attribute msg sizeAttribute size = Attrs.class (case size of Small -> "is-small" Medium -> "is-medium" Large -> "is-large" ) {-| Internal. Transforms the `reader` function into a valid Html.Attribute. -} readerAttribute : model -> Input model msg -> Html.Attribute msg readerAttribute model (Input config) = (Attrs.value << Maybe.withDefault "" << config.reader) model {-| Internal. Transforms the `tagger` function into a valid Html.Attribute. -} taggerAttribute : Input model msg -> Html.Attribute msg taggerAttribute (Input config) = Events.onInput config.tagger {-| Internal. Transforms the `Validation` status into an Html.Attribute `class`. -} validationAttribute : model -> Input model msg -> Html.Attribute msg validationAttribute model inputModel = let warnings = warningValidations model (computeOptions inputModel) errors = errorsValidations model (computeOptions inputModel) in case ( errors, warnings ) of ( [], [] ) -> Attrs.class "is-valid" ( [], _ ) -> Attrs.class "has-warning" ( _, _ ) -> Attrs.class "has-error" isPristine : model -> Input model msg -> Bool isPristine model ((Input config) as inputModel) = let options = computeOptions inputModel in case ( Value (config.reader model) == options.defaultValue, config.reader model ) of ( True, _ ) -> True ( False, Nothing ) -> True ( False, Just _ ) -> False {-| Internal. Applies the `pristine/touched` visual state to the component. -} pristineAttribute : model -> Input model msg -> Html.Attribute msg pristineAttribute model inputModel = if isPristine model inputModel then Attrs.class "is-pristine" else Attrs.class "is-touched" {-| Internal. Applies all the customizations and returns the internal `Options` type. -} computeOptions : Input model msg -> Options model msg computeOptions (Input config) = List.foldl applyOption defaultOptions config.options {-| Internal. Determines whether the field should be validated or not. -} shouldBeValidated : model -> Input model msg -> Options model msg -> Bool shouldBeValidated model inputModel options = (not <| isPristine model inputModel) || options.isSubmitted model {-| Internal. Transforms all the customizations into a list of valid Html.Attribute(s). -} buildAttributes : model -> Input model msg -> List (Html.Attribute msg) buildAttributes model ((Input config) as inputModel) = let options : Options model msg options = computeOptions inputModel in [ options.id |> Maybe.map Attrs.id , options.name |> Maybe.map Attrs.name , options.disabled |> Maybe.map Attrs.disabled , options.placeholder |> Maybe.map Attrs.placeholder , options.onBlur |> Maybe.map Events.onBlur , options.onFocus |> Maybe.map Events.onFocus ] |> List.filterMap identity |> (++) options.attributes |> (::) (H.classesAttribute options.classes) |> (::) (readerAttribute model inputModel) |> (::) (taggerAttribute inputModel) |> (::) (typeAttribute config.type_) |> (::) (sizeAttribute options.size) |> H.addIf (shouldBeValidated model inputModel options) (validationAttribute model inputModel) |> (::) (pristineAttribute model inputModel) {-| ## Renders the `Input`. import Html import Prima.Pyxis.Form.Input as Input import Prima.Pyxis.Form.Validation as Validation ... type Msg = OnInput String type alias Model = { username : Maybe String , isSubmitted : Bool } ... view : Html Msg view = Html.div [] (Input.email .username OnInput |> Input.withClass "my-custom-class" |> Input.withValidation (Maybe.andThen validate << .username) |> Input.withIsSubmitted .isSubmitted ) validate : String -> Validation.Type validate str = if String.isEmpty str then Just <| Validation.ErrorWithMessage "Username is empty". else Nothing -} render : model -> Input model msg -> List (Html msg) render model inputModel = let options = computeOptions inputModel hasValidations = shouldBeValidated model inputModel options in case ( options.prependGroup, options.appendGroup ) of ( Just html, _ ) -> [ renderGroup (renderPrependGroup inputModel html :: renderInput model inputModel :: renderValidationMessages model inputModel hasValidations ) ] ( _, Just html ) -> [ renderGroup (renderAppendGroup inputModel html :: renderInput model inputModel :: renderValidationMessages model inputModel hasValidations ) ] _ -> renderInput model inputModel :: renderValidationMessages model inputModel hasValidations {-| Internal. Renders the `Input` alone. -} renderInput : model -> Input model msg -> Html msg renderInput model inputModel = Html.input (buildAttributes model inputModel) [] {-| Internal. Renders the `InputGroup` which wraps the `Input`. -} renderGroup : List (Html msg) -> Html msg renderGroup = Html.div [ Attrs.class "form-input-group" ] {-| Internal. Renders the `InputGroup` which wraps the `Input`. -} renderAppendGroup : Input model msg -> List (Html msg) -> Html msg renderAppendGroup inputModel = let options = computeOptions inputModel in Html.div [ Attrs.class "form-input-group__append" , Attrs.class <| String.join " " options.groupClasses ] {-| Internal. Renders the `InputGroup` which wraps the `Input`. -} renderPrependGroup : Input model msg -> List (Html msg) -> Html msg renderPrependGroup inputModel = let options = computeOptions inputModel in Html.div [ Attrs.class "form-input-group__prepend" , Attrs.class <| String.join " " options.groupClasses ] {-| Internal. Renders the list of errors if present. Renders the list of warnings if not. -} renderValidationMessages : model -> Input model msg -> Bool -> List (Html msg) renderValidationMessages model inputModel showValidation = let warnings = warningValidations model (computeOptions inputModel) errors = errorsValidations model (computeOptions inputModel) in case ( showValidation, errors, warnings ) of ( True, [], _ ) -> List.map Validation.render warnings ( True, _, _ ) -> List.map Validation.render errors ( False, _, _ ) -> [] warningValidations : model -> Options model msg -> List Validation.Type warningValidations model options = options.validations |> List.filterMap (H.flip identity model) |> List.filter Validation.isWarning errorsValidations : model -> Options model msg -> List Validation.Type errorsValidations model options = options.validations |> List.filterMap (H.flip identity model) |> List.filter Validation.isError
true
module Prima.Pyxis.Form.Input exposing ( Input , text, password, date, number, email , render , withAttribute, withClass, withDefaultValue, withDisabled, withId, withName, withMediumSize, withSmallSize, withLargeSize, withPlaceholder, withOverridingClass, withIsSubmitted , withPrependGroup, withAppendGroup, withGroupClass , withOnBlur, withOnFocus , withValidation ) {-| ## Configuration @docs Input ## Configuration Methods @docs text, password, date, number, email ## Rendering @docs render ## Options @docs withAttribute, withClass, withDefaultValue, withDisabled, withId, withName, withMediumSize, withSmallSize, withLargeSize, withPlaceholder, withOverridingClass, withIsSubmitted ## Group Options @docs withPrependGroup, withAppendGroup, withGroupClass ## Event Options @docs withOnBlur, withOnFocus ## Validation @docs withValidation -} import Html exposing (Html) import Html.Attributes as Attrs import Html.Events as Events import Prima.Pyxis.Form.Validation as Validation import Prima.Pyxis.Helpers as H {-| Represent the opaque `Input` configuration. -} type Input model msg = Input (InputConfig model msg) {-| Internal. Represent the `Input` configuration. -} type alias InputConfig model msg = { options : List (InputOption model msg) , type_ : InputType , reader : model -> Maybe String , tagger : String -> msg } {-| Internal. Represent the `Input` type. -} type InputType = Text | Password | Date | Number | Email {-| Internal. Create the configuration. -} input : InputType -> (model -> Maybe String) -> (String -> msg) -> Input model msg input type_ reader tagger = Input <| InputConfig [] type_ reader tagger {-| Create an `input[type="text"]`. -} text : (model -> Maybe String) -> (String -> msg) -> Input model msg text reader tagger = input Text reader tagger {-| Create an `input[type="password"]`. -} password : (model -> Maybe String) -> (String -> msg) -> Input model msg password reader tagger = input Password reader tagger {-| Create an `input[type="date"]`. -} date : (model -> Maybe String) -> (String -> msg) -> Input model msg date reader tagger = input Date reader tagger {-| Create an `input[type="number"]`. -} number : (model -> Maybe String) -> (String -> msg) -> Input model msg number reader tagger = input Number reader tagger {-| Create an `input[type="email"]`. -} email : (model -> Maybe String) -> (String -> msg) -> Input model msg email reader tagger = input Email reader tagger {-| Internal. Represent the possible modifiers for an `Input`. -} type InputOption model msg = AppendGroup (List (Html msg)) | Attribute (Html.Attribute msg) | Class String | DefaultValue (Maybe String) | Disabled Bool | GroupClass String | Id String | IsSubmitted (model -> Bool) | Name String | OnBlur msg | OnFocus msg | OverridingClass String | Placeholder String | PrependGroup (List (Html msg)) | Size InputSize | Validation (model -> Maybe Validation.Type) type Default = Indeterminate | Value (Maybe String) {-| Internal. Represent the `Input` size. -} type InputSize = Small | Medium | Large {-| Appends an `InputGroup` with custom `Html`. -} withAppendGroup : List (Html msg) -> Input model msg -> Input model msg withAppendGroup html = addOption (AppendGroup html) {-| Adds a generic Html.Attribute to the `Input`. -} withAttribute : Html.Attribute msg -> Input model msg -> Input model msg withAttribute attribute = addOption (Attribute attribute) {-| Adds a `class` to the `Input`. -} withClass : String -> Input model msg -> Input model msg withClass class_ = addOption (Class class_) {-| Adds a default value to the `Input`. Useful to teach the component about it's `pristine/touched` state. -} withDefaultValue : Maybe String -> Input model msg -> Input model msg withDefaultValue value = addOption (DefaultValue value) {-| Adds a `disabled` Html.Attribute to the `Input`. -} withDisabled : Bool -> Input model msg -> Input model msg withDisabled disabled = addOption (Disabled disabled) {-| Adds a `class` to the `InputGroup` which wraps the `Input`. -} withGroupClass : String -> Input model msg -> Input model msg withGroupClass class = addOption (GroupClass class) {-| Adds an `id` Html.Attribute to the `Input`. -} withId : String -> Input model msg -> Input model msg withId id = addOption (Id id) {-| Adds an `isSubmitted` predicate to the `Input`. -} withIsSubmitted : (model -> Bool) -> Input model msg -> Input model msg withIsSubmitted isSubmitted = addOption (IsSubmitted isSubmitted) {-| Adds a `name` Html.Attribute to the `Input`. -} withName : String -> Input model msg -> Input model msg withName name = addOption (Name name) {-| Attaches the `onBlur` event to the `Input`. -} withOnBlur : msg -> Input model msg -> Input model msg withOnBlur tagger = addOption (OnBlur tagger) {-| Attaches the `onFocus` event to the `Input`. -} withOnFocus : msg -> Input model msg -> Input model msg withOnFocus tagger = addOption (OnFocus tagger) {-| Adds a `class` to the `Input` which overrides all the previous. -} withOverridingClass : String -> Input model msg -> Input model msg withOverridingClass class = addOption (OverridingClass class) {-| Adds a `placeholder` Html.Attribute to the `Input`. -} withPlaceholder : String -> Input model msg -> Input model msg withPlaceholder placeholder = addOption (Placeholder placeholder) {-| Prepends an `InputGroup` with custom `Html`. -} withPrependGroup : List (Html msg) -> Input model msg -> Input model msg withPrependGroup html = addOption (PrependGroup html) {-| Adds a `size` of `Large` to the `Input`. -} withLargeSize : Input model msg -> Input model msg withLargeSize = addOption (Size Large) {-| Adds a `size` of `Medium` to the `Input`. -} withMediumSize : Input model msg -> Input model msg withMediumSize = addOption (Size Medium) {-| Sets a `size` of `Small` to the `Input`. -} withSmallSize : Input model msg -> Input model msg withSmallSize = addOption (Size Small) {-| Adds a `Validation` rule to the `Input`. -} withValidation : (model -> Maybe Validation.Type) -> Input model msg -> Input model msg withValidation validation = addOption (Validation validation) {-| Internal. Adds a generic option to the `Input`. -} addOption : InputOption model msg -> Input model msg -> Input model msg addOption option (Input inputConfig) = Input { inputConfig | options = inputConfig.options ++ [ option ] } {-| Internal. Represent the list of customizations for the `Input` component. -} type alias Options model msg = { appendGroup : Maybe (List (Html msg)) , attributes : List (Html.Attribute msg) , defaultValue : Default , disabled : Maybe Bool , classes : List String , groupClasses : List String , id : Maybe String , isSubmitted : model -> Bool , name : Maybe String , onFocus : Maybe msg , onBlur : Maybe msg , placeholder : Maybe String , prependGroup : Maybe (List (Html msg)) , size : InputSize , validations : List (model -> Maybe Validation.Type) } {-| Internal. Represent the initial state of the list of customizations for the `Input` component. -} defaultOptions : Options model msg defaultOptions = { appendGroup = Nothing , attributes = [] , defaultValue = Indeterminate , disabled = Nothing , classes = [ "form-input" ] , groupClasses = [] , id = Nothing , isSubmitted = always True , name = Nothing , onFocus = Nothing , onBlur = Nothing , placeholder = Nothing , prependGroup = Nothing , size = Medium , validations = [] } {-| Internal. Applies the customizations made by end user to the `Input` component. -} applyOption : InputOption model msg -> Options model msg -> Options model msg applyOption modifier options = case modifier of AppendGroup html -> { options | appendGroup = Just html } Attribute attribute -> { options | attributes = attribute :: options.attributes } Class class -> { options | classes = class :: options.classes } OverridingClass class -> { options | classes = [ class ] } DefaultValue value -> { options | defaultValue = Value value } Disabled disabled -> { options | disabled = Just disabled } GroupClass class -> { options | groupClasses = class :: options.groupClasses } Id id -> { options | id = Just id } IsSubmitted predicate -> { options | isSubmitted = predicate } Name name -> { options | name = Just name } OnBlur onBlur -> { options | onBlur = Just onBlur } OnFocus onFocus -> { options | onFocus = Just onFocus } Placeholder placeholder -> { options | placeholder = Just placeholder } PrependGroup html -> { options | prependGroup = Just html } Size size -> { options | size = size } Validation validation -> { options | validations = validation :: options.validations } {-| Internal. Transforms an `InputType` into a valid Html.Attribute. -} typeAttribute : InputType -> Html.Attribute msg typeAttribute type_ = Attrs.type_ (case type_ of Text -> "text" Password -> "PI:PASSWORD:<PASSWORD>END_PI" Email -> "email" Date -> "date" Number -> "number" ) {-| Internal. Transforms an `InputSize` into a valid Html.Attribute. -} sizeAttribute : InputSize -> Html.Attribute msg sizeAttribute size = Attrs.class (case size of Small -> "is-small" Medium -> "is-medium" Large -> "is-large" ) {-| Internal. Transforms the `reader` function into a valid Html.Attribute. -} readerAttribute : model -> Input model msg -> Html.Attribute msg readerAttribute model (Input config) = (Attrs.value << Maybe.withDefault "" << config.reader) model {-| Internal. Transforms the `tagger` function into a valid Html.Attribute. -} taggerAttribute : Input model msg -> Html.Attribute msg taggerAttribute (Input config) = Events.onInput config.tagger {-| Internal. Transforms the `Validation` status into an Html.Attribute `class`. -} validationAttribute : model -> Input model msg -> Html.Attribute msg validationAttribute model inputModel = let warnings = warningValidations model (computeOptions inputModel) errors = errorsValidations model (computeOptions inputModel) in case ( errors, warnings ) of ( [], [] ) -> Attrs.class "is-valid" ( [], _ ) -> Attrs.class "has-warning" ( _, _ ) -> Attrs.class "has-error" isPristine : model -> Input model msg -> Bool isPristine model ((Input config) as inputModel) = let options = computeOptions inputModel in case ( Value (config.reader model) == options.defaultValue, config.reader model ) of ( True, _ ) -> True ( False, Nothing ) -> True ( False, Just _ ) -> False {-| Internal. Applies the `pristine/touched` visual state to the component. -} pristineAttribute : model -> Input model msg -> Html.Attribute msg pristineAttribute model inputModel = if isPristine model inputModel then Attrs.class "is-pristine" else Attrs.class "is-touched" {-| Internal. Applies all the customizations and returns the internal `Options` type. -} computeOptions : Input model msg -> Options model msg computeOptions (Input config) = List.foldl applyOption defaultOptions config.options {-| Internal. Determines whether the field should be validated or not. -} shouldBeValidated : model -> Input model msg -> Options model msg -> Bool shouldBeValidated model inputModel options = (not <| isPristine model inputModel) || options.isSubmitted model {-| Internal. Transforms all the customizations into a list of valid Html.Attribute(s). -} buildAttributes : model -> Input model msg -> List (Html.Attribute msg) buildAttributes model ((Input config) as inputModel) = let options : Options model msg options = computeOptions inputModel in [ options.id |> Maybe.map Attrs.id , options.name |> Maybe.map Attrs.name , options.disabled |> Maybe.map Attrs.disabled , options.placeholder |> Maybe.map Attrs.placeholder , options.onBlur |> Maybe.map Events.onBlur , options.onFocus |> Maybe.map Events.onFocus ] |> List.filterMap identity |> (++) options.attributes |> (::) (H.classesAttribute options.classes) |> (::) (readerAttribute model inputModel) |> (::) (taggerAttribute inputModel) |> (::) (typeAttribute config.type_) |> (::) (sizeAttribute options.size) |> H.addIf (shouldBeValidated model inputModel options) (validationAttribute model inputModel) |> (::) (pristineAttribute model inputModel) {-| ## Renders the `Input`. import Html import Prima.Pyxis.Form.Input as Input import Prima.Pyxis.Form.Validation as Validation ... type Msg = OnInput String type alias Model = { username : Maybe String , isSubmitted : Bool } ... view : Html Msg view = Html.div [] (Input.email .username OnInput |> Input.withClass "my-custom-class" |> Input.withValidation (Maybe.andThen validate << .username) |> Input.withIsSubmitted .isSubmitted ) validate : String -> Validation.Type validate str = if String.isEmpty str then Just <| Validation.ErrorWithMessage "Username is empty". else Nothing -} render : model -> Input model msg -> List (Html msg) render model inputModel = let options = computeOptions inputModel hasValidations = shouldBeValidated model inputModel options in case ( options.prependGroup, options.appendGroup ) of ( Just html, _ ) -> [ renderGroup (renderPrependGroup inputModel html :: renderInput model inputModel :: renderValidationMessages model inputModel hasValidations ) ] ( _, Just html ) -> [ renderGroup (renderAppendGroup inputModel html :: renderInput model inputModel :: renderValidationMessages model inputModel hasValidations ) ] _ -> renderInput model inputModel :: renderValidationMessages model inputModel hasValidations {-| Internal. Renders the `Input` alone. -} renderInput : model -> Input model msg -> Html msg renderInput model inputModel = Html.input (buildAttributes model inputModel) [] {-| Internal. Renders the `InputGroup` which wraps the `Input`. -} renderGroup : List (Html msg) -> Html msg renderGroup = Html.div [ Attrs.class "form-input-group" ] {-| Internal. Renders the `InputGroup` which wraps the `Input`. -} renderAppendGroup : Input model msg -> List (Html msg) -> Html msg renderAppendGroup inputModel = let options = computeOptions inputModel in Html.div [ Attrs.class "form-input-group__append" , Attrs.class <| String.join " " options.groupClasses ] {-| Internal. Renders the `InputGroup` which wraps the `Input`. -} renderPrependGroup : Input model msg -> List (Html msg) -> Html msg renderPrependGroup inputModel = let options = computeOptions inputModel in Html.div [ Attrs.class "form-input-group__prepend" , Attrs.class <| String.join " " options.groupClasses ] {-| Internal. Renders the list of errors if present. Renders the list of warnings if not. -} renderValidationMessages : model -> Input model msg -> Bool -> List (Html msg) renderValidationMessages model inputModel showValidation = let warnings = warningValidations model (computeOptions inputModel) errors = errorsValidations model (computeOptions inputModel) in case ( showValidation, errors, warnings ) of ( True, [], _ ) -> List.map Validation.render warnings ( True, _, _ ) -> List.map Validation.render errors ( False, _, _ ) -> [] warningValidations : model -> Options model msg -> List Validation.Type warningValidations model options = options.validations |> List.filterMap (H.flip identity model) |> List.filter Validation.isWarning errorsValidations : model -> Options model msg -> List Validation.Type errorsValidations model options = options.validations |> List.filterMap (H.flip identity model) |> List.filter Validation.isError
elm
[ { "context": "loration,tribal-wars-2\n authors-forum-usernames:viir\n-}\n\n\nmodule Bot exposing\n ( State\n , initSt", "end": 786, "score": 0.9992630482, "start": 782, "tag": "USERNAME", "value": "viir" }, { "context": ",\"y\":502},\"villageByCoordinates\":{\"id\":24,\"name\":\"Pueblo de e.é45\",\"x\":498,\"y\":502,\"character\\_id\":null,\"province\\_", "end": 13899, "score": 0.999358058, "start": 13884, "tag": "NAME", "value": "Pueblo de e.é45" } ]
explore/2020-01-06.explore-tribal-wars-2/src/Bot.elm
kiwi12456/fleet_hauler
101
{- Explore farming barbarian villages in Tribal Wars 2 This version only reads your villages. The bot automatically opens a new web browser window. The first time you run it, it might take more time because it needs to download the web browser software. When the web browser has opened, navigate to Tribal Wars 2 and log in to your account, so you see your villages. You then will probably at an URL like https://es.tribalwars2.com/game.php?world=es77&character_id=123456# The bot then outputs the number of villages and the ID of the currently selected village. When you change the village in-game, you can see the output from the bot changing as well to indicate the new selected village. bot-catalog-tags:exploration,tribal-wars-2 authors-forum-usernames:viir -} module Bot exposing ( State , initState , processEvent ) import BotEngine.Interface_To_Host_20190808 as InterfaceToHost import Dict import Json.Decode import Limbara.SimpleLimbara as SimpleLimbara exposing (BotEventAtTime, BotRequest(..)) import Set type alias SimpleState = { lastRunJavascriptResult : Maybe { response : SimpleLimbara.RunJavascriptInCurrentPageResponseStructure , parseResult : Result Json.Decode.Error RootInformationStructure } , gameRootInformation : Maybe TribalWars2RootInformation , ownVillagesDetails : Dict.Dict Int VillageDetails , searchVillageByCoordinatesResults : Dict.Dict ( Int, Int ) VillageByCoordinatesResult , parseResponseError : Maybe Json.Decode.Error } type alias State = SimpleLimbara.StateIncludingSetup SimpleState type ResponseFromBrowser = RootInformation RootInformationStructure | ReadSelectedCharacterVillageDetailsResponse ReadSelectedCharacterVillageDetailsResponseStructure | ReadVillageByCoordinatesResponse ReadVillageByCoordinatesResponseStructure type alias RootInformationStructure = { location : String , tribalWars2 : Maybe TribalWars2RootInformation } type alias TribalWars2RootInformation = { readyVillages : List Int , selectedVillageId : Int } type alias ReadSelectedCharacterVillageDetailsResponseStructure = { villageId : Int , villageDetails : VillageDetails } type alias ReadVillageByCoordinatesResponseStructure = { villageCoordinates : VillageCoordinates } type alias VillageDetails = { locationX : Int , locationY : Int } type VillageByCoordinatesResult = NoVillageThere | VillageThere VillageByCoordinatesDetails type alias VillageByCoordinatesDetails = { affiliation : VillageByCoordinatesAffiliation } type VillageByCoordinatesAffiliation = AffiliationBarbarian | AffiliationOther type alias VillageCoordinates = { x : Int , y : Int } initState : State initState = SimpleLimbara.initState { lastRunJavascriptResult = Nothing , gameRootInformation = Nothing , ownVillagesDetails = Dict.empty , searchVillageByCoordinatesResults = Dict.empty , parseResponseError = Nothing } processEvent : InterfaceToHost.BotEvent -> State -> ( State, InterfaceToHost.BotResponse ) processEvent = SimpleLimbara.processEvent simpleProcessEvent simpleProcessEvent : BotEventAtTime -> SimpleState -> { newState : SimpleState, request : BotRequest, statusMessage : String } simpleProcessEvent eventAtTime stateBefore = let state = case eventAtTime.event of SimpleLimbara.SetBotConfiguration _ -> stateBefore SimpleLimbara.RunJavascriptInCurrentPageResponse runJavascriptInCurrentPageResponse -> let parseAsRootInfoResult = runJavascriptInCurrentPageResponse.directReturnValueAsString |> Json.Decode.decodeString decodeRootInformation stateAfterIntegrateResponse = { stateBefore | lastRunJavascriptResult = Just { response = runJavascriptInCurrentPageResponse , parseResult = parseAsRootInfoResult } } parseResult = runJavascriptInCurrentPageResponse.directReturnValueAsString |> Json.Decode.decodeString decodeResponseFromBrowser in case parseResult of Err error -> { stateAfterIntegrateResponse | parseResponseError = Just error } Ok parseSuccess -> let stateAfterParseSuccess = { stateAfterIntegrateResponse | parseResponseError = Nothing } in case parseSuccess of RootInformation rootInformation -> case rootInformation.tribalWars2 of Nothing -> stateAfterIntegrateResponse Just gameRootInformation -> { stateAfterParseSuccess | gameRootInformation = Just gameRootInformation } ReadSelectedCharacterVillageDetailsResponse readVillageDetailsResponse -> { stateAfterParseSuccess | ownVillagesDetails = stateAfterParseSuccess.ownVillagesDetails |> Dict.insert readVillageDetailsResponse.villageId readVillageDetailsResponse.villageDetails } ReadVillageByCoordinatesResponse readVillageByCoordinatesResponse -> case runJavascriptInCurrentPageResponse.callbackReturnValueAsString of Nothing -> -- This case indicates the timeout while waiting for the result from the callback. stateAfterParseSuccess Just callbackReturnValueAsString -> case callbackReturnValueAsString |> Json.Decode.decodeString decodeVillageByCoordinatesResult of Err error -> { stateAfterParseSuccess | parseResponseError = Just error } Ok villageByCoordinates -> { stateAfterParseSuccess | searchVillageByCoordinatesResults = stateAfterParseSuccess.searchVillageByCoordinatesResults |> Dict.insert ( readVillageByCoordinatesResponse.villageCoordinates.x, readVillageByCoordinatesResponse.villageCoordinates.y ) villageByCoordinates } in { newState = state , request = requestToFramework state , statusMessage = statusMessageFromState state } requestToFramework : SimpleState -> BotRequest requestToFramework state = let javascript = case state.gameRootInformation of Nothing -> readRootInformationScript Just gameRootInformation -> let villagesWithoutDetails = gameRootInformation.readyVillages |> List.filter (\villageId -> state.ownVillagesDetails |> Dict.member villageId |> not) in case villagesWithoutDetails of villageWithoutDetailsId :: _ -> readSelectedCharacterVillageDetailsScript villageWithoutDetailsId [] -> let allCoordinatesToInspect = state.ownVillagesDetails |> Dict.values |> List.map (\village -> { x = village.locationX, y = village.locationY }) |> coordinatesToSearchFromOwnVillagesCoordinates remainingCoordinatesToInspect = allCoordinatesToInspect |> List.filter (\coordinates -> state.searchVillageByCoordinatesResults |> Dict.member ( coordinates.x, coordinates.y ) |> not) in case remainingCoordinatesToInspect |> List.head of Nothing -> readRootInformationScript Just coordinates -> startReadVillageByCoordinatesScript coordinates in SimpleLimbara.RunJavascriptInCurrentPageRequest { javascript = javascript , requestId = "request-id" , timeToWaitForCallbackMilliseconds = 1000 } coordinatesToSearchFromOwnVillagesCoordinates : List VillageCoordinates -> List VillageCoordinates coordinatesToSearchFromOwnVillagesCoordinates ownVillagesCoordinates = let radius = 4 coordinatesFromSingleOwnVillageCoordinates ownVillageCoordinates = List.range -radius radius |> List.concatMap (\offsetX -> List.range -radius radius |> List.map (\offsetY -> ( ownVillageCoordinates.x + offsetX, ownVillageCoordinates.y + offsetY )) ) allCoordinates : Set.Set ( Int, Int ) allCoordinates = ownVillagesCoordinates |> List.concatMap coordinatesFromSingleOwnVillageCoordinates |> Set.fromList in allCoordinates |> Set.toList |> List.map (\( x, y ) -> { x = x, y = y }) readRootInformationScript : String readRootInformationScript = """ (function () { tribalWars2 = (function(){ if (typeof angular == 'undefined' || !(angular.element(document.body).injector().has('modelDataService'))) return { NotInTribalWars: true}; modelDataService = angular.element(document.body).injector().get('modelDataService'); selectedCharacter = modelDataService.getSelectedCharacter() if (selectedCharacter == null) return { NotInTribalWars: true}; return { InTribalWars2 : { readyVillages : selectedCharacter.data.readyVillages , selectedVillageId : selectedCharacter.data.selectedVillage.data.villageId } }; })(); return JSON.stringify({ location : location.href, tribalWars2 : tribalWars2}); })() """ decodeResponseFromBrowser : Json.Decode.Decoder ResponseFromBrowser decodeResponseFromBrowser = Json.Decode.oneOf [ decodeRootInformation |> Json.Decode.map RootInformation , decodeReadSelectedCharacterVillageDetailsResponse |> Json.Decode.map ReadSelectedCharacterVillageDetailsResponse , decodeReadVillageByCoordinatesResponse |> Json.Decode.map ReadVillageByCoordinatesResponse ] decodeRootInformation : Json.Decode.Decoder RootInformationStructure decodeRootInformation = Json.Decode.map2 RootInformationStructure (Json.Decode.field "location" Json.Decode.string) (Json.Decode.field "tribalWars2" (Json.Decode.oneOf [ Json.Decode.field "NotInTribalWars" (Json.Decode.succeed Nothing) , Json.Decode.field "InTribalWars2" (decodeTribalWars2RootInformation |> Json.Decode.map Just) ] ) ) decodeTribalWars2RootInformation : Json.Decode.Decoder TribalWars2RootInformation decodeTribalWars2RootInformation = Json.Decode.map2 TribalWars2RootInformation (Json.Decode.field "readyVillages" (Json.Decode.list Json.Decode.int)) (Json.Decode.field "selectedVillageId" Json.Decode.int) readSelectedCharacterVillageDetailsScript : Int -> String readSelectedCharacterVillageDetailsScript villageId = """ (function () { modelDataService = angular.element(document.body).injector().get('modelDataService'); return JSON.stringify(modelDataService.getSelectedCharacter().data.villages[""" ++ "\"" ++ (villageId |> String.fromInt) ++ "\"" ++ """]); })() """ decodeSelectedCharacterVillageDetails : Json.Decode.Decoder VillageDetails decodeSelectedCharacterVillageDetails = Json.Decode.field "data" (Json.Decode.map2 VillageDetails (Json.Decode.field "x" Json.Decode.int) (Json.Decode.field "y" Json.Decode.int) ) decodeReadSelectedCharacterVillageDetailsResponse : Json.Decode.Decoder ReadSelectedCharacterVillageDetailsResponseStructure decodeReadSelectedCharacterVillageDetailsResponse = Json.Decode.map2 ReadSelectedCharacterVillageDetailsResponseStructure (Json.Decode.field "data" (Json.Decode.field "villageId" Json.Decode.int)) decodeSelectedCharacterVillageDetails {-| Example result: {"coordinates":{"x":498,"y":502},"villageByCoordinates":{"id":24,"name":"Pueblo de e.é45","x":498,"y":502,"character\_id":null,"province\_name":"Daufahlsur","character\_name":null,"character\_points":null,"points":96,"fortress":0,"tribe\_id":null,"tribe\_name":null,"tribe\_tag":null,"tribe\_points":null,"attack\_protection":0,"barbarian\_boost":null,"flags":{},"affiliation":"barbarian"}} When there is no village: {"coordinates":{"x":499,"y":502},"villageByCoordinates":{"villages":[]}} -} startReadVillageByCoordinatesScript : { x : Int, y : Int } -> String startReadVillageByCoordinatesScript { x, y } = """ (function inspectCoordinates(item) { autoCompleteService = angular.element(document.body).injector().get('autoCompleteService'); autoCompleteService.villageByCoordinates(item, function(data) { // console.log(JSON.stringify({ coordinates : item, villageByCoordinates: data})); ____callback____(JSON.stringify(data)); }); return JSON.stringify({ startedVillageByCoordinates : item }); })({x:""" ++ (x |> String.fromInt) ++ ", y:" ++ (y |> String.fromInt) ++ "})" decodeReadVillageByCoordinatesResponseTag : Json.Decode.Decoder VillageCoordinates decodeReadVillageByCoordinatesResponseTag = Json.Decode.field "startedVillageByCoordinates" (Json.Decode.map2 VillageCoordinates (Json.Decode.field "x" Json.Decode.int) (Json.Decode.field "y" Json.Decode.int) ) decodeReadVillageByCoordinatesResponse : Json.Decode.Decoder ReadVillageByCoordinatesResponseStructure decodeReadVillageByCoordinatesResponse = Json.Decode.map ReadVillageByCoordinatesResponseStructure decodeReadVillageByCoordinatesResponseTag decodeVillageByCoordinatesResult : Json.Decode.Decoder VillageByCoordinatesResult decodeVillageByCoordinatesResult = Json.Decode.oneOf [ Json.Decode.keyValuePairs (Json.Decode.list Json.Decode.value) |> Json.Decode.andThen (\keyValuePairs -> case keyValuePairs of [ ( singlePropertyName, singlePropertyValue ) ] -> if singlePropertyName == "villages" then Json.Decode.succeed NoVillageThere else Json.Decode.fail "Other property name." _ -> Json.Decode.fail "Other number of properties." ) , decodeVillageByCoordinatesDetails |> Json.Decode.map VillageThere ] decodeVillageByCoordinatesDetails : Json.Decode.Decoder VillageByCoordinatesDetails decodeVillageByCoordinatesDetails = Json.Decode.map VillageByCoordinatesDetails (Json.Decode.field "affiliation" Json.Decode.string |> Json.Decode.map (\affiliation -> case affiliation |> String.toLower of "barbarian" -> AffiliationBarbarian _ -> AffiliationOther ) ) statusMessageFromState : SimpleState -> String statusMessageFromState state = let jsRunResult = "lastRunJavascriptResult:\n" ++ (state.lastRunJavascriptResult |> Maybe.map .response |> describeMaybe describeRunJavascriptInCurrentPageResponseStructure) aboutGame = case state.gameRootInformation of Nothing -> "Did not yet read game root information." Just gameRootInformation -> "Found " ++ (gameRootInformation.readyVillages |> List.length |> String.fromInt) ++ " villages. Currently selected is " ++ (gameRootInformation.selectedVillageId |> String.fromInt) ++ "." villagesByCoordinates = state.searchVillageByCoordinatesResults |> Dict.toList |> List.filterMap (\( coordinates, scanResult ) -> case scanResult of NoVillageThere -> Nothing VillageThere village -> Just ( coordinates, village ) ) |> Dict.fromList villagesByCoordinatesReport = "Searched " ++ (state.searchVillageByCoordinatesResults |> Dict.size |> String.fromInt) ++ " coordindates and found " ++ (villagesByCoordinates |> Dict.size |> String.fromInt) ++ " villages, " ++ (villagesByCoordinates |> Dict.filter (\_ village -> village.affiliation == AffiliationBarbarian) |> Dict.size |> String.fromInt) ++ " of wich are barbarian villages." parseResponseErrorReport = case state.parseResponseError of Nothing -> "" Just parseResponseError -> Json.Decode.errorToString parseResponseError in [ jsRunResult, aboutGame, villagesByCoordinatesReport, parseResponseErrorReport ] |> String.join "\n" describeRunJavascriptInCurrentPageResponseStructure : SimpleLimbara.RunJavascriptInCurrentPageResponseStructure -> String describeRunJavascriptInCurrentPageResponseStructure response = "{ directReturnValueAsString = " ++ describeString 300 response.directReturnValueAsString ++ "\n" ++ ", callbackReturnValueAsString = " ++ describeMaybe (describeString 300) response.callbackReturnValueAsString ++ "\n}" describeString : Int -> String -> String describeString maxLength string = "\"" ++ (string |> stringEllipsis maxLength "...") ++ "\"" describeMaybe : (just -> String) -> Maybe just -> String describeMaybe describeJust maybe = case maybe of Nothing -> "Nothing" Just just -> describeJust just stringEllipsis : Int -> String -> String -> String stringEllipsis howLong append string = if String.length string <= howLong then string else String.left (howLong - String.length append) string ++ append
28645
{- Explore farming barbarian villages in Tribal Wars 2 This version only reads your villages. The bot automatically opens a new web browser window. The first time you run it, it might take more time because it needs to download the web browser software. When the web browser has opened, navigate to Tribal Wars 2 and log in to your account, so you see your villages. You then will probably at an URL like https://es.tribalwars2.com/game.php?world=es77&character_id=123456# The bot then outputs the number of villages and the ID of the currently selected village. When you change the village in-game, you can see the output from the bot changing as well to indicate the new selected village. bot-catalog-tags:exploration,tribal-wars-2 authors-forum-usernames:viir -} module Bot exposing ( State , initState , processEvent ) import BotEngine.Interface_To_Host_20190808 as InterfaceToHost import Dict import Json.Decode import Limbara.SimpleLimbara as SimpleLimbara exposing (BotEventAtTime, BotRequest(..)) import Set type alias SimpleState = { lastRunJavascriptResult : Maybe { response : SimpleLimbara.RunJavascriptInCurrentPageResponseStructure , parseResult : Result Json.Decode.Error RootInformationStructure } , gameRootInformation : Maybe TribalWars2RootInformation , ownVillagesDetails : Dict.Dict Int VillageDetails , searchVillageByCoordinatesResults : Dict.Dict ( Int, Int ) VillageByCoordinatesResult , parseResponseError : Maybe Json.Decode.Error } type alias State = SimpleLimbara.StateIncludingSetup SimpleState type ResponseFromBrowser = RootInformation RootInformationStructure | ReadSelectedCharacterVillageDetailsResponse ReadSelectedCharacterVillageDetailsResponseStructure | ReadVillageByCoordinatesResponse ReadVillageByCoordinatesResponseStructure type alias RootInformationStructure = { location : String , tribalWars2 : Maybe TribalWars2RootInformation } type alias TribalWars2RootInformation = { readyVillages : List Int , selectedVillageId : Int } type alias ReadSelectedCharacterVillageDetailsResponseStructure = { villageId : Int , villageDetails : VillageDetails } type alias ReadVillageByCoordinatesResponseStructure = { villageCoordinates : VillageCoordinates } type alias VillageDetails = { locationX : Int , locationY : Int } type VillageByCoordinatesResult = NoVillageThere | VillageThere VillageByCoordinatesDetails type alias VillageByCoordinatesDetails = { affiliation : VillageByCoordinatesAffiliation } type VillageByCoordinatesAffiliation = AffiliationBarbarian | AffiliationOther type alias VillageCoordinates = { x : Int , y : Int } initState : State initState = SimpleLimbara.initState { lastRunJavascriptResult = Nothing , gameRootInformation = Nothing , ownVillagesDetails = Dict.empty , searchVillageByCoordinatesResults = Dict.empty , parseResponseError = Nothing } processEvent : InterfaceToHost.BotEvent -> State -> ( State, InterfaceToHost.BotResponse ) processEvent = SimpleLimbara.processEvent simpleProcessEvent simpleProcessEvent : BotEventAtTime -> SimpleState -> { newState : SimpleState, request : BotRequest, statusMessage : String } simpleProcessEvent eventAtTime stateBefore = let state = case eventAtTime.event of SimpleLimbara.SetBotConfiguration _ -> stateBefore SimpleLimbara.RunJavascriptInCurrentPageResponse runJavascriptInCurrentPageResponse -> let parseAsRootInfoResult = runJavascriptInCurrentPageResponse.directReturnValueAsString |> Json.Decode.decodeString decodeRootInformation stateAfterIntegrateResponse = { stateBefore | lastRunJavascriptResult = Just { response = runJavascriptInCurrentPageResponse , parseResult = parseAsRootInfoResult } } parseResult = runJavascriptInCurrentPageResponse.directReturnValueAsString |> Json.Decode.decodeString decodeResponseFromBrowser in case parseResult of Err error -> { stateAfterIntegrateResponse | parseResponseError = Just error } Ok parseSuccess -> let stateAfterParseSuccess = { stateAfterIntegrateResponse | parseResponseError = Nothing } in case parseSuccess of RootInformation rootInformation -> case rootInformation.tribalWars2 of Nothing -> stateAfterIntegrateResponse Just gameRootInformation -> { stateAfterParseSuccess | gameRootInformation = Just gameRootInformation } ReadSelectedCharacterVillageDetailsResponse readVillageDetailsResponse -> { stateAfterParseSuccess | ownVillagesDetails = stateAfterParseSuccess.ownVillagesDetails |> Dict.insert readVillageDetailsResponse.villageId readVillageDetailsResponse.villageDetails } ReadVillageByCoordinatesResponse readVillageByCoordinatesResponse -> case runJavascriptInCurrentPageResponse.callbackReturnValueAsString of Nothing -> -- This case indicates the timeout while waiting for the result from the callback. stateAfterParseSuccess Just callbackReturnValueAsString -> case callbackReturnValueAsString |> Json.Decode.decodeString decodeVillageByCoordinatesResult of Err error -> { stateAfterParseSuccess | parseResponseError = Just error } Ok villageByCoordinates -> { stateAfterParseSuccess | searchVillageByCoordinatesResults = stateAfterParseSuccess.searchVillageByCoordinatesResults |> Dict.insert ( readVillageByCoordinatesResponse.villageCoordinates.x, readVillageByCoordinatesResponse.villageCoordinates.y ) villageByCoordinates } in { newState = state , request = requestToFramework state , statusMessage = statusMessageFromState state } requestToFramework : SimpleState -> BotRequest requestToFramework state = let javascript = case state.gameRootInformation of Nothing -> readRootInformationScript Just gameRootInformation -> let villagesWithoutDetails = gameRootInformation.readyVillages |> List.filter (\villageId -> state.ownVillagesDetails |> Dict.member villageId |> not) in case villagesWithoutDetails of villageWithoutDetailsId :: _ -> readSelectedCharacterVillageDetailsScript villageWithoutDetailsId [] -> let allCoordinatesToInspect = state.ownVillagesDetails |> Dict.values |> List.map (\village -> { x = village.locationX, y = village.locationY }) |> coordinatesToSearchFromOwnVillagesCoordinates remainingCoordinatesToInspect = allCoordinatesToInspect |> List.filter (\coordinates -> state.searchVillageByCoordinatesResults |> Dict.member ( coordinates.x, coordinates.y ) |> not) in case remainingCoordinatesToInspect |> List.head of Nothing -> readRootInformationScript Just coordinates -> startReadVillageByCoordinatesScript coordinates in SimpleLimbara.RunJavascriptInCurrentPageRequest { javascript = javascript , requestId = "request-id" , timeToWaitForCallbackMilliseconds = 1000 } coordinatesToSearchFromOwnVillagesCoordinates : List VillageCoordinates -> List VillageCoordinates coordinatesToSearchFromOwnVillagesCoordinates ownVillagesCoordinates = let radius = 4 coordinatesFromSingleOwnVillageCoordinates ownVillageCoordinates = List.range -radius radius |> List.concatMap (\offsetX -> List.range -radius radius |> List.map (\offsetY -> ( ownVillageCoordinates.x + offsetX, ownVillageCoordinates.y + offsetY )) ) allCoordinates : Set.Set ( Int, Int ) allCoordinates = ownVillagesCoordinates |> List.concatMap coordinatesFromSingleOwnVillageCoordinates |> Set.fromList in allCoordinates |> Set.toList |> List.map (\( x, y ) -> { x = x, y = y }) readRootInformationScript : String readRootInformationScript = """ (function () { tribalWars2 = (function(){ if (typeof angular == 'undefined' || !(angular.element(document.body).injector().has('modelDataService'))) return { NotInTribalWars: true}; modelDataService = angular.element(document.body).injector().get('modelDataService'); selectedCharacter = modelDataService.getSelectedCharacter() if (selectedCharacter == null) return { NotInTribalWars: true}; return { InTribalWars2 : { readyVillages : selectedCharacter.data.readyVillages , selectedVillageId : selectedCharacter.data.selectedVillage.data.villageId } }; })(); return JSON.stringify({ location : location.href, tribalWars2 : tribalWars2}); })() """ decodeResponseFromBrowser : Json.Decode.Decoder ResponseFromBrowser decodeResponseFromBrowser = Json.Decode.oneOf [ decodeRootInformation |> Json.Decode.map RootInformation , decodeReadSelectedCharacterVillageDetailsResponse |> Json.Decode.map ReadSelectedCharacterVillageDetailsResponse , decodeReadVillageByCoordinatesResponse |> Json.Decode.map ReadVillageByCoordinatesResponse ] decodeRootInformation : Json.Decode.Decoder RootInformationStructure decodeRootInformation = Json.Decode.map2 RootInformationStructure (Json.Decode.field "location" Json.Decode.string) (Json.Decode.field "tribalWars2" (Json.Decode.oneOf [ Json.Decode.field "NotInTribalWars" (Json.Decode.succeed Nothing) , Json.Decode.field "InTribalWars2" (decodeTribalWars2RootInformation |> Json.Decode.map Just) ] ) ) decodeTribalWars2RootInformation : Json.Decode.Decoder TribalWars2RootInformation decodeTribalWars2RootInformation = Json.Decode.map2 TribalWars2RootInformation (Json.Decode.field "readyVillages" (Json.Decode.list Json.Decode.int)) (Json.Decode.field "selectedVillageId" Json.Decode.int) readSelectedCharacterVillageDetailsScript : Int -> String readSelectedCharacterVillageDetailsScript villageId = """ (function () { modelDataService = angular.element(document.body).injector().get('modelDataService'); return JSON.stringify(modelDataService.getSelectedCharacter().data.villages[""" ++ "\"" ++ (villageId |> String.fromInt) ++ "\"" ++ """]); })() """ decodeSelectedCharacterVillageDetails : Json.Decode.Decoder VillageDetails decodeSelectedCharacterVillageDetails = Json.Decode.field "data" (Json.Decode.map2 VillageDetails (Json.Decode.field "x" Json.Decode.int) (Json.Decode.field "y" Json.Decode.int) ) decodeReadSelectedCharacterVillageDetailsResponse : Json.Decode.Decoder ReadSelectedCharacterVillageDetailsResponseStructure decodeReadSelectedCharacterVillageDetailsResponse = Json.Decode.map2 ReadSelectedCharacterVillageDetailsResponseStructure (Json.Decode.field "data" (Json.Decode.field "villageId" Json.Decode.int)) decodeSelectedCharacterVillageDetails {-| Example result: {"coordinates":{"x":498,"y":502},"villageByCoordinates":{"id":24,"name":"<NAME>","x":498,"y":502,"character\_id":null,"province\_name":"Daufahlsur","character\_name":null,"character\_points":null,"points":96,"fortress":0,"tribe\_id":null,"tribe\_name":null,"tribe\_tag":null,"tribe\_points":null,"attack\_protection":0,"barbarian\_boost":null,"flags":{},"affiliation":"barbarian"}} When there is no village: {"coordinates":{"x":499,"y":502},"villageByCoordinates":{"villages":[]}} -} startReadVillageByCoordinatesScript : { x : Int, y : Int } -> String startReadVillageByCoordinatesScript { x, y } = """ (function inspectCoordinates(item) { autoCompleteService = angular.element(document.body).injector().get('autoCompleteService'); autoCompleteService.villageByCoordinates(item, function(data) { // console.log(JSON.stringify({ coordinates : item, villageByCoordinates: data})); ____callback____(JSON.stringify(data)); }); return JSON.stringify({ startedVillageByCoordinates : item }); })({x:""" ++ (x |> String.fromInt) ++ ", y:" ++ (y |> String.fromInt) ++ "})" decodeReadVillageByCoordinatesResponseTag : Json.Decode.Decoder VillageCoordinates decodeReadVillageByCoordinatesResponseTag = Json.Decode.field "startedVillageByCoordinates" (Json.Decode.map2 VillageCoordinates (Json.Decode.field "x" Json.Decode.int) (Json.Decode.field "y" Json.Decode.int) ) decodeReadVillageByCoordinatesResponse : Json.Decode.Decoder ReadVillageByCoordinatesResponseStructure decodeReadVillageByCoordinatesResponse = Json.Decode.map ReadVillageByCoordinatesResponseStructure decodeReadVillageByCoordinatesResponseTag decodeVillageByCoordinatesResult : Json.Decode.Decoder VillageByCoordinatesResult decodeVillageByCoordinatesResult = Json.Decode.oneOf [ Json.Decode.keyValuePairs (Json.Decode.list Json.Decode.value) |> Json.Decode.andThen (\keyValuePairs -> case keyValuePairs of [ ( singlePropertyName, singlePropertyValue ) ] -> if singlePropertyName == "villages" then Json.Decode.succeed NoVillageThere else Json.Decode.fail "Other property name." _ -> Json.Decode.fail "Other number of properties." ) , decodeVillageByCoordinatesDetails |> Json.Decode.map VillageThere ] decodeVillageByCoordinatesDetails : Json.Decode.Decoder VillageByCoordinatesDetails decodeVillageByCoordinatesDetails = Json.Decode.map VillageByCoordinatesDetails (Json.Decode.field "affiliation" Json.Decode.string |> Json.Decode.map (\affiliation -> case affiliation |> String.toLower of "barbarian" -> AffiliationBarbarian _ -> AffiliationOther ) ) statusMessageFromState : SimpleState -> String statusMessageFromState state = let jsRunResult = "lastRunJavascriptResult:\n" ++ (state.lastRunJavascriptResult |> Maybe.map .response |> describeMaybe describeRunJavascriptInCurrentPageResponseStructure) aboutGame = case state.gameRootInformation of Nothing -> "Did not yet read game root information." Just gameRootInformation -> "Found " ++ (gameRootInformation.readyVillages |> List.length |> String.fromInt) ++ " villages. Currently selected is " ++ (gameRootInformation.selectedVillageId |> String.fromInt) ++ "." villagesByCoordinates = state.searchVillageByCoordinatesResults |> Dict.toList |> List.filterMap (\( coordinates, scanResult ) -> case scanResult of NoVillageThere -> Nothing VillageThere village -> Just ( coordinates, village ) ) |> Dict.fromList villagesByCoordinatesReport = "Searched " ++ (state.searchVillageByCoordinatesResults |> Dict.size |> String.fromInt) ++ " coordindates and found " ++ (villagesByCoordinates |> Dict.size |> String.fromInt) ++ " villages, " ++ (villagesByCoordinates |> Dict.filter (\_ village -> village.affiliation == AffiliationBarbarian) |> Dict.size |> String.fromInt) ++ " of wich are barbarian villages." parseResponseErrorReport = case state.parseResponseError of Nothing -> "" Just parseResponseError -> Json.Decode.errorToString parseResponseError in [ jsRunResult, aboutGame, villagesByCoordinatesReport, parseResponseErrorReport ] |> String.join "\n" describeRunJavascriptInCurrentPageResponseStructure : SimpleLimbara.RunJavascriptInCurrentPageResponseStructure -> String describeRunJavascriptInCurrentPageResponseStructure response = "{ directReturnValueAsString = " ++ describeString 300 response.directReturnValueAsString ++ "\n" ++ ", callbackReturnValueAsString = " ++ describeMaybe (describeString 300) response.callbackReturnValueAsString ++ "\n}" describeString : Int -> String -> String describeString maxLength string = "\"" ++ (string |> stringEllipsis maxLength "...") ++ "\"" describeMaybe : (just -> String) -> Maybe just -> String describeMaybe describeJust maybe = case maybe of Nothing -> "Nothing" Just just -> describeJust just stringEllipsis : Int -> String -> String -> String stringEllipsis howLong append string = if String.length string <= howLong then string else String.left (howLong - String.length append) string ++ append
true
{- Explore farming barbarian villages in Tribal Wars 2 This version only reads your villages. The bot automatically opens a new web browser window. The first time you run it, it might take more time because it needs to download the web browser software. When the web browser has opened, navigate to Tribal Wars 2 and log in to your account, so you see your villages. You then will probably at an URL like https://es.tribalwars2.com/game.php?world=es77&character_id=123456# The bot then outputs the number of villages and the ID of the currently selected village. When you change the village in-game, you can see the output from the bot changing as well to indicate the new selected village. bot-catalog-tags:exploration,tribal-wars-2 authors-forum-usernames:viir -} module Bot exposing ( State , initState , processEvent ) import BotEngine.Interface_To_Host_20190808 as InterfaceToHost import Dict import Json.Decode import Limbara.SimpleLimbara as SimpleLimbara exposing (BotEventAtTime, BotRequest(..)) import Set type alias SimpleState = { lastRunJavascriptResult : Maybe { response : SimpleLimbara.RunJavascriptInCurrentPageResponseStructure , parseResult : Result Json.Decode.Error RootInformationStructure } , gameRootInformation : Maybe TribalWars2RootInformation , ownVillagesDetails : Dict.Dict Int VillageDetails , searchVillageByCoordinatesResults : Dict.Dict ( Int, Int ) VillageByCoordinatesResult , parseResponseError : Maybe Json.Decode.Error } type alias State = SimpleLimbara.StateIncludingSetup SimpleState type ResponseFromBrowser = RootInformation RootInformationStructure | ReadSelectedCharacterVillageDetailsResponse ReadSelectedCharacterVillageDetailsResponseStructure | ReadVillageByCoordinatesResponse ReadVillageByCoordinatesResponseStructure type alias RootInformationStructure = { location : String , tribalWars2 : Maybe TribalWars2RootInformation } type alias TribalWars2RootInformation = { readyVillages : List Int , selectedVillageId : Int } type alias ReadSelectedCharacterVillageDetailsResponseStructure = { villageId : Int , villageDetails : VillageDetails } type alias ReadVillageByCoordinatesResponseStructure = { villageCoordinates : VillageCoordinates } type alias VillageDetails = { locationX : Int , locationY : Int } type VillageByCoordinatesResult = NoVillageThere | VillageThere VillageByCoordinatesDetails type alias VillageByCoordinatesDetails = { affiliation : VillageByCoordinatesAffiliation } type VillageByCoordinatesAffiliation = AffiliationBarbarian | AffiliationOther type alias VillageCoordinates = { x : Int , y : Int } initState : State initState = SimpleLimbara.initState { lastRunJavascriptResult = Nothing , gameRootInformation = Nothing , ownVillagesDetails = Dict.empty , searchVillageByCoordinatesResults = Dict.empty , parseResponseError = Nothing } processEvent : InterfaceToHost.BotEvent -> State -> ( State, InterfaceToHost.BotResponse ) processEvent = SimpleLimbara.processEvent simpleProcessEvent simpleProcessEvent : BotEventAtTime -> SimpleState -> { newState : SimpleState, request : BotRequest, statusMessage : String } simpleProcessEvent eventAtTime stateBefore = let state = case eventAtTime.event of SimpleLimbara.SetBotConfiguration _ -> stateBefore SimpleLimbara.RunJavascriptInCurrentPageResponse runJavascriptInCurrentPageResponse -> let parseAsRootInfoResult = runJavascriptInCurrentPageResponse.directReturnValueAsString |> Json.Decode.decodeString decodeRootInformation stateAfterIntegrateResponse = { stateBefore | lastRunJavascriptResult = Just { response = runJavascriptInCurrentPageResponse , parseResult = parseAsRootInfoResult } } parseResult = runJavascriptInCurrentPageResponse.directReturnValueAsString |> Json.Decode.decodeString decodeResponseFromBrowser in case parseResult of Err error -> { stateAfterIntegrateResponse | parseResponseError = Just error } Ok parseSuccess -> let stateAfterParseSuccess = { stateAfterIntegrateResponse | parseResponseError = Nothing } in case parseSuccess of RootInformation rootInformation -> case rootInformation.tribalWars2 of Nothing -> stateAfterIntegrateResponse Just gameRootInformation -> { stateAfterParseSuccess | gameRootInformation = Just gameRootInformation } ReadSelectedCharacterVillageDetailsResponse readVillageDetailsResponse -> { stateAfterParseSuccess | ownVillagesDetails = stateAfterParseSuccess.ownVillagesDetails |> Dict.insert readVillageDetailsResponse.villageId readVillageDetailsResponse.villageDetails } ReadVillageByCoordinatesResponse readVillageByCoordinatesResponse -> case runJavascriptInCurrentPageResponse.callbackReturnValueAsString of Nothing -> -- This case indicates the timeout while waiting for the result from the callback. stateAfterParseSuccess Just callbackReturnValueAsString -> case callbackReturnValueAsString |> Json.Decode.decodeString decodeVillageByCoordinatesResult of Err error -> { stateAfterParseSuccess | parseResponseError = Just error } Ok villageByCoordinates -> { stateAfterParseSuccess | searchVillageByCoordinatesResults = stateAfterParseSuccess.searchVillageByCoordinatesResults |> Dict.insert ( readVillageByCoordinatesResponse.villageCoordinates.x, readVillageByCoordinatesResponse.villageCoordinates.y ) villageByCoordinates } in { newState = state , request = requestToFramework state , statusMessage = statusMessageFromState state } requestToFramework : SimpleState -> BotRequest requestToFramework state = let javascript = case state.gameRootInformation of Nothing -> readRootInformationScript Just gameRootInformation -> let villagesWithoutDetails = gameRootInformation.readyVillages |> List.filter (\villageId -> state.ownVillagesDetails |> Dict.member villageId |> not) in case villagesWithoutDetails of villageWithoutDetailsId :: _ -> readSelectedCharacterVillageDetailsScript villageWithoutDetailsId [] -> let allCoordinatesToInspect = state.ownVillagesDetails |> Dict.values |> List.map (\village -> { x = village.locationX, y = village.locationY }) |> coordinatesToSearchFromOwnVillagesCoordinates remainingCoordinatesToInspect = allCoordinatesToInspect |> List.filter (\coordinates -> state.searchVillageByCoordinatesResults |> Dict.member ( coordinates.x, coordinates.y ) |> not) in case remainingCoordinatesToInspect |> List.head of Nothing -> readRootInformationScript Just coordinates -> startReadVillageByCoordinatesScript coordinates in SimpleLimbara.RunJavascriptInCurrentPageRequest { javascript = javascript , requestId = "request-id" , timeToWaitForCallbackMilliseconds = 1000 } coordinatesToSearchFromOwnVillagesCoordinates : List VillageCoordinates -> List VillageCoordinates coordinatesToSearchFromOwnVillagesCoordinates ownVillagesCoordinates = let radius = 4 coordinatesFromSingleOwnVillageCoordinates ownVillageCoordinates = List.range -radius radius |> List.concatMap (\offsetX -> List.range -radius radius |> List.map (\offsetY -> ( ownVillageCoordinates.x + offsetX, ownVillageCoordinates.y + offsetY )) ) allCoordinates : Set.Set ( Int, Int ) allCoordinates = ownVillagesCoordinates |> List.concatMap coordinatesFromSingleOwnVillageCoordinates |> Set.fromList in allCoordinates |> Set.toList |> List.map (\( x, y ) -> { x = x, y = y }) readRootInformationScript : String readRootInformationScript = """ (function () { tribalWars2 = (function(){ if (typeof angular == 'undefined' || !(angular.element(document.body).injector().has('modelDataService'))) return { NotInTribalWars: true}; modelDataService = angular.element(document.body).injector().get('modelDataService'); selectedCharacter = modelDataService.getSelectedCharacter() if (selectedCharacter == null) return { NotInTribalWars: true}; return { InTribalWars2 : { readyVillages : selectedCharacter.data.readyVillages , selectedVillageId : selectedCharacter.data.selectedVillage.data.villageId } }; })(); return JSON.stringify({ location : location.href, tribalWars2 : tribalWars2}); })() """ decodeResponseFromBrowser : Json.Decode.Decoder ResponseFromBrowser decodeResponseFromBrowser = Json.Decode.oneOf [ decodeRootInformation |> Json.Decode.map RootInformation , decodeReadSelectedCharacterVillageDetailsResponse |> Json.Decode.map ReadSelectedCharacterVillageDetailsResponse , decodeReadVillageByCoordinatesResponse |> Json.Decode.map ReadVillageByCoordinatesResponse ] decodeRootInformation : Json.Decode.Decoder RootInformationStructure decodeRootInformation = Json.Decode.map2 RootInformationStructure (Json.Decode.field "location" Json.Decode.string) (Json.Decode.field "tribalWars2" (Json.Decode.oneOf [ Json.Decode.field "NotInTribalWars" (Json.Decode.succeed Nothing) , Json.Decode.field "InTribalWars2" (decodeTribalWars2RootInformation |> Json.Decode.map Just) ] ) ) decodeTribalWars2RootInformation : Json.Decode.Decoder TribalWars2RootInformation decodeTribalWars2RootInformation = Json.Decode.map2 TribalWars2RootInformation (Json.Decode.field "readyVillages" (Json.Decode.list Json.Decode.int)) (Json.Decode.field "selectedVillageId" Json.Decode.int) readSelectedCharacterVillageDetailsScript : Int -> String readSelectedCharacterVillageDetailsScript villageId = """ (function () { modelDataService = angular.element(document.body).injector().get('modelDataService'); return JSON.stringify(modelDataService.getSelectedCharacter().data.villages[""" ++ "\"" ++ (villageId |> String.fromInt) ++ "\"" ++ """]); })() """ decodeSelectedCharacterVillageDetails : Json.Decode.Decoder VillageDetails decodeSelectedCharacterVillageDetails = Json.Decode.field "data" (Json.Decode.map2 VillageDetails (Json.Decode.field "x" Json.Decode.int) (Json.Decode.field "y" Json.Decode.int) ) decodeReadSelectedCharacterVillageDetailsResponse : Json.Decode.Decoder ReadSelectedCharacterVillageDetailsResponseStructure decodeReadSelectedCharacterVillageDetailsResponse = Json.Decode.map2 ReadSelectedCharacterVillageDetailsResponseStructure (Json.Decode.field "data" (Json.Decode.field "villageId" Json.Decode.int)) decodeSelectedCharacterVillageDetails {-| Example result: {"coordinates":{"x":498,"y":502},"villageByCoordinates":{"id":24,"name":"PI:NAME:<NAME>END_PI","x":498,"y":502,"character\_id":null,"province\_name":"Daufahlsur","character\_name":null,"character\_points":null,"points":96,"fortress":0,"tribe\_id":null,"tribe\_name":null,"tribe\_tag":null,"tribe\_points":null,"attack\_protection":0,"barbarian\_boost":null,"flags":{},"affiliation":"barbarian"}} When there is no village: {"coordinates":{"x":499,"y":502},"villageByCoordinates":{"villages":[]}} -} startReadVillageByCoordinatesScript : { x : Int, y : Int } -> String startReadVillageByCoordinatesScript { x, y } = """ (function inspectCoordinates(item) { autoCompleteService = angular.element(document.body).injector().get('autoCompleteService'); autoCompleteService.villageByCoordinates(item, function(data) { // console.log(JSON.stringify({ coordinates : item, villageByCoordinates: data})); ____callback____(JSON.stringify(data)); }); return JSON.stringify({ startedVillageByCoordinates : item }); })({x:""" ++ (x |> String.fromInt) ++ ", y:" ++ (y |> String.fromInt) ++ "})" decodeReadVillageByCoordinatesResponseTag : Json.Decode.Decoder VillageCoordinates decodeReadVillageByCoordinatesResponseTag = Json.Decode.field "startedVillageByCoordinates" (Json.Decode.map2 VillageCoordinates (Json.Decode.field "x" Json.Decode.int) (Json.Decode.field "y" Json.Decode.int) ) decodeReadVillageByCoordinatesResponse : Json.Decode.Decoder ReadVillageByCoordinatesResponseStructure decodeReadVillageByCoordinatesResponse = Json.Decode.map ReadVillageByCoordinatesResponseStructure decodeReadVillageByCoordinatesResponseTag decodeVillageByCoordinatesResult : Json.Decode.Decoder VillageByCoordinatesResult decodeVillageByCoordinatesResult = Json.Decode.oneOf [ Json.Decode.keyValuePairs (Json.Decode.list Json.Decode.value) |> Json.Decode.andThen (\keyValuePairs -> case keyValuePairs of [ ( singlePropertyName, singlePropertyValue ) ] -> if singlePropertyName == "villages" then Json.Decode.succeed NoVillageThere else Json.Decode.fail "Other property name." _ -> Json.Decode.fail "Other number of properties." ) , decodeVillageByCoordinatesDetails |> Json.Decode.map VillageThere ] decodeVillageByCoordinatesDetails : Json.Decode.Decoder VillageByCoordinatesDetails decodeVillageByCoordinatesDetails = Json.Decode.map VillageByCoordinatesDetails (Json.Decode.field "affiliation" Json.Decode.string |> Json.Decode.map (\affiliation -> case affiliation |> String.toLower of "barbarian" -> AffiliationBarbarian _ -> AffiliationOther ) ) statusMessageFromState : SimpleState -> String statusMessageFromState state = let jsRunResult = "lastRunJavascriptResult:\n" ++ (state.lastRunJavascriptResult |> Maybe.map .response |> describeMaybe describeRunJavascriptInCurrentPageResponseStructure) aboutGame = case state.gameRootInformation of Nothing -> "Did not yet read game root information." Just gameRootInformation -> "Found " ++ (gameRootInformation.readyVillages |> List.length |> String.fromInt) ++ " villages. Currently selected is " ++ (gameRootInformation.selectedVillageId |> String.fromInt) ++ "." villagesByCoordinates = state.searchVillageByCoordinatesResults |> Dict.toList |> List.filterMap (\( coordinates, scanResult ) -> case scanResult of NoVillageThere -> Nothing VillageThere village -> Just ( coordinates, village ) ) |> Dict.fromList villagesByCoordinatesReport = "Searched " ++ (state.searchVillageByCoordinatesResults |> Dict.size |> String.fromInt) ++ " coordindates and found " ++ (villagesByCoordinates |> Dict.size |> String.fromInt) ++ " villages, " ++ (villagesByCoordinates |> Dict.filter (\_ village -> village.affiliation == AffiliationBarbarian) |> Dict.size |> String.fromInt) ++ " of wich are barbarian villages." parseResponseErrorReport = case state.parseResponseError of Nothing -> "" Just parseResponseError -> Json.Decode.errorToString parseResponseError in [ jsRunResult, aboutGame, villagesByCoordinatesReport, parseResponseErrorReport ] |> String.join "\n" describeRunJavascriptInCurrentPageResponseStructure : SimpleLimbara.RunJavascriptInCurrentPageResponseStructure -> String describeRunJavascriptInCurrentPageResponseStructure response = "{ directReturnValueAsString = " ++ describeString 300 response.directReturnValueAsString ++ "\n" ++ ", callbackReturnValueAsString = " ++ describeMaybe (describeString 300) response.callbackReturnValueAsString ++ "\n}" describeString : Int -> String -> String describeString maxLength string = "\"" ++ (string |> stringEllipsis maxLength "...") ++ "\"" describeMaybe : (just -> String) -> Maybe just -> String describeMaybe describeJust maybe = case maybe of Nothing -> "Nothing" Just just -> describeJust just stringEllipsis : Int -> String -> String -> String stringEllipsis howLong append string = if String.length string <= howLong then string else String.left (howLong - String.length append) string ++ append
elm
[ { "context": "\"\n{\n \"data\" : {\n \"id\" : \"123\",\n \"email\" : \"Joe@domain.net\",\n \"isPremium\" : true,\n \"profile\" : {\n ", "end": 807, "score": 0.9999044538, "start": 793, "tag": "EMAIL", "value": "Joe@domain.net" } ]
beginning-elm/egghead-json-decode/DecodeJsonErrorSuccessDataIntoElmUnionTypes.elm
guilhermegregio/learning-elm-lang
0
module Main exposing (..) import Html exposing (text) import Json.Decode exposing (..) import Json.Decode.Extra exposing ((|:), date, parseInt, fromResult) import Json.Decode.Pipeline exposing (decode, optional, optionalAt, required, requiredAt) import Date exposing (Date) main = sampleFailure |> decodeString response |> toString |> text type Membership = Standard | Premium type Gender = Female | Male type alias User = { id : Int , email : String , membership : Membership , gender : Maybe Gender , dateOfBirth : Date , notifications : List Notification } type alias Notification = { title : String , message : String } sampleSuccess = """ { "data" : { "id" : "123", "email" : "Joe@domain.net", "isPremium" : true, "profile" : { "gender": "male", "dateOfBirth": "Sun Jan 07 2018 00:18:17 GMT+0100 (CET)" }, "notifications" : [ { "title" : "Welcome back!", "message" : "We've been missing you" }, { "title" : "Weather alert", "message" : "Expect stormy weather" } ] } } """ sampleFailure = """ { "error": { "message": "wrong_password" } } """ response : Decoder (Result String User) response = oneOf [ field "data" user |> map Ok , at [ "error", "message" ] string |> map Err ] user = decode User |> required "id" parseInt |> required "email" (string |> map String.toLower) |> required "isPremium" membership |> optionalAt [ "profile", "gender" ] (gender |> map Just) Nothing |> requiredAt [ "profile", "dateOfBirth" ] date |> optional "notifications" (list notification) [] notification = map2 Notification (field "title" string) (field "message" string) gender = let toGender s = case s of "male" -> succeed Male "female" -> succeed Female _ -> fail (s ++ " is not a valid gender") in string |> andThen toGender membership = let toMembership b = case b of True -> Premium False -> Standard in bool |> map toMembership
22356
module Main exposing (..) import Html exposing (text) import Json.Decode exposing (..) import Json.Decode.Extra exposing ((|:), date, parseInt, fromResult) import Json.Decode.Pipeline exposing (decode, optional, optionalAt, required, requiredAt) import Date exposing (Date) main = sampleFailure |> decodeString response |> toString |> text type Membership = Standard | Premium type Gender = Female | Male type alias User = { id : Int , email : String , membership : Membership , gender : Maybe Gender , dateOfBirth : Date , notifications : List Notification } type alias Notification = { title : String , message : String } sampleSuccess = """ { "data" : { "id" : "123", "email" : "<EMAIL>", "isPremium" : true, "profile" : { "gender": "male", "dateOfBirth": "Sun Jan 07 2018 00:18:17 GMT+0100 (CET)" }, "notifications" : [ { "title" : "Welcome back!", "message" : "We've been missing you" }, { "title" : "Weather alert", "message" : "Expect stormy weather" } ] } } """ sampleFailure = """ { "error": { "message": "wrong_password" } } """ response : Decoder (Result String User) response = oneOf [ field "data" user |> map Ok , at [ "error", "message" ] string |> map Err ] user = decode User |> required "id" parseInt |> required "email" (string |> map String.toLower) |> required "isPremium" membership |> optionalAt [ "profile", "gender" ] (gender |> map Just) Nothing |> requiredAt [ "profile", "dateOfBirth" ] date |> optional "notifications" (list notification) [] notification = map2 Notification (field "title" string) (field "message" string) gender = let toGender s = case s of "male" -> succeed Male "female" -> succeed Female _ -> fail (s ++ " is not a valid gender") in string |> andThen toGender membership = let toMembership b = case b of True -> Premium False -> Standard in bool |> map toMembership
true
module Main exposing (..) import Html exposing (text) import Json.Decode exposing (..) import Json.Decode.Extra exposing ((|:), date, parseInt, fromResult) import Json.Decode.Pipeline exposing (decode, optional, optionalAt, required, requiredAt) import Date exposing (Date) main = sampleFailure |> decodeString response |> toString |> text type Membership = Standard | Premium type Gender = Female | Male type alias User = { id : Int , email : String , membership : Membership , gender : Maybe Gender , dateOfBirth : Date , notifications : List Notification } type alias Notification = { title : String , message : String } sampleSuccess = """ { "data" : { "id" : "123", "email" : "PI:EMAIL:<EMAIL>END_PI", "isPremium" : true, "profile" : { "gender": "male", "dateOfBirth": "Sun Jan 07 2018 00:18:17 GMT+0100 (CET)" }, "notifications" : [ { "title" : "Welcome back!", "message" : "We've been missing you" }, { "title" : "Weather alert", "message" : "Expect stormy weather" } ] } } """ sampleFailure = """ { "error": { "message": "wrong_password" } } """ response : Decoder (Result String User) response = oneOf [ field "data" user |> map Ok , at [ "error", "message" ] string |> map Err ] user = decode User |> required "id" parseInt |> required "email" (string |> map String.toLower) |> required "isPremium" membership |> optionalAt [ "profile", "gender" ] (gender |> map Just) Nothing |> requiredAt [ "profile", "dateOfBirth" ] date |> optional "notifications" (list notification) [] notification = map2 Notification (field "title" string) (field "message" string) gender = let toGender s = case s of "male" -> succeed Male "female" -> succeed Female _ -> fail (s ++ " is not a valid gender") in string |> andThen toGender membership = let toMembership b = case b of True -> Premium False -> Standard in bool |> map toMembership
elm
[ { "context": "{-\nCopyright 2020 Morgan Stanley\n\nLicensed under the Apache License, Version 2.0 (", "end": 32, "score": 0.9998259544, "start": 18, "tag": "NAME", "value": "Morgan Stanley" } ]
src/Morphir/SDK/Float.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 Morphir.SDK.Float exposing (..) {-| A `Float` is a [floating-point number][fp]. Valid syntax for floats includes: 0 42 3.14 0.1234 6.022e23 -- == (6.022 * 10^23) 6.022e+23 -- == (6.022 * 10^23) 1.602e−19 -- == (1.602 * 10^-19) 1e3 -- == (1 * 10^3) == 1000 **Historical Note:** The particular details of floats (e.g. `NaN`) are specified by [IEEE 754][ieee] which is literally hard-coded into almost all CPUs in the world. That means if you think `NaN` is weird, you must successfully overtake Intel and AMD with a chip that is not backwards compatible with any widely-used assembly language. [fp]: https://en.wikipedia.org/wiki/Floating-point_arithmetic [ieee]: https://en.wikipedia.org/wiki/IEEE_754 -} import Morphir.SDK.Int exposing (Int) type alias Float = Basics.Float {-| Represents a 32 bit floating-point value. -} type alias Float32 = Basics.Float {-| Represents a 64 bit floating-point value. -} type alias Float64 = Basics.Float {-| Floating-point division: 10 / 4 == 2.5 11 / 4 == 2.75 12 / 4 == 3 13 / 4 == 3.25 14 / 4 == 3.5 - 1 / 4 == -0.25 - 5 / 4 == -1.25 -} divide : Float -> Float -> Float divide = (/) -- INT TO FLOAT / FLOAT TO INT {-| Convert an integer into a float. Useful when mixing `Int` and `Float` values like this: halfOf : Int -> Float halfOf number = fromInt number / 2 -} fromInt : Int -> Float fromInt = Basics.toFloat {-| Round a number to the nearest integer. round 1.0 == 1 round 1.2 == 1 round 1.5 == 2 round 1.8 == 2 round -1.2 == -1 round -1.5 == -1 round -1.8 == -2 -} round : Float -> Int round = Basics.round {-| Floor function, rounding down. floor 1.0 == 1 floor 1.2 == 1 floor 1.5 == 1 floor 1.8 == 1 floor -1.2 == -2 floor -1.5 == -2 floor -1.8 == -2 -} floor : Float -> Int floor = Basics.floor {-| Ceiling function, rounding up. ceiling 1.0 == 1 ceiling 1.2 == 2 ceiling 1.5 == 2 ceiling 1.8 == 2 ceiling -1.2 == -1 ceiling -1.5 == -1 ceiling -1.8 == -1 -} ceiling : Float -> Int ceiling = Basics.ceiling {-| Truncate a number, rounding towards zero. truncate 1.0 == 1 truncate 1.2 == 1 truncate 1.5 == 1 truncate 1.8 == 1 truncate -1.2 == -1 truncate -1.5 == -1 truncate -1.8 == -1 -} truncate : Float -> Int truncate = Basics.truncate {-| Take the square root of a number. sqrt 4 == 2 sqrt 9 == 3 sqrt 16 == 4 sqrt 25 == 5 -} sqrt : Float -> Float sqrt = Elm.Kernel.Basics.sqrt {-| Calculate the logarithm of a number with a given base. logBase 10 100 == 2 logBase 2 256 == 8 -} logBase : Float -> Float -> Float logBase base number = divide (Elm.Kernel.Basics.log number) (Elm.Kernel.Basics.log base) {-| An approximation of e. -} e : Float e = Elm.Kernel.Basics.e -- TRIGONOMETRY {-| An approximation of pi. -} pi : Float pi = Elm.Kernel.Basics.pi {-| Figure out the cosine given an angle in radians. cos (degrees 60) == 0.5000000000000001 cos (turns (1 / 6)) == 0.5000000000000001 cos (radians (pi / 3)) == 0.5000000000000001 cos (pi / 3) == 0.5000000000000001 -} cos : Float -> Float cos = Elm.Kernel.Basics.cos {-| Figure out the sine given an angle in radians. sin (degrees 30) == 0.49999999999999994 sin (turns (1 / 12)) == 0.49999999999999994 sin (radians (pi / 6)) == 0.49999999999999994 sin (pi / 6) == 0.49999999999999994 -} sin : Float -> Float sin = Elm.Kernel.Basics.sin {-| Figure out the tangent given an angle in radians. tan (degrees 45) == 0.9999999999999999 tan (turns (1 / 8)) == 0.9999999999999999 tan (radians (pi / 4)) == 0.9999999999999999 tan (pi / 4) == 0.9999999999999999 -} tan : Float -> Float tan = Elm.Kernel.Basics.tan {-| Figure out the arccosine for `adjacent / hypotenuse` in radians: acos (1 / 2) == 1.0471975511965979 -- 60° or pi/3 radians -} acos : Float -> Float acos = Elm.Kernel.Basics.acos {-| Figure out the arcsine for `opposite / hypotenuse` in radians: asin (1 / 2) == 0.5235987755982989 -- 30° or pi/6 radians -} asin : Float -> Float asin = Elm.Kernel.Basics.asin {-| This helps you find the angle (in radians) to an `(x,y)` coordinate, but in a way that is rarely useful in programming. **You probably want [`atan2`](#atan2) instead!** This version takes `y/x` as its argument, so there is no way to know whether the negative signs comes from the `y` or `x` value. So as we go counter-clockwise around the origin from point `(1,1)` to `(1,-1)` to `(-1,-1)` to `(-1,1)` we do not get angles that go in the full circle: atan (1 / 1) == 0.7853981633974483 -- 45° or pi/4 radians atan (1 / -1) == -0.7853981633974483 -- 315° or 7*pi/4 radians atan (-1 / -1) == 0.7853981633974483 -- 45° or pi/4 radians atan (-1 / 1) == -0.7853981633974483 -- 315° or 7*pi/4 radians Notice that everything is between `pi/2` and `-pi/2`. That is pretty useless for figuring out angles in any sort of visualization, so again, check out [`atan2`](#atan2) instead! -} atan : Float -> Float atan = Elm.Kernel.Basics.atan {-| This helps you find the angle (in radians) to an `(x,y)` coordinate. So rather than saying `atan (y/x)` you say `atan2 y x` and you can get a full range of angles: atan2 1 1 == 0.7853981633974483 -- 45° or pi/4 radians atan2 1 -1 == 2.356194490192345 -- 135° or 3*pi/4 radians atan2 -1 -1 == -2.356194490192345 -- 225° or 5*pi/4 radians atan2 -1 1 == -0.7853981633974483 -- 315° or 7*pi/4 radians -} atan2 : Float -> Float -> Float atan2 = Elm.Kernel.Basics.atan2 -- CRAZY FLOATS {-| Determine whether a float is an undefined or unrepresentable number. NaN stands for _not a number_ and it is [a standardized part of floating point numbers](https://en.wikipedia.org/wiki/NaN). isNaN (0 / 0) == True isNaN (sqrt -1) == True isNaN (1 / 0) == False -- infinity is a number isNaN 1 == False -} isNaN : Float -> Bool isNaN = Elm.Kernel.Basics.isNaN {-| Determine whether a float is positive or negative infinity. isInfinite (0 / 0) == False isInfinite (sqrt -1) == False isInfinite (1 / 0) == True isInfinite 1 == False Notice that NaN is not infinite! For float `n` to be finite implies that `not (isInfinite n || isNaN n)` evaluates to `True`. -} isInfinite : Float -> Bool isInfinite = Elm.Kernel.Basics.isInfinite
52442
{- 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 Morphir.SDK.Float exposing (..) {-| A `Float` is a [floating-point number][fp]. Valid syntax for floats includes: 0 42 3.14 0.1234 6.022e23 -- == (6.022 * 10^23) 6.022e+23 -- == (6.022 * 10^23) 1.602e−19 -- == (1.602 * 10^-19) 1e3 -- == (1 * 10^3) == 1000 **Historical Note:** The particular details of floats (e.g. `NaN`) are specified by [IEEE 754][ieee] which is literally hard-coded into almost all CPUs in the world. That means if you think `NaN` is weird, you must successfully overtake Intel and AMD with a chip that is not backwards compatible with any widely-used assembly language. [fp]: https://en.wikipedia.org/wiki/Floating-point_arithmetic [ieee]: https://en.wikipedia.org/wiki/IEEE_754 -} import Morphir.SDK.Int exposing (Int) type alias Float = Basics.Float {-| Represents a 32 bit floating-point value. -} type alias Float32 = Basics.Float {-| Represents a 64 bit floating-point value. -} type alias Float64 = Basics.Float {-| Floating-point division: 10 / 4 == 2.5 11 / 4 == 2.75 12 / 4 == 3 13 / 4 == 3.25 14 / 4 == 3.5 - 1 / 4 == -0.25 - 5 / 4 == -1.25 -} divide : Float -> Float -> Float divide = (/) -- INT TO FLOAT / FLOAT TO INT {-| Convert an integer into a float. Useful when mixing `Int` and `Float` values like this: halfOf : Int -> Float halfOf number = fromInt number / 2 -} fromInt : Int -> Float fromInt = Basics.toFloat {-| Round a number to the nearest integer. round 1.0 == 1 round 1.2 == 1 round 1.5 == 2 round 1.8 == 2 round -1.2 == -1 round -1.5 == -1 round -1.8 == -2 -} round : Float -> Int round = Basics.round {-| Floor function, rounding down. floor 1.0 == 1 floor 1.2 == 1 floor 1.5 == 1 floor 1.8 == 1 floor -1.2 == -2 floor -1.5 == -2 floor -1.8 == -2 -} floor : Float -> Int floor = Basics.floor {-| Ceiling function, rounding up. ceiling 1.0 == 1 ceiling 1.2 == 2 ceiling 1.5 == 2 ceiling 1.8 == 2 ceiling -1.2 == -1 ceiling -1.5 == -1 ceiling -1.8 == -1 -} ceiling : Float -> Int ceiling = Basics.ceiling {-| Truncate a number, rounding towards zero. truncate 1.0 == 1 truncate 1.2 == 1 truncate 1.5 == 1 truncate 1.8 == 1 truncate -1.2 == -1 truncate -1.5 == -1 truncate -1.8 == -1 -} truncate : Float -> Int truncate = Basics.truncate {-| Take the square root of a number. sqrt 4 == 2 sqrt 9 == 3 sqrt 16 == 4 sqrt 25 == 5 -} sqrt : Float -> Float sqrt = Elm.Kernel.Basics.sqrt {-| Calculate the logarithm of a number with a given base. logBase 10 100 == 2 logBase 2 256 == 8 -} logBase : Float -> Float -> Float logBase base number = divide (Elm.Kernel.Basics.log number) (Elm.Kernel.Basics.log base) {-| An approximation of e. -} e : Float e = Elm.Kernel.Basics.e -- TRIGONOMETRY {-| An approximation of pi. -} pi : Float pi = Elm.Kernel.Basics.pi {-| Figure out the cosine given an angle in radians. cos (degrees 60) == 0.5000000000000001 cos (turns (1 / 6)) == 0.5000000000000001 cos (radians (pi / 3)) == 0.5000000000000001 cos (pi / 3) == 0.5000000000000001 -} cos : Float -> Float cos = Elm.Kernel.Basics.cos {-| Figure out the sine given an angle in radians. sin (degrees 30) == 0.49999999999999994 sin (turns (1 / 12)) == 0.49999999999999994 sin (radians (pi / 6)) == 0.49999999999999994 sin (pi / 6) == 0.49999999999999994 -} sin : Float -> Float sin = Elm.Kernel.Basics.sin {-| Figure out the tangent given an angle in radians. tan (degrees 45) == 0.9999999999999999 tan (turns (1 / 8)) == 0.9999999999999999 tan (radians (pi / 4)) == 0.9999999999999999 tan (pi / 4) == 0.9999999999999999 -} tan : Float -> Float tan = Elm.Kernel.Basics.tan {-| Figure out the arccosine for `adjacent / hypotenuse` in radians: acos (1 / 2) == 1.0471975511965979 -- 60° or pi/3 radians -} acos : Float -> Float acos = Elm.Kernel.Basics.acos {-| Figure out the arcsine for `opposite / hypotenuse` in radians: asin (1 / 2) == 0.5235987755982989 -- 30° or pi/6 radians -} asin : Float -> Float asin = Elm.Kernel.Basics.asin {-| This helps you find the angle (in radians) to an `(x,y)` coordinate, but in a way that is rarely useful in programming. **You probably want [`atan2`](#atan2) instead!** This version takes `y/x` as its argument, so there is no way to know whether the negative signs comes from the `y` or `x` value. So as we go counter-clockwise around the origin from point `(1,1)` to `(1,-1)` to `(-1,-1)` to `(-1,1)` we do not get angles that go in the full circle: atan (1 / 1) == 0.7853981633974483 -- 45° or pi/4 radians atan (1 / -1) == -0.7853981633974483 -- 315° or 7*pi/4 radians atan (-1 / -1) == 0.7853981633974483 -- 45° or pi/4 radians atan (-1 / 1) == -0.7853981633974483 -- 315° or 7*pi/4 radians Notice that everything is between `pi/2` and `-pi/2`. That is pretty useless for figuring out angles in any sort of visualization, so again, check out [`atan2`](#atan2) instead! -} atan : Float -> Float atan = Elm.Kernel.Basics.atan {-| This helps you find the angle (in radians) to an `(x,y)` coordinate. So rather than saying `atan (y/x)` you say `atan2 y x` and you can get a full range of angles: atan2 1 1 == 0.7853981633974483 -- 45° or pi/4 radians atan2 1 -1 == 2.356194490192345 -- 135° or 3*pi/4 radians atan2 -1 -1 == -2.356194490192345 -- 225° or 5*pi/4 radians atan2 -1 1 == -0.7853981633974483 -- 315° or 7*pi/4 radians -} atan2 : Float -> Float -> Float atan2 = Elm.Kernel.Basics.atan2 -- CRAZY FLOATS {-| Determine whether a float is an undefined or unrepresentable number. NaN stands for _not a number_ and it is [a standardized part of floating point numbers](https://en.wikipedia.org/wiki/NaN). isNaN (0 / 0) == True isNaN (sqrt -1) == True isNaN (1 / 0) == False -- infinity is a number isNaN 1 == False -} isNaN : Float -> Bool isNaN = Elm.Kernel.Basics.isNaN {-| Determine whether a float is positive or negative infinity. isInfinite (0 / 0) == False isInfinite (sqrt -1) == False isInfinite (1 / 0) == True isInfinite 1 == False Notice that NaN is not infinite! For float `n` to be finite implies that `not (isInfinite n || isNaN n)` evaluates to `True`. -} isInfinite : Float -> Bool isInfinite = Elm.Kernel.Basics.isInfinite
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 Morphir.SDK.Float exposing (..) {-| A `Float` is a [floating-point number][fp]. Valid syntax for floats includes: 0 42 3.14 0.1234 6.022e23 -- == (6.022 * 10^23) 6.022e+23 -- == (6.022 * 10^23) 1.602e−19 -- == (1.602 * 10^-19) 1e3 -- == (1 * 10^3) == 1000 **Historical Note:** The particular details of floats (e.g. `NaN`) are specified by [IEEE 754][ieee] which is literally hard-coded into almost all CPUs in the world. That means if you think `NaN` is weird, you must successfully overtake Intel and AMD with a chip that is not backwards compatible with any widely-used assembly language. [fp]: https://en.wikipedia.org/wiki/Floating-point_arithmetic [ieee]: https://en.wikipedia.org/wiki/IEEE_754 -} import Morphir.SDK.Int exposing (Int) type alias Float = Basics.Float {-| Represents a 32 bit floating-point value. -} type alias Float32 = Basics.Float {-| Represents a 64 bit floating-point value. -} type alias Float64 = Basics.Float {-| Floating-point division: 10 / 4 == 2.5 11 / 4 == 2.75 12 / 4 == 3 13 / 4 == 3.25 14 / 4 == 3.5 - 1 / 4 == -0.25 - 5 / 4 == -1.25 -} divide : Float -> Float -> Float divide = (/) -- INT TO FLOAT / FLOAT TO INT {-| Convert an integer into a float. Useful when mixing `Int` and `Float` values like this: halfOf : Int -> Float halfOf number = fromInt number / 2 -} fromInt : Int -> Float fromInt = Basics.toFloat {-| Round a number to the nearest integer. round 1.0 == 1 round 1.2 == 1 round 1.5 == 2 round 1.8 == 2 round -1.2 == -1 round -1.5 == -1 round -1.8 == -2 -} round : Float -> Int round = Basics.round {-| Floor function, rounding down. floor 1.0 == 1 floor 1.2 == 1 floor 1.5 == 1 floor 1.8 == 1 floor -1.2 == -2 floor -1.5 == -2 floor -1.8 == -2 -} floor : Float -> Int floor = Basics.floor {-| Ceiling function, rounding up. ceiling 1.0 == 1 ceiling 1.2 == 2 ceiling 1.5 == 2 ceiling 1.8 == 2 ceiling -1.2 == -1 ceiling -1.5 == -1 ceiling -1.8 == -1 -} ceiling : Float -> Int ceiling = Basics.ceiling {-| Truncate a number, rounding towards zero. truncate 1.0 == 1 truncate 1.2 == 1 truncate 1.5 == 1 truncate 1.8 == 1 truncate -1.2 == -1 truncate -1.5 == -1 truncate -1.8 == -1 -} truncate : Float -> Int truncate = Basics.truncate {-| Take the square root of a number. sqrt 4 == 2 sqrt 9 == 3 sqrt 16 == 4 sqrt 25 == 5 -} sqrt : Float -> Float sqrt = Elm.Kernel.Basics.sqrt {-| Calculate the logarithm of a number with a given base. logBase 10 100 == 2 logBase 2 256 == 8 -} logBase : Float -> Float -> Float logBase base number = divide (Elm.Kernel.Basics.log number) (Elm.Kernel.Basics.log base) {-| An approximation of e. -} e : Float e = Elm.Kernel.Basics.e -- TRIGONOMETRY {-| An approximation of pi. -} pi : Float pi = Elm.Kernel.Basics.pi {-| Figure out the cosine given an angle in radians. cos (degrees 60) == 0.5000000000000001 cos (turns (1 / 6)) == 0.5000000000000001 cos (radians (pi / 3)) == 0.5000000000000001 cos (pi / 3) == 0.5000000000000001 -} cos : Float -> Float cos = Elm.Kernel.Basics.cos {-| Figure out the sine given an angle in radians. sin (degrees 30) == 0.49999999999999994 sin (turns (1 / 12)) == 0.49999999999999994 sin (radians (pi / 6)) == 0.49999999999999994 sin (pi / 6) == 0.49999999999999994 -} sin : Float -> Float sin = Elm.Kernel.Basics.sin {-| Figure out the tangent given an angle in radians. tan (degrees 45) == 0.9999999999999999 tan (turns (1 / 8)) == 0.9999999999999999 tan (radians (pi / 4)) == 0.9999999999999999 tan (pi / 4) == 0.9999999999999999 -} tan : Float -> Float tan = Elm.Kernel.Basics.tan {-| Figure out the arccosine for `adjacent / hypotenuse` in radians: acos (1 / 2) == 1.0471975511965979 -- 60° or pi/3 radians -} acos : Float -> Float acos = Elm.Kernel.Basics.acos {-| Figure out the arcsine for `opposite / hypotenuse` in radians: asin (1 / 2) == 0.5235987755982989 -- 30° or pi/6 radians -} asin : Float -> Float asin = Elm.Kernel.Basics.asin {-| This helps you find the angle (in radians) to an `(x,y)` coordinate, but in a way that is rarely useful in programming. **You probably want [`atan2`](#atan2) instead!** This version takes `y/x` as its argument, so there is no way to know whether the negative signs comes from the `y` or `x` value. So as we go counter-clockwise around the origin from point `(1,1)` to `(1,-1)` to `(-1,-1)` to `(-1,1)` we do not get angles that go in the full circle: atan (1 / 1) == 0.7853981633974483 -- 45° or pi/4 radians atan (1 / -1) == -0.7853981633974483 -- 315° or 7*pi/4 radians atan (-1 / -1) == 0.7853981633974483 -- 45° or pi/4 radians atan (-1 / 1) == -0.7853981633974483 -- 315° or 7*pi/4 radians Notice that everything is between `pi/2` and `-pi/2`. That is pretty useless for figuring out angles in any sort of visualization, so again, check out [`atan2`](#atan2) instead! -} atan : Float -> Float atan = Elm.Kernel.Basics.atan {-| This helps you find the angle (in radians) to an `(x,y)` coordinate. So rather than saying `atan (y/x)` you say `atan2 y x` and you can get a full range of angles: atan2 1 1 == 0.7853981633974483 -- 45° or pi/4 radians atan2 1 -1 == 2.356194490192345 -- 135° or 3*pi/4 radians atan2 -1 -1 == -2.356194490192345 -- 225° or 5*pi/4 radians atan2 -1 1 == -0.7853981633974483 -- 315° or 7*pi/4 radians -} atan2 : Float -> Float -> Float atan2 = Elm.Kernel.Basics.atan2 -- CRAZY FLOATS {-| Determine whether a float is an undefined or unrepresentable number. NaN stands for _not a number_ and it is [a standardized part of floating point numbers](https://en.wikipedia.org/wiki/NaN). isNaN (0 / 0) == True isNaN (sqrt -1) == True isNaN (1 / 0) == False -- infinity is a number isNaN 1 == False -} isNaN : Float -> Bool isNaN = Elm.Kernel.Basics.isNaN {-| Determine whether a float is positive or negative infinity. isInfinite (0 / 0) == False isInfinite (sqrt -1) == False isInfinite (1 / 0) == True isInfinite 1 == False Notice that NaN is not infinite! For float `n` to be finite implies that `not (isInfinite n || isNaN n)` evaluates to `True`. -} isInfinite : Float -> Bool isInfinite = Elm.Kernel.Basics.isInfinite
elm
[ { "context": "docs dayOfMonthWithSuffix\n\nCopyright (c) 2016-2018 Robin Luiten\n\n-}\n\nimport Date exposing (Day(..), Month(..))\nim", "end": 217, "score": 0.9998672605, "start": 205, "tag": "NAME", "value": "Robin Luiten" } ]
src/Date/Extra/I18n/I_en_us.elm
AdrianRibao/elm-date-extra
81
module Date.Extra.I18n.I_en_us exposing (..) {-| English 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 -> "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" {-| Returns a common english idiom for days of month. Pad indicates space pad the day of month value so single digit outputs have space padding to make them same length as double digit days of monnth. -} dayOfMonthWithSuffix : Bool -> Int -> String dayOfMonthWithSuffix pad day = let value = case day of 1 -> "1st" 21 -> "21st" 2 -> "2nd" 22 -> "22nd" 3 -> "3rd" 23 -> "23rd" 31 -> "31st" _ -> (toString day) ++ "th" in if pad then padLeft 4 ' ' value else value
18525
module Date.Extra.I18n.I_en_us exposing (..) {-| English 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 -> "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" {-| Returns a common english idiom for days of month. Pad indicates space pad the day of month value so single digit outputs have space padding to make them same length as double digit days of monnth. -} dayOfMonthWithSuffix : Bool -> Int -> String dayOfMonthWithSuffix pad day = let value = case day of 1 -> "1st" 21 -> "21st" 2 -> "2nd" 22 -> "22nd" 3 -> "3rd" 23 -> "23rd" 31 -> "31st" _ -> (toString day) ++ "th" in if pad then padLeft 4 ' ' value else value
true
module Date.Extra.I18n.I_en_us exposing (..) {-| English 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 -> "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" {-| Returns a common english idiom for days of month. Pad indicates space pad the day of month value so single digit outputs have space padding to make them same length as double digit days of monnth. -} dayOfMonthWithSuffix : Bool -> Int -> String dayOfMonthWithSuffix pad day = let value = case day of 1 -> "1st" 21 -> "21st" 2 -> "2nd" 22 -> "22nd" 3 -> "3rd" 23 -> "23rd" 31 -> "31st" _ -> (toString day) ++ "th" in if pad then padLeft 4 ' ' value else value
elm
[ { "context": "\n [ h1 [ class \"job-header-text\" ] [ text \"HN Jobs\" ]\n , div [ class \"divide\" ] []\n , ", "end": 2898, "score": 0.939653635, "start": 2891, "tag": "NAME", "value": "HN Jobs" } ]
src/Main.elm
emattiza/frontendeval-hn-jobs
0
module Main exposing (main) import Array exposing (Array) import Browser import Html exposing (Html, a, article, button, div, h1, h2, p, text) import Html.Attributes exposing (class, href) import Html.Events exposing (..) import Job exposing (Job, viewJob) import JobFeed exposing (JobFeed) import Msg exposing (Msg(..), getCurrentJobFeed, getFirstJobs, getMoreJobs) import RemoteData exposing (RemoteData(..), WebData) import String exposing (padLeft) import Task import Time exposing (millisToPosix) type alias Model = { jobs : Array Job , jobFeed : WebData JobFeed , firstJobs : WebData (List Job) , nextJobs : WebData (List Job) } init : flags -> ( Model, Cmd Msg ) init _ = ( { jobs = Array.empty , jobFeed = Loading , firstJobs = NotAsked , nextJobs = NotAsked } , Task.attempt (\result -> LoadFeed (RemoteData.fromResult result)) getCurrentJobFeed ) main : Program () Model Msg main = Browser.element { init = init , update = update , view = view , subscriptions = \_ -> Sub.none } update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of LoadMoreJobs -> let start = Array.length model.jobs - 1 end = start + 6 in ( model, Task.perform GotMoreJobs (getMoreJobs model.jobFeed start end) ) LoadFeed feed -> case feed of Success newFeed -> ( { model | jobFeed = feed , firstJobs = Loading } , Task.attempt (\result -> GotFirstJobs <| RemoteData.fromResult result) (getFirstJobs newFeed) ) _ -> ( { model | jobFeed = feed }, Cmd.none ) GotFirstJobs newJobs -> case newJobs of Success gotJobs -> ( { model | firstJobs = newJobs , jobs = Array.fromList gotJobs } , Cmd.none ) _ -> ( { model | firstJobs = newJobs }, Cmd.none ) GotMoreJobs moreJobs -> case moreJobs of Success gotJobs -> ( { model | nextJobs = moreJobs , jobs = Array.append model.jobs (Array.fromList gotJobs) } , Cmd.none ) _ -> ( { model | nextJobs = moreJobs }, Cmd.none ) view : Model -> Html Msg view model = div [ class "app-container" ] [ h1 [ class "job-header-text" ] [ text "HN Jobs" ] , div [ class "divide" ] [] , viewJobs model.jobs , div [ class "btn-container" ] [ button [ onClick LoadMoreJobs, class "load-more-jobs-btn" ] [ text "Load More..." ] ] ] viewJobs : Array Job -> Html Msg viewJobs jobs = div [ class "jobs-container" ] (Array.toList <| Array.map viewJob jobs)
30773
module Main exposing (main) import Array exposing (Array) import Browser import Html exposing (Html, a, article, button, div, h1, h2, p, text) import Html.Attributes exposing (class, href) import Html.Events exposing (..) import Job exposing (Job, viewJob) import JobFeed exposing (JobFeed) import Msg exposing (Msg(..), getCurrentJobFeed, getFirstJobs, getMoreJobs) import RemoteData exposing (RemoteData(..), WebData) import String exposing (padLeft) import Task import Time exposing (millisToPosix) type alias Model = { jobs : Array Job , jobFeed : WebData JobFeed , firstJobs : WebData (List Job) , nextJobs : WebData (List Job) } init : flags -> ( Model, Cmd Msg ) init _ = ( { jobs = Array.empty , jobFeed = Loading , firstJobs = NotAsked , nextJobs = NotAsked } , Task.attempt (\result -> LoadFeed (RemoteData.fromResult result)) getCurrentJobFeed ) main : Program () Model Msg main = Browser.element { init = init , update = update , view = view , subscriptions = \_ -> Sub.none } update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of LoadMoreJobs -> let start = Array.length model.jobs - 1 end = start + 6 in ( model, Task.perform GotMoreJobs (getMoreJobs model.jobFeed start end) ) LoadFeed feed -> case feed of Success newFeed -> ( { model | jobFeed = feed , firstJobs = Loading } , Task.attempt (\result -> GotFirstJobs <| RemoteData.fromResult result) (getFirstJobs newFeed) ) _ -> ( { model | jobFeed = feed }, Cmd.none ) GotFirstJobs newJobs -> case newJobs of Success gotJobs -> ( { model | firstJobs = newJobs , jobs = Array.fromList gotJobs } , Cmd.none ) _ -> ( { model | firstJobs = newJobs }, Cmd.none ) GotMoreJobs moreJobs -> case moreJobs of Success gotJobs -> ( { model | nextJobs = moreJobs , jobs = Array.append model.jobs (Array.fromList gotJobs) } , Cmd.none ) _ -> ( { model | nextJobs = moreJobs }, Cmd.none ) view : Model -> Html Msg view model = div [ class "app-container" ] [ h1 [ class "job-header-text" ] [ text "<NAME>" ] , div [ class "divide" ] [] , viewJobs model.jobs , div [ class "btn-container" ] [ button [ onClick LoadMoreJobs, class "load-more-jobs-btn" ] [ text "Load More..." ] ] ] viewJobs : Array Job -> Html Msg viewJobs jobs = div [ class "jobs-container" ] (Array.toList <| Array.map viewJob jobs)
true
module Main exposing (main) import Array exposing (Array) import Browser import Html exposing (Html, a, article, button, div, h1, h2, p, text) import Html.Attributes exposing (class, href) import Html.Events exposing (..) import Job exposing (Job, viewJob) import JobFeed exposing (JobFeed) import Msg exposing (Msg(..), getCurrentJobFeed, getFirstJobs, getMoreJobs) import RemoteData exposing (RemoteData(..), WebData) import String exposing (padLeft) import Task import Time exposing (millisToPosix) type alias Model = { jobs : Array Job , jobFeed : WebData JobFeed , firstJobs : WebData (List Job) , nextJobs : WebData (List Job) } init : flags -> ( Model, Cmd Msg ) init _ = ( { jobs = Array.empty , jobFeed = Loading , firstJobs = NotAsked , nextJobs = NotAsked } , Task.attempt (\result -> LoadFeed (RemoteData.fromResult result)) getCurrentJobFeed ) main : Program () Model Msg main = Browser.element { init = init , update = update , view = view , subscriptions = \_ -> Sub.none } update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of LoadMoreJobs -> let start = Array.length model.jobs - 1 end = start + 6 in ( model, Task.perform GotMoreJobs (getMoreJobs model.jobFeed start end) ) LoadFeed feed -> case feed of Success newFeed -> ( { model | jobFeed = feed , firstJobs = Loading } , Task.attempt (\result -> GotFirstJobs <| RemoteData.fromResult result) (getFirstJobs newFeed) ) _ -> ( { model | jobFeed = feed }, Cmd.none ) GotFirstJobs newJobs -> case newJobs of Success gotJobs -> ( { model | firstJobs = newJobs , jobs = Array.fromList gotJobs } , Cmd.none ) _ -> ( { model | firstJobs = newJobs }, Cmd.none ) GotMoreJobs moreJobs -> case moreJobs of Success gotJobs -> ( { model | nextJobs = moreJobs , jobs = Array.append model.jobs (Array.fromList gotJobs) } , Cmd.none ) _ -> ( { model | nextJobs = moreJobs }, Cmd.none ) view : Model -> Html Msg view model = div [ class "app-container" ] [ h1 [ class "job-header-text" ] [ text "PI:NAME:<NAME>END_PI" ] , div [ class "divide" ] [] , viewJobs model.jobs , div [ class "btn-container" ] [ button [ onClick LoadMoreJobs, class "load-more-jobs-btn" ] [ text "Load More..." ] ] ] viewJobs : Array Job -> Html Msg viewJobs jobs = div [ class "jobs-container" ] (Array.toList <| Array.map viewJob jobs)
elm
[ { "context": "{-\n Copyright 2020 Morgan Stanley\n\n Licensed under the Apache License, Version 2.", "end": 35, "score": 0.9998385906, "start": 21, "tag": "NAME", "value": "Morgan Stanley" } ]
src/Morphir/IR/SDK/Rule.elm
bekand/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 Morphir.IR.SDK.Rule exposing (..) import Dict import Morphir.IR.Documented exposing (Documented) import Morphir.IR.Module as Module exposing (ModuleName) import Morphir.IR.Name as Name import Morphir.IR.Path as Path import Morphir.IR.SDK.Basics exposing (boolType) import Morphir.IR.SDK.Common exposing (tFun, tVar, toFQName, vSpec) import Morphir.IR.SDK.List exposing (listType) import Morphir.IR.SDK.Maybe exposing (maybeType) import Morphir.IR.Type as Type exposing (Specification(..), Type(..)) import Morphir.IR.Value as Value exposing (Value) moduleName : ModuleName moduleName = Path.fromString "Rule" moduleSpec : Module.Specification () moduleSpec = { types = Dict.fromList [ ( Name.fromString "Rule", TypeAliasSpecification [ [ "a" ], [ "b" ] ] (tFun [ tVar "a" ] (maybeType () (tVar "b"))) |> Documented "Type that represents an rule." ) ] , values = Dict.fromList [ vSpec "chain" [ ( "rules", listType () (ruleType () (tVar "a") (tVar "b")) ) ] (ruleType () (tVar "a") (tVar "b")) , vSpec "any" [ ( "value", tVar "a" ) ] (boolType ()) , vSpec "is" [ ( "ref", tVar "a" ) , ( "value", tVar "a" ) ] (boolType ()) , vSpec "anyOf" [ ( "ref", listType () (tVar "a") ) , ( "value", tVar "a" ) ] (boolType ()) , vSpec "noneOf" [ ( "ref", listType () (tVar "a") ) , ( "value", tVar "a" ) ] (boolType ()) ] } ruleType : a -> Type a -> Type a -> Type a ruleType attributes itemType1 itemType2 = Type.Reference attributes (toFQName moduleName "Rule") [ itemType1, itemType2 ]
5729
{- 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 Morphir.IR.SDK.Rule exposing (..) import Dict import Morphir.IR.Documented exposing (Documented) import Morphir.IR.Module as Module exposing (ModuleName) import Morphir.IR.Name as Name import Morphir.IR.Path as Path import Morphir.IR.SDK.Basics exposing (boolType) import Morphir.IR.SDK.Common exposing (tFun, tVar, toFQName, vSpec) import Morphir.IR.SDK.List exposing (listType) import Morphir.IR.SDK.Maybe exposing (maybeType) import Morphir.IR.Type as Type exposing (Specification(..), Type(..)) import Morphir.IR.Value as Value exposing (Value) moduleName : ModuleName moduleName = Path.fromString "Rule" moduleSpec : Module.Specification () moduleSpec = { types = Dict.fromList [ ( Name.fromString "Rule", TypeAliasSpecification [ [ "a" ], [ "b" ] ] (tFun [ tVar "a" ] (maybeType () (tVar "b"))) |> Documented "Type that represents an rule." ) ] , values = Dict.fromList [ vSpec "chain" [ ( "rules", listType () (ruleType () (tVar "a") (tVar "b")) ) ] (ruleType () (tVar "a") (tVar "b")) , vSpec "any" [ ( "value", tVar "a" ) ] (boolType ()) , vSpec "is" [ ( "ref", tVar "a" ) , ( "value", tVar "a" ) ] (boolType ()) , vSpec "anyOf" [ ( "ref", listType () (tVar "a") ) , ( "value", tVar "a" ) ] (boolType ()) , vSpec "noneOf" [ ( "ref", listType () (tVar "a") ) , ( "value", tVar "a" ) ] (boolType ()) ] } ruleType : a -> Type a -> Type a -> Type a ruleType attributes itemType1 itemType2 = Type.Reference attributes (toFQName moduleName "Rule") [ itemType1, itemType2 ]
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 Morphir.IR.SDK.Rule exposing (..) import Dict import Morphir.IR.Documented exposing (Documented) import Morphir.IR.Module as Module exposing (ModuleName) import Morphir.IR.Name as Name import Morphir.IR.Path as Path import Morphir.IR.SDK.Basics exposing (boolType) import Morphir.IR.SDK.Common exposing (tFun, tVar, toFQName, vSpec) import Morphir.IR.SDK.List exposing (listType) import Morphir.IR.SDK.Maybe exposing (maybeType) import Morphir.IR.Type as Type exposing (Specification(..), Type(..)) import Morphir.IR.Value as Value exposing (Value) moduleName : ModuleName moduleName = Path.fromString "Rule" moduleSpec : Module.Specification () moduleSpec = { types = Dict.fromList [ ( Name.fromString "Rule", TypeAliasSpecification [ [ "a" ], [ "b" ] ] (tFun [ tVar "a" ] (maybeType () (tVar "b"))) |> Documented "Type that represents an rule." ) ] , values = Dict.fromList [ vSpec "chain" [ ( "rules", listType () (ruleType () (tVar "a") (tVar "b")) ) ] (ruleType () (tVar "a") (tVar "b")) , vSpec "any" [ ( "value", tVar "a" ) ] (boolType ()) , vSpec "is" [ ( "ref", tVar "a" ) , ( "value", tVar "a" ) ] (boolType ()) , vSpec "anyOf" [ ( "ref", listType () (tVar "a") ) , ( "value", tVar "a" ) ] (boolType ()) , vSpec "noneOf" [ ( "ref", listType () (tVar "a") ) , ( "value", tVar "a" ) ] (boolType ()) ] } ruleType : a -> Type a -> Type a -> Type a ruleType attributes itemType1 itemType2 = Type.Reference attributes (toFQName moduleName "Rule") [ itemType1, itemType2 ]
elm
[ { "context": "ORGANIZER\"\n , Property.CalAddress \"dillon@incrementalelm.com\"\n , [ Property.Parameter ( \"CN\", \"", "end": 333, "score": 0.9999284744, "start": 308, "tag": "EMAIL", "value": "dillon@incrementalelm.com" }, { "context": "\"\n , [ Property.Parameter ( \"CN\", \"Dillon Kearns\" ) ]\n )\n |> Pro", "end": 396, "score": 0.9998007417, "start": 383, "tag": "NAME", "value": "Dillon Kearns" }, { "context": " |> Expect.equal \"\"\"ORGANIZER;CN=Dillon Kearns:mailto:dillon@incrementalelm.com\"\"\"\n , tes", "end": 532, "score": 0.9997733235, "start": 519, "tag": "NAME", "value": "Dillon Kearns" }, { "context": "Expect.equal \"\"\"ORGANIZER;CN=Dillon Kearns:mailto:dillon@incrementalelm.com\"\"\"\n , test \"escape datetime with parameter", "end": 565, "score": 0.9999284744, "start": 540, "tag": "EMAIL", "value": "dillon@incrementalelm.com" } ]
tests/PropertyTests.elm
dillonkearns/elm-ical
3
module PropertyTests exposing (suite) import Expect import Iso8601 import Property import Test exposing (..) import Time suite : Test suite = describe "property" [ test "organizer is escaped correctly" <| \() -> ( "ORGANIZER" , Property.CalAddress "dillon@incrementalelm.com" , [ Property.Parameter ( "CN", "Dillon Kearns" ) ] ) |> Property.encodeProperty |> Expect.equal """ORGANIZER;CN=Dillon Kearns:mailto:dillon@incrementalelm.com""" , test "escape datetime with parameter" <| \() -> -- example from https://tools.ietf.org/html/rfc5545#section-3.3.5 ( "DTSTART" , Property.DateTime (toIso8601 "1997-07-14T13:30:00.000Z") , [ Property.Parameter ( "TZID", "America/New_York" ) ] ) |> Property.encodeProperty |> Expect.equal """DTSTART;TZID=America/New_York:19970714T133000Z""" ] toIso8601 : String -> Time.Posix toIso8601 string = case Iso8601.toTime string of Ok parsed -> parsed Err error -> Debug.todo (Debug.toString error)
18048
module PropertyTests exposing (suite) import Expect import Iso8601 import Property import Test exposing (..) import Time suite : Test suite = describe "property" [ test "organizer is escaped correctly" <| \() -> ( "ORGANIZER" , Property.CalAddress "<EMAIL>" , [ Property.Parameter ( "CN", "<NAME>" ) ] ) |> Property.encodeProperty |> Expect.equal """ORGANIZER;CN=<NAME>:mailto:<EMAIL>""" , test "escape datetime with parameter" <| \() -> -- example from https://tools.ietf.org/html/rfc5545#section-3.3.5 ( "DTSTART" , Property.DateTime (toIso8601 "1997-07-14T13:30:00.000Z") , [ Property.Parameter ( "TZID", "America/New_York" ) ] ) |> Property.encodeProperty |> Expect.equal """DTSTART;TZID=America/New_York:19970714T133000Z""" ] toIso8601 : String -> Time.Posix toIso8601 string = case Iso8601.toTime string of Ok parsed -> parsed Err error -> Debug.todo (Debug.toString error)
true
module PropertyTests exposing (suite) import Expect import Iso8601 import Property import Test exposing (..) import Time suite : Test suite = describe "property" [ test "organizer is escaped correctly" <| \() -> ( "ORGANIZER" , Property.CalAddress "PI:EMAIL:<EMAIL>END_PI" , [ Property.Parameter ( "CN", "PI:NAME:<NAME>END_PI" ) ] ) |> Property.encodeProperty |> Expect.equal """ORGANIZER;CN=PI:NAME:<NAME>END_PI:mailto:PI:EMAIL:<EMAIL>END_PI""" , test "escape datetime with parameter" <| \() -> -- example from https://tools.ietf.org/html/rfc5545#section-3.3.5 ( "DTSTART" , Property.DateTime (toIso8601 "1997-07-14T13:30:00.000Z") , [ Property.Parameter ( "TZID", "America/New_York" ) ] ) |> Property.encodeProperty |> Expect.equal """DTSTART;TZID=America/New_York:19970714T133000Z""" ] toIso8601 : String -> Time.Posix toIso8601 string = case Iso8601.toTime string of Ok parsed -> parsed Err error -> Debug.todo (Debug.toString error)
elm
[ { "context": "Timer.RestCounting\n , label = \"test\"\n , startTime = 20000\n ", "end": 5701, "score": 0.7094470859, "start": 5697, "tag": "NAME", "value": "test" }, { "context": "Timer.Counting\n , label = \"test\"\n , startTime = 20000\n ", "end": 6295, "score": 0.619964838, "start": 6291, "tag": "NAME", "value": "test" } ]
tests/Example.elm
MichaelCombs28/multitimer
0
module Example exposing (..) import Expect exposing (Expectation) import Fuzz exposing (Fuzzer, int, list, string) import Main import Swipe import Test exposing (..) import Timer suite : Test suite = describe "Utilities" [ test "secondsToDigital" <| \_ -> Expect.equal (Main.millisToDigital 7379000) "02:02:59" , test "fromActive perfect" <| \_ -> Expect.equal { state = Timer.Reset , label = "test" , startTime = 10000 , currentTime = 0 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 3 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 30000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 1 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive one rep left" <| \_ -> Expect.equal { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 3 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 20000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 1 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive two reps left" <| \_ -> Expect.equal { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 3 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 20000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 1 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive with rest time" <| \_ -> Expect.equal { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 2 , restTime = 10000 , currentRestTime = 10000 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 20000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 1 , restTime = 10000 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive still resting" <| \_ -> Expect.equal { state = Timer.RestCounting , label = "test" , startTime = 20000 , currentTime = 20000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 2 , restTime = 20000 , currentRestTime = 10000 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 30000 { state = Timer.Counting , label = "test" , startTime = 20000 , currentTime = 20000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 2 , restTime = 20000 , currentRestTime = 20000 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) ]
39445
module Example exposing (..) import Expect exposing (Expectation) import Fuzz exposing (Fuzzer, int, list, string) import Main import Swipe import Test exposing (..) import Timer suite : Test suite = describe "Utilities" [ test "secondsToDigital" <| \_ -> Expect.equal (Main.millisToDigital 7379000) "02:02:59" , test "fromActive perfect" <| \_ -> Expect.equal { state = Timer.Reset , label = "test" , startTime = 10000 , currentTime = 0 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 3 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 30000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 1 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive one rep left" <| \_ -> Expect.equal { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 3 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 20000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 1 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive two reps left" <| \_ -> Expect.equal { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 3 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 20000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 1 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive with rest time" <| \_ -> Expect.equal { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 2 , restTime = 10000 , currentRestTime = 10000 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 20000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 1 , restTime = 10000 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive still resting" <| \_ -> Expect.equal { state = Timer.RestCounting , label = "<NAME>" , startTime = 20000 , currentTime = 20000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 2 , restTime = 20000 , currentRestTime = 10000 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 30000 { state = Timer.Counting , label = "<NAME>" , startTime = 20000 , currentTime = 20000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 2 , restTime = 20000 , currentRestTime = 20000 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) ]
true
module Example exposing (..) import Expect exposing (Expectation) import Fuzz exposing (Fuzzer, int, list, string) import Main import Swipe import Test exposing (..) import Timer suite : Test suite = describe "Utilities" [ test "secondsToDigital" <| \_ -> Expect.equal (Main.millisToDigital 7379000) "02:02:59" , test "fromActive perfect" <| \_ -> Expect.equal { state = Timer.Reset , label = "test" , startTime = 10000 , currentTime = 0 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 3 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 30000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 1 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive one rep left" <| \_ -> Expect.equal { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 3 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 20000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 3 , currentRepetition = 1 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive two reps left" <| \_ -> Expect.equal { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 3 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 20000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 1 , restTime = 0 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive with rest time" <| \_ -> Expect.equal { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 2 , restTime = 10000 , currentRestTime = 10000 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 20000 { state = Timer.Counting , label = "test" , startTime = 10000 , currentTime = 10000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 1 , restTime = 10000 , currentRestTime = 0 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) , test "fromActive still resting" <| \_ -> Expect.equal { state = Timer.RestCounting , label = "PI:NAME:<NAME>END_PI" , startTime = 20000 , currentTime = 20000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 2 , restTime = 20000 , currentRestTime = 10000 , color = Timer.salmon , swipe = Swipe.init , id = 0 } (Main.fromActive 30000 { state = Timer.Counting , label = "PI:NAME:<NAME>END_PI" , startTime = 20000 , currentTime = 20000 , tone = Timer.None , vibrate = True , repetitions = 4 , currentRepetition = 2 , restTime = 20000 , currentRestTime = 20000 , color = Timer.salmon , swipe = Swipe.init , id = 0 } ) ]
elm
[ { "context": " address = \"Penthouse 1, One Corporate Center, Dona Julia Vargas Ave cor Meralco Ave, Ortigas Center, Pasig, Phili", "end": 8858, "score": 0.9252586365, "start": 8844, "tag": "NAME", "value": "a Julia Vargas" }, { "context": ", Font.underline\n ]\n (Element.text \"hello@ownally.com\")\n\n\nviewPhone : Element msg\nviewPhone =\n Eleme", "end": 9751, "score": 0.9999170899, "start": 9734, "tag": "EMAIL", "value": "hello@ownally.com" } ]
src/Page/Home.elm
Ownally/Ownally.github.io
0
module Page.Home exposing ( viewBigDesktopLandscape , viewBigDesktopPortrait , viewDesktopLandscape , viewDesktopPortrait , viewPhoneLandscape , viewPhonePortrait , viewTabletLandscape , viewTabletPortrait ) import Element exposing (Attribute, Color, Element) import Element.Background as Background import Element.Font as Font import GoogleMap import Image exposing (Image) import Window exposing (Window) -- VIEW viewPhonePortrait : Window -> Element msg viewPhonePortrait = view viewTabletPortrait : Window -> Element msg viewTabletPortrait = view viewDesktopPortrait : Window -> Element msg viewDesktopPortrait = view viewBigDesktopPortrait : Window -> Element msg viewBigDesktopPortrait = view viewPhoneLandscape : Window -> Element msg viewPhoneLandscape = view viewTabletLandscape : Window -> Element msg viewTabletLandscape = view viewDesktopLandscape : Window -> Element msg viewDesktopLandscape = view viewBigDesktopLandscape : Window -> Element msg viewBigDesktopLandscape = view view : Window -> Element msg view window = Element.column [ Element.width Element.fill ] [ viewLanding window , viewHow , viewBenefit , viewContact , viewFooter ] -- LANDING viewLanding : Window -> Element msg viewLanding window = Element.column [ Element.width Element.fill , Window.toAttribute window , Element.paddingXY 144 72 , Element.spacing 36 , Image.toBackground Image.house , Element.behindContent viewFadeWhite ] [ viewHeadline , viewSubHeadline ] viewFadeWhite : Element msg viewFadeWhite = Element.el attributeFadeWhite Element.none attributeFadeWhite : List (Attribute msg) attributeFadeWhite = [ Element.width Element.fill , Element.height Element.fill , Background.gradient { angle = pi / 2 , steps = [ white, transparent ] } ] -- HEADLINE viewHeadline : Element msg viewHeadline = Element.paragraph attributeHeadline [ Element.text "Own your home at your terms" ] attributeHeadline : List (Attribute msg) attributeHeadline = List.concat [ shrinkContent , [ Element.alignLeft , Element.centerY ] , [ Font.color lightBlack , Font.size 72 , Font.alignLeft , Font.bold ] ] -- SUBHEADLINE viewSubHeadline : Element msg viewSubHeadline = Element.paragraph attributeSubHeadline [ Element.text "Lower monthly payments + No loans and interest" ] attributeSubHeadline : List (Attribute msg) attributeSubHeadline = List.concat [ shrinkContent , [ Element.alignLeft , Element.centerY ] , [ Font.color lightBlack , Font.size 36 , Font.alignLeft ] ] -- HOW viewHow : Element msg viewHow = Element.row attributeHow [ viewEquity , viewRental , viewTrade ] attributeHow : List (Attribute msg) attributeHow = List.concat [ fillWidth , bodyPadding , [ Background.color white ] ] viewEquity : Element msg viewEquity = viewBox Image.pieChart "Sell fractional equities of your property to Ownally and investors, so you have the funds to purchase your property without loans." viewRental : Element msg viewRental = viewBox Image.rentalContract "Only pay fractional rent for the proportional equities you don't own. More equities you own, lesser the rent." viewTrade : Element msg viewTrade = viewBox Image.tradeGrowth "Freely trade equities with Ownally and investors anytime you want. Slowly build your wealth without debt." viewBox : Image -> String -> Element msg viewBox image string = Element.column attributeBox [ viewImageIcon image , viewStep string ] attributeBox : List (Attribute msg) attributeBox = List.concat [ fillWidth , [ Element.padding 48 , Element.spacing 48 , Element.alignTop ] ] viewImageIcon : Image -> Element msg viewImageIcon = Image.toElement attributeImageIcon attributeImageIcon : List (Attribute msg) attributeImageIcon = [ Element.width <| Element.px 150 , Element.height <| Element.px 150 , Element.centerX ] viewStep : String -> Element msg viewStep string = Element.paragraph attributeStep [ Element.text string ] attributeStep : List (Attribute msg) attributeStep = List.concat [ fillWidth , [ Font.color lightBlack , Font.size 24 , Font.justify ] ] -- BENEFIT viewBenefit : Element msg viewBenefit = Element.column attributeBenefit [ viewLesser , viewInvest , viewBigData , viewEmergency ] attributeBenefit : List (Attribute msg) attributeBenefit = fillWidth viewLesser : Element msg viewLesser = viewWithPic Image.buildings "Customizable monthly payments for you" viewInvest : Element msg viewInvest = viewBlack "Own your property" viewBigData : Element msg viewBigData = viewWithPic Image.technology "Determination of prices using Big Data and AI" viewEmergency : Element msg viewEmergency = viewBlack "Seamless conversion of equity to cash in times of need" viewWithPic : Image -> String -> Element msg viewWithPic image string = Element.paragraph (attributeWithPic image) [ Element.text string ] attributeWithPic : Image -> List (Attribute msg) attributeWithPic image = List.concat [ fillWidth , bodyPadding , [ Image.toBackground image , Element.behindContent viewFadeBlack , Font.color white , Font.size 48 , Font.alignRight , Font.bold ] ] viewFadeBlack : Element msg viewFadeBlack = Element.el attributeFadeBlack Element.none attributeFadeBlack : List (Attribute msg) attributeFadeBlack = List.concat [ fillWindow , [ Background.gradient { angle = pi / 2 , steps = [ transparent, lightBlack ] } ] ] viewBlack : String -> Element msg viewBlack string = Element.paragraph attributeBlack [ Element.text string ] attributeBlack : List (Attribute msg) attributeBlack = List.concat [ fillWidth , bodyPadding , [ Background.color lightBlack , Font.color white , Font.size 48 , Font.alignLeft , Font.bold ] ] -- CONTACT viewContact : Element msg viewContact = Element.column [ Element.width Element.fill , Element.paddingXY 144 72 , Element.spacing 36 ] [ viewContactUs , viewContactDetails ] viewContactUs : Element msg viewContactUs = Element.el [ Font.color lightBlack , Font.size 36 , Font.heavy ] (Element.text "Contact Us") viewContactDetails : Element msg viewContactDetails = Element.row [ Element.width Element.fill , Element.spacing 36 ] [ viewSingaporeMap , viewAddresses , viewPhilippines ] viewSingaporeMap : Element msg viewSingaporeMap = GoogleMap.toElement GoogleMap.singapore 600 450 [] viewPhilippines : Element msg viewPhilippines = GoogleMap.toElement GoogleMap.philippines 600 450 [] viewAddresses : Element msg viewAddresses = Element.column [ Element.width Element.fill , Element.height Element.fill ] [ viewSingaporeDetails , viewPhilippinesDetails ] -- DETAILS viewSingaporeDetails : Element msg viewSingaporeDetails = viewDetails Top [ viewSingaporeAddress , viewEmailLeft ] viewPhilippinesDetails : Element msg viewPhilippinesDetails = viewDetails Bottom [ viewPhillippineAddress , viewEmailRight , viewPhone ] viewDetails : VerticalAlignment -> List (Element msg) -> Element msg viewDetails alignment = Element.column [ Element.width Element.fill , Element.spacing 12 , fromVerticalAlignmentToAttribute alignment ] -- ADDRESS viewSingaporeAddress : Element msg viewSingaporeAddress = viewAddress { alignment = Left , fontAlignment = AlignLeft , address = "07-07, TripleOne Somerset, 111 Somerset Road, Singapore 238164" } viewPhillippineAddress : Element msg viewPhillippineAddress = viewAddress { alignment = Right , fontAlignment = AlignRight , address = "Penthouse 1, One Corporate Center, Dona Julia Vargas Ave cor Meralco Ave, Ortigas Center, Pasig, Philippines 1605" } viewAddress : { alignment : HorizontalAlignment, fontAlignment : FontAlignment, address : String } -> Element msg viewAddress details = Element.paragraph [ fromHorizontalAlignmentToAttribute details.alignment , Font.color lightBlack , Font.size 24 , fromFontAlignmentToAttribute details.fontAlignment , Font.bold ] [ Element.text details.address ] -- EMAIL viewEmailLeft : Element msg viewEmailLeft = viewEmail Left viewEmailRight : Element msg viewEmailRight = viewEmail Right viewEmail : HorizontalAlignment -> Element msg viewEmail alignment = Element.el [ fromHorizontalAlignmentToAttribute alignment , Font.color blue , Font.size 24 , Font.underline ] (Element.text "hello@ownally.com") viewPhone : Element msg viewPhone = Element.el [ Element.alignRight , Font.color lightBlack , Font.size 24 ] (Element.text "+632 8285 9735") -- VERTICAL ALIGNMENT type VerticalAlignment = Top | Bottom fromVerticalAlignmentToAttribute : VerticalAlignment -> Attribute msg fromVerticalAlignmentToAttribute verticalAlignment = case verticalAlignment of Top -> Element.alignTop Bottom -> Element.alignBottom -- HORIZONTAL ALIGNMENT type HorizontalAlignment = Left | Right fromHorizontalAlignmentToAttribute : HorizontalAlignment -> Attribute msg fromHorizontalAlignmentToAttribute horizontalAlignment = case horizontalAlignment of Left -> Element.alignLeft Right -> Element.alignRight -- FONT ALIGNMENT type FontAlignment = AlignLeft | AlignRight fromFontAlignmentToAttribute : FontAlignment -> Attribute msg fromFontAlignmentToAttribute fontAlignment = case fontAlignment of AlignLeft -> Font.alignLeft AlignRight -> Font.alignRight -- FOOTER viewFooterPhonePortrait : Element msg viewFooterPhonePortrait = viewFooter viewFooterTabletPortrait : Element msg viewFooterTabletPortrait = viewFooter viewFooterDesktopPortrait : Element msg viewFooterDesktopPortrait = viewFooter viewFooterBigDesktopPortrait : Element msg viewFooterBigDesktopPortrait = viewFooter viewFooterPhoneLandscape : Element msg viewFooterPhoneLandscape = viewFooter viewFooterTabletLandscape : Element msg viewFooterTabletLandscape = viewFooter viewFooterDesktopLandscape : Element msg viewFooterDesktopLandscape = viewFooter viewFooterBigDesktopLandscape : Element msg viewFooterBigDesktopLandscape = viewFooter viewFooter : Element msg viewFooter = Element.el attributeFooter <| Element.text "Ownally Footer" attributeFooter : List (Attribute msg) attributeFooter = List.concat [ fillWidth , [ Element.paddingXY 144 48 ] , [ Background.color lightBlack ] , [ Font.color white , Font.size 36 , Font.alignLeft , Font.bold ] ] -- SIZE fillWindow : List (Attribute msg) fillWindow = [ Element.width Element.fill , Element.height Element.fill ] fillWidth : List (Attribute msg) fillWidth = [ Element.width Element.fill , Element.height Element.shrink ] shrinkContent : List (Attribute msg) shrinkContent = [ Element.width Element.shrink , Element.height Element.shrink ] -- PADDING AND SPACING bodyPadding : List (Attribute msg) bodyPadding = [ Element.paddingXY 144 72 , Element.spacing 36 ] -- COLOR white : Color white = Element.fromRgb255 { red = 255 , green = 255 , blue = 255 , alpha = 1 } lightBlack : Color lightBlack = Element.fromRgb255 { red = 32 , green = 32 , blue = 32 , alpha = 1 } transparent : Color transparent = Element.fromRgb255 { red = 255 , green = 255 , blue = 255 , alpha = 0 } blue : Color blue = Element.fromRgb255 { red = 0 , green = 0 , blue = 255 , alpha = 1 }
5484
module Page.Home exposing ( viewBigDesktopLandscape , viewBigDesktopPortrait , viewDesktopLandscape , viewDesktopPortrait , viewPhoneLandscape , viewPhonePortrait , viewTabletLandscape , viewTabletPortrait ) import Element exposing (Attribute, Color, Element) import Element.Background as Background import Element.Font as Font import GoogleMap import Image exposing (Image) import Window exposing (Window) -- VIEW viewPhonePortrait : Window -> Element msg viewPhonePortrait = view viewTabletPortrait : Window -> Element msg viewTabletPortrait = view viewDesktopPortrait : Window -> Element msg viewDesktopPortrait = view viewBigDesktopPortrait : Window -> Element msg viewBigDesktopPortrait = view viewPhoneLandscape : Window -> Element msg viewPhoneLandscape = view viewTabletLandscape : Window -> Element msg viewTabletLandscape = view viewDesktopLandscape : Window -> Element msg viewDesktopLandscape = view viewBigDesktopLandscape : Window -> Element msg viewBigDesktopLandscape = view view : Window -> Element msg view window = Element.column [ Element.width Element.fill ] [ viewLanding window , viewHow , viewBenefit , viewContact , viewFooter ] -- LANDING viewLanding : Window -> Element msg viewLanding window = Element.column [ Element.width Element.fill , Window.toAttribute window , Element.paddingXY 144 72 , Element.spacing 36 , Image.toBackground Image.house , Element.behindContent viewFadeWhite ] [ viewHeadline , viewSubHeadline ] viewFadeWhite : Element msg viewFadeWhite = Element.el attributeFadeWhite Element.none attributeFadeWhite : List (Attribute msg) attributeFadeWhite = [ Element.width Element.fill , Element.height Element.fill , Background.gradient { angle = pi / 2 , steps = [ white, transparent ] } ] -- HEADLINE viewHeadline : Element msg viewHeadline = Element.paragraph attributeHeadline [ Element.text "Own your home at your terms" ] attributeHeadline : List (Attribute msg) attributeHeadline = List.concat [ shrinkContent , [ Element.alignLeft , Element.centerY ] , [ Font.color lightBlack , Font.size 72 , Font.alignLeft , Font.bold ] ] -- SUBHEADLINE viewSubHeadline : Element msg viewSubHeadline = Element.paragraph attributeSubHeadline [ Element.text "Lower monthly payments + No loans and interest" ] attributeSubHeadline : List (Attribute msg) attributeSubHeadline = List.concat [ shrinkContent , [ Element.alignLeft , Element.centerY ] , [ Font.color lightBlack , Font.size 36 , Font.alignLeft ] ] -- HOW viewHow : Element msg viewHow = Element.row attributeHow [ viewEquity , viewRental , viewTrade ] attributeHow : List (Attribute msg) attributeHow = List.concat [ fillWidth , bodyPadding , [ Background.color white ] ] viewEquity : Element msg viewEquity = viewBox Image.pieChart "Sell fractional equities of your property to Ownally and investors, so you have the funds to purchase your property without loans." viewRental : Element msg viewRental = viewBox Image.rentalContract "Only pay fractional rent for the proportional equities you don't own. More equities you own, lesser the rent." viewTrade : Element msg viewTrade = viewBox Image.tradeGrowth "Freely trade equities with Ownally and investors anytime you want. Slowly build your wealth without debt." viewBox : Image -> String -> Element msg viewBox image string = Element.column attributeBox [ viewImageIcon image , viewStep string ] attributeBox : List (Attribute msg) attributeBox = List.concat [ fillWidth , [ Element.padding 48 , Element.spacing 48 , Element.alignTop ] ] viewImageIcon : Image -> Element msg viewImageIcon = Image.toElement attributeImageIcon attributeImageIcon : List (Attribute msg) attributeImageIcon = [ Element.width <| Element.px 150 , Element.height <| Element.px 150 , Element.centerX ] viewStep : String -> Element msg viewStep string = Element.paragraph attributeStep [ Element.text string ] attributeStep : List (Attribute msg) attributeStep = List.concat [ fillWidth , [ Font.color lightBlack , Font.size 24 , Font.justify ] ] -- BENEFIT viewBenefit : Element msg viewBenefit = Element.column attributeBenefit [ viewLesser , viewInvest , viewBigData , viewEmergency ] attributeBenefit : List (Attribute msg) attributeBenefit = fillWidth viewLesser : Element msg viewLesser = viewWithPic Image.buildings "Customizable monthly payments for you" viewInvest : Element msg viewInvest = viewBlack "Own your property" viewBigData : Element msg viewBigData = viewWithPic Image.technology "Determination of prices using Big Data and AI" viewEmergency : Element msg viewEmergency = viewBlack "Seamless conversion of equity to cash in times of need" viewWithPic : Image -> String -> Element msg viewWithPic image string = Element.paragraph (attributeWithPic image) [ Element.text string ] attributeWithPic : Image -> List (Attribute msg) attributeWithPic image = List.concat [ fillWidth , bodyPadding , [ Image.toBackground image , Element.behindContent viewFadeBlack , Font.color white , Font.size 48 , Font.alignRight , Font.bold ] ] viewFadeBlack : Element msg viewFadeBlack = Element.el attributeFadeBlack Element.none attributeFadeBlack : List (Attribute msg) attributeFadeBlack = List.concat [ fillWindow , [ Background.gradient { angle = pi / 2 , steps = [ transparent, lightBlack ] } ] ] viewBlack : String -> Element msg viewBlack string = Element.paragraph attributeBlack [ Element.text string ] attributeBlack : List (Attribute msg) attributeBlack = List.concat [ fillWidth , bodyPadding , [ Background.color lightBlack , Font.color white , Font.size 48 , Font.alignLeft , Font.bold ] ] -- CONTACT viewContact : Element msg viewContact = Element.column [ Element.width Element.fill , Element.paddingXY 144 72 , Element.spacing 36 ] [ viewContactUs , viewContactDetails ] viewContactUs : Element msg viewContactUs = Element.el [ Font.color lightBlack , Font.size 36 , Font.heavy ] (Element.text "Contact Us") viewContactDetails : Element msg viewContactDetails = Element.row [ Element.width Element.fill , Element.spacing 36 ] [ viewSingaporeMap , viewAddresses , viewPhilippines ] viewSingaporeMap : Element msg viewSingaporeMap = GoogleMap.toElement GoogleMap.singapore 600 450 [] viewPhilippines : Element msg viewPhilippines = GoogleMap.toElement GoogleMap.philippines 600 450 [] viewAddresses : Element msg viewAddresses = Element.column [ Element.width Element.fill , Element.height Element.fill ] [ viewSingaporeDetails , viewPhilippinesDetails ] -- DETAILS viewSingaporeDetails : Element msg viewSingaporeDetails = viewDetails Top [ viewSingaporeAddress , viewEmailLeft ] viewPhilippinesDetails : Element msg viewPhilippinesDetails = viewDetails Bottom [ viewPhillippineAddress , viewEmailRight , viewPhone ] viewDetails : VerticalAlignment -> List (Element msg) -> Element msg viewDetails alignment = Element.column [ Element.width Element.fill , Element.spacing 12 , fromVerticalAlignmentToAttribute alignment ] -- ADDRESS viewSingaporeAddress : Element msg viewSingaporeAddress = viewAddress { alignment = Left , fontAlignment = AlignLeft , address = "07-07, TripleOne Somerset, 111 Somerset Road, Singapore 238164" } viewPhillippineAddress : Element msg viewPhillippineAddress = viewAddress { alignment = Right , fontAlignment = AlignRight , address = "Penthouse 1, One Corporate Center, Don<NAME> Ave cor Meralco Ave, Ortigas Center, Pasig, Philippines 1605" } viewAddress : { alignment : HorizontalAlignment, fontAlignment : FontAlignment, address : String } -> Element msg viewAddress details = Element.paragraph [ fromHorizontalAlignmentToAttribute details.alignment , Font.color lightBlack , Font.size 24 , fromFontAlignmentToAttribute details.fontAlignment , Font.bold ] [ Element.text details.address ] -- EMAIL viewEmailLeft : Element msg viewEmailLeft = viewEmail Left viewEmailRight : Element msg viewEmailRight = viewEmail Right viewEmail : HorizontalAlignment -> Element msg viewEmail alignment = Element.el [ fromHorizontalAlignmentToAttribute alignment , Font.color blue , Font.size 24 , Font.underline ] (Element.text "<EMAIL>") viewPhone : Element msg viewPhone = Element.el [ Element.alignRight , Font.color lightBlack , Font.size 24 ] (Element.text "+632 8285 9735") -- VERTICAL ALIGNMENT type VerticalAlignment = Top | Bottom fromVerticalAlignmentToAttribute : VerticalAlignment -> Attribute msg fromVerticalAlignmentToAttribute verticalAlignment = case verticalAlignment of Top -> Element.alignTop Bottom -> Element.alignBottom -- HORIZONTAL ALIGNMENT type HorizontalAlignment = Left | Right fromHorizontalAlignmentToAttribute : HorizontalAlignment -> Attribute msg fromHorizontalAlignmentToAttribute horizontalAlignment = case horizontalAlignment of Left -> Element.alignLeft Right -> Element.alignRight -- FONT ALIGNMENT type FontAlignment = AlignLeft | AlignRight fromFontAlignmentToAttribute : FontAlignment -> Attribute msg fromFontAlignmentToAttribute fontAlignment = case fontAlignment of AlignLeft -> Font.alignLeft AlignRight -> Font.alignRight -- FOOTER viewFooterPhonePortrait : Element msg viewFooterPhonePortrait = viewFooter viewFooterTabletPortrait : Element msg viewFooterTabletPortrait = viewFooter viewFooterDesktopPortrait : Element msg viewFooterDesktopPortrait = viewFooter viewFooterBigDesktopPortrait : Element msg viewFooterBigDesktopPortrait = viewFooter viewFooterPhoneLandscape : Element msg viewFooterPhoneLandscape = viewFooter viewFooterTabletLandscape : Element msg viewFooterTabletLandscape = viewFooter viewFooterDesktopLandscape : Element msg viewFooterDesktopLandscape = viewFooter viewFooterBigDesktopLandscape : Element msg viewFooterBigDesktopLandscape = viewFooter viewFooter : Element msg viewFooter = Element.el attributeFooter <| Element.text "Ownally Footer" attributeFooter : List (Attribute msg) attributeFooter = List.concat [ fillWidth , [ Element.paddingXY 144 48 ] , [ Background.color lightBlack ] , [ Font.color white , Font.size 36 , Font.alignLeft , Font.bold ] ] -- SIZE fillWindow : List (Attribute msg) fillWindow = [ Element.width Element.fill , Element.height Element.fill ] fillWidth : List (Attribute msg) fillWidth = [ Element.width Element.fill , Element.height Element.shrink ] shrinkContent : List (Attribute msg) shrinkContent = [ Element.width Element.shrink , Element.height Element.shrink ] -- PADDING AND SPACING bodyPadding : List (Attribute msg) bodyPadding = [ Element.paddingXY 144 72 , Element.spacing 36 ] -- COLOR white : Color white = Element.fromRgb255 { red = 255 , green = 255 , blue = 255 , alpha = 1 } lightBlack : Color lightBlack = Element.fromRgb255 { red = 32 , green = 32 , blue = 32 , alpha = 1 } transparent : Color transparent = Element.fromRgb255 { red = 255 , green = 255 , blue = 255 , alpha = 0 } blue : Color blue = Element.fromRgb255 { red = 0 , green = 0 , blue = 255 , alpha = 1 }
true
module Page.Home exposing ( viewBigDesktopLandscape , viewBigDesktopPortrait , viewDesktopLandscape , viewDesktopPortrait , viewPhoneLandscape , viewPhonePortrait , viewTabletLandscape , viewTabletPortrait ) import Element exposing (Attribute, Color, Element) import Element.Background as Background import Element.Font as Font import GoogleMap import Image exposing (Image) import Window exposing (Window) -- VIEW viewPhonePortrait : Window -> Element msg viewPhonePortrait = view viewTabletPortrait : Window -> Element msg viewTabletPortrait = view viewDesktopPortrait : Window -> Element msg viewDesktopPortrait = view viewBigDesktopPortrait : Window -> Element msg viewBigDesktopPortrait = view viewPhoneLandscape : Window -> Element msg viewPhoneLandscape = view viewTabletLandscape : Window -> Element msg viewTabletLandscape = view viewDesktopLandscape : Window -> Element msg viewDesktopLandscape = view viewBigDesktopLandscape : Window -> Element msg viewBigDesktopLandscape = view view : Window -> Element msg view window = Element.column [ Element.width Element.fill ] [ viewLanding window , viewHow , viewBenefit , viewContact , viewFooter ] -- LANDING viewLanding : Window -> Element msg viewLanding window = Element.column [ Element.width Element.fill , Window.toAttribute window , Element.paddingXY 144 72 , Element.spacing 36 , Image.toBackground Image.house , Element.behindContent viewFadeWhite ] [ viewHeadline , viewSubHeadline ] viewFadeWhite : Element msg viewFadeWhite = Element.el attributeFadeWhite Element.none attributeFadeWhite : List (Attribute msg) attributeFadeWhite = [ Element.width Element.fill , Element.height Element.fill , Background.gradient { angle = pi / 2 , steps = [ white, transparent ] } ] -- HEADLINE viewHeadline : Element msg viewHeadline = Element.paragraph attributeHeadline [ Element.text "Own your home at your terms" ] attributeHeadline : List (Attribute msg) attributeHeadline = List.concat [ shrinkContent , [ Element.alignLeft , Element.centerY ] , [ Font.color lightBlack , Font.size 72 , Font.alignLeft , Font.bold ] ] -- SUBHEADLINE viewSubHeadline : Element msg viewSubHeadline = Element.paragraph attributeSubHeadline [ Element.text "Lower monthly payments + No loans and interest" ] attributeSubHeadline : List (Attribute msg) attributeSubHeadline = List.concat [ shrinkContent , [ Element.alignLeft , Element.centerY ] , [ Font.color lightBlack , Font.size 36 , Font.alignLeft ] ] -- HOW viewHow : Element msg viewHow = Element.row attributeHow [ viewEquity , viewRental , viewTrade ] attributeHow : List (Attribute msg) attributeHow = List.concat [ fillWidth , bodyPadding , [ Background.color white ] ] viewEquity : Element msg viewEquity = viewBox Image.pieChart "Sell fractional equities of your property to Ownally and investors, so you have the funds to purchase your property without loans." viewRental : Element msg viewRental = viewBox Image.rentalContract "Only pay fractional rent for the proportional equities you don't own. More equities you own, lesser the rent." viewTrade : Element msg viewTrade = viewBox Image.tradeGrowth "Freely trade equities with Ownally and investors anytime you want. Slowly build your wealth without debt." viewBox : Image -> String -> Element msg viewBox image string = Element.column attributeBox [ viewImageIcon image , viewStep string ] attributeBox : List (Attribute msg) attributeBox = List.concat [ fillWidth , [ Element.padding 48 , Element.spacing 48 , Element.alignTop ] ] viewImageIcon : Image -> Element msg viewImageIcon = Image.toElement attributeImageIcon attributeImageIcon : List (Attribute msg) attributeImageIcon = [ Element.width <| Element.px 150 , Element.height <| Element.px 150 , Element.centerX ] viewStep : String -> Element msg viewStep string = Element.paragraph attributeStep [ Element.text string ] attributeStep : List (Attribute msg) attributeStep = List.concat [ fillWidth , [ Font.color lightBlack , Font.size 24 , Font.justify ] ] -- BENEFIT viewBenefit : Element msg viewBenefit = Element.column attributeBenefit [ viewLesser , viewInvest , viewBigData , viewEmergency ] attributeBenefit : List (Attribute msg) attributeBenefit = fillWidth viewLesser : Element msg viewLesser = viewWithPic Image.buildings "Customizable monthly payments for you" viewInvest : Element msg viewInvest = viewBlack "Own your property" viewBigData : Element msg viewBigData = viewWithPic Image.technology "Determination of prices using Big Data and AI" viewEmergency : Element msg viewEmergency = viewBlack "Seamless conversion of equity to cash in times of need" viewWithPic : Image -> String -> Element msg viewWithPic image string = Element.paragraph (attributeWithPic image) [ Element.text string ] attributeWithPic : Image -> List (Attribute msg) attributeWithPic image = List.concat [ fillWidth , bodyPadding , [ Image.toBackground image , Element.behindContent viewFadeBlack , Font.color white , Font.size 48 , Font.alignRight , Font.bold ] ] viewFadeBlack : Element msg viewFadeBlack = Element.el attributeFadeBlack Element.none attributeFadeBlack : List (Attribute msg) attributeFadeBlack = List.concat [ fillWindow , [ Background.gradient { angle = pi / 2 , steps = [ transparent, lightBlack ] } ] ] viewBlack : String -> Element msg viewBlack string = Element.paragraph attributeBlack [ Element.text string ] attributeBlack : List (Attribute msg) attributeBlack = List.concat [ fillWidth , bodyPadding , [ Background.color lightBlack , Font.color white , Font.size 48 , Font.alignLeft , Font.bold ] ] -- CONTACT viewContact : Element msg viewContact = Element.column [ Element.width Element.fill , Element.paddingXY 144 72 , Element.spacing 36 ] [ viewContactUs , viewContactDetails ] viewContactUs : Element msg viewContactUs = Element.el [ Font.color lightBlack , Font.size 36 , Font.heavy ] (Element.text "Contact Us") viewContactDetails : Element msg viewContactDetails = Element.row [ Element.width Element.fill , Element.spacing 36 ] [ viewSingaporeMap , viewAddresses , viewPhilippines ] viewSingaporeMap : Element msg viewSingaporeMap = GoogleMap.toElement GoogleMap.singapore 600 450 [] viewPhilippines : Element msg viewPhilippines = GoogleMap.toElement GoogleMap.philippines 600 450 [] viewAddresses : Element msg viewAddresses = Element.column [ Element.width Element.fill , Element.height Element.fill ] [ viewSingaporeDetails , viewPhilippinesDetails ] -- DETAILS viewSingaporeDetails : Element msg viewSingaporeDetails = viewDetails Top [ viewSingaporeAddress , viewEmailLeft ] viewPhilippinesDetails : Element msg viewPhilippinesDetails = viewDetails Bottom [ viewPhillippineAddress , viewEmailRight , viewPhone ] viewDetails : VerticalAlignment -> List (Element msg) -> Element msg viewDetails alignment = Element.column [ Element.width Element.fill , Element.spacing 12 , fromVerticalAlignmentToAttribute alignment ] -- ADDRESS viewSingaporeAddress : Element msg viewSingaporeAddress = viewAddress { alignment = Left , fontAlignment = AlignLeft , address = "07-07, TripleOne Somerset, 111 Somerset Road, Singapore 238164" } viewPhillippineAddress : Element msg viewPhillippineAddress = viewAddress { alignment = Right , fontAlignment = AlignRight , address = "Penthouse 1, One Corporate Center, DonPI:NAME:<NAME>END_PI Ave cor Meralco Ave, Ortigas Center, Pasig, Philippines 1605" } viewAddress : { alignment : HorizontalAlignment, fontAlignment : FontAlignment, address : String } -> Element msg viewAddress details = Element.paragraph [ fromHorizontalAlignmentToAttribute details.alignment , Font.color lightBlack , Font.size 24 , fromFontAlignmentToAttribute details.fontAlignment , Font.bold ] [ Element.text details.address ] -- EMAIL viewEmailLeft : Element msg viewEmailLeft = viewEmail Left viewEmailRight : Element msg viewEmailRight = viewEmail Right viewEmail : HorizontalAlignment -> Element msg viewEmail alignment = Element.el [ fromHorizontalAlignmentToAttribute alignment , Font.color blue , Font.size 24 , Font.underline ] (Element.text "PI:EMAIL:<EMAIL>END_PI") viewPhone : Element msg viewPhone = Element.el [ Element.alignRight , Font.color lightBlack , Font.size 24 ] (Element.text "+632 8285 9735") -- VERTICAL ALIGNMENT type VerticalAlignment = Top | Bottom fromVerticalAlignmentToAttribute : VerticalAlignment -> Attribute msg fromVerticalAlignmentToAttribute verticalAlignment = case verticalAlignment of Top -> Element.alignTop Bottom -> Element.alignBottom -- HORIZONTAL ALIGNMENT type HorizontalAlignment = Left | Right fromHorizontalAlignmentToAttribute : HorizontalAlignment -> Attribute msg fromHorizontalAlignmentToAttribute horizontalAlignment = case horizontalAlignment of Left -> Element.alignLeft Right -> Element.alignRight -- FONT ALIGNMENT type FontAlignment = AlignLeft | AlignRight fromFontAlignmentToAttribute : FontAlignment -> Attribute msg fromFontAlignmentToAttribute fontAlignment = case fontAlignment of AlignLeft -> Font.alignLeft AlignRight -> Font.alignRight -- FOOTER viewFooterPhonePortrait : Element msg viewFooterPhonePortrait = viewFooter viewFooterTabletPortrait : Element msg viewFooterTabletPortrait = viewFooter viewFooterDesktopPortrait : Element msg viewFooterDesktopPortrait = viewFooter viewFooterBigDesktopPortrait : Element msg viewFooterBigDesktopPortrait = viewFooter viewFooterPhoneLandscape : Element msg viewFooterPhoneLandscape = viewFooter viewFooterTabletLandscape : Element msg viewFooterTabletLandscape = viewFooter viewFooterDesktopLandscape : Element msg viewFooterDesktopLandscape = viewFooter viewFooterBigDesktopLandscape : Element msg viewFooterBigDesktopLandscape = viewFooter viewFooter : Element msg viewFooter = Element.el attributeFooter <| Element.text "Ownally Footer" attributeFooter : List (Attribute msg) attributeFooter = List.concat [ fillWidth , [ Element.paddingXY 144 48 ] , [ Background.color lightBlack ] , [ Font.color white , Font.size 36 , Font.alignLeft , Font.bold ] ] -- SIZE fillWindow : List (Attribute msg) fillWindow = [ Element.width Element.fill , Element.height Element.fill ] fillWidth : List (Attribute msg) fillWidth = [ Element.width Element.fill , Element.height Element.shrink ] shrinkContent : List (Attribute msg) shrinkContent = [ Element.width Element.shrink , Element.height Element.shrink ] -- PADDING AND SPACING bodyPadding : List (Attribute msg) bodyPadding = [ Element.paddingXY 144 72 , Element.spacing 36 ] -- COLOR white : Color white = Element.fromRgb255 { red = 255 , green = 255 , blue = 255 , alpha = 1 } lightBlack : Color lightBlack = Element.fromRgb255 { red = 32 , green = 32 , blue = 32 , alpha = 1 } transparent : Color transparent = Element.fromRgb255 { red = 255 , green = 255 , blue = 255 , alpha = 0 } blue : Color blue = Element.fromRgb255 { red = 0 , green = 0 , blue = 255 , alpha = 1 }
elm
[ { "context": " normalizedName = Nothing\n , rawName = Just \"SlOPPy JOe\"\n }\n\n\nupdate : Action -> Model -> Model\n", "end": 334, "score": 0.374029994, "start": 332, "tag": "PASSWORD", "value": "OP" }, { "context": "ormalizedName = Nothing\n , rawName = Just \"SlOPPy JOe\"\n }\n\n\nupdate : Action -> Model -> Model\nup", "end": 336, "score": 0.3598981798, "start": 334, "tag": "USERNAME", "value": "Py" }, { "context": "malizedName = Nothing\n , rawName = Just \"SlOPPy JOe\"\n }\n\n\nupdate : Action -> Model -> Model\nupdate", "end": 340, "score": 0.3389545977, "start": 337, "tag": "PASSWORD", "value": "JOe" } ]
normalized-form-input/Main.elm
ethagnawl/elm-ui-patterns
2
module Main exposing (init) import Browser import Html import Html.Attributes import Html.Events type alias Model = { normalizedName : Maybe String , rawName : Maybe String } type Action = UpdateName String | None defaultModel : Model defaultModel = { normalizedName = Nothing , rawName = Just "SlOPPy JOe" } update : Action -> Model -> Model update msg model = case msg of UpdateName rawInput -> let normalizedName_ = Just <| (String.replace " " "_") <| String.toLower <| String.trim rawInput in { model | normalizedName = normalizedName_ , rawName = Just rawInput } _ -> model init : Model init = let rawName = Maybe.withDefault "" defaultModel.rawName in (update (UpdateName rawName) defaultModel) view : Model -> Html.Html Action view model = let normalizedName = Maybe.withDefault "" model.normalizedName rawName = Maybe.withDefault "" model.rawName in Html.div [] [ Html.form [] [ Html.fieldset [] [ Html.label [] [ Html.text "rawName (what user sees during input and maybe elsewhere in the UI): " ] , Html.input [ Html.Attributes.type_ "text" , Html.Attributes.value rawName , Html.Events.onInput UpdateName ] [] ] , Html.fieldset [] [ Html.label [] [ Html.text "normalizedName (what Elm uses for business logic): " ] , Html.output [] [ Html.text normalizedName ] ] ] ] main = Browser.sandbox { init = init , update = update , view = view }
39244
module Main exposing (init) import Browser import Html import Html.Attributes import Html.Events type alias Model = { normalizedName : Maybe String , rawName : Maybe String } type Action = UpdateName String | None defaultModel : Model defaultModel = { normalizedName = Nothing , rawName = Just "Sl<PASSWORD>Py <PASSWORD>" } update : Action -> Model -> Model update msg model = case msg of UpdateName rawInput -> let normalizedName_ = Just <| (String.replace " " "_") <| String.toLower <| String.trim rawInput in { model | normalizedName = normalizedName_ , rawName = Just rawInput } _ -> model init : Model init = let rawName = Maybe.withDefault "" defaultModel.rawName in (update (UpdateName rawName) defaultModel) view : Model -> Html.Html Action view model = let normalizedName = Maybe.withDefault "" model.normalizedName rawName = Maybe.withDefault "" model.rawName in Html.div [] [ Html.form [] [ Html.fieldset [] [ Html.label [] [ Html.text "rawName (what user sees during input and maybe elsewhere in the UI): " ] , Html.input [ Html.Attributes.type_ "text" , Html.Attributes.value rawName , Html.Events.onInput UpdateName ] [] ] , Html.fieldset [] [ Html.label [] [ Html.text "normalizedName (what Elm uses for business logic): " ] , Html.output [] [ Html.text normalizedName ] ] ] ] main = Browser.sandbox { init = init , update = update , view = view }
true
module Main exposing (init) import Browser import Html import Html.Attributes import Html.Events type alias Model = { normalizedName : Maybe String , rawName : Maybe String } type Action = UpdateName String | None defaultModel : Model defaultModel = { normalizedName = Nothing , rawName = Just "SlPI:PASSWORD:<PASSWORD>END_PIPy PI:PASSWORD:<PASSWORD>END_PI" } update : Action -> Model -> Model update msg model = case msg of UpdateName rawInput -> let normalizedName_ = Just <| (String.replace " " "_") <| String.toLower <| String.trim rawInput in { model | normalizedName = normalizedName_ , rawName = Just rawInput } _ -> model init : Model init = let rawName = Maybe.withDefault "" defaultModel.rawName in (update (UpdateName rawName) defaultModel) view : Model -> Html.Html Action view model = let normalizedName = Maybe.withDefault "" model.normalizedName rawName = Maybe.withDefault "" model.rawName in Html.div [] [ Html.form [] [ Html.fieldset [] [ Html.label [] [ Html.text "rawName (what user sees during input and maybe elsewhere in the UI): " ] , Html.input [ Html.Attributes.type_ "text" , Html.Attributes.value rawName , Html.Events.onInput UpdateName ] [] ] , Html.fieldset [] [ Html.label [] [ Html.text "normalizedName (what Elm uses for business logic): " ] , Html.output [] [ Html.text normalizedName ] ] ] ] main = Browser.sandbox { init = init , update = update , view = view }
elm
[ { "context": "7-.5 54.1-.7 81.3-27.2.1-54.2.3-81.2.6v80.9c27 .3 54.2.5 81.2.8.3 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-8", "end": 412, "score": 0.8949477673, "start": 406, "tag": "IP_ADDRESS", "value": "54.2.5" }, { "context": ".1-.7 81.3-27.2.1-54.2.3-81.2.6v80.9c27 .3 54.2.5 81.2.8.3 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-81.3 27.2-", "end": 421, "score": 0.9992665052, "start": 413, "tag": "IP_ADDRESS", "value": "81.2.8.3" }, { "context": ".1-54.2.3-81.2.6v80.9c27 .3 54.2.5 81.2.8.3 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-81.3 27.2-.3 54.2-.4 81", "end": 434, "score": 0.9910004735, "start": 428, "tag": "IP_ADDRESS", "value": "54.1.5" }, { "context": ".1-.7 81.3-27.2.1-54.2.3-81.2.6v80.9c27 .3 54.2.5 81.2.8.3 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-81.3 27.2-", "end": 1164, "score": 0.9794313908, "start": 1156, "tag": "IP_ADDRESS", "value": "81.2.8.3" }, { "context": "-54.2.3-81.2.6v80.9c27 .3 54.2.5 81.2.8.3 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-81.3 27.2-.3 54.2-.4", "end": 1173, "score": 0.6784946918, "start": 1173, "tag": "IP_ADDRESS", "value": "" } ]
src/Ant/Icons/Svg/GooglePlusOutlined.elm
lemol/ant-design-icons-elm
3
-- GENERATE BY ./scripts/generate.ts -- DO NOT EDIT IT MANUALLY module Ant.Icons.Svg.GooglePlusOutlined exposing (view, viewWithAttributes) import Html exposing (Html) import Svg exposing (..) import Svg.Attributes exposing (..) view : Html msg view = svg [ viewBox "64 64 896 896" ] [ Svg.path [ d "M879.5 470.4c-.3-27-.4-54.2-.5-81.3h-80.8c-.3 27-.5 54.1-.7 81.3-27.2.1-54.2.3-81.2.6v80.9c27 .3 54.2.5 81.2.8.3 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-81.3 27.2-.3 54.2-.4 81.2-.7v-80.9c-26.9-.2-54.1-.2-81.1-.5zm-530 .4c-.1 32.3 0 64.7.1 97 54.2 1.8 108.5 1 162.7 1.8-23.9 120.3-187.4 159.3-273.9 80.7-89-68.9-84.8-220 7.7-284 64.7-51.6 156.6-38.9 221.3 5.8 25.4-23.5 49.2-48.7 72.1-74.7-53.8-42.9-119.8-73.5-190-70.3-146.6-4.9-281.3 123.5-283.7 270.2-9.4 119.9 69.4 237.4 180.6 279.8 110.8 42.7 252.9 13.6 323.7-86 46.7-62.9 56.8-143.9 51.3-220-90.7-.7-181.3-.6-271.9-.3z" ] [] ] viewWithAttributes : List (Html.Attribute msg) -> Html msg viewWithAttributes attributes = svg ([ viewBox "64 64 896 896" ] ++ attributes) [ Svg.path [ d "M879.5 470.4c-.3-27-.4-54.2-.5-81.3h-80.8c-.3 27-.5 54.1-.7 81.3-27.2.1-54.2.3-81.2.6v80.9c27 .3 54.2.5 81.2.8.3 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-81.3 27.2-.3 54.2-.4 81.2-.7v-80.9c-26.9-.2-54.1-.2-81.1-.5zm-530 .4c-.1 32.3 0 64.7.1 97 54.2 1.8 108.5 1 162.7 1.8-23.9 120.3-187.4 159.3-273.9 80.7-89-68.9-84.8-220 7.7-284 64.7-51.6 156.6-38.9 221.3 5.8 25.4-23.5 49.2-48.7 72.1-74.7-53.8-42.9-119.8-73.5-190-70.3-146.6-4.9-281.3 123.5-283.7 270.2-9.4 119.9 69.4 237.4 180.6 279.8 110.8 42.7 252.9 13.6 323.7-86 46.7-62.9 56.8-143.9 51.3-220-90.7-.7-181.3-.6-271.9-.3z" ] [] ]
51850
-- GENERATE BY ./scripts/generate.ts -- DO NOT EDIT IT MANUALLY module Ant.Icons.Svg.GooglePlusOutlined exposing (view, viewWithAttributes) import Html exposing (Html) import Svg exposing (..) import Svg.Attributes exposing (..) view : Html msg view = svg [ viewBox "64 64 896 896" ] [ Svg.path [ d "M879.5 470.4c-.3-27-.4-54.2-.5-81.3h-80.8c-.3 27-.5 54.1-.7 81.3-27.2.1-54.2.3-81.2.6v80.9c27 .3 54.2.5 172.16.58.3 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-81.3 27.2-.3 54.2-.4 81.2-.7v-80.9c-26.9-.2-54.1-.2-81.1-.5zm-530 .4c-.1 32.3 0 64.7.1 97 54.2 1.8 108.5 1 162.7 1.8-23.9 120.3-187.4 159.3-273.9 80.7-89-68.9-84.8-220 7.7-284 64.7-51.6 156.6-38.9 221.3 5.8 25.4-23.5 49.2-48.7 72.1-74.7-53.8-42.9-119.8-73.5-190-70.3-146.6-4.9-281.3 123.5-283.7 270.2-9.4 119.9 69.4 237.4 180.6 279.8 110.8 42.7 252.9 13.6 323.7-86 46.7-62.9 56.8-143.9 51.3-220-90.7-.7-181.3-.6-271.9-.3z" ] [] ] viewWithAttributes : List (Html.Attribute msg) -> Html msg viewWithAttributes attributes = svg ([ viewBox "64 64 896 896" ] ++ attributes) [ Svg.path [ d "M879.5 470.4c-.3-27-.4-54.2-.5-81.3h-80.8c-.3 27-.5 54.1-.7 81.3-27.2.1-54.2.3-81.2.6v80.9c27 .3 54.2.5 172.16.58.3 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-81.3 27.2-.3 54.2-.4 81.2-.7v-80.9c-26.9-.2-54.1-.2-81.1-.5zm-530 .4c-.1 32.3 0 64.7.1 97 54.2 1.8 108.5 1 162.7 1.8-23.9 120.3-187.4 159.3-273.9 80.7-89-68.9-84.8-220 7.7-284 64.7-51.6 156.6-38.9 221.3 5.8 25.4-23.5 49.2-48.7 72.1-74.7-53.8-42.9-119.8-73.5-190-70.3-146.6-4.9-281.3 123.5-283.7 270.2-9.4 119.9 69.4 237.4 180.6 279.8 110.8 42.7 252.9 13.6 323.7-86 46.7-62.9 56.8-143.9 51.3-220-90.7-.7-181.3-.6-271.9-.3z" ] [] ]
true
-- GENERATE BY ./scripts/generate.ts -- DO NOT EDIT IT MANUALLY module Ant.Icons.Svg.GooglePlusOutlined exposing (view, viewWithAttributes) import Html exposing (Html) import Svg exposing (..) import Svg.Attributes exposing (..) view : Html msg view = svg [ viewBox "64 64 896 896" ] [ Svg.path [ d "M879.5 470.4c-.3-27-.4-54.2-.5-81.3h-80.8c-.3 27-.5 54.1-.7 81.3-27.2.1-54.2.3-81.2.6v80.9c27 .3 54.2.5 PI:IP_ADDRESS:172.16.58.3END_PI 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-81.3 27.2-.3 54.2-.4 81.2-.7v-80.9c-26.9-.2-54.1-.2-81.1-.5zm-530 .4c-.1 32.3 0 64.7.1 97 54.2 1.8 108.5 1 162.7 1.8-23.9 120.3-187.4 159.3-273.9 80.7-89-68.9-84.8-220 7.7-284 64.7-51.6 156.6-38.9 221.3 5.8 25.4-23.5 49.2-48.7 72.1-74.7-53.8-42.9-119.8-73.5-190-70.3-146.6-4.9-281.3 123.5-283.7 270.2-9.4 119.9 69.4 237.4 180.6 279.8 110.8 42.7 252.9 13.6 323.7-86 46.7-62.9 56.8-143.9 51.3-220-90.7-.7-181.3-.6-271.9-.3z" ] [] ] viewWithAttributes : List (Html.Attribute msg) -> Html msg viewWithAttributes attributes = svg ([ viewBox "64 64 896 896" ] ++ attributes) [ Svg.path [ d "M879.5 470.4c-.3-27-.4-54.2-.5-81.3h-80.8c-.3 27-.5 54.1-.7 81.3-27.2.1-54.2.3-81.2.6v80.9c27 .3 54.2.5 PI:IP_ADDRESS:172.16.58.3END_PI 27 .3 54.1.5 81.1h80.9c.1-27 .3-54.1.5-81.3 27.2-.3 54.2-.4 81.2-.7v-80.9c-26.9-.2-54.1-.2-81.1-.5zm-530 .4c-.1 32.3 0 64.7.1 97 54.2 1.8 108.5 1 162.7 1.8-23.9 120.3-187.4 159.3-273.9 80.7-89-68.9-84.8-220 7.7-284 64.7-51.6 156.6-38.9 221.3 5.8 25.4-23.5 49.2-48.7 72.1-74.7-53.8-42.9-119.8-73.5-190-70.3-146.6-4.9-281.3 123.5-283.7 270.2-9.4 119.9 69.4 237.4 180.6 279.8 110.8 42.7 252.9 13.6 323.7-86 46.7-62.9 56.8-143.9 51.3-220-90.7-.7-181.3-.6-271.9-.3z" ] [] ]
elm
[ { "context": "RootStyles resetCss =\n case resetCss of\n EricMeyer ->\n [ margin zero\n , p", "end": 2252, "score": 0.6911660433, "start": 2248, "tag": "NAME", "value": "Eric" }, { "context": "yles resetCss =\n case resetCss of\n EricMeyer ->\n [ margin zero\n , padd", "end": 2255, "score": 0.6090760231, "start": 2253, "tag": "NAME", "value": "ey" }, { "context": "Css of\n EricMeyer ->\n { name = \"Eric Meyer’s Reset CSS\"\n , version = \"v2.0\"\n ", "end": 4650, "score": 0.8800991178, "start": 4640, "tag": "NAME", "value": "Eric Meyer" }, { "context": " updatedAt = \"2011-01-26\"\n , author = \"Eric Meyer\"\n , license = \"none (public domain)\"\n ", "end": 4768, "score": 0.9998635054, "start": 4758, "tag": "NAME", "value": "Eric Meyer" }, { "context": " updatedAt = \"2010-09-17\"\n , author = \"Richard Clark\"\n , license = \"Free of charge under a ", "end": 5085, "score": 0.9999036193, "start": 5072, "tag": "NAME", "value": "Richard Clark" }, { "context": " License\"\n , url = \"https://github.com/richclark/HTML5resetCSS\"\n }\n\n Destyle ->\n", "end": 5230, "score": 0.9565716386, "start": 5221, "tag": "USERNAME", "value": "richclark" }, { "context": " updatedAt = \"2021-09-06\"\n , author = \"Nicolas Cusan\"\n , license = \"MIT\"\n , url ", "end": 5424, "score": 0.9998961091, "start": 5411, "tag": "NAME", "value": "Nicolas Cusan" }, { "context": "e = \"MIT\"\n , url = \"https://github.com/nicolas-cusan/destyle.css\"\n }\n\n Normalize ->\n", "end": 5509, "score": 0.989074409, "start": 5496, "tag": "USERNAME", "value": "nicolas-cusan" }, { "context": " updatedAt = \"2018-11-05\"\n , author = \"Nicolas Gallagher\"\n , license = \"MIT\"\n , url ", "end": 5709, "score": 0.9999043345, "start": 5692, "tag": "NAME", "value": "Nicolas Gallagher" }, { "context": "e = \"MIT\"\n , url = \"https://github.com/necolas/normalize.css/\"\n }\n\n Ress ->\n ", "end": 5788, "score": 0.9898750186, "start": 5781, "tag": "USERNAME", "value": "necolas" }, { "context": " updatedAt = \"2021-04-21\"\n , author = \"Filipe Linhares\"\n , license = \"MIT\"\n , url ", "end": 5975, "score": 0.9999033809, "start": 5960, "tag": "NAME", "value": "Filipe Linhares" }, { "context": "e = \"MIT\"\n , url = \"https://github.com/filipelinhares/ress\"\n }\n\n Sanitize ->\n ", "end": 6061, "score": 0.9918573499, "start": 6047, "tag": "USERNAME", "value": "filipelinhares" }, { "context": " updatedAt = \"2021-09-14\"\n , author = \"CSS Tools\"\n , license = \"CC0 1.0 Universal\"\n ", "end": 6245, "score": 0.9481727481, "start": 6236, "tag": "USERNAME", "value": "CSS Tools" }, { "context": "niversal\"\n , url = \"https://github.com/csstools/sanitize.css\"\n }\n\n TheNewCssRes", "end": 6339, "score": 0.9991129041, "start": 6331, "tag": "USERNAME", "value": "csstools" }, { "context": " updatedAt = \"2021-07-23\"\n , author = \"Elad Shechter\"\n , license = \"MIT\"\n , url ", "end": 6545, "score": 0.9999028444, "start": 6532, "tag": "NAME", "value": "Elad Shechter" }, { "context": "e = \"MIT\"\n , url = \"https://github.com/elad2412/the-new-css-reset\"\n }\n\n ElmRese", "end": 6625, "score": 0.9991957545, "start": 6617, "tag": "USERNAME", "value": "elad2412" }, { "context": " updatedAt = \"2021-10-09\"\n , author = \"Yoshitaka Totsuka\"\n , license = \"MIT\"\n , url ", "end": 6860, "score": 0.9999018312, "start": 6843, "tag": "NAME", "value": "Yoshitaka Totsuka" }, { "context": "e = \"MIT\"\n , url = \"https://github.com/y047aka/elm-reset-css\"\n }\n\n ElmResetCss", "end": 6939, "score": 0.9994682074, "start": 6932, "tag": "USERNAME", "value": "y047aka" }, { "context": " updatedAt = \"2021-10-09\"\n , author = \"Yoshitaka Totsuka\"\n , license = \"MIT\"\n , url ", "end": 7169, "score": 0.9999023676, "start": 7152, "tag": "NAME", "value": "Yoshitaka Totsuka" }, { "context": "e = \"MIT\"\n , url = \"https://github.com/y047aka/elm-reset-css\"\n }\n\n\nall : List ResetCs", "end": 7248, "score": 0.9995204806, "start": 7241, "tag": "USERNAME", "value": "y047aka" } ]
docs/src/Data/ResetCss.elm
y047aka/elm-reset-css
2
module Data.ResetCss exposing (ResetCss(..), all, fromString, toLibrary, toRootStyles, toSnippet, toString) import Css exposing (..) import Css.Global exposing (Snippet) import Css.Reset exposing (..) import Css.Reset.ElmResetCss as ERC exposing (ResetMode(..)) type ResetCss = EricMeyer | Html5Doctor | Destyle | Normalize | Ress | Sanitize | TheNewCssReset | ElmResetCss ResetMode type alias Library = { author : String , license : String , name : String , updatedAt : String , url : String , version : String } fromString : String -> Maybe ResetCss fromString str = case str of "EricMeyer" -> Just EricMeyer "Html5Doctor" -> Just Html5Doctor "Destyle" -> Just Destyle "Normalize" -> Just Normalize "Ress" -> Just Ress "Sanitize" -> Just Sanitize "TheNewCssReset" -> Just TheNewCssReset "ElmHardReset" -> Just (ElmResetCss ERC.HardReset) "ElmNormalize" -> Just (ElmResetCss ERC.Normalize) _ -> Nothing toString : ResetCss -> String toString resetCss = case resetCss of EricMeyer -> "EricMeyer" Html5Doctor -> "Html5Doctor" Destyle -> "Destyle" Normalize -> "Normalize" Ress -> "Ress" Sanitize -> "Sanitize" TheNewCssReset -> "TheNewCssReset" ElmResetCss ERC.HardReset -> "ElmHardReset" ElmResetCss ERC.Normalize -> "ElmNormalize" toSnippet : ResetCss -> List Snippet toSnippet resetCss = case resetCss of EricMeyer -> ericMeyer Html5Doctor -> html5Doctor Destyle -> destyle Normalize -> normalize Ress -> ress Sanitize -> sanitize TheNewCssReset -> theNewCssReset ElmResetCss opiton -> ERC.snippets opiton toRootStyles : ResetCss -> List Style toRootStyles resetCss = case resetCss of EricMeyer -> [ margin zero , padding zero , border zero , fontSize (pct 100) , property "font" "inherit" , verticalAlign baseline , lineHeight (int 1) ] Html5Doctor -> [ margin zero , padding zero , border zero , outline zero , fontSize (pct 100) , verticalAlign baseline , property "background" "transparent" , lineHeight (int 1) ] Destyle -> [ lineHeight (num 1.15) , property "-webkit-text-size-adjust" "100%" , property "-webkit-tap-highlight-color" "transparent" ] Normalize -> [ lineHeight (num 1.15) , property "-webkit-text-size-adjust" "100%" ] Ress -> [ boxSizing borderBox , property "-webkit-text-size-adjust" "100%" -- Prevent adjustments of font size after orientation changes in iOS , property "word-break" "normal" , property "-moz-tab-size" "4" , property "tab-size" "4" ] Sanitize -> [ cursor default , lineHeight (num 1.5) , property "overflow-wrap" "break-word" , property "-moz-tab-size" "4" , property "tab-size" "4" , property "-webkit-tap-highlight-color" "transparent" , property "-webkit-text-size-adjust" "100%" ] TheNewCssReset -> [ Css.all unset , property "display" "revert" ] ElmResetCss ERC.HardReset -> [ lineHeight (num 1.15) , property "-webkit-text-size-adjust" "100%" , property "-webkit-tap-highlight-color" "transparent" ] ElmResetCss ERC.Normalize -> [ cursor default -- 1 , lineHeight (num 1.5) -- 2 , property "overflow-wrap" "break-word" -- 3 , property "-moz-tab-size" "4" -- 4 , property "tab-size" "4" -- 4 , property "-webkit-tap-highlight-color" "transparent" -- 5 , property "-webkit-text-size-adjust" "100%" -- 6 ] toLibrary : ResetCss -> Library toLibrary resetCss = case resetCss of EricMeyer -> { name = "Eric Meyer’s Reset CSS" , version = "v2.0" , updatedAt = "2011-01-26" , author = "Eric Meyer" , license = "none (public domain)" , url = "https://meyerweb.com/eric/tools/css/reset/" } Html5Doctor -> { name = "html5doctor.com Reset Stylesheet" , version = "v1.6.1" , updatedAt = "2010-09-17" , author = "Richard Clark" , license = "Free of charge under a CC0 Public Domain Dedication and MIT License" , url = "https://github.com/richclark/HTML5resetCSS" } Destyle -> { name = "destyle.css" , version = "v3.0.0" , updatedAt = "2021-09-06" , author = "Nicolas Cusan" , license = "MIT" , url = "https://github.com/nicolas-cusan/destyle.css" } Normalize -> { name = "Normalize.css" , version = "v8.0.1" , updatedAt = "2018-11-05" , author = "Nicolas Gallagher" , license = "MIT" , url = "https://github.com/necolas/normalize.css/" } Ress -> { name = "ress" , version = "v4.0.0" , updatedAt = "2021-04-21" , author = "Filipe Linhares" , license = "MIT" , url = "https://github.com/filipelinhares/ress" } Sanitize -> { name = "sanitize.css" , version = "v13.0.0" , updatedAt = "2021-09-14" , author = "CSS Tools" , license = "CC0 1.0 Universal" , url = "https://github.com/csstools/sanitize.css" } TheNewCssReset -> { name = "The New CSS Reset" , version = "v1.2.0" , updatedAt = "2021-07-23" , author = "Elad Shechter" , license = "MIT" , url = "https://github.com/elad2412/the-new-css-reset" } ElmResetCss ERC.HardReset -> { name = "elm-reset-css (hard reset)" , version = "v0.0.0" , updatedAt = "2021-10-09" , author = "Yoshitaka Totsuka" , license = "MIT" , url = "https://github.com/y047aka/elm-reset-css" } ElmResetCss ERC.Normalize -> { name = "elm-reset-css (normalize)" , version = "v0.0.0" , updatedAt = "2021-10-09" , author = "Yoshitaka Totsuka" , license = "MIT" , url = "https://github.com/y047aka/elm-reset-css" } all : List ResetCss all = [ EricMeyer , Html5Doctor , Destyle , Normalize , Ress , Sanitize , TheNewCssReset , ElmResetCss ERC.HardReset , ElmResetCss ERC.Normalize ]
42446
module Data.ResetCss exposing (ResetCss(..), all, fromString, toLibrary, toRootStyles, toSnippet, toString) import Css exposing (..) import Css.Global exposing (Snippet) import Css.Reset exposing (..) import Css.Reset.ElmResetCss as ERC exposing (ResetMode(..)) type ResetCss = EricMeyer | Html5Doctor | Destyle | Normalize | Ress | Sanitize | TheNewCssReset | ElmResetCss ResetMode type alias Library = { author : String , license : String , name : String , updatedAt : String , url : String , version : String } fromString : String -> Maybe ResetCss fromString str = case str of "EricMeyer" -> Just EricMeyer "Html5Doctor" -> Just Html5Doctor "Destyle" -> Just Destyle "Normalize" -> Just Normalize "Ress" -> Just Ress "Sanitize" -> Just Sanitize "TheNewCssReset" -> Just TheNewCssReset "ElmHardReset" -> Just (ElmResetCss ERC.HardReset) "ElmNormalize" -> Just (ElmResetCss ERC.Normalize) _ -> Nothing toString : ResetCss -> String toString resetCss = case resetCss of EricMeyer -> "EricMeyer" Html5Doctor -> "Html5Doctor" Destyle -> "Destyle" Normalize -> "Normalize" Ress -> "Ress" Sanitize -> "Sanitize" TheNewCssReset -> "TheNewCssReset" ElmResetCss ERC.HardReset -> "ElmHardReset" ElmResetCss ERC.Normalize -> "ElmNormalize" toSnippet : ResetCss -> List Snippet toSnippet resetCss = case resetCss of EricMeyer -> ericMeyer Html5Doctor -> html5Doctor Destyle -> destyle Normalize -> normalize Ress -> ress Sanitize -> sanitize TheNewCssReset -> theNewCssReset ElmResetCss opiton -> ERC.snippets opiton toRootStyles : ResetCss -> List Style toRootStyles resetCss = case resetCss of <NAME>M<NAME>er -> [ margin zero , padding zero , border zero , fontSize (pct 100) , property "font" "inherit" , verticalAlign baseline , lineHeight (int 1) ] Html5Doctor -> [ margin zero , padding zero , border zero , outline zero , fontSize (pct 100) , verticalAlign baseline , property "background" "transparent" , lineHeight (int 1) ] Destyle -> [ lineHeight (num 1.15) , property "-webkit-text-size-adjust" "100%" , property "-webkit-tap-highlight-color" "transparent" ] Normalize -> [ lineHeight (num 1.15) , property "-webkit-text-size-adjust" "100%" ] Ress -> [ boxSizing borderBox , property "-webkit-text-size-adjust" "100%" -- Prevent adjustments of font size after orientation changes in iOS , property "word-break" "normal" , property "-moz-tab-size" "4" , property "tab-size" "4" ] Sanitize -> [ cursor default , lineHeight (num 1.5) , property "overflow-wrap" "break-word" , property "-moz-tab-size" "4" , property "tab-size" "4" , property "-webkit-tap-highlight-color" "transparent" , property "-webkit-text-size-adjust" "100%" ] TheNewCssReset -> [ Css.all unset , property "display" "revert" ] ElmResetCss ERC.HardReset -> [ lineHeight (num 1.15) , property "-webkit-text-size-adjust" "100%" , property "-webkit-tap-highlight-color" "transparent" ] ElmResetCss ERC.Normalize -> [ cursor default -- 1 , lineHeight (num 1.5) -- 2 , property "overflow-wrap" "break-word" -- 3 , property "-moz-tab-size" "4" -- 4 , property "tab-size" "4" -- 4 , property "-webkit-tap-highlight-color" "transparent" -- 5 , property "-webkit-text-size-adjust" "100%" -- 6 ] toLibrary : ResetCss -> Library toLibrary resetCss = case resetCss of EricMeyer -> { name = "<NAME>’s Reset CSS" , version = "v2.0" , updatedAt = "2011-01-26" , author = "<NAME>" , license = "none (public domain)" , url = "https://meyerweb.com/eric/tools/css/reset/" } Html5Doctor -> { name = "html5doctor.com Reset Stylesheet" , version = "v1.6.1" , updatedAt = "2010-09-17" , author = "<NAME>" , license = "Free of charge under a CC0 Public Domain Dedication and MIT License" , url = "https://github.com/richclark/HTML5resetCSS" } Destyle -> { name = "destyle.css" , version = "v3.0.0" , updatedAt = "2021-09-06" , author = "<NAME>" , license = "MIT" , url = "https://github.com/nicolas-cusan/destyle.css" } Normalize -> { name = "Normalize.css" , version = "v8.0.1" , updatedAt = "2018-11-05" , author = "<NAME>" , license = "MIT" , url = "https://github.com/necolas/normalize.css/" } Ress -> { name = "ress" , version = "v4.0.0" , updatedAt = "2021-04-21" , author = "<NAME>" , license = "MIT" , url = "https://github.com/filipelinhares/ress" } Sanitize -> { name = "sanitize.css" , version = "v13.0.0" , updatedAt = "2021-09-14" , author = "CSS Tools" , license = "CC0 1.0 Universal" , url = "https://github.com/csstools/sanitize.css" } TheNewCssReset -> { name = "The New CSS Reset" , version = "v1.2.0" , updatedAt = "2021-07-23" , author = "<NAME>" , license = "MIT" , url = "https://github.com/elad2412/the-new-css-reset" } ElmResetCss ERC.HardReset -> { name = "elm-reset-css (hard reset)" , version = "v0.0.0" , updatedAt = "2021-10-09" , author = "<NAME>" , license = "MIT" , url = "https://github.com/y047aka/elm-reset-css" } ElmResetCss ERC.Normalize -> { name = "elm-reset-css (normalize)" , version = "v0.0.0" , updatedAt = "2021-10-09" , author = "<NAME>" , license = "MIT" , url = "https://github.com/y047aka/elm-reset-css" } all : List ResetCss all = [ EricMeyer , Html5Doctor , Destyle , Normalize , Ress , Sanitize , TheNewCssReset , ElmResetCss ERC.HardReset , ElmResetCss ERC.Normalize ]
true
module Data.ResetCss exposing (ResetCss(..), all, fromString, toLibrary, toRootStyles, toSnippet, toString) import Css exposing (..) import Css.Global exposing (Snippet) import Css.Reset exposing (..) import Css.Reset.ElmResetCss as ERC exposing (ResetMode(..)) type ResetCss = EricMeyer | Html5Doctor | Destyle | Normalize | Ress | Sanitize | TheNewCssReset | ElmResetCss ResetMode type alias Library = { author : String , license : String , name : String , updatedAt : String , url : String , version : String } fromString : String -> Maybe ResetCss fromString str = case str of "EricMeyer" -> Just EricMeyer "Html5Doctor" -> Just Html5Doctor "Destyle" -> Just Destyle "Normalize" -> Just Normalize "Ress" -> Just Ress "Sanitize" -> Just Sanitize "TheNewCssReset" -> Just TheNewCssReset "ElmHardReset" -> Just (ElmResetCss ERC.HardReset) "ElmNormalize" -> Just (ElmResetCss ERC.Normalize) _ -> Nothing toString : ResetCss -> String toString resetCss = case resetCss of EricMeyer -> "EricMeyer" Html5Doctor -> "Html5Doctor" Destyle -> "Destyle" Normalize -> "Normalize" Ress -> "Ress" Sanitize -> "Sanitize" TheNewCssReset -> "TheNewCssReset" ElmResetCss ERC.HardReset -> "ElmHardReset" ElmResetCss ERC.Normalize -> "ElmNormalize" toSnippet : ResetCss -> List Snippet toSnippet resetCss = case resetCss of EricMeyer -> ericMeyer Html5Doctor -> html5Doctor Destyle -> destyle Normalize -> normalize Ress -> ress Sanitize -> sanitize TheNewCssReset -> theNewCssReset ElmResetCss opiton -> ERC.snippets opiton toRootStyles : ResetCss -> List Style toRootStyles resetCss = case resetCss of PI:NAME:<NAME>END_PIMPI:NAME:<NAME>END_PIer -> [ margin zero , padding zero , border zero , fontSize (pct 100) , property "font" "inherit" , verticalAlign baseline , lineHeight (int 1) ] Html5Doctor -> [ margin zero , padding zero , border zero , outline zero , fontSize (pct 100) , verticalAlign baseline , property "background" "transparent" , lineHeight (int 1) ] Destyle -> [ lineHeight (num 1.15) , property "-webkit-text-size-adjust" "100%" , property "-webkit-tap-highlight-color" "transparent" ] Normalize -> [ lineHeight (num 1.15) , property "-webkit-text-size-adjust" "100%" ] Ress -> [ boxSizing borderBox , property "-webkit-text-size-adjust" "100%" -- Prevent adjustments of font size after orientation changes in iOS , property "word-break" "normal" , property "-moz-tab-size" "4" , property "tab-size" "4" ] Sanitize -> [ cursor default , lineHeight (num 1.5) , property "overflow-wrap" "break-word" , property "-moz-tab-size" "4" , property "tab-size" "4" , property "-webkit-tap-highlight-color" "transparent" , property "-webkit-text-size-adjust" "100%" ] TheNewCssReset -> [ Css.all unset , property "display" "revert" ] ElmResetCss ERC.HardReset -> [ lineHeight (num 1.15) , property "-webkit-text-size-adjust" "100%" , property "-webkit-tap-highlight-color" "transparent" ] ElmResetCss ERC.Normalize -> [ cursor default -- 1 , lineHeight (num 1.5) -- 2 , property "overflow-wrap" "break-word" -- 3 , property "-moz-tab-size" "4" -- 4 , property "tab-size" "4" -- 4 , property "-webkit-tap-highlight-color" "transparent" -- 5 , property "-webkit-text-size-adjust" "100%" -- 6 ] toLibrary : ResetCss -> Library toLibrary resetCss = case resetCss of EricMeyer -> { name = "PI:NAME:<NAME>END_PI’s Reset CSS" , version = "v2.0" , updatedAt = "2011-01-26" , author = "PI:NAME:<NAME>END_PI" , license = "none (public domain)" , url = "https://meyerweb.com/eric/tools/css/reset/" } Html5Doctor -> { name = "html5doctor.com Reset Stylesheet" , version = "v1.6.1" , updatedAt = "2010-09-17" , author = "PI:NAME:<NAME>END_PI" , license = "Free of charge under a CC0 Public Domain Dedication and MIT License" , url = "https://github.com/richclark/HTML5resetCSS" } Destyle -> { name = "destyle.css" , version = "v3.0.0" , updatedAt = "2021-09-06" , author = "PI:NAME:<NAME>END_PI" , license = "MIT" , url = "https://github.com/nicolas-cusan/destyle.css" } Normalize -> { name = "Normalize.css" , version = "v8.0.1" , updatedAt = "2018-11-05" , author = "PI:NAME:<NAME>END_PI" , license = "MIT" , url = "https://github.com/necolas/normalize.css/" } Ress -> { name = "ress" , version = "v4.0.0" , updatedAt = "2021-04-21" , author = "PI:NAME:<NAME>END_PI" , license = "MIT" , url = "https://github.com/filipelinhares/ress" } Sanitize -> { name = "sanitize.css" , version = "v13.0.0" , updatedAt = "2021-09-14" , author = "CSS Tools" , license = "CC0 1.0 Universal" , url = "https://github.com/csstools/sanitize.css" } TheNewCssReset -> { name = "The New CSS Reset" , version = "v1.2.0" , updatedAt = "2021-07-23" , author = "PI:NAME:<NAME>END_PI" , license = "MIT" , url = "https://github.com/elad2412/the-new-css-reset" } ElmResetCss ERC.HardReset -> { name = "elm-reset-css (hard reset)" , version = "v0.0.0" , updatedAt = "2021-10-09" , author = "PI:NAME:<NAME>END_PI" , license = "MIT" , url = "https://github.com/y047aka/elm-reset-css" } ElmResetCss ERC.Normalize -> { name = "elm-reset-css (normalize)" , version = "v0.0.0" , updatedAt = "2021-10-09" , author = "PI:NAME:<NAME>END_PI" , license = "MIT" , url = "https://github.com/y047aka/elm-reset-css" } all : List ResetCss all = [ EricMeyer , Html5Doctor , Destyle , Normalize , Ress , Sanitize , TheNewCssReset , ElmResetCss ERC.HardReset , ElmResetCss ERC.Normalize ]
elm
[ { "context": "cketId )\n , ( \"user\", Encode.string userName )\n ]\n )\n ]\n ", "end": 6589, "score": 0.9933509231, "start": 6581, "tag": "USERNAME", "value": "userName" }, { "context": "socket )\n , ( \"user\", Encode.string userName )\n ]\n )\n ]\n ", "end": 7990, "score": 0.9683123827, "start": 7982, "tag": "USERNAME", "value": "userName" }, { "context": " ]\n ]\n [ text \"Dolphin\" ]\n\n -- CONTROLS\n , div\n ", "end": 26592, "score": 0.9798388481, "start": 26585, "tag": "NAME", "value": "Dolphin" } ]
src/Main.elm
andrewgryan/games
0
module Main exposing (main) import Browser import Browser.Navigation as Navigation exposing (Key) import Container import Dict exposing (Dict) import Header import Helper exposing (classes, ifIsEnter) import Heroicons exposing (menu, pencil) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (on, onClick, onInput) import Http import Json.Decode as D exposing (Decoder) import Json.Encode as Encode import LeaderBoard exposing (LeaderBoard) import Outgoing import Player exposing (Move(..), Player(..)) import Ports exposing (messageReceiver, sendMessage) import Quiz exposing (Answer, Question, Quiz) import Review import Route exposing (Route(..)) import Score exposing (Score) import Set exposing (Set) import Socket.ID exposing (ID) import Url exposing (Url) import User exposing (User(..)) -- INIT type alias Flags = { user : Maybe User , quiz : Maybe Quiz , player : Maybe Player , leaderBoard : Maybe LeaderBoard } flagsDecoder : Decoder Flags flagsDecoder = D.map4 Flags (D.field "user" (D.maybe User.decoder)) (D.field "quiz" (D.maybe Quiz.decoder)) (D.field "player" (D.maybe Player.decoder)) (D.field "leaderBoard" (D.maybe LeaderBoard.decoder)) init : D.Value -> Url -> Key -> ( Model, Cmd msg ) init value url key = let model = { key = key , errorMessage = Nothing , user = User.anonymous , userDraft = "" -- ADMIN , adminText = "" -- ROUTING , route = Route.fromUrl url -- QUIZ , leaderBoard = LeaderBoard.empty , quiz = Quiz.second , player = Player.thinking 0 -- INTER-APP COMMS , socket = Nothing , sockets = Dict.empty , users = Dict.empty } in case D.decodeValue flagsDecoder value of Ok flags -> ( { model | user = Maybe.withDefault model.user flags.user , quiz = Maybe.withDefault model.quiz flags.quiz , player = Maybe.withDefault model.player flags.player , leaderBoard = Maybe.withDefault model.leaderBoard flags.leaderBoard } , Cmd.none ) Err _ -> ( model, Cmd.none ) -- MODEL type alias Model = { user : User , userDraft : String , errorMessage : Maybe D.Error , quiz : Quiz , player : Player , leaderBoard : LeaderBoard -- ADMIN , adminText : String -- ROUTING , route : Route -- Navigation , key : Navigation.Key -- Inter-app communication , socket : Maybe String , sockets : Dict String Player , users : Dict String String } -- MSG type Msg = -- USER UserDraftChanged String -- QUIZ | GotUsername | StartQuiz | FinishQuiz | SelectAnswer Answer | LockAnswerIn -- PORT | Recv Encode.Value -- NAVIGATION | LinkClicked Browser.UrlRequest | UrlChanged Url.Url -- ADMIN | ClearScoreboard | GotText (Result Http.Error String) type PortMsg = LeaderBoardMsg LeaderBoard | ExitMsg String | EnterMsg String | JoinMsg Channel Socket.ID.ID | StartMsg Channel Socket.ID.ID | UserMsg Channel String String | PlayerMsg Channel Player String type Channel = Public | Private portDecoder : D.Decoder PortMsg portDecoder = D.oneOf [ D.map LeaderBoardMsg LeaderBoard.decoder , D.field "type" D.string |> D.andThen payloadDecoder ] payloadDecoder : String -> D.Decoder PortMsg payloadDecoder label = case label of "enter" -> D.map EnterMsg (D.field "payload" (D.field "id" D.string)) "join" -> D.map2 JoinMsg (D.field "channel" channelDecoder) (D.field "payload" (D.map Socket.ID.ID (D.field "id" D.string))) "start" -> D.map2 StartMsg (D.field "channel" channelDecoder) (D.field "payload" (D.map Socket.ID.ID (D.field "id" D.string))) "user" -> D.map3 UserMsg (D.field "channel" channelDecoder) (D.field "payload" (D.field "user" D.string)) (D.field "payload" (D.field "id" D.string)) "player" -> D.map3 PlayerMsg (D.field "channel" channelDecoder) (D.field "payload" (D.field "player" Player.decoder)) (D.field "payload" (D.field "id" D.string)) "exit" -> D.map ExitMsg (D.field "payload" (D.field "id" D.string)) _ -> D.fail "Unrecognised msg type" channelDecoder : D.Decoder Channel channelDecoder = D.string |> D.andThen (\str -> case str of "public" -> D.succeed Public "private" -> D.succeed Private _ -> D.fail "Unknown channel type" ) joinRoomPayload : Int -> Encode.Value joinRoomPayload n = Encode.object [ ( "room", Encode.int n ) ] encodeSocket : Maybe String -> Encode.Value encodeSocket maybeSocket = case maybeSocket of Just str -> Encode.string str Nothing -> Encode.null sessionStorage : String -> String -> Cmd Msg sessionStorage key value = Encode.object [ ( "type", Encode.string "sessionStorage" ) , ( "payload" , Encode.object [ ( "key", Encode.string key ) , ( "value", Encode.string value ) ] ) ] |> Ports.sendMessage -- BROADCAST type alias Socket = Maybe String broadcastPublicJoin : String -> Cmd Msg broadcastPublicJoin str = Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "join" ) , ( "payload" , Encode.object [ ( "id", Encode.string str ) ] ) ] |> Ports.sendMessage broadcastPublicUser : Socket -> String -> Cmd Msg broadcastPublicUser socketId userName = Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "user" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socketId ) , ( "user", Encode.string userName ) ] ) ] |> Ports.sendMessage broadcastPublicPlayer : Socket -> Player -> Cmd Msg broadcastPublicPlayer socketId player = Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "player" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socketId ) , ( "player", Player.encode player ) ] ) ] |> Ports.sendMessage broadcastPrivatePlayer : String -> Socket -> Player -> Cmd Msg broadcastPrivatePlayer toSocketID socket player = Encode.object [ ( "channel", Encode.string "private" ) , ( "to", Encode.string toSocketID ) , ( "type", Encode.string "player" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socket ) , ( "player", Player.encode player ) ] ) ] |> Ports.sendMessage broadcastPrivateUser : String -> Socket -> String -> Cmd Msg broadcastPrivateUser toSocketID socket userName = Encode.object [ ( "channel", Encode.string "private" ) , ( "to", Encode.string toSocketID ) , ( "type", Encode.string "user" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socket ) , ( "user", Encode.string userName ) ] ) ] |> Ports.sendMessage -- UPDATE update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of -- ADMIN ClearScoreboard -> let cmd = Http.get { url = "/clear" , expect = Http.expectString GotText } in ( model, cmd ) GotText result -> case result of Ok str -> ( { model | adminText = str }, Cmd.none ) Err _ -> ( model, Cmd.none ) -- NAVIGATION LinkClicked urlRequest -> case urlRequest of Browser.Internal url -> ( model , Navigation.pushUrl model.key (Url.toString url) ) Browser.External href -> ( model, Navigation.load href ) UrlChanged url -> let route = Route.fromUrl url in ( { model | route = route }, Cmd.none ) UserDraftChanged str -> ( { model | userDraft = str }, Cmd.none ) -- QUIZ GotUsername -> let user = User.loggedIn model.userDraft cmd = Cmd.batch [ -- BROADCAST broadcastPublicUser model.socket model.userDraft -- SESSION STORAGE , sessionStorage "user" (User.toString user) -- GO TO WAITING ROOM , Navigation.pushUrl model.key "/waiting" ] in ( { model | user = user } , cmd ) StartQuiz -> let cmd = Cmd.batch [ -- GO TO QUIZ Navigation.pushUrl model.key "/quiz" -- BROADCAST TO PLAYERS , Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "start" ) , ( "payload" , Encode.object [ ( "id", encodeSocket model.socket ) ] ) ] |> Ports.sendMessage ] in ( model, cmd ) FinishQuiz -> let score = Score.fromInt model.user (Quiz.tally model.quiz) cmd = Cmd.batch [ Outgoing.save score |> Outgoing.encode |> sendMessage -- GO TO SCOREBOARD , Navigation.pushUrl model.key "/scoreboard" ] in ( { model | leaderBoard = LeaderBoard.empty } , cmd ) SelectAnswer answer -> let quiz = Quiz.selectAnswer answer model.quiz cmd = sessionStorage "quiz" (Quiz.toString quiz) in ( { model | quiz = quiz }, cmd ) LockAnswerIn -> let newPlayer = Player.done (model.quiz |> Quiz.getQuestionIndex ) cmd = broadcastPublicPlayer model.socket newPlayer in case Player.chooseMove newPlayer (Dict.values model.sockets) of Forward -> let quiz = Quiz.nextQuestion model.quiz questionIndex = Quiz.getQuestionIndex quiz player = Thinking questionIndex cmds = Cmd.batch [ cmd , sessionStorage "quiz" (Quiz.toString quiz) , sessionStorage "player" (Player.toString player) ] in ( { model | quiz = quiz , player = player } , cmds ) Wait -> -- WAIT FOR OTHER PLAYERS let cmds = Cmd.batch [ cmd , sessionStorage "player" (Player.toString newPlayer) ] in ( { model | player = newPlayer } , cmds ) -- PORT Recv value -> case D.decodeValue portDecoder value of Ok portMsg -> case portMsg of -- LEADERBOARD LeaderBoardMsg leaderBoard -> let cmd = sessionStorage "leaderBoard" (LeaderBoard.toString leaderBoard) in ( { model | leaderBoard = leaderBoard }, cmd ) EnterMsg str -> let cmd = broadcastPublicJoin str socket = Just str in case model.user of Anonymous -> ( { model | socket = socket }, cmd ) LoggedIn userName -> ( { model | socket = socket } , Cmd.batch [ cmd , broadcastPublicUser socket userName ] ) JoinMsg channel socketID -> let str = Socket.ID.toString socketID in ( { model | sockets = Dict.insert str (Player.thinking 0) model.sockets } , Cmd.none ) StartMsg channel socketID -> let cmd = Cmd.batch [ -- GO TO QUIZ Navigation.pushUrl model.key "/quiz" ] in ( model, cmd ) UserMsg channel str id -> let cmd = case channel of Public -> case model.user of Anonymous -> Cmd.none LoggedIn name -> Cmd.batch [ broadcastPrivateUser id model.socket name , broadcastPrivatePlayer id model.socket model.player ] Private -> Cmd.none in ( { model | users = Dict.insert id str model.users } , cmd ) PlayerMsg channel player socketID -> let cmd = case channel of Public -> broadcastPrivatePlayer socketID model.socket model.player Private -> Cmd.none sockets = Dict.insert socketID player model.sockets in case Player.chooseMove model.player (Dict.values sockets) of Forward -> -- ALL DONE let quiz = Quiz.nextQuestion model.quiz questionIndex = Quiz.getQuestionIndex quiz nextPlayer = Thinking questionIndex cmds = Cmd.batch [ cmd , sessionStorage "quiz" (Quiz.toString quiz) , sessionStorage "player" (Player.toString nextPlayer) ] in ( { model | sockets = sockets , quiz = quiz , player = nextPlayer } , cmds ) Wait -> -- WAIT FOR EVERYONE ( { model | sockets = sockets } , cmd ) ExitMsg str -> ( { model | sockets = Dict.remove str model.sockets , users = Dict.remove str model.users } , Cmd.none ) Err error -> -- TODO report errors -- let -- _ = -- Debug.log "error" error -- in ( model, Cmd.none ) -- VIEW view : Model -> Browser.Document Msg view model = case model.route of Index -> { body = [ viewIndex model ] , title = "The Quiet Ryan's" } Quiz -> { body = [ viewBody model ] , title = "The Quiet Ryan's" } WaitingRoom -> { body = [ viewWaitingRoom model ] , title = "The Quiet Ryan's" } ScoreBoard -> { body = [ viewScoreBoard model ] , title = "The Quiet Ryan's" } Admin -> { body = [ viewAdmin model.adminText ] , title = "Admin" } viewWaitingRoom : Model -> Html Msg viewWaitingRoom model = let players = Dict.values model.users in case players of [] -> viewWaitingForFriends "Waiting for people to join..." _ -> div [ classes [ "flex" , "flex-col" , "h-screen" , "w-screen" ] ] [ Header.view , div [ classes [ "flex" , "flex-col" , "items-center" , "justify-between" , "flex-grow" ] ] [ viewUser model.user , viewPlayers players ] ] viewPlayers : List String -> Html Msg viewPlayers players = div [ classes [ "flex" , "flex-col" , "flex-grow" , "justify-center" , "items-center" , "space-y-2" , "w-full" ] ] [ h1 [ classes [ "text-2xl" , "font-bold" , "text-teal-600" ] ] [ text "Other players" ] , div [] (List.map (\u -> div [] [ text u ] ) players ) , button [ classes [ "p-4" , "bg-teal-700" , "w-full" , "uppercase" , "font-bold" , "text-white" ] , onClick StartQuiz ] [ text "Everyone's here" ] ] classes : List String -> Attribute Msg classes = class << String.join " " viewAdmin : String -> Html Msg viewAdmin str = div [ class <| String.join " " <| [ "flex" , "flex-col" , "justify-center" , "items-center" , "h-screen" ] ] [ button [ class <| String.join " " <| [ "border-red-600" , "border-2" , "text-red-600" , "p-4" , "mx-2" ] , onClick ClearScoreboard ] [ text "Clear scoreboard" ] , div [] [ text str ] ] viewIndex : Model -> Html Msg viewIndex model = viewStartPage model.userDraft viewBody : Model -> Html Msg viewBody model = let friends = Dict.values model.users |> List.sort in case model.player of Done _ -> viewWaitingForFriends "Waiting for everyone..." Thinking _ -> let remaining = Quiz.getNext model.quiz question = Quiz.getQuestion model.quiz in div [ class "flex" , class "flex-col" , class "h-screen" ] [ -- QUIZ Header.view , div [ class "flex" , class "flex-row" , class "justify-between" ] [ div [] [ viewUser model.user , viewFriends friends ] , viewRemaining remaining ] , div [ class "flex" , class "flex-col" , class "justify-center" , class "flex-grow" , class "space-y-4" ] [ div [ class "flex" , class "justify-center" , class "items-center" ] [ Quiz.viewQuestion SelectAnswer question ] , viewNav model.quiz ] ] viewScoreBoard : Model -> Html Msg viewScoreBoard model = div [] [ Header.view , viewError model.errorMessage , LeaderBoard.view model.leaderBoard , Review.view model.quiz ] viewRooms : (Int -> Msg) -> Html Msg viewRooms toMsg = div [ classes [ "flex flex-col" , "h-screen" ] ] [ -- NAV Header.view -- CONTENT , div [ classes [ "flex-auto" , "p-4" , "flex" , "flex-col" , "space-y-4" ] ] [ div [ classes [ "text-xl" , "py-4" ] ] [ text "Q. Odd one out?" ] -- ANSWERS , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "Giraffe" ] , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "Tiger" ] , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "Banana" ] , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "Dolphin" ] -- CONTROLS , div [ classes [ "flex" , "flex-row" , "justify-end" ] ] [ div [ classes [ "bg-teal-300" , "p-4" , "rounded-full" , "shadow" , "text-gray-700" ] ] [ Heroicons.chevronRight ] ] ] ] viewFriends : List String -> Html Msg viewFriends friends = div [ class "font-light text-sm p-1" ] [ div [ class "inline" ] [ text "Friends online: " ] , div [ class "font-bold" , class "inline" ] [ text (String.join " " friends) ] ] viewStartPage : String -> Html Msg viewStartPage draftName = div [ class "w-screen" , class "h-screen" , class "flex" , class "flex-col" ] [ Header.view , div [ class <| String.join " " <| [ "flex" , "flex-col" , "justify-center" , "items-center" , "flex-grow" , "px-2" , "space-y-4" ] ] [ div [ class "w-full" ] [ label [ class <| String.join " " <| [ "block" , "text-gray-700" , "text-md" , "font-bold" ] ] [ text "Enter name:" ] , input [ type_ "text" , placeholder "Enter text" , onInput UserDraftChanged , on "keydown" (ifIsEnter GotUsername) , value draftName , class <| String.join " " <| [ "shadow" , "appearence-none" , "border" , "bg-gray-200" , "py-4" , "px-4" , "text-xl" , "w-full" ] ] [] ] , if draftName /= "" then button [ onClick GotUsername , class <| String.join " " <| [ "w-full" , "p-4" , "bg-blue-500" , "uppercase" , "text-xl" , "text-white" ] ] [ text "Start Quiz" ] else text "" ] ] primaryButtonStyle : Html.Attribute Msg primaryButtonStyle = class <| String.join " " <| [ "text-white" , "p-4" , "py-6" ] viewNav : Quiz -> Html Msg viewNav quiz = let question = Quiz.getQuestion quiz remaining = Quiz.getNext quiz in div [ class "flex" , class "pb-8" ] [ if Quiz.answered question then case remaining of [] -> finishButton FinishQuiz _ -> lockInButton LockAnswerIn else text "" ] viewRemaining : List Question -> Html Msg viewRemaining remaining = let n = List.length remaining in div [ class "text-sm text-gray-400 px-2" ] [ text (String.fromInt n ++ " " ++ plural n ++ " to go") ] plural : Int -> String plural n = if n > 0 then "questions" else "question" lockInButton : Msg -> Html Msg lockInButton toMsg = button [ class <| String.join " " <| [ "bg-yellow-400" , "flex-grow" , "uppercase" , "px-4" , "py-6" , "mx-2" ] , onClick toMsg ] [ div [ class <| String.join " " <| [ "flex" , "flex-row" , "justify-center" , "items-center" ] ] [ Heroicons.lockOpen , div [ class "pl-2" ] [ text "Lock answer in" ] ] ] viewWaitingForFriends : String -> Html Msg viewWaitingForFriends messageText = div [ class <| String.join " " <| [ "bg-purple-500" , "text-white" , "flex" , "flex-row" , "justify-center" , "items-center" , "h-screen" ] ] [ div [ class <| String.join " " <| [ "flex" , "flex-row" , "justify-center" , "items-center" , "animate-pulse" ] ] [ Heroicons.sparkle , div [ class <| String.join " " <| [ "pl-2" , "uppercase" ] ] [ text messageText ] ] ] finishButton : Msg -> Html Msg finishButton toMsg = button [ primaryButtonStyle , class <| String.join " " <| [ "flex-grow" , "bg-blue-600" , "uppercase" , "mx-2" ] , onClick toMsg ] [ text "Finish quiz" ] viewError : Maybe D.Error -> Html Msg viewError maybeError = case maybeError of Nothing -> text "" Just error -> div [] [ text (D.errorToString error) ] viewUser : User -> Html Msg viewUser user = div [ class "font-light text-sm p-1" ] [ text "Signed in as " , span [ class "font-bold" ] [ text (User.toString user) ] ] -- MAIN main : Program D.Value Model Msg main = Browser.application { init = init , onUrlChange = UrlChanged , onUrlRequest = LinkClicked , update = update , view = view , subscriptions = subscriptions } -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions _ = messageReceiver Recv
19803
module Main exposing (main) import Browser import Browser.Navigation as Navigation exposing (Key) import Container import Dict exposing (Dict) import Header import Helper exposing (classes, ifIsEnter) import Heroicons exposing (menu, pencil) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (on, onClick, onInput) import Http import Json.Decode as D exposing (Decoder) import Json.Encode as Encode import LeaderBoard exposing (LeaderBoard) import Outgoing import Player exposing (Move(..), Player(..)) import Ports exposing (messageReceiver, sendMessage) import Quiz exposing (Answer, Question, Quiz) import Review import Route exposing (Route(..)) import Score exposing (Score) import Set exposing (Set) import Socket.ID exposing (ID) import Url exposing (Url) import User exposing (User(..)) -- INIT type alias Flags = { user : Maybe User , quiz : Maybe Quiz , player : Maybe Player , leaderBoard : Maybe LeaderBoard } flagsDecoder : Decoder Flags flagsDecoder = D.map4 Flags (D.field "user" (D.maybe User.decoder)) (D.field "quiz" (D.maybe Quiz.decoder)) (D.field "player" (D.maybe Player.decoder)) (D.field "leaderBoard" (D.maybe LeaderBoard.decoder)) init : D.Value -> Url -> Key -> ( Model, Cmd msg ) init value url key = let model = { key = key , errorMessage = Nothing , user = User.anonymous , userDraft = "" -- ADMIN , adminText = "" -- ROUTING , route = Route.fromUrl url -- QUIZ , leaderBoard = LeaderBoard.empty , quiz = Quiz.second , player = Player.thinking 0 -- INTER-APP COMMS , socket = Nothing , sockets = Dict.empty , users = Dict.empty } in case D.decodeValue flagsDecoder value of Ok flags -> ( { model | user = Maybe.withDefault model.user flags.user , quiz = Maybe.withDefault model.quiz flags.quiz , player = Maybe.withDefault model.player flags.player , leaderBoard = Maybe.withDefault model.leaderBoard flags.leaderBoard } , Cmd.none ) Err _ -> ( model, Cmd.none ) -- MODEL type alias Model = { user : User , userDraft : String , errorMessage : Maybe D.Error , quiz : Quiz , player : Player , leaderBoard : LeaderBoard -- ADMIN , adminText : String -- ROUTING , route : Route -- Navigation , key : Navigation.Key -- Inter-app communication , socket : Maybe String , sockets : Dict String Player , users : Dict String String } -- MSG type Msg = -- USER UserDraftChanged String -- QUIZ | GotUsername | StartQuiz | FinishQuiz | SelectAnswer Answer | LockAnswerIn -- PORT | Recv Encode.Value -- NAVIGATION | LinkClicked Browser.UrlRequest | UrlChanged Url.Url -- ADMIN | ClearScoreboard | GotText (Result Http.Error String) type PortMsg = LeaderBoardMsg LeaderBoard | ExitMsg String | EnterMsg String | JoinMsg Channel Socket.ID.ID | StartMsg Channel Socket.ID.ID | UserMsg Channel String String | PlayerMsg Channel Player String type Channel = Public | Private portDecoder : D.Decoder PortMsg portDecoder = D.oneOf [ D.map LeaderBoardMsg LeaderBoard.decoder , D.field "type" D.string |> D.andThen payloadDecoder ] payloadDecoder : String -> D.Decoder PortMsg payloadDecoder label = case label of "enter" -> D.map EnterMsg (D.field "payload" (D.field "id" D.string)) "join" -> D.map2 JoinMsg (D.field "channel" channelDecoder) (D.field "payload" (D.map Socket.ID.ID (D.field "id" D.string))) "start" -> D.map2 StartMsg (D.field "channel" channelDecoder) (D.field "payload" (D.map Socket.ID.ID (D.field "id" D.string))) "user" -> D.map3 UserMsg (D.field "channel" channelDecoder) (D.field "payload" (D.field "user" D.string)) (D.field "payload" (D.field "id" D.string)) "player" -> D.map3 PlayerMsg (D.field "channel" channelDecoder) (D.field "payload" (D.field "player" Player.decoder)) (D.field "payload" (D.field "id" D.string)) "exit" -> D.map ExitMsg (D.field "payload" (D.field "id" D.string)) _ -> D.fail "Unrecognised msg type" channelDecoder : D.Decoder Channel channelDecoder = D.string |> D.andThen (\str -> case str of "public" -> D.succeed Public "private" -> D.succeed Private _ -> D.fail "Unknown channel type" ) joinRoomPayload : Int -> Encode.Value joinRoomPayload n = Encode.object [ ( "room", Encode.int n ) ] encodeSocket : Maybe String -> Encode.Value encodeSocket maybeSocket = case maybeSocket of Just str -> Encode.string str Nothing -> Encode.null sessionStorage : String -> String -> Cmd Msg sessionStorage key value = Encode.object [ ( "type", Encode.string "sessionStorage" ) , ( "payload" , Encode.object [ ( "key", Encode.string key ) , ( "value", Encode.string value ) ] ) ] |> Ports.sendMessage -- BROADCAST type alias Socket = Maybe String broadcastPublicJoin : String -> Cmd Msg broadcastPublicJoin str = Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "join" ) , ( "payload" , Encode.object [ ( "id", Encode.string str ) ] ) ] |> Ports.sendMessage broadcastPublicUser : Socket -> String -> Cmd Msg broadcastPublicUser socketId userName = Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "user" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socketId ) , ( "user", Encode.string userName ) ] ) ] |> Ports.sendMessage broadcastPublicPlayer : Socket -> Player -> Cmd Msg broadcastPublicPlayer socketId player = Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "player" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socketId ) , ( "player", Player.encode player ) ] ) ] |> Ports.sendMessage broadcastPrivatePlayer : String -> Socket -> Player -> Cmd Msg broadcastPrivatePlayer toSocketID socket player = Encode.object [ ( "channel", Encode.string "private" ) , ( "to", Encode.string toSocketID ) , ( "type", Encode.string "player" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socket ) , ( "player", Player.encode player ) ] ) ] |> Ports.sendMessage broadcastPrivateUser : String -> Socket -> String -> Cmd Msg broadcastPrivateUser toSocketID socket userName = Encode.object [ ( "channel", Encode.string "private" ) , ( "to", Encode.string toSocketID ) , ( "type", Encode.string "user" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socket ) , ( "user", Encode.string userName ) ] ) ] |> Ports.sendMessage -- UPDATE update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of -- ADMIN ClearScoreboard -> let cmd = Http.get { url = "/clear" , expect = Http.expectString GotText } in ( model, cmd ) GotText result -> case result of Ok str -> ( { model | adminText = str }, Cmd.none ) Err _ -> ( model, Cmd.none ) -- NAVIGATION LinkClicked urlRequest -> case urlRequest of Browser.Internal url -> ( model , Navigation.pushUrl model.key (Url.toString url) ) Browser.External href -> ( model, Navigation.load href ) UrlChanged url -> let route = Route.fromUrl url in ( { model | route = route }, Cmd.none ) UserDraftChanged str -> ( { model | userDraft = str }, Cmd.none ) -- QUIZ GotUsername -> let user = User.loggedIn model.userDraft cmd = Cmd.batch [ -- BROADCAST broadcastPublicUser model.socket model.userDraft -- SESSION STORAGE , sessionStorage "user" (User.toString user) -- GO TO WAITING ROOM , Navigation.pushUrl model.key "/waiting" ] in ( { model | user = user } , cmd ) StartQuiz -> let cmd = Cmd.batch [ -- GO TO QUIZ Navigation.pushUrl model.key "/quiz" -- BROADCAST TO PLAYERS , Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "start" ) , ( "payload" , Encode.object [ ( "id", encodeSocket model.socket ) ] ) ] |> Ports.sendMessage ] in ( model, cmd ) FinishQuiz -> let score = Score.fromInt model.user (Quiz.tally model.quiz) cmd = Cmd.batch [ Outgoing.save score |> Outgoing.encode |> sendMessage -- GO TO SCOREBOARD , Navigation.pushUrl model.key "/scoreboard" ] in ( { model | leaderBoard = LeaderBoard.empty } , cmd ) SelectAnswer answer -> let quiz = Quiz.selectAnswer answer model.quiz cmd = sessionStorage "quiz" (Quiz.toString quiz) in ( { model | quiz = quiz }, cmd ) LockAnswerIn -> let newPlayer = Player.done (model.quiz |> Quiz.getQuestionIndex ) cmd = broadcastPublicPlayer model.socket newPlayer in case Player.chooseMove newPlayer (Dict.values model.sockets) of Forward -> let quiz = Quiz.nextQuestion model.quiz questionIndex = Quiz.getQuestionIndex quiz player = Thinking questionIndex cmds = Cmd.batch [ cmd , sessionStorage "quiz" (Quiz.toString quiz) , sessionStorage "player" (Player.toString player) ] in ( { model | quiz = quiz , player = player } , cmds ) Wait -> -- WAIT FOR OTHER PLAYERS let cmds = Cmd.batch [ cmd , sessionStorage "player" (Player.toString newPlayer) ] in ( { model | player = newPlayer } , cmds ) -- PORT Recv value -> case D.decodeValue portDecoder value of Ok portMsg -> case portMsg of -- LEADERBOARD LeaderBoardMsg leaderBoard -> let cmd = sessionStorage "leaderBoard" (LeaderBoard.toString leaderBoard) in ( { model | leaderBoard = leaderBoard }, cmd ) EnterMsg str -> let cmd = broadcastPublicJoin str socket = Just str in case model.user of Anonymous -> ( { model | socket = socket }, cmd ) LoggedIn userName -> ( { model | socket = socket } , Cmd.batch [ cmd , broadcastPublicUser socket userName ] ) JoinMsg channel socketID -> let str = Socket.ID.toString socketID in ( { model | sockets = Dict.insert str (Player.thinking 0) model.sockets } , Cmd.none ) StartMsg channel socketID -> let cmd = Cmd.batch [ -- GO TO QUIZ Navigation.pushUrl model.key "/quiz" ] in ( model, cmd ) UserMsg channel str id -> let cmd = case channel of Public -> case model.user of Anonymous -> Cmd.none LoggedIn name -> Cmd.batch [ broadcastPrivateUser id model.socket name , broadcastPrivatePlayer id model.socket model.player ] Private -> Cmd.none in ( { model | users = Dict.insert id str model.users } , cmd ) PlayerMsg channel player socketID -> let cmd = case channel of Public -> broadcastPrivatePlayer socketID model.socket model.player Private -> Cmd.none sockets = Dict.insert socketID player model.sockets in case Player.chooseMove model.player (Dict.values sockets) of Forward -> -- ALL DONE let quiz = Quiz.nextQuestion model.quiz questionIndex = Quiz.getQuestionIndex quiz nextPlayer = Thinking questionIndex cmds = Cmd.batch [ cmd , sessionStorage "quiz" (Quiz.toString quiz) , sessionStorage "player" (Player.toString nextPlayer) ] in ( { model | sockets = sockets , quiz = quiz , player = nextPlayer } , cmds ) Wait -> -- WAIT FOR EVERYONE ( { model | sockets = sockets } , cmd ) ExitMsg str -> ( { model | sockets = Dict.remove str model.sockets , users = Dict.remove str model.users } , Cmd.none ) Err error -> -- TODO report errors -- let -- _ = -- Debug.log "error" error -- in ( model, Cmd.none ) -- VIEW view : Model -> Browser.Document Msg view model = case model.route of Index -> { body = [ viewIndex model ] , title = "The Quiet Ryan's" } Quiz -> { body = [ viewBody model ] , title = "The Quiet Ryan's" } WaitingRoom -> { body = [ viewWaitingRoom model ] , title = "The Quiet Ryan's" } ScoreBoard -> { body = [ viewScoreBoard model ] , title = "The Quiet Ryan's" } Admin -> { body = [ viewAdmin model.adminText ] , title = "Admin" } viewWaitingRoom : Model -> Html Msg viewWaitingRoom model = let players = Dict.values model.users in case players of [] -> viewWaitingForFriends "Waiting for people to join..." _ -> div [ classes [ "flex" , "flex-col" , "h-screen" , "w-screen" ] ] [ Header.view , div [ classes [ "flex" , "flex-col" , "items-center" , "justify-between" , "flex-grow" ] ] [ viewUser model.user , viewPlayers players ] ] viewPlayers : List String -> Html Msg viewPlayers players = div [ classes [ "flex" , "flex-col" , "flex-grow" , "justify-center" , "items-center" , "space-y-2" , "w-full" ] ] [ h1 [ classes [ "text-2xl" , "font-bold" , "text-teal-600" ] ] [ text "Other players" ] , div [] (List.map (\u -> div [] [ text u ] ) players ) , button [ classes [ "p-4" , "bg-teal-700" , "w-full" , "uppercase" , "font-bold" , "text-white" ] , onClick StartQuiz ] [ text "Everyone's here" ] ] classes : List String -> Attribute Msg classes = class << String.join " " viewAdmin : String -> Html Msg viewAdmin str = div [ class <| String.join " " <| [ "flex" , "flex-col" , "justify-center" , "items-center" , "h-screen" ] ] [ button [ class <| String.join " " <| [ "border-red-600" , "border-2" , "text-red-600" , "p-4" , "mx-2" ] , onClick ClearScoreboard ] [ text "Clear scoreboard" ] , div [] [ text str ] ] viewIndex : Model -> Html Msg viewIndex model = viewStartPage model.userDraft viewBody : Model -> Html Msg viewBody model = let friends = Dict.values model.users |> List.sort in case model.player of Done _ -> viewWaitingForFriends "Waiting for everyone..." Thinking _ -> let remaining = Quiz.getNext model.quiz question = Quiz.getQuestion model.quiz in div [ class "flex" , class "flex-col" , class "h-screen" ] [ -- QUIZ Header.view , div [ class "flex" , class "flex-row" , class "justify-between" ] [ div [] [ viewUser model.user , viewFriends friends ] , viewRemaining remaining ] , div [ class "flex" , class "flex-col" , class "justify-center" , class "flex-grow" , class "space-y-4" ] [ div [ class "flex" , class "justify-center" , class "items-center" ] [ Quiz.viewQuestion SelectAnswer question ] , viewNav model.quiz ] ] viewScoreBoard : Model -> Html Msg viewScoreBoard model = div [] [ Header.view , viewError model.errorMessage , LeaderBoard.view model.leaderBoard , Review.view model.quiz ] viewRooms : (Int -> Msg) -> Html Msg viewRooms toMsg = div [ classes [ "flex flex-col" , "h-screen" ] ] [ -- NAV Header.view -- CONTENT , div [ classes [ "flex-auto" , "p-4" , "flex" , "flex-col" , "space-y-4" ] ] [ div [ classes [ "text-xl" , "py-4" ] ] [ text "Q. Odd one out?" ] -- ANSWERS , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "Giraffe" ] , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "Tiger" ] , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "Banana" ] , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "<NAME>" ] -- CONTROLS , div [ classes [ "flex" , "flex-row" , "justify-end" ] ] [ div [ classes [ "bg-teal-300" , "p-4" , "rounded-full" , "shadow" , "text-gray-700" ] ] [ Heroicons.chevronRight ] ] ] ] viewFriends : List String -> Html Msg viewFriends friends = div [ class "font-light text-sm p-1" ] [ div [ class "inline" ] [ text "Friends online: " ] , div [ class "font-bold" , class "inline" ] [ text (String.join " " friends) ] ] viewStartPage : String -> Html Msg viewStartPage draftName = div [ class "w-screen" , class "h-screen" , class "flex" , class "flex-col" ] [ Header.view , div [ class <| String.join " " <| [ "flex" , "flex-col" , "justify-center" , "items-center" , "flex-grow" , "px-2" , "space-y-4" ] ] [ div [ class "w-full" ] [ label [ class <| String.join " " <| [ "block" , "text-gray-700" , "text-md" , "font-bold" ] ] [ text "Enter name:" ] , input [ type_ "text" , placeholder "Enter text" , onInput UserDraftChanged , on "keydown" (ifIsEnter GotUsername) , value draftName , class <| String.join " " <| [ "shadow" , "appearence-none" , "border" , "bg-gray-200" , "py-4" , "px-4" , "text-xl" , "w-full" ] ] [] ] , if draftName /= "" then button [ onClick GotUsername , class <| String.join " " <| [ "w-full" , "p-4" , "bg-blue-500" , "uppercase" , "text-xl" , "text-white" ] ] [ text "Start Quiz" ] else text "" ] ] primaryButtonStyle : Html.Attribute Msg primaryButtonStyle = class <| String.join " " <| [ "text-white" , "p-4" , "py-6" ] viewNav : Quiz -> Html Msg viewNav quiz = let question = Quiz.getQuestion quiz remaining = Quiz.getNext quiz in div [ class "flex" , class "pb-8" ] [ if Quiz.answered question then case remaining of [] -> finishButton FinishQuiz _ -> lockInButton LockAnswerIn else text "" ] viewRemaining : List Question -> Html Msg viewRemaining remaining = let n = List.length remaining in div [ class "text-sm text-gray-400 px-2" ] [ text (String.fromInt n ++ " " ++ plural n ++ " to go") ] plural : Int -> String plural n = if n > 0 then "questions" else "question" lockInButton : Msg -> Html Msg lockInButton toMsg = button [ class <| String.join " " <| [ "bg-yellow-400" , "flex-grow" , "uppercase" , "px-4" , "py-6" , "mx-2" ] , onClick toMsg ] [ div [ class <| String.join " " <| [ "flex" , "flex-row" , "justify-center" , "items-center" ] ] [ Heroicons.lockOpen , div [ class "pl-2" ] [ text "Lock answer in" ] ] ] viewWaitingForFriends : String -> Html Msg viewWaitingForFriends messageText = div [ class <| String.join " " <| [ "bg-purple-500" , "text-white" , "flex" , "flex-row" , "justify-center" , "items-center" , "h-screen" ] ] [ div [ class <| String.join " " <| [ "flex" , "flex-row" , "justify-center" , "items-center" , "animate-pulse" ] ] [ Heroicons.sparkle , div [ class <| String.join " " <| [ "pl-2" , "uppercase" ] ] [ text messageText ] ] ] finishButton : Msg -> Html Msg finishButton toMsg = button [ primaryButtonStyle , class <| String.join " " <| [ "flex-grow" , "bg-blue-600" , "uppercase" , "mx-2" ] , onClick toMsg ] [ text "Finish quiz" ] viewError : Maybe D.Error -> Html Msg viewError maybeError = case maybeError of Nothing -> text "" Just error -> div [] [ text (D.errorToString error) ] viewUser : User -> Html Msg viewUser user = div [ class "font-light text-sm p-1" ] [ text "Signed in as " , span [ class "font-bold" ] [ text (User.toString user) ] ] -- MAIN main : Program D.Value Model Msg main = Browser.application { init = init , onUrlChange = UrlChanged , onUrlRequest = LinkClicked , update = update , view = view , subscriptions = subscriptions } -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions _ = messageReceiver Recv
true
module Main exposing (main) import Browser import Browser.Navigation as Navigation exposing (Key) import Container import Dict exposing (Dict) import Header import Helper exposing (classes, ifIsEnter) import Heroicons exposing (menu, pencil) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (on, onClick, onInput) import Http import Json.Decode as D exposing (Decoder) import Json.Encode as Encode import LeaderBoard exposing (LeaderBoard) import Outgoing import Player exposing (Move(..), Player(..)) import Ports exposing (messageReceiver, sendMessage) import Quiz exposing (Answer, Question, Quiz) import Review import Route exposing (Route(..)) import Score exposing (Score) import Set exposing (Set) import Socket.ID exposing (ID) import Url exposing (Url) import User exposing (User(..)) -- INIT type alias Flags = { user : Maybe User , quiz : Maybe Quiz , player : Maybe Player , leaderBoard : Maybe LeaderBoard } flagsDecoder : Decoder Flags flagsDecoder = D.map4 Flags (D.field "user" (D.maybe User.decoder)) (D.field "quiz" (D.maybe Quiz.decoder)) (D.field "player" (D.maybe Player.decoder)) (D.field "leaderBoard" (D.maybe LeaderBoard.decoder)) init : D.Value -> Url -> Key -> ( Model, Cmd msg ) init value url key = let model = { key = key , errorMessage = Nothing , user = User.anonymous , userDraft = "" -- ADMIN , adminText = "" -- ROUTING , route = Route.fromUrl url -- QUIZ , leaderBoard = LeaderBoard.empty , quiz = Quiz.second , player = Player.thinking 0 -- INTER-APP COMMS , socket = Nothing , sockets = Dict.empty , users = Dict.empty } in case D.decodeValue flagsDecoder value of Ok flags -> ( { model | user = Maybe.withDefault model.user flags.user , quiz = Maybe.withDefault model.quiz flags.quiz , player = Maybe.withDefault model.player flags.player , leaderBoard = Maybe.withDefault model.leaderBoard flags.leaderBoard } , Cmd.none ) Err _ -> ( model, Cmd.none ) -- MODEL type alias Model = { user : User , userDraft : String , errorMessage : Maybe D.Error , quiz : Quiz , player : Player , leaderBoard : LeaderBoard -- ADMIN , adminText : String -- ROUTING , route : Route -- Navigation , key : Navigation.Key -- Inter-app communication , socket : Maybe String , sockets : Dict String Player , users : Dict String String } -- MSG type Msg = -- USER UserDraftChanged String -- QUIZ | GotUsername | StartQuiz | FinishQuiz | SelectAnswer Answer | LockAnswerIn -- PORT | Recv Encode.Value -- NAVIGATION | LinkClicked Browser.UrlRequest | UrlChanged Url.Url -- ADMIN | ClearScoreboard | GotText (Result Http.Error String) type PortMsg = LeaderBoardMsg LeaderBoard | ExitMsg String | EnterMsg String | JoinMsg Channel Socket.ID.ID | StartMsg Channel Socket.ID.ID | UserMsg Channel String String | PlayerMsg Channel Player String type Channel = Public | Private portDecoder : D.Decoder PortMsg portDecoder = D.oneOf [ D.map LeaderBoardMsg LeaderBoard.decoder , D.field "type" D.string |> D.andThen payloadDecoder ] payloadDecoder : String -> D.Decoder PortMsg payloadDecoder label = case label of "enter" -> D.map EnterMsg (D.field "payload" (D.field "id" D.string)) "join" -> D.map2 JoinMsg (D.field "channel" channelDecoder) (D.field "payload" (D.map Socket.ID.ID (D.field "id" D.string))) "start" -> D.map2 StartMsg (D.field "channel" channelDecoder) (D.field "payload" (D.map Socket.ID.ID (D.field "id" D.string))) "user" -> D.map3 UserMsg (D.field "channel" channelDecoder) (D.field "payload" (D.field "user" D.string)) (D.field "payload" (D.field "id" D.string)) "player" -> D.map3 PlayerMsg (D.field "channel" channelDecoder) (D.field "payload" (D.field "player" Player.decoder)) (D.field "payload" (D.field "id" D.string)) "exit" -> D.map ExitMsg (D.field "payload" (D.field "id" D.string)) _ -> D.fail "Unrecognised msg type" channelDecoder : D.Decoder Channel channelDecoder = D.string |> D.andThen (\str -> case str of "public" -> D.succeed Public "private" -> D.succeed Private _ -> D.fail "Unknown channel type" ) joinRoomPayload : Int -> Encode.Value joinRoomPayload n = Encode.object [ ( "room", Encode.int n ) ] encodeSocket : Maybe String -> Encode.Value encodeSocket maybeSocket = case maybeSocket of Just str -> Encode.string str Nothing -> Encode.null sessionStorage : String -> String -> Cmd Msg sessionStorage key value = Encode.object [ ( "type", Encode.string "sessionStorage" ) , ( "payload" , Encode.object [ ( "key", Encode.string key ) , ( "value", Encode.string value ) ] ) ] |> Ports.sendMessage -- BROADCAST type alias Socket = Maybe String broadcastPublicJoin : String -> Cmd Msg broadcastPublicJoin str = Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "join" ) , ( "payload" , Encode.object [ ( "id", Encode.string str ) ] ) ] |> Ports.sendMessage broadcastPublicUser : Socket -> String -> Cmd Msg broadcastPublicUser socketId userName = Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "user" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socketId ) , ( "user", Encode.string userName ) ] ) ] |> Ports.sendMessage broadcastPublicPlayer : Socket -> Player -> Cmd Msg broadcastPublicPlayer socketId player = Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "player" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socketId ) , ( "player", Player.encode player ) ] ) ] |> Ports.sendMessage broadcastPrivatePlayer : String -> Socket -> Player -> Cmd Msg broadcastPrivatePlayer toSocketID socket player = Encode.object [ ( "channel", Encode.string "private" ) , ( "to", Encode.string toSocketID ) , ( "type", Encode.string "player" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socket ) , ( "player", Player.encode player ) ] ) ] |> Ports.sendMessage broadcastPrivateUser : String -> Socket -> String -> Cmd Msg broadcastPrivateUser toSocketID socket userName = Encode.object [ ( "channel", Encode.string "private" ) , ( "to", Encode.string toSocketID ) , ( "type", Encode.string "user" ) , ( "payload" , Encode.object [ ( "id", encodeSocket socket ) , ( "user", Encode.string userName ) ] ) ] |> Ports.sendMessage -- UPDATE update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of -- ADMIN ClearScoreboard -> let cmd = Http.get { url = "/clear" , expect = Http.expectString GotText } in ( model, cmd ) GotText result -> case result of Ok str -> ( { model | adminText = str }, Cmd.none ) Err _ -> ( model, Cmd.none ) -- NAVIGATION LinkClicked urlRequest -> case urlRequest of Browser.Internal url -> ( model , Navigation.pushUrl model.key (Url.toString url) ) Browser.External href -> ( model, Navigation.load href ) UrlChanged url -> let route = Route.fromUrl url in ( { model | route = route }, Cmd.none ) UserDraftChanged str -> ( { model | userDraft = str }, Cmd.none ) -- QUIZ GotUsername -> let user = User.loggedIn model.userDraft cmd = Cmd.batch [ -- BROADCAST broadcastPublicUser model.socket model.userDraft -- SESSION STORAGE , sessionStorage "user" (User.toString user) -- GO TO WAITING ROOM , Navigation.pushUrl model.key "/waiting" ] in ( { model | user = user } , cmd ) StartQuiz -> let cmd = Cmd.batch [ -- GO TO QUIZ Navigation.pushUrl model.key "/quiz" -- BROADCAST TO PLAYERS , Encode.object [ ( "channel", Encode.string "public" ) , ( "type", Encode.string "start" ) , ( "payload" , Encode.object [ ( "id", encodeSocket model.socket ) ] ) ] |> Ports.sendMessage ] in ( model, cmd ) FinishQuiz -> let score = Score.fromInt model.user (Quiz.tally model.quiz) cmd = Cmd.batch [ Outgoing.save score |> Outgoing.encode |> sendMessage -- GO TO SCOREBOARD , Navigation.pushUrl model.key "/scoreboard" ] in ( { model | leaderBoard = LeaderBoard.empty } , cmd ) SelectAnswer answer -> let quiz = Quiz.selectAnswer answer model.quiz cmd = sessionStorage "quiz" (Quiz.toString quiz) in ( { model | quiz = quiz }, cmd ) LockAnswerIn -> let newPlayer = Player.done (model.quiz |> Quiz.getQuestionIndex ) cmd = broadcastPublicPlayer model.socket newPlayer in case Player.chooseMove newPlayer (Dict.values model.sockets) of Forward -> let quiz = Quiz.nextQuestion model.quiz questionIndex = Quiz.getQuestionIndex quiz player = Thinking questionIndex cmds = Cmd.batch [ cmd , sessionStorage "quiz" (Quiz.toString quiz) , sessionStorage "player" (Player.toString player) ] in ( { model | quiz = quiz , player = player } , cmds ) Wait -> -- WAIT FOR OTHER PLAYERS let cmds = Cmd.batch [ cmd , sessionStorage "player" (Player.toString newPlayer) ] in ( { model | player = newPlayer } , cmds ) -- PORT Recv value -> case D.decodeValue portDecoder value of Ok portMsg -> case portMsg of -- LEADERBOARD LeaderBoardMsg leaderBoard -> let cmd = sessionStorage "leaderBoard" (LeaderBoard.toString leaderBoard) in ( { model | leaderBoard = leaderBoard }, cmd ) EnterMsg str -> let cmd = broadcastPublicJoin str socket = Just str in case model.user of Anonymous -> ( { model | socket = socket }, cmd ) LoggedIn userName -> ( { model | socket = socket } , Cmd.batch [ cmd , broadcastPublicUser socket userName ] ) JoinMsg channel socketID -> let str = Socket.ID.toString socketID in ( { model | sockets = Dict.insert str (Player.thinking 0) model.sockets } , Cmd.none ) StartMsg channel socketID -> let cmd = Cmd.batch [ -- GO TO QUIZ Navigation.pushUrl model.key "/quiz" ] in ( model, cmd ) UserMsg channel str id -> let cmd = case channel of Public -> case model.user of Anonymous -> Cmd.none LoggedIn name -> Cmd.batch [ broadcastPrivateUser id model.socket name , broadcastPrivatePlayer id model.socket model.player ] Private -> Cmd.none in ( { model | users = Dict.insert id str model.users } , cmd ) PlayerMsg channel player socketID -> let cmd = case channel of Public -> broadcastPrivatePlayer socketID model.socket model.player Private -> Cmd.none sockets = Dict.insert socketID player model.sockets in case Player.chooseMove model.player (Dict.values sockets) of Forward -> -- ALL DONE let quiz = Quiz.nextQuestion model.quiz questionIndex = Quiz.getQuestionIndex quiz nextPlayer = Thinking questionIndex cmds = Cmd.batch [ cmd , sessionStorage "quiz" (Quiz.toString quiz) , sessionStorage "player" (Player.toString nextPlayer) ] in ( { model | sockets = sockets , quiz = quiz , player = nextPlayer } , cmds ) Wait -> -- WAIT FOR EVERYONE ( { model | sockets = sockets } , cmd ) ExitMsg str -> ( { model | sockets = Dict.remove str model.sockets , users = Dict.remove str model.users } , Cmd.none ) Err error -> -- TODO report errors -- let -- _ = -- Debug.log "error" error -- in ( model, Cmd.none ) -- VIEW view : Model -> Browser.Document Msg view model = case model.route of Index -> { body = [ viewIndex model ] , title = "The Quiet Ryan's" } Quiz -> { body = [ viewBody model ] , title = "The Quiet Ryan's" } WaitingRoom -> { body = [ viewWaitingRoom model ] , title = "The Quiet Ryan's" } ScoreBoard -> { body = [ viewScoreBoard model ] , title = "The Quiet Ryan's" } Admin -> { body = [ viewAdmin model.adminText ] , title = "Admin" } viewWaitingRoom : Model -> Html Msg viewWaitingRoom model = let players = Dict.values model.users in case players of [] -> viewWaitingForFriends "Waiting for people to join..." _ -> div [ classes [ "flex" , "flex-col" , "h-screen" , "w-screen" ] ] [ Header.view , div [ classes [ "flex" , "flex-col" , "items-center" , "justify-between" , "flex-grow" ] ] [ viewUser model.user , viewPlayers players ] ] viewPlayers : List String -> Html Msg viewPlayers players = div [ classes [ "flex" , "flex-col" , "flex-grow" , "justify-center" , "items-center" , "space-y-2" , "w-full" ] ] [ h1 [ classes [ "text-2xl" , "font-bold" , "text-teal-600" ] ] [ text "Other players" ] , div [] (List.map (\u -> div [] [ text u ] ) players ) , button [ classes [ "p-4" , "bg-teal-700" , "w-full" , "uppercase" , "font-bold" , "text-white" ] , onClick StartQuiz ] [ text "Everyone's here" ] ] classes : List String -> Attribute Msg classes = class << String.join " " viewAdmin : String -> Html Msg viewAdmin str = div [ class <| String.join " " <| [ "flex" , "flex-col" , "justify-center" , "items-center" , "h-screen" ] ] [ button [ class <| String.join " " <| [ "border-red-600" , "border-2" , "text-red-600" , "p-4" , "mx-2" ] , onClick ClearScoreboard ] [ text "Clear scoreboard" ] , div [] [ text str ] ] viewIndex : Model -> Html Msg viewIndex model = viewStartPage model.userDraft viewBody : Model -> Html Msg viewBody model = let friends = Dict.values model.users |> List.sort in case model.player of Done _ -> viewWaitingForFriends "Waiting for everyone..." Thinking _ -> let remaining = Quiz.getNext model.quiz question = Quiz.getQuestion model.quiz in div [ class "flex" , class "flex-col" , class "h-screen" ] [ -- QUIZ Header.view , div [ class "flex" , class "flex-row" , class "justify-between" ] [ div [] [ viewUser model.user , viewFriends friends ] , viewRemaining remaining ] , div [ class "flex" , class "flex-col" , class "justify-center" , class "flex-grow" , class "space-y-4" ] [ div [ class "flex" , class "justify-center" , class "items-center" ] [ Quiz.viewQuestion SelectAnswer question ] , viewNav model.quiz ] ] viewScoreBoard : Model -> Html Msg viewScoreBoard model = div [] [ Header.view , viewError model.errorMessage , LeaderBoard.view model.leaderBoard , Review.view model.quiz ] viewRooms : (Int -> Msg) -> Html Msg viewRooms toMsg = div [ classes [ "flex flex-col" , "h-screen" ] ] [ -- NAV Header.view -- CONTENT , div [ classes [ "flex-auto" , "p-4" , "flex" , "flex-col" , "space-y-4" ] ] [ div [ classes [ "text-xl" , "py-4" ] ] [ text "Q. Odd one out?" ] -- ANSWERS , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "Giraffe" ] , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "Tiger" ] , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "Banana" ] , div [ classes [ "bg-gray-100" , "shadow" , "p-4" ] ] [ text "PI:NAME:<NAME>END_PI" ] -- CONTROLS , div [ classes [ "flex" , "flex-row" , "justify-end" ] ] [ div [ classes [ "bg-teal-300" , "p-4" , "rounded-full" , "shadow" , "text-gray-700" ] ] [ Heroicons.chevronRight ] ] ] ] viewFriends : List String -> Html Msg viewFriends friends = div [ class "font-light text-sm p-1" ] [ div [ class "inline" ] [ text "Friends online: " ] , div [ class "font-bold" , class "inline" ] [ text (String.join " " friends) ] ] viewStartPage : String -> Html Msg viewStartPage draftName = div [ class "w-screen" , class "h-screen" , class "flex" , class "flex-col" ] [ Header.view , div [ class <| String.join " " <| [ "flex" , "flex-col" , "justify-center" , "items-center" , "flex-grow" , "px-2" , "space-y-4" ] ] [ div [ class "w-full" ] [ label [ class <| String.join " " <| [ "block" , "text-gray-700" , "text-md" , "font-bold" ] ] [ text "Enter name:" ] , input [ type_ "text" , placeholder "Enter text" , onInput UserDraftChanged , on "keydown" (ifIsEnter GotUsername) , value draftName , class <| String.join " " <| [ "shadow" , "appearence-none" , "border" , "bg-gray-200" , "py-4" , "px-4" , "text-xl" , "w-full" ] ] [] ] , if draftName /= "" then button [ onClick GotUsername , class <| String.join " " <| [ "w-full" , "p-4" , "bg-blue-500" , "uppercase" , "text-xl" , "text-white" ] ] [ text "Start Quiz" ] else text "" ] ] primaryButtonStyle : Html.Attribute Msg primaryButtonStyle = class <| String.join " " <| [ "text-white" , "p-4" , "py-6" ] viewNav : Quiz -> Html Msg viewNav quiz = let question = Quiz.getQuestion quiz remaining = Quiz.getNext quiz in div [ class "flex" , class "pb-8" ] [ if Quiz.answered question then case remaining of [] -> finishButton FinishQuiz _ -> lockInButton LockAnswerIn else text "" ] viewRemaining : List Question -> Html Msg viewRemaining remaining = let n = List.length remaining in div [ class "text-sm text-gray-400 px-2" ] [ text (String.fromInt n ++ " " ++ plural n ++ " to go") ] plural : Int -> String plural n = if n > 0 then "questions" else "question" lockInButton : Msg -> Html Msg lockInButton toMsg = button [ class <| String.join " " <| [ "bg-yellow-400" , "flex-grow" , "uppercase" , "px-4" , "py-6" , "mx-2" ] , onClick toMsg ] [ div [ class <| String.join " " <| [ "flex" , "flex-row" , "justify-center" , "items-center" ] ] [ Heroicons.lockOpen , div [ class "pl-2" ] [ text "Lock answer in" ] ] ] viewWaitingForFriends : String -> Html Msg viewWaitingForFriends messageText = div [ class <| String.join " " <| [ "bg-purple-500" , "text-white" , "flex" , "flex-row" , "justify-center" , "items-center" , "h-screen" ] ] [ div [ class <| String.join " " <| [ "flex" , "flex-row" , "justify-center" , "items-center" , "animate-pulse" ] ] [ Heroicons.sparkle , div [ class <| String.join " " <| [ "pl-2" , "uppercase" ] ] [ text messageText ] ] ] finishButton : Msg -> Html Msg finishButton toMsg = button [ primaryButtonStyle , class <| String.join " " <| [ "flex-grow" , "bg-blue-600" , "uppercase" , "mx-2" ] , onClick toMsg ] [ text "Finish quiz" ] viewError : Maybe D.Error -> Html Msg viewError maybeError = case maybeError of Nothing -> text "" Just error -> div [] [ text (D.errorToString error) ] viewUser : User -> Html Msg viewUser user = div [ class "font-light text-sm p-1" ] [ text "Signed in as " , span [ class "font-bold" ] [ text (User.toString user) ] ] -- MAIN main : Program D.Value Model Msg main = Browser.application { init = init , onUrlChange = UrlChanged , onUrlRequest = LinkClicked , update = update , view = view , subscriptions = subscriptions } -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions _ = messageReceiver Recv
elm
[ { "context": " ,div[class \"pure-u-1\"][ footer[][text \"Copyright Isaac Smyth 2018\"]]\n ]\n\nviewTestPings : Model -> Html Msg\n", "end": 689, "score": 0.999533236, "start": 678, "tag": "NAME", "value": "Isaac Smyth" } ]
src/view/Experiments.elm
TronoTheMerciless/PersonalWebsite
0
module Experiments exposing (view) import Model exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Model exposing (Model, Msg) view : Model -> Html Msg view model = div[][ div [ class "pure-g-u-1"] [ div [class "pure-u-1"][ h1 [] [ text "On to the Experiments!" ] ] , viewDiceRoll model ] , br [][] , viewIncrements model ,br[][] ,viewTestPings model , br [][] ,div[class "pure-u-1"][ footer[][text "Copyright Isaac Smyth 2018"]] ] viewTestPings : Model -> Html Msg viewTestPings model = div[][p [] [ text "Click on the button below to increment the state." ] , div [ class "pure-g" ] [ div [ class "pure-u-1-3" ] [ button [ class "pure-button pure-button-primary" , onClick Model.Inc ] [ text "+ 1" ] , text <| String.fromInt model.counter ] , div [ class "pure-u-1-3" ] [] , div [ class "pure-u-1-3" ] [ button [ class "pure-button pure-button-primary" , onClick Model.TestServer ] [ text "ping dev server" ] , text model.serverMessage ] ] ] viewDiceRoll : Model -> Html Msg viewDiceRoll model = div[][ div [class "pure-u-1"][ h1 [] [ text (dieImage model.dieFace) ]] , div [class "pure-u-1"][button [class "pure-button button-roll", onClick Model.Roll ] [ text "Roll" ]] ] viewIncrements : Model -> Html Msg viewIncrements model = div[][ div [class "pure-g-u-1"] [ div [class "pure-u-1-6"] [button[class "pure-button button-decrement", onClick Model.Decrement10][text "-10"] , button[class "pure-button button-decrement", onClick Model.Decrement][text "-"] ] , div [class "pure-u-1-6"] [text (String.fromInt model.value)] , div [class "pure-u-1-6"] [ button [class "pure-button button-increment", onClick Model.Increment] [text "+"] , button[class "pure-button button-increment", onClick Model.Increment10][text "+10"] ] ] , br [][] ,div [class "pure-g-u-1"] [ div [class "pure-u-1"] [button [class "pure-button button-reset", onClick Model.Reset] [text "Reset"]] , div [class "pure-u-1"] [ input [ placeholder "Text to reverse", value model.content, onInput Model.Change ] [] ] , div [class "pure-u-1"] [ text (String.reverse model.content) ] ] ] dieImage : Int -> String dieImage value = case value of 1 -> "⚀" 2 -> "⚁" 3 -> "⚂" 4 -> "⚃" 5 -> "⚄" 6 -> "⚅" _ -> ""
16567
module Experiments exposing (view) import Model exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Model exposing (Model, Msg) view : Model -> Html Msg view model = div[][ div [ class "pure-g-u-1"] [ div [class "pure-u-1"][ h1 [] [ text "On to the Experiments!" ] ] , viewDiceRoll model ] , br [][] , viewIncrements model ,br[][] ,viewTestPings model , br [][] ,div[class "pure-u-1"][ footer[][text "Copyright <NAME> 2018"]] ] viewTestPings : Model -> Html Msg viewTestPings model = div[][p [] [ text "Click on the button below to increment the state." ] , div [ class "pure-g" ] [ div [ class "pure-u-1-3" ] [ button [ class "pure-button pure-button-primary" , onClick Model.Inc ] [ text "+ 1" ] , text <| String.fromInt model.counter ] , div [ class "pure-u-1-3" ] [] , div [ class "pure-u-1-3" ] [ button [ class "pure-button pure-button-primary" , onClick Model.TestServer ] [ text "ping dev server" ] , text model.serverMessage ] ] ] viewDiceRoll : Model -> Html Msg viewDiceRoll model = div[][ div [class "pure-u-1"][ h1 [] [ text (dieImage model.dieFace) ]] , div [class "pure-u-1"][button [class "pure-button button-roll", onClick Model.Roll ] [ text "Roll" ]] ] viewIncrements : Model -> Html Msg viewIncrements model = div[][ div [class "pure-g-u-1"] [ div [class "pure-u-1-6"] [button[class "pure-button button-decrement", onClick Model.Decrement10][text "-10"] , button[class "pure-button button-decrement", onClick Model.Decrement][text "-"] ] , div [class "pure-u-1-6"] [text (String.fromInt model.value)] , div [class "pure-u-1-6"] [ button [class "pure-button button-increment", onClick Model.Increment] [text "+"] , button[class "pure-button button-increment", onClick Model.Increment10][text "+10"] ] ] , br [][] ,div [class "pure-g-u-1"] [ div [class "pure-u-1"] [button [class "pure-button button-reset", onClick Model.Reset] [text "Reset"]] , div [class "pure-u-1"] [ input [ placeholder "Text to reverse", value model.content, onInput Model.Change ] [] ] , div [class "pure-u-1"] [ text (String.reverse model.content) ] ] ] dieImage : Int -> String dieImage value = case value of 1 -> "⚀" 2 -> "⚁" 3 -> "⚂" 4 -> "⚃" 5 -> "⚄" 6 -> "⚅" _ -> ""
true
module Experiments exposing (view) import Model exposing (..) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Model exposing (Model, Msg) view : Model -> Html Msg view model = div[][ div [ class "pure-g-u-1"] [ div [class "pure-u-1"][ h1 [] [ text "On to the Experiments!" ] ] , viewDiceRoll model ] , br [][] , viewIncrements model ,br[][] ,viewTestPings model , br [][] ,div[class "pure-u-1"][ footer[][text "Copyright PI:NAME:<NAME>END_PI 2018"]] ] viewTestPings : Model -> Html Msg viewTestPings model = div[][p [] [ text "Click on the button below to increment the state." ] , div [ class "pure-g" ] [ div [ class "pure-u-1-3" ] [ button [ class "pure-button pure-button-primary" , onClick Model.Inc ] [ text "+ 1" ] , text <| String.fromInt model.counter ] , div [ class "pure-u-1-3" ] [] , div [ class "pure-u-1-3" ] [ button [ class "pure-button pure-button-primary" , onClick Model.TestServer ] [ text "ping dev server" ] , text model.serverMessage ] ] ] viewDiceRoll : Model -> Html Msg viewDiceRoll model = div[][ div [class "pure-u-1"][ h1 [] [ text (dieImage model.dieFace) ]] , div [class "pure-u-1"][button [class "pure-button button-roll", onClick Model.Roll ] [ text "Roll" ]] ] viewIncrements : Model -> Html Msg viewIncrements model = div[][ div [class "pure-g-u-1"] [ div [class "pure-u-1-6"] [button[class "pure-button button-decrement", onClick Model.Decrement10][text "-10"] , button[class "pure-button button-decrement", onClick Model.Decrement][text "-"] ] , div [class "pure-u-1-6"] [text (String.fromInt model.value)] , div [class "pure-u-1-6"] [ button [class "pure-button button-increment", onClick Model.Increment] [text "+"] , button[class "pure-button button-increment", onClick Model.Increment10][text "+10"] ] ] , br [][] ,div [class "pure-g-u-1"] [ div [class "pure-u-1"] [button [class "pure-button button-reset", onClick Model.Reset] [text "Reset"]] , div [class "pure-u-1"] [ input [ placeholder "Text to reverse", value model.content, onInput Model.Change ] [] ] , div [class "pure-u-1"] [ text (String.reverse model.content) ] ] ] dieImage : Int -> String dieImage value = case value of 1 -> "⚀" 2 -> "⚁" 3 -> "⚂" 4 -> "⚃" 5 -> "⚄" 6 -> "⚅" _ -> ""
elm
[ { "context": " [ h1 [ styles.headerPrimary ] [ text__ \"Vladimir Logachev\" ]\n , div [ css [ marginBottom (px 8) ", "end": 4512, "score": 0.9998978376, "start": 4495, "tag": "NAME", "value": "Vladimir Logachev" }, { "context": "s.link, css [ marginBottom (px 8) ], href \"mailto: logachev.dev@ya.ru\", targetBlank, noOpener ] [ text__ \"logachev.dev@", "end": 4813, "score": 0.9999169111, "start": 4795, "tag": "EMAIL", "value": "logachev.dev@ya.ru" }, { "context": "hev.dev@ya.ru\", targetBlank, noOpener ] [ text__ \"logachev.dev@ya.ru\" ]\n , div [ css [ displayFlex, marginB", "end": 4868, "score": 0.9999167919, "start": 4850, "tag": "EMAIL", "value": "logachev.dev@ya.ru" }, { "context": " , printableLink \"GitHub\" \"https://github.com/vladimirlogachev\"\n , printableLink \"Telegram\" \"http", "end": 5161, "score": 0.999674201, "start": 5145, "tag": "USERNAME", "value": "vladimirlogachev" }, { "context": " , printableLink \"Telegram\" \"https://t.me/vladimirlogachev\"\n , printableLink \"Twitter\" \"https", "end": 5236, "score": 0.9996483922, "start": 5220, "tag": "USERNAME", "value": "vladimirlogachev" }, { "context": " , printableLink \"Twitter\" \"https://twitter.com/logachev_dev\"\n , printableLink \"LinkedIn\" \"http", "end": 5313, "score": 0.9996264577, "start": 5301, "tag": "USERNAME", "value": "logachev_dev" }, { "context": "tableLink \"LinkedIn\" \"https://www.linkedin.com/in/vladimirlogachev\"\n ]\n , div [ css [ marg", "end": 5403, "score": 0.9996749759, "start": 5387, "tag": "USERNAME", "value": "vladimirlogachev" }, { "context": "Library CMS\"\n -- , url = \"https://github.com/VladimirLogachev/library\"\n -- , description = \"A GraphQL API ", "end": 11323, "score": 0.9984134436, "start": 11307, "tag": "USERNAME", "value": "VladimirLogachev" }, { "context": "to-elm example\"\n , url = \"https://github.com/VladimirLogachev/servant-to-elm-example\"\n , description = \"\"\"", "end": 11714, "score": 0.9622135162, "start": 11698, "tag": "USERNAME", "value": "VladimirLogachev" }, { "context": "e (assessment)\"\n , url = \"https://github.com/VladimirLogachev/transitive_closure\"\n , description = \"\"\"A fu", "end": 12331, "score": 0.9945469499, "start": 12315, "tag": "USERNAME", "value": "VladimirLogachev" }, { "context": "e (assessment)\"\n , url = \"https://github.com/VladimirLogachev/crawler\"\n , description = \"\"\"A microservice ", "end": 12873, "score": 0.9867315292, "start": 12857, "tag": "USERNAME", "value": "VladimirLogachev" }, { "context": "ql-example-elm\"\n , url = \"https://github.com/higherkindness/mu-graphql-example-elm\"\n , description = \"An", "end": 13709, "score": 0.990206182, "start": 13695, "tag": "USERNAME", "value": "higherkindness" }, { "context": " in JavaScript\"\n , url = \"https://github.com/MostlyAdequate/mostly-adequate-guide-ru\"\n , description = \"", "end": 14244, "score": 0.9955117702, "start": 14230, "tag": "USERNAME", "value": "MostlyAdequate" }, { "context": "ications.\n The translation was initiated by Maxim Filippov and stopped at 60%. Then me and Sakayama joined t", "end": 14496, "score": 0.9998666048, "start": 14482, "tag": "NAME", "value": "Maxim Filippov" }, { "context": "rd\nexperienceRecords =\n [ { companyAndTitle = \"Pamir, frontend developer\"\n , startDate = Date 5", "end": 17145, "score": 0.5746980906, "start": 17142, "tag": "NAME", "value": "Pam" } ]
src/Cv.elm
VladimirLogachev/logachev.dev
2
module Cv exposing (view) import Css exposing (..) import Css.Media as Media exposing (only, print, screen, withMedia) import Html.Styled exposing (..) import Html.Styled.Attributes as Attributes exposing (alt, attribute, css, href, src, title) import Typography exposing (text__) styles = { page = css [ margin2 zero auto , fontFamilies [ "Source Sans Pro", "sans-serif" ] , fontStyle normal , color (hex "212121") , fontWeight normal , fromPx fontSize 16 , fromPx lineHeight 20 , mediaScreen [ maxWidth (px 768), padding4 (px 40) (px 16) (px 40) (px 16) ] , mediaPrint [ padding zero ] ] , itemBlock = css [ displayFlex , flexDirection column , marginBottom (px 28) , property "break-inside" "avoid" , firstOfType [ property "break-before" "avoid" ] ] , section = css [ marginBottom (px 60) ] , summary = css [ displayFlex , mediaMobile [ flexDirection column ] , marginBottom (px 40) ] , summaryTextContent = css [ displayFlex , flexDirection column , mediaDesktop [ fromPx marginLeft 32 ] , mediaMobile [ important <| marginLeft zero, marginTop (px 24) ] ] , photo = css [ fromPx width 200 , fromPx height 200 , borderRadius (px 8) , backgroundColor (hex "efefef") ] -- Text styles , headerPrimary = css [ fontWeight bold , fromPx fontSize 32 , fromPx lineHeight 40 , marginBottom (px 12) ] , subheader = css [ fontWeight bold , fromPx fontSize 24 , fromPx lineHeight 30 , marginBottom (px 20) , property "break-after" "avoid" ] , item = css [ fontWeight normal , fromPx fontSize 20 , fromPx lineHeight 25 , marginBottom (px 8) ] , link = css [ color (hex "0d7da9") , textDecoration none ] , period = css [ fontWeight normal , fromPx fontSize 20 , fromPx lineHeight 25 , color (hex "707070") , marginLeft (px 12) ] , detail = css [ color (hex "707070") ] } {- TODO: - выпилить все размеры в px, поресёрчить способ фиксирования размера поинта для разных медиа. Цель - просто задавать число в поинтах, желательно равное числу пикселей на десктопе, и получать абсолютно такой же выход на печати. Альтернативный вариант - возвращать record (но это сильно замарает код). - убрать important - перенос тегов на новую строку - явные height и width для изображений, мультисорс, alt - пустые ссылки сделать maybe - дрочкануть lighthouse - длинные ссылки выбиваются за пределы мобильного холста - обозначить софт скиллы - обозначить долгосрочные профессиональные цели -} view : Html msg view = div [ styles.page ] [ summarySection , bioSection , skillsSection , showcaseProjectsSection , contributionsSection , educationSection , experienceSection ] -- Summary printableLink : String -> String -> Html msg printableLink title url = span [] [ span [ css [ marginRight (px 12), mediaPrint [ display none ] ] ] [ a [ styles.link, href url, targetBlank, noOpener ] [ text__ title ] ] , span [ css [ mediaScreen [ display none ] ] ] [ span [ css [ fromPx marginRight 6 ] ] [ text__ <| title ++ ":" ] , a [ styles.link, href url, targetBlank, noOpener ] [ text__ url ] ] ] icon : String -> String -> Html msg icon filename altText = img [ css [ height (px 28), marginRight (px 10) ] , src <| "/logos/" ++ filename , alt altText , title altText ] [] summarySection : Html msg summarySection = div [ styles.summary ] [ img [ styles.photo, src "https://avatars2.githubusercontent.com/u/17773003?s=400" ] [] , div [ styles.summaryTextContent ] [ h1 [ styles.headerPrimary ] [ text__ "Vladimir Logachev" ] , div [ css [ marginBottom (px 8) ] ] [ p [] [ text__ "Fullstack developer, FP enthusiast." ] , p [] [ text__ "Remote (Novosibirsk, Russia)" ] ] , a [ styles.link, css [ marginBottom (px 8) ], href "mailto: logachev.dev@ya.ru", targetBlank, noOpener ] [ text__ "logachev.dev@ya.ru" ] , div [ css [ displayFlex, marginBottom (px 8), mediaPrint [ flexDirection column ] ] ] [ span [ css [ mediaScreen [ display none ] ] ] [ printableLink "Site" "https://logachev.dev" ] , printableLink "GitHub" "https://github.com/vladimirlogachev" , printableLink "Telegram" "https://t.me/vladimirlogachev" , printableLink "Twitter" "https://twitter.com/logachev_dev" , printableLink "LinkedIn" "https://www.linkedin.com/in/vladimirlogachev" ] , div [ css [ marginBottom (px 8), mediaPrint [ display none ] ] ] [ a [ styles.link, href "https://logachev.dev/cv_vladimir_logachev.pdf", targetBlank, noOpener ] [ text__ "Download cv" ] ] ] ] -- Bio bioSection : Html msg bioSection = section [ styles.section ] [ h2 [ styles.subheader ] [ text__ "About me" ] , p [ css [ marginBottom (px 12) ] ] [ text__ "I prefer functional languages that implement strict static typing. I use Haskell, Elm, and Scala, but am also ready to tackle any other typed functional language." ] , p [ css [ marginBottom (px 12) ] ] [ text__ "I associate the success in my career with FP, so I devote a lot of time and attention not only to code but also to people. My mission as a developer is to make functional programming deliver value to both companies and individual specialists." ] , p [ css [ marginBottom (px 12) ] ] [ text__ "I'm a big fan of meetups and reading groups, which I run at my workplaces from time to time, and also I consider pair programming and pair testing to be an effective practice." ] , p [ css [ marginBottom (px 12) ] ] [ text__ "In programming, I prefer not to rely on intuition (which, I believe, is usually based on previous experiences and tends to fail in unprecedented situations), but instead, read books well in advance." ] -- , p [ css [ marginBottom (px 12) ] ] [ text__ "Although most of my commercial experience is in front-end development, I am looking for an opportunity to specialize in the backend and am not interested in job offers that involve doing tasks using JS / TS." ] ] -- Skills type alias Detail = { name : String, text : String } type alias SkillRecord = { icon : Maybe String , title : String , description : String , details : List Detail } skillRecords : List SkillRecord skillRecords = [ { icon = Just "haskell.svg" , title = "Haskell" , description = "" , details = [ { name = "Concepts" , text = "Monads, applicatives, monad transformers" } , { name = "Libraries" , text = "mu-hakell, postgres-typed, aeson, parsec, transformers, mtl, wai, servant" } , { name = "Language extensions" , text = "TypeApplications, TypeOperators, PartialTypeSignatures, DeriveFunctor, StandaloneDeriving, OverloadedStrings" } ] } , { icon = Just "scala.svg" , title = "Scala" , description = "" , details = [ { name = "FP" , text = "cats-core, cats-effect, fs2, scala-parser-combinators" } , { name = "Testing" , text = "scalatest, scalacheck, specs2" } , { name = "Other libraries" , text = "scodec, akka, akka-http, akka-stream, scala-parser-combinators" } ] } , { icon = Just "elm.svg" , title = "Elm" , description = "" , details = [ { name = "Concepts" , text = "Tasks, Ports, JSON encoding/decoding, Browser API Interop (Websockets)" } , { name = "Libraries" , text = "elm-css, elm-graphql, elm-ordering, elm-units, elm-dropbox, elm-crypto-string" } ] } , { icon = Nothing , title = "Other" , description = "" , details = [ { name = "Databases" , text = "PostgreSQL, Redis, Clickhouse, MongoDB" -- Kafka, Spark, Hazelcast } , { name = "Infrastructure and tooling" , text = "Docker, Dhall, GitHub Actions" -- Nix, NixOS, AmazonAWS, K8s } , { name = "APIs" , text = "GraphQL" -- gRPC, Auth0, OpenAPI, JWT, KeyCloak } ] } -- , { icon = Nothing -- , title = "Soft skills" -- , description = "" -- , details = -- [ { name = "" -- , text = "" -- } -- ] -- } ] showDetail : Detail -> Html msg showDetail x = div [] [ span [ css [ fromPx marginRight 6 ] ] [ text__ (x.name ++ ": ") ] , span [ styles.detail ] [ text__ x.text ] ] showSkillRecord : SkillRecord -> Html msg showSkillRecord x = div [ styles.itemBlock ] [ h3 [ styles.item, css [ displayFlex, alignItems center ] ] [ Maybe.map (\iconFile -> icon iconFile x.title) x.icon |> Maybe.withDefault (text__ "") , text__ x.title ] , span [] [ text__ x.description ] , div [] <| List.map showDetail x.details ] skillsSection : Html msg skillsSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Skills and usage experience" ] :: List.map showSkillRecord skillRecords) -- Showcase Projects type alias Project = { title : String , url : String , description : String , tags : String } showProject : Project -> Html msg showProject x = div [ styles.itemBlock ] [ a [ css [ mediaPrint [ color (hex "212121") ] ] , styles.item , styles.link , href x.url , targetBlank , noOpener ] [ text__ x.title ] , a [ css [ mediaScreen [ display none ] ] , styles.item , styles.link , href x.url , targetBlank , noOpener ] [ text__ x.url ] , span [] [ text__ x.description ] , span [ styles.detail ] [ text__ x.tags ] ] showcaseProjects : List Project showcaseProjects = [ -- { title = "Library CMS" -- , url = "https://github.com/VladimirLogachev/library" -- , description = "A GraphQL API and frontend for my personal offline library. Key feature: compile-time typecheck against both PostgreSQL and GraphQL schemas (both backend and frontend)." -- , tags = "Haskell, Elm, GraphQL, Mu-Haskell, postgres-typed, elm-graphql" -- } { title = "servant-to-elm example" , url = "https://github.com/VladimirLogachev/servant-to-elm-example" , description = """An example full-stack web application, built in a typesafe functional way. What's cool there is that servant-to-elm does the job of generating types and decoders/encoders from Haskell types and Servant definition to Elm, which not only catches regressions in the compile-time but also provides ready (and highly configurable) Elm functions to fetch necessary data from the server.""" , tags = "Elm, Haskell, Servant, SQLite" } , { title = "Transitive Closure (assessment)" , url = "https://github.com/VladimirLogachev/transitive_closure" , description = """A function that accepts list of object ids and returns those objects and all objects which they refer to (directly or indirectly) from some Repository with monadic interface. The code is pretty abstract, but still well-tested (including tests for cases like very large referencing graphs and cyclic references).""" , tags = "Scala, Cats, ScalaTest" } , { title = "Web crawler microservice (assessment)" , url = "https://github.com/VladimirLogachev/crawler" , description = """A microservice that accepts a list of page urls and returns a list of page titles. It takes into account situations like bad urls, duplicate urls, redirects, concurrency and backpressure.""" , tags = "Scala, Akka HTTP" } -- Meetup platform -- Captain Million -- Scalac-like assessment -- DataWorks-like assessment with tables -- CFT-like assessment ] showcaseProjectsSection : Html msg showcaseProjectsSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Showcase projects and assessments" ] :: List.map showProject showcaseProjects) -- Contributions contributionRecords : List Project contributionRecords = [ { title = "higherkindness/mu-graphql-example-elm" , url = "https://github.com/higherkindness/mu-graphql-example-elm" , description = "An example of how to implement both frontend and backend in a schema-first, typesafe, and functional way (for the mu-haskell library, demonstrating its GraphQL capabilities). I rebuilt its Elm frontend and made minor changes to Haskell backend (and also discovered a couple of bugs)." , tags = "Elm, Haskell, GraphQL" } , { title = "Russian translation of the Mostly Adequate Guide to Functional Programming in JavaScript" , url = "https://github.com/MostlyAdequate/mostly-adequate-guide-ru" , description = """The book introduces the reader to the functional programming paradigm and describes a functional approach to developing JavaScript applications. The translation was initiated by Maxim Filippov and stopped at 60%. Then me and Sakayama joined the translation, refactored every chapter translated before us and then finished the translation.""" , tags = "JavaScript" } , { title = "FP Specialty" , url = "https://fpspecialty.github.io" , description = "I lead a functional programming reading group for English speaking users of all functional programming skills." , tags = "Reading group" } ] contributionsSection : Html msg contributionsSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Notable contributions" ] :: List.map showProject contributionRecords) -- Education type alias EducationRecord = { title : String , url : String , details : String } educationRecords : List EducationRecord educationRecords = [ { title = "Mastering Haskell Programming" , url = "https://www.udemy.com/certificate/UC-DRMAMOQ5" , details = "Packt, 2019" } , { title = "Functional Programming in Haskell, part 2 (certificate with honors)" , url = "https://stepik.org/cert/207739" , details = "Computer Science Center, 2019" } , { title = "Functional Programming in Haskell, part 1 (certificate with honors)" , url = "https://stepik.org/cert/196007" , details = "Computer Science Center, 2019" } , { title = "Computer Science Summer School, Theory of Programming Languages" , url = "" , details = "Novosibirsk State University, 2019" } , { title = "Maintenance of computer equipment and computer networks" , url = "" , details = "Novosibirsk Aviation Technical College, 2004 — 2008" } ] showEducationRecord : EducationRecord -> Html msg showEducationRecord x = div [ styles.itemBlock ] [ span [ styles.item ] [ text__ x.title ] , a [ styles.link, href x.url, targetBlank, noOpener ] [ text__ x.url ] , span [ styles.detail ] [ text__ x.details ] ] educationSection : Html msg educationSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Education and courses" ] :: List.map showEducationRecord educationRecords) -- Experience type alias ExperienceRecord = { companyAndTitle : String , startDate : Date , endDate : Maybe Date , url : String , roleDescription : String , tags : String } showDate : Date -> String showDate d = (String.padLeft 2 '0' <| String.fromInt d.month) ++ "/" ++ (String.padLeft 4 '0' <| String.fromInt d.year) experienceRecords : List ExperienceRecord experienceRecords = [ { companyAndTitle = "Pamir, frontend developer" , startDate = Date 5 2020 , endDate = Just <| Date 12 2020 , url = "" , roleDescription = "Developed a web application, which utilizes server-side rendering and covered it with unit tests. Packaged everything in Docker and set up CI. I also mentored the second frontend developer who joined the team later." , tags = """Frontend: TypeScript, React, Next.js, GraphQL, Apollo, FP-TS, Emotion, Jest; Infrastructure: Nginx, Docker, GitHub Actions""" } , { companyAndTitle = "Eldis, software engineer" , startDate = Date 10 2019 , endDate = Just <| Date 12 2019 , url = "https://eldis.ru" , roleDescription = "I developed a declarative decoder for the internal binary document format, covered it with tests, including property-based testing." , tags = "Scala, scodec, cats, fs2, decline, specs2, scalacheck" } , { companyAndTitle = "Neolab-Nsk, fullstack developer" , startDate = Date 1 2019 , endDate = Just <| Date 9 2019 , url = "" , roleDescription = "I implemented new functionality in existing web applications, fixed defects and developed new applications, and microservices, covered them with unit tests and integration tests." , tags = """Frontend: TypeScript, React, Redux, Saga, RxJS, FP-TS; Backend: TypeScript, Node, Redux, Saga, RxJS, Redis, Lua, Mongo, PostgreSQL, Clickhouse, Docker""" } , { companyAndTitle = "SocialSweet Inc, frontend developer" , startDate = Date 8 2018 , endDate = Just <| Date 1 2019 , url = "https://sweet.io" , roleDescription = """Sweet's product is a loyalty platform, social network and online store. I performed tasks related to business logic at the front end and was engaged in covering the existing code with unit tests and tuning them, thanks to which the tests were launched using CI pipeline, and the defects associated with an unsuccessful merging of Git branches in a huge codebase really began to be prevented.""" , tags = "TypeScript, Angular, RxJS" } , { companyAndTitle = "Allmax, frontend developer" , startDate = Date 11 2017 , endDate = Just <| Date 8 2018 , url = "https://savl.com/" , roleDescription = """I worked in the Savl project — this is a mobile application, wallet with support for 6 cryptocurrencies. I was responsible for the data layer in the mobile application. I applied everything that I learned from books about functional programming and software design, and also completely covered the business logic with tests, as a result of which the application became fault-tolerant and modular, that is, it stopped crashing due to exceptions or unexpected behavior of external services, and allowed to enable and disable support for individual cryptocurrencies at any time. Also inside the company, I made several presentations on functional programming.""" , tags = "JavaScript, Flow, React Native, Redux, Saga, Ramda, Sanctuary, Socket.io" } ] showExperienceRecord : ExperienceRecord -> Html msg showExperienceRecord x = div [ styles.itemBlock ] [ span [ styles.item ] [ text__ x.companyAndTitle , span [ styles.period ] [ text__ (showDate x.startDate ++ " — " ++ (x.endDate |> Maybe.map showDate |> Maybe.withDefault "present") ) ] ] , a [ styles.link, href x.url, targetBlank, noOpener ] [ text__ x.url ] , span [] [ text__ x.roleDescription ] , span [ styles.detail ] [ text__ x.tags ] ] experienceSection : Html msg experienceSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Experience" ] :: List.map showExperienceRecord experienceRecords ) -- Reusable stuff type alias Date = { month : Int, year : Int } mobileBreakpoint : Float mobileBreakpoint = 600 mediaMobile : List Style -> Style mediaMobile = withMedia [ only screen [ Media.maxWidth (px (mobileBreakpoint - 1)) ] ] mediaDesktop : List Style -> Style mediaDesktop = withMedia [ only screen [ Media.minWidth (px mobileBreakpoint) ] ] mediaScreen : List Style -> Style mediaScreen = withMedia [ only screen [] ] mediaPrint : List Style -> Style mediaPrint = withMedia [ only print [] ] noOpener : Html.Styled.Attribute msg noOpener = attribute "rel" "noopener noreferrer" targetBlank : Html.Styled.Attribute msg targetBlank = Attributes.target "_blank" -- Print specific screenMultiplier : Float screenMultiplier = 0.75 printMultiplier : Float printMultiplier = 1.18 {-| Convert pixels (like in figma) to both screen- and print-friendly units -} fromPx : (Pt -> Style) -> Int -> Style fromPx f pixels = batch [ mediaScreen [ f <| pt (toFloat pixels * screenMultiplier) ] , mediaPrint [ f <| pt (toFloat pixels * printMultiplier) ] ]
35531
module Cv exposing (view) import Css exposing (..) import Css.Media as Media exposing (only, print, screen, withMedia) import Html.Styled exposing (..) import Html.Styled.Attributes as Attributes exposing (alt, attribute, css, href, src, title) import Typography exposing (text__) styles = { page = css [ margin2 zero auto , fontFamilies [ "Source Sans Pro", "sans-serif" ] , fontStyle normal , color (hex "212121") , fontWeight normal , fromPx fontSize 16 , fromPx lineHeight 20 , mediaScreen [ maxWidth (px 768), padding4 (px 40) (px 16) (px 40) (px 16) ] , mediaPrint [ padding zero ] ] , itemBlock = css [ displayFlex , flexDirection column , marginBottom (px 28) , property "break-inside" "avoid" , firstOfType [ property "break-before" "avoid" ] ] , section = css [ marginBottom (px 60) ] , summary = css [ displayFlex , mediaMobile [ flexDirection column ] , marginBottom (px 40) ] , summaryTextContent = css [ displayFlex , flexDirection column , mediaDesktop [ fromPx marginLeft 32 ] , mediaMobile [ important <| marginLeft zero, marginTop (px 24) ] ] , photo = css [ fromPx width 200 , fromPx height 200 , borderRadius (px 8) , backgroundColor (hex "efefef") ] -- Text styles , headerPrimary = css [ fontWeight bold , fromPx fontSize 32 , fromPx lineHeight 40 , marginBottom (px 12) ] , subheader = css [ fontWeight bold , fromPx fontSize 24 , fromPx lineHeight 30 , marginBottom (px 20) , property "break-after" "avoid" ] , item = css [ fontWeight normal , fromPx fontSize 20 , fromPx lineHeight 25 , marginBottom (px 8) ] , link = css [ color (hex "0d7da9") , textDecoration none ] , period = css [ fontWeight normal , fromPx fontSize 20 , fromPx lineHeight 25 , color (hex "707070") , marginLeft (px 12) ] , detail = css [ color (hex "707070") ] } {- TODO: - выпилить все размеры в px, поресёрчить способ фиксирования размера поинта для разных медиа. Цель - просто задавать число в поинтах, желательно равное числу пикселей на десктопе, и получать абсолютно такой же выход на печати. Альтернативный вариант - возвращать record (но это сильно замарает код). - убрать important - перенос тегов на новую строку - явные height и width для изображений, мультисорс, alt - пустые ссылки сделать maybe - дрочкануть lighthouse - длинные ссылки выбиваются за пределы мобильного холста - обозначить софт скиллы - обозначить долгосрочные профессиональные цели -} view : Html msg view = div [ styles.page ] [ summarySection , bioSection , skillsSection , showcaseProjectsSection , contributionsSection , educationSection , experienceSection ] -- Summary printableLink : String -> String -> Html msg printableLink title url = span [] [ span [ css [ marginRight (px 12), mediaPrint [ display none ] ] ] [ a [ styles.link, href url, targetBlank, noOpener ] [ text__ title ] ] , span [ css [ mediaScreen [ display none ] ] ] [ span [ css [ fromPx marginRight 6 ] ] [ text__ <| title ++ ":" ] , a [ styles.link, href url, targetBlank, noOpener ] [ text__ url ] ] ] icon : String -> String -> Html msg icon filename altText = img [ css [ height (px 28), marginRight (px 10) ] , src <| "/logos/" ++ filename , alt altText , title altText ] [] summarySection : Html msg summarySection = div [ styles.summary ] [ img [ styles.photo, src "https://avatars2.githubusercontent.com/u/17773003?s=400" ] [] , div [ styles.summaryTextContent ] [ h1 [ styles.headerPrimary ] [ text__ "<NAME>" ] , div [ css [ marginBottom (px 8) ] ] [ p [] [ text__ "Fullstack developer, FP enthusiast." ] , p [] [ text__ "Remote (Novosibirsk, Russia)" ] ] , a [ styles.link, css [ marginBottom (px 8) ], href "mailto: <EMAIL>", targetBlank, noOpener ] [ text__ "<EMAIL>" ] , div [ css [ displayFlex, marginBottom (px 8), mediaPrint [ flexDirection column ] ] ] [ span [ css [ mediaScreen [ display none ] ] ] [ printableLink "Site" "https://logachev.dev" ] , printableLink "GitHub" "https://github.com/vladimirlogachev" , printableLink "Telegram" "https://t.me/vladimirlogachev" , printableLink "Twitter" "https://twitter.com/logachev_dev" , printableLink "LinkedIn" "https://www.linkedin.com/in/vladimirlogachev" ] , div [ css [ marginBottom (px 8), mediaPrint [ display none ] ] ] [ a [ styles.link, href "https://logachev.dev/cv_vladimir_logachev.pdf", targetBlank, noOpener ] [ text__ "Download cv" ] ] ] ] -- Bio bioSection : Html msg bioSection = section [ styles.section ] [ h2 [ styles.subheader ] [ text__ "About me" ] , p [ css [ marginBottom (px 12) ] ] [ text__ "I prefer functional languages that implement strict static typing. I use Haskell, Elm, and Scala, but am also ready to tackle any other typed functional language." ] , p [ css [ marginBottom (px 12) ] ] [ text__ "I associate the success in my career with FP, so I devote a lot of time and attention not only to code but also to people. My mission as a developer is to make functional programming deliver value to both companies and individual specialists." ] , p [ css [ marginBottom (px 12) ] ] [ text__ "I'm a big fan of meetups and reading groups, which I run at my workplaces from time to time, and also I consider pair programming and pair testing to be an effective practice." ] , p [ css [ marginBottom (px 12) ] ] [ text__ "In programming, I prefer not to rely on intuition (which, I believe, is usually based on previous experiences and tends to fail in unprecedented situations), but instead, read books well in advance." ] -- , p [ css [ marginBottom (px 12) ] ] [ text__ "Although most of my commercial experience is in front-end development, I am looking for an opportunity to specialize in the backend and am not interested in job offers that involve doing tasks using JS / TS." ] ] -- Skills type alias Detail = { name : String, text : String } type alias SkillRecord = { icon : Maybe String , title : String , description : String , details : List Detail } skillRecords : List SkillRecord skillRecords = [ { icon = Just "haskell.svg" , title = "Haskell" , description = "" , details = [ { name = "Concepts" , text = "Monads, applicatives, monad transformers" } , { name = "Libraries" , text = "mu-hakell, postgres-typed, aeson, parsec, transformers, mtl, wai, servant" } , { name = "Language extensions" , text = "TypeApplications, TypeOperators, PartialTypeSignatures, DeriveFunctor, StandaloneDeriving, OverloadedStrings" } ] } , { icon = Just "scala.svg" , title = "Scala" , description = "" , details = [ { name = "FP" , text = "cats-core, cats-effect, fs2, scala-parser-combinators" } , { name = "Testing" , text = "scalatest, scalacheck, specs2" } , { name = "Other libraries" , text = "scodec, akka, akka-http, akka-stream, scala-parser-combinators" } ] } , { icon = Just "elm.svg" , title = "Elm" , description = "" , details = [ { name = "Concepts" , text = "Tasks, Ports, JSON encoding/decoding, Browser API Interop (Websockets)" } , { name = "Libraries" , text = "elm-css, elm-graphql, elm-ordering, elm-units, elm-dropbox, elm-crypto-string" } ] } , { icon = Nothing , title = "Other" , description = "" , details = [ { name = "Databases" , text = "PostgreSQL, Redis, Clickhouse, MongoDB" -- Kafka, Spark, Hazelcast } , { name = "Infrastructure and tooling" , text = "Docker, Dhall, GitHub Actions" -- Nix, NixOS, AmazonAWS, K8s } , { name = "APIs" , text = "GraphQL" -- gRPC, Auth0, OpenAPI, JWT, KeyCloak } ] } -- , { icon = Nothing -- , title = "Soft skills" -- , description = "" -- , details = -- [ { name = "" -- , text = "" -- } -- ] -- } ] showDetail : Detail -> Html msg showDetail x = div [] [ span [ css [ fromPx marginRight 6 ] ] [ text__ (x.name ++ ": ") ] , span [ styles.detail ] [ text__ x.text ] ] showSkillRecord : SkillRecord -> Html msg showSkillRecord x = div [ styles.itemBlock ] [ h3 [ styles.item, css [ displayFlex, alignItems center ] ] [ Maybe.map (\iconFile -> icon iconFile x.title) x.icon |> Maybe.withDefault (text__ "") , text__ x.title ] , span [] [ text__ x.description ] , div [] <| List.map showDetail x.details ] skillsSection : Html msg skillsSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Skills and usage experience" ] :: List.map showSkillRecord skillRecords) -- Showcase Projects type alias Project = { title : String , url : String , description : String , tags : String } showProject : Project -> Html msg showProject x = div [ styles.itemBlock ] [ a [ css [ mediaPrint [ color (hex "212121") ] ] , styles.item , styles.link , href x.url , targetBlank , noOpener ] [ text__ x.title ] , a [ css [ mediaScreen [ display none ] ] , styles.item , styles.link , href x.url , targetBlank , noOpener ] [ text__ x.url ] , span [] [ text__ x.description ] , span [ styles.detail ] [ text__ x.tags ] ] showcaseProjects : List Project showcaseProjects = [ -- { title = "Library CMS" -- , url = "https://github.com/VladimirLogachev/library" -- , description = "A GraphQL API and frontend for my personal offline library. Key feature: compile-time typecheck against both PostgreSQL and GraphQL schemas (both backend and frontend)." -- , tags = "Haskell, Elm, GraphQL, Mu-Haskell, postgres-typed, elm-graphql" -- } { title = "servant-to-elm example" , url = "https://github.com/VladimirLogachev/servant-to-elm-example" , description = """An example full-stack web application, built in a typesafe functional way. What's cool there is that servant-to-elm does the job of generating types and decoders/encoders from Haskell types and Servant definition to Elm, which not only catches regressions in the compile-time but also provides ready (and highly configurable) Elm functions to fetch necessary data from the server.""" , tags = "Elm, Haskell, Servant, SQLite" } , { title = "Transitive Closure (assessment)" , url = "https://github.com/VladimirLogachev/transitive_closure" , description = """A function that accepts list of object ids and returns those objects and all objects which they refer to (directly or indirectly) from some Repository with monadic interface. The code is pretty abstract, but still well-tested (including tests for cases like very large referencing graphs and cyclic references).""" , tags = "Scala, Cats, ScalaTest" } , { title = "Web crawler microservice (assessment)" , url = "https://github.com/VladimirLogachev/crawler" , description = """A microservice that accepts a list of page urls and returns a list of page titles. It takes into account situations like bad urls, duplicate urls, redirects, concurrency and backpressure.""" , tags = "Scala, Akka HTTP" } -- Meetup platform -- Captain Million -- Scalac-like assessment -- DataWorks-like assessment with tables -- CFT-like assessment ] showcaseProjectsSection : Html msg showcaseProjectsSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Showcase projects and assessments" ] :: List.map showProject showcaseProjects) -- Contributions contributionRecords : List Project contributionRecords = [ { title = "higherkindness/mu-graphql-example-elm" , url = "https://github.com/higherkindness/mu-graphql-example-elm" , description = "An example of how to implement both frontend and backend in a schema-first, typesafe, and functional way (for the mu-haskell library, demonstrating its GraphQL capabilities). I rebuilt its Elm frontend and made minor changes to Haskell backend (and also discovered a couple of bugs)." , tags = "Elm, Haskell, GraphQL" } , { title = "Russian translation of the Mostly Adequate Guide to Functional Programming in JavaScript" , url = "https://github.com/MostlyAdequate/mostly-adequate-guide-ru" , description = """The book introduces the reader to the functional programming paradigm and describes a functional approach to developing JavaScript applications. The translation was initiated by <NAME> and stopped at 60%. Then me and Sakayama joined the translation, refactored every chapter translated before us and then finished the translation.""" , tags = "JavaScript" } , { title = "FP Specialty" , url = "https://fpspecialty.github.io" , description = "I lead a functional programming reading group for English speaking users of all functional programming skills." , tags = "Reading group" } ] contributionsSection : Html msg contributionsSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Notable contributions" ] :: List.map showProject contributionRecords) -- Education type alias EducationRecord = { title : String , url : String , details : String } educationRecords : List EducationRecord educationRecords = [ { title = "Mastering Haskell Programming" , url = "https://www.udemy.com/certificate/UC-DRMAMOQ5" , details = "Packt, 2019" } , { title = "Functional Programming in Haskell, part 2 (certificate with honors)" , url = "https://stepik.org/cert/207739" , details = "Computer Science Center, 2019" } , { title = "Functional Programming in Haskell, part 1 (certificate with honors)" , url = "https://stepik.org/cert/196007" , details = "Computer Science Center, 2019" } , { title = "Computer Science Summer School, Theory of Programming Languages" , url = "" , details = "Novosibirsk State University, 2019" } , { title = "Maintenance of computer equipment and computer networks" , url = "" , details = "Novosibirsk Aviation Technical College, 2004 — 2008" } ] showEducationRecord : EducationRecord -> Html msg showEducationRecord x = div [ styles.itemBlock ] [ span [ styles.item ] [ text__ x.title ] , a [ styles.link, href x.url, targetBlank, noOpener ] [ text__ x.url ] , span [ styles.detail ] [ text__ x.details ] ] educationSection : Html msg educationSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Education and courses" ] :: List.map showEducationRecord educationRecords) -- Experience type alias ExperienceRecord = { companyAndTitle : String , startDate : Date , endDate : Maybe Date , url : String , roleDescription : String , tags : String } showDate : Date -> String showDate d = (String.padLeft 2 '0' <| String.fromInt d.month) ++ "/" ++ (String.padLeft 4 '0' <| String.fromInt d.year) experienceRecords : List ExperienceRecord experienceRecords = [ { companyAndTitle = "<NAME>ir, frontend developer" , startDate = Date 5 2020 , endDate = Just <| Date 12 2020 , url = "" , roleDescription = "Developed a web application, which utilizes server-side rendering and covered it with unit tests. Packaged everything in Docker and set up CI. I also mentored the second frontend developer who joined the team later." , tags = """Frontend: TypeScript, React, Next.js, GraphQL, Apollo, FP-TS, Emotion, Jest; Infrastructure: Nginx, Docker, GitHub Actions""" } , { companyAndTitle = "Eldis, software engineer" , startDate = Date 10 2019 , endDate = Just <| Date 12 2019 , url = "https://eldis.ru" , roleDescription = "I developed a declarative decoder for the internal binary document format, covered it with tests, including property-based testing." , tags = "Scala, scodec, cats, fs2, decline, specs2, scalacheck" } , { companyAndTitle = "Neolab-Nsk, fullstack developer" , startDate = Date 1 2019 , endDate = Just <| Date 9 2019 , url = "" , roleDescription = "I implemented new functionality in existing web applications, fixed defects and developed new applications, and microservices, covered them with unit tests and integration tests." , tags = """Frontend: TypeScript, React, Redux, Saga, RxJS, FP-TS; Backend: TypeScript, Node, Redux, Saga, RxJS, Redis, Lua, Mongo, PostgreSQL, Clickhouse, Docker""" } , { companyAndTitle = "SocialSweet Inc, frontend developer" , startDate = Date 8 2018 , endDate = Just <| Date 1 2019 , url = "https://sweet.io" , roleDescription = """Sweet's product is a loyalty platform, social network and online store. I performed tasks related to business logic at the front end and was engaged in covering the existing code with unit tests and tuning them, thanks to which the tests were launched using CI pipeline, and the defects associated with an unsuccessful merging of Git branches in a huge codebase really began to be prevented.""" , tags = "TypeScript, Angular, RxJS" } , { companyAndTitle = "Allmax, frontend developer" , startDate = Date 11 2017 , endDate = Just <| Date 8 2018 , url = "https://savl.com/" , roleDescription = """I worked in the Savl project — this is a mobile application, wallet with support for 6 cryptocurrencies. I was responsible for the data layer in the mobile application. I applied everything that I learned from books about functional programming and software design, and also completely covered the business logic with tests, as a result of which the application became fault-tolerant and modular, that is, it stopped crashing due to exceptions or unexpected behavior of external services, and allowed to enable and disable support for individual cryptocurrencies at any time. Also inside the company, I made several presentations on functional programming.""" , tags = "JavaScript, Flow, React Native, Redux, Saga, Ramda, Sanctuary, Socket.io" } ] showExperienceRecord : ExperienceRecord -> Html msg showExperienceRecord x = div [ styles.itemBlock ] [ span [ styles.item ] [ text__ x.companyAndTitle , span [ styles.period ] [ text__ (showDate x.startDate ++ " — " ++ (x.endDate |> Maybe.map showDate |> Maybe.withDefault "present") ) ] ] , a [ styles.link, href x.url, targetBlank, noOpener ] [ text__ x.url ] , span [] [ text__ x.roleDescription ] , span [ styles.detail ] [ text__ x.tags ] ] experienceSection : Html msg experienceSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Experience" ] :: List.map showExperienceRecord experienceRecords ) -- Reusable stuff type alias Date = { month : Int, year : Int } mobileBreakpoint : Float mobileBreakpoint = 600 mediaMobile : List Style -> Style mediaMobile = withMedia [ only screen [ Media.maxWidth (px (mobileBreakpoint - 1)) ] ] mediaDesktop : List Style -> Style mediaDesktop = withMedia [ only screen [ Media.minWidth (px mobileBreakpoint) ] ] mediaScreen : List Style -> Style mediaScreen = withMedia [ only screen [] ] mediaPrint : List Style -> Style mediaPrint = withMedia [ only print [] ] noOpener : Html.Styled.Attribute msg noOpener = attribute "rel" "noopener noreferrer" targetBlank : Html.Styled.Attribute msg targetBlank = Attributes.target "_blank" -- Print specific screenMultiplier : Float screenMultiplier = 0.75 printMultiplier : Float printMultiplier = 1.18 {-| Convert pixels (like in figma) to both screen- and print-friendly units -} fromPx : (Pt -> Style) -> Int -> Style fromPx f pixels = batch [ mediaScreen [ f <| pt (toFloat pixels * screenMultiplier) ] , mediaPrint [ f <| pt (toFloat pixels * printMultiplier) ] ]
true
module Cv exposing (view) import Css exposing (..) import Css.Media as Media exposing (only, print, screen, withMedia) import Html.Styled exposing (..) import Html.Styled.Attributes as Attributes exposing (alt, attribute, css, href, src, title) import Typography exposing (text__) styles = { page = css [ margin2 zero auto , fontFamilies [ "Source Sans Pro", "sans-serif" ] , fontStyle normal , color (hex "212121") , fontWeight normal , fromPx fontSize 16 , fromPx lineHeight 20 , mediaScreen [ maxWidth (px 768), padding4 (px 40) (px 16) (px 40) (px 16) ] , mediaPrint [ padding zero ] ] , itemBlock = css [ displayFlex , flexDirection column , marginBottom (px 28) , property "break-inside" "avoid" , firstOfType [ property "break-before" "avoid" ] ] , section = css [ marginBottom (px 60) ] , summary = css [ displayFlex , mediaMobile [ flexDirection column ] , marginBottom (px 40) ] , summaryTextContent = css [ displayFlex , flexDirection column , mediaDesktop [ fromPx marginLeft 32 ] , mediaMobile [ important <| marginLeft zero, marginTop (px 24) ] ] , photo = css [ fromPx width 200 , fromPx height 200 , borderRadius (px 8) , backgroundColor (hex "efefef") ] -- Text styles , headerPrimary = css [ fontWeight bold , fromPx fontSize 32 , fromPx lineHeight 40 , marginBottom (px 12) ] , subheader = css [ fontWeight bold , fromPx fontSize 24 , fromPx lineHeight 30 , marginBottom (px 20) , property "break-after" "avoid" ] , item = css [ fontWeight normal , fromPx fontSize 20 , fromPx lineHeight 25 , marginBottom (px 8) ] , link = css [ color (hex "0d7da9") , textDecoration none ] , period = css [ fontWeight normal , fromPx fontSize 20 , fromPx lineHeight 25 , color (hex "707070") , marginLeft (px 12) ] , detail = css [ color (hex "707070") ] } {- TODO: - выпилить все размеры в px, поресёрчить способ фиксирования размера поинта для разных медиа. Цель - просто задавать число в поинтах, желательно равное числу пикселей на десктопе, и получать абсолютно такой же выход на печати. Альтернативный вариант - возвращать record (но это сильно замарает код). - убрать important - перенос тегов на новую строку - явные height и width для изображений, мультисорс, alt - пустые ссылки сделать maybe - дрочкануть lighthouse - длинные ссылки выбиваются за пределы мобильного холста - обозначить софт скиллы - обозначить долгосрочные профессиональные цели -} view : Html msg view = div [ styles.page ] [ summarySection , bioSection , skillsSection , showcaseProjectsSection , contributionsSection , educationSection , experienceSection ] -- Summary printableLink : String -> String -> Html msg printableLink title url = span [] [ span [ css [ marginRight (px 12), mediaPrint [ display none ] ] ] [ a [ styles.link, href url, targetBlank, noOpener ] [ text__ title ] ] , span [ css [ mediaScreen [ display none ] ] ] [ span [ css [ fromPx marginRight 6 ] ] [ text__ <| title ++ ":" ] , a [ styles.link, href url, targetBlank, noOpener ] [ text__ url ] ] ] icon : String -> String -> Html msg icon filename altText = img [ css [ height (px 28), marginRight (px 10) ] , src <| "/logos/" ++ filename , alt altText , title altText ] [] summarySection : Html msg summarySection = div [ styles.summary ] [ img [ styles.photo, src "https://avatars2.githubusercontent.com/u/17773003?s=400" ] [] , div [ styles.summaryTextContent ] [ h1 [ styles.headerPrimary ] [ text__ "PI:NAME:<NAME>END_PI" ] , div [ css [ marginBottom (px 8) ] ] [ p [] [ text__ "Fullstack developer, FP enthusiast." ] , p [] [ text__ "Remote (Novosibirsk, Russia)" ] ] , a [ styles.link, css [ marginBottom (px 8) ], href "mailto: PI:EMAIL:<EMAIL>END_PI", targetBlank, noOpener ] [ text__ "PI:EMAIL:<EMAIL>END_PI" ] , div [ css [ displayFlex, marginBottom (px 8), mediaPrint [ flexDirection column ] ] ] [ span [ css [ mediaScreen [ display none ] ] ] [ printableLink "Site" "https://logachev.dev" ] , printableLink "GitHub" "https://github.com/vladimirlogachev" , printableLink "Telegram" "https://t.me/vladimirlogachev" , printableLink "Twitter" "https://twitter.com/logachev_dev" , printableLink "LinkedIn" "https://www.linkedin.com/in/vladimirlogachev" ] , div [ css [ marginBottom (px 8), mediaPrint [ display none ] ] ] [ a [ styles.link, href "https://logachev.dev/cv_vladimir_logachev.pdf", targetBlank, noOpener ] [ text__ "Download cv" ] ] ] ] -- Bio bioSection : Html msg bioSection = section [ styles.section ] [ h2 [ styles.subheader ] [ text__ "About me" ] , p [ css [ marginBottom (px 12) ] ] [ text__ "I prefer functional languages that implement strict static typing. I use Haskell, Elm, and Scala, but am also ready to tackle any other typed functional language." ] , p [ css [ marginBottom (px 12) ] ] [ text__ "I associate the success in my career with FP, so I devote a lot of time and attention not only to code but also to people. My mission as a developer is to make functional programming deliver value to both companies and individual specialists." ] , p [ css [ marginBottom (px 12) ] ] [ text__ "I'm a big fan of meetups and reading groups, which I run at my workplaces from time to time, and also I consider pair programming and pair testing to be an effective practice." ] , p [ css [ marginBottom (px 12) ] ] [ text__ "In programming, I prefer not to rely on intuition (which, I believe, is usually based on previous experiences and tends to fail in unprecedented situations), but instead, read books well in advance." ] -- , p [ css [ marginBottom (px 12) ] ] [ text__ "Although most of my commercial experience is in front-end development, I am looking for an opportunity to specialize in the backend and am not interested in job offers that involve doing tasks using JS / TS." ] ] -- Skills type alias Detail = { name : String, text : String } type alias SkillRecord = { icon : Maybe String , title : String , description : String , details : List Detail } skillRecords : List SkillRecord skillRecords = [ { icon = Just "haskell.svg" , title = "Haskell" , description = "" , details = [ { name = "Concepts" , text = "Monads, applicatives, monad transformers" } , { name = "Libraries" , text = "mu-hakell, postgres-typed, aeson, parsec, transformers, mtl, wai, servant" } , { name = "Language extensions" , text = "TypeApplications, TypeOperators, PartialTypeSignatures, DeriveFunctor, StandaloneDeriving, OverloadedStrings" } ] } , { icon = Just "scala.svg" , title = "Scala" , description = "" , details = [ { name = "FP" , text = "cats-core, cats-effect, fs2, scala-parser-combinators" } , { name = "Testing" , text = "scalatest, scalacheck, specs2" } , { name = "Other libraries" , text = "scodec, akka, akka-http, akka-stream, scala-parser-combinators" } ] } , { icon = Just "elm.svg" , title = "Elm" , description = "" , details = [ { name = "Concepts" , text = "Tasks, Ports, JSON encoding/decoding, Browser API Interop (Websockets)" } , { name = "Libraries" , text = "elm-css, elm-graphql, elm-ordering, elm-units, elm-dropbox, elm-crypto-string" } ] } , { icon = Nothing , title = "Other" , description = "" , details = [ { name = "Databases" , text = "PostgreSQL, Redis, Clickhouse, MongoDB" -- Kafka, Spark, Hazelcast } , { name = "Infrastructure and tooling" , text = "Docker, Dhall, GitHub Actions" -- Nix, NixOS, AmazonAWS, K8s } , { name = "APIs" , text = "GraphQL" -- gRPC, Auth0, OpenAPI, JWT, KeyCloak } ] } -- , { icon = Nothing -- , title = "Soft skills" -- , description = "" -- , details = -- [ { name = "" -- , text = "" -- } -- ] -- } ] showDetail : Detail -> Html msg showDetail x = div [] [ span [ css [ fromPx marginRight 6 ] ] [ text__ (x.name ++ ": ") ] , span [ styles.detail ] [ text__ x.text ] ] showSkillRecord : SkillRecord -> Html msg showSkillRecord x = div [ styles.itemBlock ] [ h3 [ styles.item, css [ displayFlex, alignItems center ] ] [ Maybe.map (\iconFile -> icon iconFile x.title) x.icon |> Maybe.withDefault (text__ "") , text__ x.title ] , span [] [ text__ x.description ] , div [] <| List.map showDetail x.details ] skillsSection : Html msg skillsSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Skills and usage experience" ] :: List.map showSkillRecord skillRecords) -- Showcase Projects type alias Project = { title : String , url : String , description : String , tags : String } showProject : Project -> Html msg showProject x = div [ styles.itemBlock ] [ a [ css [ mediaPrint [ color (hex "212121") ] ] , styles.item , styles.link , href x.url , targetBlank , noOpener ] [ text__ x.title ] , a [ css [ mediaScreen [ display none ] ] , styles.item , styles.link , href x.url , targetBlank , noOpener ] [ text__ x.url ] , span [] [ text__ x.description ] , span [ styles.detail ] [ text__ x.tags ] ] showcaseProjects : List Project showcaseProjects = [ -- { title = "Library CMS" -- , url = "https://github.com/VladimirLogachev/library" -- , description = "A GraphQL API and frontend for my personal offline library. Key feature: compile-time typecheck against both PostgreSQL and GraphQL schemas (both backend and frontend)." -- , tags = "Haskell, Elm, GraphQL, Mu-Haskell, postgres-typed, elm-graphql" -- } { title = "servant-to-elm example" , url = "https://github.com/VladimirLogachev/servant-to-elm-example" , description = """An example full-stack web application, built in a typesafe functional way. What's cool there is that servant-to-elm does the job of generating types and decoders/encoders from Haskell types and Servant definition to Elm, which not only catches regressions in the compile-time but also provides ready (and highly configurable) Elm functions to fetch necessary data from the server.""" , tags = "Elm, Haskell, Servant, SQLite" } , { title = "Transitive Closure (assessment)" , url = "https://github.com/VladimirLogachev/transitive_closure" , description = """A function that accepts list of object ids and returns those objects and all objects which they refer to (directly or indirectly) from some Repository with monadic interface. The code is pretty abstract, but still well-tested (including tests for cases like very large referencing graphs and cyclic references).""" , tags = "Scala, Cats, ScalaTest" } , { title = "Web crawler microservice (assessment)" , url = "https://github.com/VladimirLogachev/crawler" , description = """A microservice that accepts a list of page urls and returns a list of page titles. It takes into account situations like bad urls, duplicate urls, redirects, concurrency and backpressure.""" , tags = "Scala, Akka HTTP" } -- Meetup platform -- Captain Million -- Scalac-like assessment -- DataWorks-like assessment with tables -- CFT-like assessment ] showcaseProjectsSection : Html msg showcaseProjectsSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Showcase projects and assessments" ] :: List.map showProject showcaseProjects) -- Contributions contributionRecords : List Project contributionRecords = [ { title = "higherkindness/mu-graphql-example-elm" , url = "https://github.com/higherkindness/mu-graphql-example-elm" , description = "An example of how to implement both frontend and backend in a schema-first, typesafe, and functional way (for the mu-haskell library, demonstrating its GraphQL capabilities). I rebuilt its Elm frontend and made minor changes to Haskell backend (and also discovered a couple of bugs)." , tags = "Elm, Haskell, GraphQL" } , { title = "Russian translation of the Mostly Adequate Guide to Functional Programming in JavaScript" , url = "https://github.com/MostlyAdequate/mostly-adequate-guide-ru" , description = """The book introduces the reader to the functional programming paradigm and describes a functional approach to developing JavaScript applications. The translation was initiated by PI:NAME:<NAME>END_PI and stopped at 60%. Then me and Sakayama joined the translation, refactored every chapter translated before us and then finished the translation.""" , tags = "JavaScript" } , { title = "FP Specialty" , url = "https://fpspecialty.github.io" , description = "I lead a functional programming reading group for English speaking users of all functional programming skills." , tags = "Reading group" } ] contributionsSection : Html msg contributionsSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Notable contributions" ] :: List.map showProject contributionRecords) -- Education type alias EducationRecord = { title : String , url : String , details : String } educationRecords : List EducationRecord educationRecords = [ { title = "Mastering Haskell Programming" , url = "https://www.udemy.com/certificate/UC-DRMAMOQ5" , details = "Packt, 2019" } , { title = "Functional Programming in Haskell, part 2 (certificate with honors)" , url = "https://stepik.org/cert/207739" , details = "Computer Science Center, 2019" } , { title = "Functional Programming in Haskell, part 1 (certificate with honors)" , url = "https://stepik.org/cert/196007" , details = "Computer Science Center, 2019" } , { title = "Computer Science Summer School, Theory of Programming Languages" , url = "" , details = "Novosibirsk State University, 2019" } , { title = "Maintenance of computer equipment and computer networks" , url = "" , details = "Novosibirsk Aviation Technical College, 2004 — 2008" } ] showEducationRecord : EducationRecord -> Html msg showEducationRecord x = div [ styles.itemBlock ] [ span [ styles.item ] [ text__ x.title ] , a [ styles.link, href x.url, targetBlank, noOpener ] [ text__ x.url ] , span [ styles.detail ] [ text__ x.details ] ] educationSection : Html msg educationSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Education and courses" ] :: List.map showEducationRecord educationRecords) -- Experience type alias ExperienceRecord = { companyAndTitle : String , startDate : Date , endDate : Maybe Date , url : String , roleDescription : String , tags : String } showDate : Date -> String showDate d = (String.padLeft 2 '0' <| String.fromInt d.month) ++ "/" ++ (String.padLeft 4 '0' <| String.fromInt d.year) experienceRecords : List ExperienceRecord experienceRecords = [ { companyAndTitle = "PI:NAME:<NAME>END_PIir, frontend developer" , startDate = Date 5 2020 , endDate = Just <| Date 12 2020 , url = "" , roleDescription = "Developed a web application, which utilizes server-side rendering and covered it with unit tests. Packaged everything in Docker and set up CI. I also mentored the second frontend developer who joined the team later." , tags = """Frontend: TypeScript, React, Next.js, GraphQL, Apollo, FP-TS, Emotion, Jest; Infrastructure: Nginx, Docker, GitHub Actions""" } , { companyAndTitle = "Eldis, software engineer" , startDate = Date 10 2019 , endDate = Just <| Date 12 2019 , url = "https://eldis.ru" , roleDescription = "I developed a declarative decoder for the internal binary document format, covered it with tests, including property-based testing." , tags = "Scala, scodec, cats, fs2, decline, specs2, scalacheck" } , { companyAndTitle = "Neolab-Nsk, fullstack developer" , startDate = Date 1 2019 , endDate = Just <| Date 9 2019 , url = "" , roleDescription = "I implemented new functionality in existing web applications, fixed defects and developed new applications, and microservices, covered them with unit tests and integration tests." , tags = """Frontend: TypeScript, React, Redux, Saga, RxJS, FP-TS; Backend: TypeScript, Node, Redux, Saga, RxJS, Redis, Lua, Mongo, PostgreSQL, Clickhouse, Docker""" } , { companyAndTitle = "SocialSweet Inc, frontend developer" , startDate = Date 8 2018 , endDate = Just <| Date 1 2019 , url = "https://sweet.io" , roleDescription = """Sweet's product is a loyalty platform, social network and online store. I performed tasks related to business logic at the front end and was engaged in covering the existing code with unit tests and tuning them, thanks to which the tests were launched using CI pipeline, and the defects associated with an unsuccessful merging of Git branches in a huge codebase really began to be prevented.""" , tags = "TypeScript, Angular, RxJS" } , { companyAndTitle = "Allmax, frontend developer" , startDate = Date 11 2017 , endDate = Just <| Date 8 2018 , url = "https://savl.com/" , roleDescription = """I worked in the Savl project — this is a mobile application, wallet with support for 6 cryptocurrencies. I was responsible for the data layer in the mobile application. I applied everything that I learned from books about functional programming and software design, and also completely covered the business logic with tests, as a result of which the application became fault-tolerant and modular, that is, it stopped crashing due to exceptions or unexpected behavior of external services, and allowed to enable and disable support for individual cryptocurrencies at any time. Also inside the company, I made several presentations on functional programming.""" , tags = "JavaScript, Flow, React Native, Redux, Saga, Ramda, Sanctuary, Socket.io" } ] showExperienceRecord : ExperienceRecord -> Html msg showExperienceRecord x = div [ styles.itemBlock ] [ span [ styles.item ] [ text__ x.companyAndTitle , span [ styles.period ] [ text__ (showDate x.startDate ++ " — " ++ (x.endDate |> Maybe.map showDate |> Maybe.withDefault "present") ) ] ] , a [ styles.link, href x.url, targetBlank, noOpener ] [ text__ x.url ] , span [] [ text__ x.roleDescription ] , span [ styles.detail ] [ text__ x.tags ] ] experienceSection : Html msg experienceSection = section [ styles.section ] (h2 [ styles.subheader ] [ text__ "Experience" ] :: List.map showExperienceRecord experienceRecords ) -- Reusable stuff type alias Date = { month : Int, year : Int } mobileBreakpoint : Float mobileBreakpoint = 600 mediaMobile : List Style -> Style mediaMobile = withMedia [ only screen [ Media.maxWidth (px (mobileBreakpoint - 1)) ] ] mediaDesktop : List Style -> Style mediaDesktop = withMedia [ only screen [ Media.minWidth (px mobileBreakpoint) ] ] mediaScreen : List Style -> Style mediaScreen = withMedia [ only screen [] ] mediaPrint : List Style -> Style mediaPrint = withMedia [ only print [] ] noOpener : Html.Styled.Attribute msg noOpener = attribute "rel" "noopener noreferrer" targetBlank : Html.Styled.Attribute msg targetBlank = Attributes.target "_blank" -- Print specific screenMultiplier : Float screenMultiplier = 0.75 printMultiplier : Float printMultiplier = 1.18 {-| Convert pixels (like in figma) to both screen- and print-friendly units -} fromPx : (Pt -> Style) -> Int -> Style fromPx f pixels = batch [ mediaScreen [ f <| pt (toFloat pixels * screenMultiplier) ] , mediaPrint [ f <| pt (toFloat pixels * printMultiplier) ] ]
elm