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": "\"ruan\", \"run\"\n\n , \"ji\", \"jia\", \"jiao\", \"jie\", \"jiu\", \"jian\", \"jin\", \"jiang\", \"jing\", \"jiong\", \"ju\", ",
"end": 8038,
"score": 0.6048828363,
"start": 8037,
"tag": "NAME",
"value": "u"
}
] | src/CharacterModel.elm | mweiss/elm-study-app | 0 | module CharacterModel (CharacterModel, Sentence, characterModel, sentenceModel, tokenizePinyin,
WorkbookProblem, workbookDecoder, workbookProblemToSentence, grade, inputToPinyin, Grade(..)) where
import Dict exposing (Dict)
import String
import Regex exposing (Regex)
import List
import Char
import Json.Decode exposing ((:=))
import Json.Decode as JSD
type alias Sentence =
{ chinese : String
, pinyin : String
}
type alias CharacterModel answer =
{ chinese : String
, pinyin : Maybe String
, answers : List answer
, selected : Bool
, currentAnswer : Maybe answer
}
type alias WorkbookProblem = {
chinese : String,
pinyin : String,
chapter : Int,
book : Int
}
-- GRADE
type Grade = Correct | Incorrect | NotGraded | DoNotGrade
grade : CharacterModel String -> Grade
grade characterModel =
case characterModel.pinyin of
Nothing -> DoNotGrade
Just p -> case (List.head characterModel.answers) of
Nothing -> NotGraded
Just a -> if String.toLower p == (String.toLower (inputToPinyin a))
then Correct
else Incorrect
-- Helper method which takes user input and converts it into pinyin. For example,
-- this method will convert a string like wo3 to wǒ. This method only returns valid
-- pinyin if the input is valid pinyin.
inputToPinyin : String -> String
inputToPinyin input =
let n = case String.toInt (String.right 1 input) of
Err _ -> -1
Ok number -> number
regexString = pinyinSyllableToRegexString (Regex.replace (Regex.AtMost 1) (Regex.regex "[0-9]$") (\_ -> "") input)
in if n < 0 || n > 4
then input
else Regex.replace
(Regex.AtMost 1)
(Regex.regex "\\[.*\\]")
(\match -> String.slice (n + 1) (n + 2) match.match)
regexString
workbookProblemToSentence : WorkbookProblem -> Sentence
workbookProblemToSentence wp = {chinese = wp.chinese, pinyin = wp.pinyin}
workbookDecoder : JSD.Decoder (List WorkbookProblem)
workbookDecoder =
JSD.list (JSD.object4 WorkbookProblem
("chinese" := JSD.string)
("pinyin" := JSD.string)
("chapter" := JSD.int)
("book" := JSD.int))
-- Helper methods to transform a sentence into a character model
sentenceModel : Sentence -> List (CharacterModel answer)
sentenceModel sentence = List.map2 characterModel (String.split "" sentence.chinese) (tokenizePinyin sentence.pinyin)
characterModel : String -> String -> CharacterModel answer
characterModel chinese pinyin =
{ chinese = chinese
, pinyin = if (Regex.contains (Regex.regex "[,.?!]") pinyin) then Nothing else (Just pinyin)
, answers = []
, selected = False
, currentAnswer = Nothing
}
tokenizePinyin : String -> List String
tokenizePinyin s = List.filter (\v -> v /= " ") (List.map (\x -> x.match) (Regex.find Regex.All pinyinRegex s))
pinyinRegex : Regex
pinyinRegex = Regex.caseInsensitive (Regex.regex stringRegex)
stringRegex = (String.join "|" (List.append ["[,.?! ]"] (List.foldr foldPinyinSyllables [] pinyinSyllables)))
foldPinyinSyllables : String -> List String -> List String
foldPinyinSyllables pinyin l = List.append [pinyinSyllableToRegexString pinyin] l
getDefaultToKey : String -> Dict String String -> String
getDefaultToKey key dict = resolveMaybe key (Dict.get key dict)
-- TODO: I actually want this to fail if it breaks. This is a convenience so I don't
-- have multi-line case statements everywhere doing the same thing
resolveMaybe : v -> Maybe v -> v
resolveMaybe default maybe =
case maybe of
Nothing -> default
Just value -> value
pinyinSyllableToRegexString : String -> String
pinyinSyllableToRegexString pinyin =
let vowel = String.filter (\c -> Dict.member (String.fromChar c) vowelToTonesMap) pinyin
vowelRegex = getDefaultToKey vowel pinyinVowelsToRegex
in Regex.replace
(Regex.AtMost 1)
(Regex.regex vowel)
(\_ -> vowelRegex)
pinyin
pinyinVowelsToRegex : Dict String String
pinyinVowelsToRegex = List.foldr foldPinyinVowels Dict.empty pinyinVowels
pinyinToRegex : String -> Int -> String
pinyinToRegex s i =
let leftStr = String.left i s
rightStr = String.dropLeft (i + 1) s
vowel = String.slice i (i + 1) s
lookupValue = getDefaultToKey vowel vowelToTonesMap
in leftStr ++ "[" ++ lookupValue ++ "]" ++ rightStr
foldPinyinVowels : String -> Dict String String -> Dict String String
foldPinyinVowels pinyin dict =
let pinyinIndex = (resolveMaybe 1 (List.head (String.indexes "*" pinyin))) - 1
key = String.filter (\c -> c /= '*') pinyin
in (Dict.insert key (pinyinToRegex key pinyinIndex) dict)
vowelToTonesMap : Dict String String
vowelToTonesMap =
Dict.fromList
[ ("a", "aāáǎà")
, ("e", "eēéěè")
, ("i", "iīíǐì")
, ("o", "oōóǒò")
, ("u", "uūúǔù")
, ("ü", "üǖǘǚǜ")
, ("A", "AĀÁǍÀ")
, ("E", "EĒÉĚÈ")
, ("I", "IĪÍǏÌ")
, ("O", "OŌÓǑÒ")
, ("U", "UŪÚǓÙ")
, ("Ü", "ÜǕǗǙǛ")
]
pinyinVowels : List String
pinyinVowels =
[ "a*", "o*", "e*", "i*", "er"
, "a*i", "e*i", "a*o", "o*u"
, "ia*", "ia*o", "ie*", "iu*", "io*"
, "u*", "ua*i", "ua*", "ue*", "ui*", "uo*"
, "üe*", "i*", "ü*"
]
pinyinSyllables = List.reverse <| List.sortBy String.length
[ "a", "o", "e", "er", "ai", "ao", "ou", "an", "en", "ang", "eng"
, "yi", "ya", "yao", "ye", "you", "yan", "yin", "yang", "ying", "yong"
, "wu", "wa", "wo","wai", "wei", "wan", "wen", "wang", "weng"
, "yu", "yue", "yuan", "yun"
, "ba", "bo", "bai", "bei", "bao", "ban", "ben", "bang", "beng", "bi"
, "biao", "bie", "bian", "bin", "bing", "bu"
, "pa", "po", "pai", "pei", "pao", "pou", "pan", "pen", "pang", "peng", "pi"
, "piao", "pie", "pian", "pin", "ping", "pu"
, "ma", "mo", "me", "mai", "mei", "mao", "mou", "man", "men", "mang", "meng", "mi", "miao"
, "mie", "miu", "mian", "min", "ming", "mu"
, "fa", "fo", "fei", "fou", "fan", "fen", "fang", "feng", "fu"
, "da", "de", "dai", "dei", "dao", "dou", "dan", "den", "dang", "deng"
, "dong", "di", "diao", "die", "diu", "dian", "ding", "du", "duo", "dui"
, "duan", "dun"
, "ta", "te", "tai", "tei", "tao", "tou", "tan", "tang", "teng", "tong", "ti", "tiao", "tie"
, "tian", "ting", "tu", "tuo", "tui", "tuan", "tun"
, "na", "ne", "nai", "nei", "nao", "nou", "nan", "nen", "nang", "neng", "nong", "ni", "niao"
, "nie", "niu", "nian", "nin", "niang", "ning", "nu", "nuo", "nuan", "nü", "nüe"
, "la", "le", "lai", "lei", "lao", "lou", "lan", "lang", "leng", "long", "li", "lia", "liao", "lie"
, "liu", "lian", "lin", "liang", "ling", "lu", "luo", "luan", "lun", "lü", "lüe"
, "ga", "ge", "gai", "gei", "gao", "gou", "gan", "gen", "gang", "geng", "gong", "gu", "gua", "guo"
, "guai", "gui", "guan", "gun", "guang"
, "ka", "ke", "kai", "kei", "kao", "kou", "kan", "ken", "kang", "keng", "kong", "ku", "kua", "kuo"
, "kuai", "kui", "kuan", "kun", "kuang"
, "ha", "he", "hai", "hei", "hao", "hou", "han", "hen", "hang", "heng", "hong", "hu", "hua", "huo"
, "huai", "hui", "huan", "hun", "huang"
, "za", "ze", "zi", "zai", "zei", "zao", "zou", "zan", "zen", "zang", "zeng", "zong", "zu", "zuo"
, "zui", "zuan", "zun"
, "ca", "ce", "ci", "cai", "cao", "cou", "can", "cen", "cang", "ceng", "cong", "cu", "cuo", "cui"
, "cuan", "cun"
, "sa", "se", "si", "sai", "sao", "sou", "san", "sen", "sang", "seng", "song", "su", "suo", "sui"
, "suan", "sun"
, "zha", "zhe", "zhi", "zhai", "zhei", "zhao", "zhou", "zhan", "zhen", "zhang", "zheng", "zhong"
, "zhu", "zhua", "zhuo", "zhuai", "zhui", "zhuan", "zhun", "zhuang"
, "cha", "che", "chi", "chai", "chao", "chou", "chan", "chen", "chang", "cheng", "chong", "chu"
, "chua", "chuo", "chuai", "chui", "chuan", "chun", "chuang"
, "sha", "she", "shi", "shai", "shei", "shao", "shou", "shan", "shen", "shang", "sheng", "shu"
, "shua", "shuo", "shuai", "shui", "shuan", "shun", "shuang"
, "re", "ri", "rao", "rou", "ran", "ren", "rang", "reng", "rong", "ru", "rua", "ruo", "rui"
, "ruan", "run"
, "ji", "jia", "jiao", "jie", "jiu", "jian", "jin", "jiang", "jing", "jiong", "ju", "jue", "juan", "jun"
, "qi", "qia", "qiao", "qie", "qiu", "qian", "qin", "qiang", "qing", "qiong", "qu", "que", "quan", "qun"
, "xi", "xia", "xiao", "xie", "xiu", "xian", "xin", "xiang", "xing", "xiong", "xu", "xue", "xuan", "xun"
] | 49585 | module CharacterModel (CharacterModel, Sentence, characterModel, sentenceModel, tokenizePinyin,
WorkbookProblem, workbookDecoder, workbookProblemToSentence, grade, inputToPinyin, Grade(..)) where
import Dict exposing (Dict)
import String
import Regex exposing (Regex)
import List
import Char
import Json.Decode exposing ((:=))
import Json.Decode as JSD
type alias Sentence =
{ chinese : String
, pinyin : String
}
type alias CharacterModel answer =
{ chinese : String
, pinyin : Maybe String
, answers : List answer
, selected : Bool
, currentAnswer : Maybe answer
}
type alias WorkbookProblem = {
chinese : String,
pinyin : String,
chapter : Int,
book : Int
}
-- GRADE
type Grade = Correct | Incorrect | NotGraded | DoNotGrade
grade : CharacterModel String -> Grade
grade characterModel =
case characterModel.pinyin of
Nothing -> DoNotGrade
Just p -> case (List.head characterModel.answers) of
Nothing -> NotGraded
Just a -> if String.toLower p == (String.toLower (inputToPinyin a))
then Correct
else Incorrect
-- Helper method which takes user input and converts it into pinyin. For example,
-- this method will convert a string like wo3 to wǒ. This method only returns valid
-- pinyin if the input is valid pinyin.
inputToPinyin : String -> String
inputToPinyin input =
let n = case String.toInt (String.right 1 input) of
Err _ -> -1
Ok number -> number
regexString = pinyinSyllableToRegexString (Regex.replace (Regex.AtMost 1) (Regex.regex "[0-9]$") (\_ -> "") input)
in if n < 0 || n > 4
then input
else Regex.replace
(Regex.AtMost 1)
(Regex.regex "\\[.*\\]")
(\match -> String.slice (n + 1) (n + 2) match.match)
regexString
workbookProblemToSentence : WorkbookProblem -> Sentence
workbookProblemToSentence wp = {chinese = wp.chinese, pinyin = wp.pinyin}
workbookDecoder : JSD.Decoder (List WorkbookProblem)
workbookDecoder =
JSD.list (JSD.object4 WorkbookProblem
("chinese" := JSD.string)
("pinyin" := JSD.string)
("chapter" := JSD.int)
("book" := JSD.int))
-- Helper methods to transform a sentence into a character model
sentenceModel : Sentence -> List (CharacterModel answer)
sentenceModel sentence = List.map2 characterModel (String.split "" sentence.chinese) (tokenizePinyin sentence.pinyin)
characterModel : String -> String -> CharacterModel answer
characterModel chinese pinyin =
{ chinese = chinese
, pinyin = if (Regex.contains (Regex.regex "[,.?!]") pinyin) then Nothing else (Just pinyin)
, answers = []
, selected = False
, currentAnswer = Nothing
}
tokenizePinyin : String -> List String
tokenizePinyin s = List.filter (\v -> v /= " ") (List.map (\x -> x.match) (Regex.find Regex.All pinyinRegex s))
pinyinRegex : Regex
pinyinRegex = Regex.caseInsensitive (Regex.regex stringRegex)
stringRegex = (String.join "|" (List.append ["[,.?! ]"] (List.foldr foldPinyinSyllables [] pinyinSyllables)))
foldPinyinSyllables : String -> List String -> List String
foldPinyinSyllables pinyin l = List.append [pinyinSyllableToRegexString pinyin] l
getDefaultToKey : String -> Dict String String -> String
getDefaultToKey key dict = resolveMaybe key (Dict.get key dict)
-- TODO: I actually want this to fail if it breaks. This is a convenience so I don't
-- have multi-line case statements everywhere doing the same thing
resolveMaybe : v -> Maybe v -> v
resolveMaybe default maybe =
case maybe of
Nothing -> default
Just value -> value
pinyinSyllableToRegexString : String -> String
pinyinSyllableToRegexString pinyin =
let vowel = String.filter (\c -> Dict.member (String.fromChar c) vowelToTonesMap) pinyin
vowelRegex = getDefaultToKey vowel pinyinVowelsToRegex
in Regex.replace
(Regex.AtMost 1)
(Regex.regex vowel)
(\_ -> vowelRegex)
pinyin
pinyinVowelsToRegex : Dict String String
pinyinVowelsToRegex = List.foldr foldPinyinVowels Dict.empty pinyinVowels
pinyinToRegex : String -> Int -> String
pinyinToRegex s i =
let leftStr = String.left i s
rightStr = String.dropLeft (i + 1) s
vowel = String.slice i (i + 1) s
lookupValue = getDefaultToKey vowel vowelToTonesMap
in leftStr ++ "[" ++ lookupValue ++ "]" ++ rightStr
foldPinyinVowels : String -> Dict String String -> Dict String String
foldPinyinVowels pinyin dict =
let pinyinIndex = (resolveMaybe 1 (List.head (String.indexes "*" pinyin))) - 1
key = String.filter (\c -> c /= '*') pinyin
in (Dict.insert key (pinyinToRegex key pinyinIndex) dict)
vowelToTonesMap : Dict String String
vowelToTonesMap =
Dict.fromList
[ ("a", "aāáǎà")
, ("e", "eēéěè")
, ("i", "iīíǐì")
, ("o", "oōóǒò")
, ("u", "uūúǔù")
, ("ü", "üǖǘǚǜ")
, ("A", "AĀÁǍÀ")
, ("E", "EĒÉĚÈ")
, ("I", "IĪÍǏÌ")
, ("O", "OŌÓǑÒ")
, ("U", "UŪÚǓÙ")
, ("Ü", "ÜǕǗǙǛ")
]
pinyinVowels : List String
pinyinVowels =
[ "a*", "o*", "e*", "i*", "er"
, "a*i", "e*i", "a*o", "o*u"
, "ia*", "ia*o", "ie*", "iu*", "io*"
, "u*", "ua*i", "ua*", "ue*", "ui*", "uo*"
, "üe*", "i*", "ü*"
]
pinyinSyllables = List.reverse <| List.sortBy String.length
[ "a", "o", "e", "er", "ai", "ao", "ou", "an", "en", "ang", "eng"
, "yi", "ya", "yao", "ye", "you", "yan", "yin", "yang", "ying", "yong"
, "wu", "wa", "wo","wai", "wei", "wan", "wen", "wang", "weng"
, "yu", "yue", "yuan", "yun"
, "ba", "bo", "bai", "bei", "bao", "ban", "ben", "bang", "beng", "bi"
, "biao", "bie", "bian", "bin", "bing", "bu"
, "pa", "po", "pai", "pei", "pao", "pou", "pan", "pen", "pang", "peng", "pi"
, "piao", "pie", "pian", "pin", "ping", "pu"
, "ma", "mo", "me", "mai", "mei", "mao", "mou", "man", "men", "mang", "meng", "mi", "miao"
, "mie", "miu", "mian", "min", "ming", "mu"
, "fa", "fo", "fei", "fou", "fan", "fen", "fang", "feng", "fu"
, "da", "de", "dai", "dei", "dao", "dou", "dan", "den", "dang", "deng"
, "dong", "di", "diao", "die", "diu", "dian", "ding", "du", "duo", "dui"
, "duan", "dun"
, "ta", "te", "tai", "tei", "tao", "tou", "tan", "tang", "teng", "tong", "ti", "tiao", "tie"
, "tian", "ting", "tu", "tuo", "tui", "tuan", "tun"
, "na", "ne", "nai", "nei", "nao", "nou", "nan", "nen", "nang", "neng", "nong", "ni", "niao"
, "nie", "niu", "nian", "nin", "niang", "ning", "nu", "nuo", "nuan", "nü", "nüe"
, "la", "le", "lai", "lei", "lao", "lou", "lan", "lang", "leng", "long", "li", "lia", "liao", "lie"
, "liu", "lian", "lin", "liang", "ling", "lu", "luo", "luan", "lun", "lü", "lüe"
, "ga", "ge", "gai", "gei", "gao", "gou", "gan", "gen", "gang", "geng", "gong", "gu", "gua", "guo"
, "guai", "gui", "guan", "gun", "guang"
, "ka", "ke", "kai", "kei", "kao", "kou", "kan", "ken", "kang", "keng", "kong", "ku", "kua", "kuo"
, "kuai", "kui", "kuan", "kun", "kuang"
, "ha", "he", "hai", "hei", "hao", "hou", "han", "hen", "hang", "heng", "hong", "hu", "hua", "huo"
, "huai", "hui", "huan", "hun", "huang"
, "za", "ze", "zi", "zai", "zei", "zao", "zou", "zan", "zen", "zang", "zeng", "zong", "zu", "zuo"
, "zui", "zuan", "zun"
, "ca", "ce", "ci", "cai", "cao", "cou", "can", "cen", "cang", "ceng", "cong", "cu", "cuo", "cui"
, "cuan", "cun"
, "sa", "se", "si", "sai", "sao", "sou", "san", "sen", "sang", "seng", "song", "su", "suo", "sui"
, "suan", "sun"
, "zha", "zhe", "zhi", "zhai", "zhei", "zhao", "zhou", "zhan", "zhen", "zhang", "zheng", "zhong"
, "zhu", "zhua", "zhuo", "zhuai", "zhui", "zhuan", "zhun", "zhuang"
, "cha", "che", "chi", "chai", "chao", "chou", "chan", "chen", "chang", "cheng", "chong", "chu"
, "chua", "chuo", "chuai", "chui", "chuan", "chun", "chuang"
, "sha", "she", "shi", "shai", "shei", "shao", "shou", "shan", "shen", "shang", "sheng", "shu"
, "shua", "shuo", "shuai", "shui", "shuan", "shun", "shuang"
, "re", "ri", "rao", "rou", "ran", "ren", "rang", "reng", "rong", "ru", "rua", "ruo", "rui"
, "ruan", "run"
, "ji", "jia", "jiao", "jie", "ji<NAME>", "jian", "jin", "jiang", "jing", "jiong", "ju", "jue", "juan", "jun"
, "qi", "qia", "qiao", "qie", "qiu", "qian", "qin", "qiang", "qing", "qiong", "qu", "que", "quan", "qun"
, "xi", "xia", "xiao", "xie", "xiu", "xian", "xin", "xiang", "xing", "xiong", "xu", "xue", "xuan", "xun"
] | true | module CharacterModel (CharacterModel, Sentence, characterModel, sentenceModel, tokenizePinyin,
WorkbookProblem, workbookDecoder, workbookProblemToSentence, grade, inputToPinyin, Grade(..)) where
import Dict exposing (Dict)
import String
import Regex exposing (Regex)
import List
import Char
import Json.Decode exposing ((:=))
import Json.Decode as JSD
type alias Sentence =
{ chinese : String
, pinyin : String
}
type alias CharacterModel answer =
{ chinese : String
, pinyin : Maybe String
, answers : List answer
, selected : Bool
, currentAnswer : Maybe answer
}
type alias WorkbookProblem = {
chinese : String,
pinyin : String,
chapter : Int,
book : Int
}
-- GRADE
type Grade = Correct | Incorrect | NotGraded | DoNotGrade
grade : CharacterModel String -> Grade
grade characterModel =
case characterModel.pinyin of
Nothing -> DoNotGrade
Just p -> case (List.head characterModel.answers) of
Nothing -> NotGraded
Just a -> if String.toLower p == (String.toLower (inputToPinyin a))
then Correct
else Incorrect
-- Helper method which takes user input and converts it into pinyin. For example,
-- this method will convert a string like wo3 to wǒ. This method only returns valid
-- pinyin if the input is valid pinyin.
inputToPinyin : String -> String
inputToPinyin input =
let n = case String.toInt (String.right 1 input) of
Err _ -> -1
Ok number -> number
regexString = pinyinSyllableToRegexString (Regex.replace (Regex.AtMost 1) (Regex.regex "[0-9]$") (\_ -> "") input)
in if n < 0 || n > 4
then input
else Regex.replace
(Regex.AtMost 1)
(Regex.regex "\\[.*\\]")
(\match -> String.slice (n + 1) (n + 2) match.match)
regexString
workbookProblemToSentence : WorkbookProblem -> Sentence
workbookProblemToSentence wp = {chinese = wp.chinese, pinyin = wp.pinyin}
workbookDecoder : JSD.Decoder (List WorkbookProblem)
workbookDecoder =
JSD.list (JSD.object4 WorkbookProblem
("chinese" := JSD.string)
("pinyin" := JSD.string)
("chapter" := JSD.int)
("book" := JSD.int))
-- Helper methods to transform a sentence into a character model
sentenceModel : Sentence -> List (CharacterModel answer)
sentenceModel sentence = List.map2 characterModel (String.split "" sentence.chinese) (tokenizePinyin sentence.pinyin)
characterModel : String -> String -> CharacterModel answer
characterModel chinese pinyin =
{ chinese = chinese
, pinyin = if (Regex.contains (Regex.regex "[,.?!]") pinyin) then Nothing else (Just pinyin)
, answers = []
, selected = False
, currentAnswer = Nothing
}
tokenizePinyin : String -> List String
tokenizePinyin s = List.filter (\v -> v /= " ") (List.map (\x -> x.match) (Regex.find Regex.All pinyinRegex s))
pinyinRegex : Regex
pinyinRegex = Regex.caseInsensitive (Regex.regex stringRegex)
stringRegex = (String.join "|" (List.append ["[,.?! ]"] (List.foldr foldPinyinSyllables [] pinyinSyllables)))
foldPinyinSyllables : String -> List String -> List String
foldPinyinSyllables pinyin l = List.append [pinyinSyllableToRegexString pinyin] l
getDefaultToKey : String -> Dict String String -> String
getDefaultToKey key dict = resolveMaybe key (Dict.get key dict)
-- TODO: I actually want this to fail if it breaks. This is a convenience so I don't
-- have multi-line case statements everywhere doing the same thing
resolveMaybe : v -> Maybe v -> v
resolveMaybe default maybe =
case maybe of
Nothing -> default
Just value -> value
pinyinSyllableToRegexString : String -> String
pinyinSyllableToRegexString pinyin =
let vowel = String.filter (\c -> Dict.member (String.fromChar c) vowelToTonesMap) pinyin
vowelRegex = getDefaultToKey vowel pinyinVowelsToRegex
in Regex.replace
(Regex.AtMost 1)
(Regex.regex vowel)
(\_ -> vowelRegex)
pinyin
pinyinVowelsToRegex : Dict String String
pinyinVowelsToRegex = List.foldr foldPinyinVowels Dict.empty pinyinVowels
pinyinToRegex : String -> Int -> String
pinyinToRegex s i =
let leftStr = String.left i s
rightStr = String.dropLeft (i + 1) s
vowel = String.slice i (i + 1) s
lookupValue = getDefaultToKey vowel vowelToTonesMap
in leftStr ++ "[" ++ lookupValue ++ "]" ++ rightStr
foldPinyinVowels : String -> Dict String String -> Dict String String
foldPinyinVowels pinyin dict =
let pinyinIndex = (resolveMaybe 1 (List.head (String.indexes "*" pinyin))) - 1
key = String.filter (\c -> c /= '*') pinyin
in (Dict.insert key (pinyinToRegex key pinyinIndex) dict)
vowelToTonesMap : Dict String String
vowelToTonesMap =
Dict.fromList
[ ("a", "aāáǎà")
, ("e", "eēéěè")
, ("i", "iīíǐì")
, ("o", "oōóǒò")
, ("u", "uūúǔù")
, ("ü", "üǖǘǚǜ")
, ("A", "AĀÁǍÀ")
, ("E", "EĒÉĚÈ")
, ("I", "IĪÍǏÌ")
, ("O", "OŌÓǑÒ")
, ("U", "UŪÚǓÙ")
, ("Ü", "ÜǕǗǙǛ")
]
pinyinVowels : List String
pinyinVowels =
[ "a*", "o*", "e*", "i*", "er"
, "a*i", "e*i", "a*o", "o*u"
, "ia*", "ia*o", "ie*", "iu*", "io*"
, "u*", "ua*i", "ua*", "ue*", "ui*", "uo*"
, "üe*", "i*", "ü*"
]
pinyinSyllables = List.reverse <| List.sortBy String.length
[ "a", "o", "e", "er", "ai", "ao", "ou", "an", "en", "ang", "eng"
, "yi", "ya", "yao", "ye", "you", "yan", "yin", "yang", "ying", "yong"
, "wu", "wa", "wo","wai", "wei", "wan", "wen", "wang", "weng"
, "yu", "yue", "yuan", "yun"
, "ba", "bo", "bai", "bei", "bao", "ban", "ben", "bang", "beng", "bi"
, "biao", "bie", "bian", "bin", "bing", "bu"
, "pa", "po", "pai", "pei", "pao", "pou", "pan", "pen", "pang", "peng", "pi"
, "piao", "pie", "pian", "pin", "ping", "pu"
, "ma", "mo", "me", "mai", "mei", "mao", "mou", "man", "men", "mang", "meng", "mi", "miao"
, "mie", "miu", "mian", "min", "ming", "mu"
, "fa", "fo", "fei", "fou", "fan", "fen", "fang", "feng", "fu"
, "da", "de", "dai", "dei", "dao", "dou", "dan", "den", "dang", "deng"
, "dong", "di", "diao", "die", "diu", "dian", "ding", "du", "duo", "dui"
, "duan", "dun"
, "ta", "te", "tai", "tei", "tao", "tou", "tan", "tang", "teng", "tong", "ti", "tiao", "tie"
, "tian", "ting", "tu", "tuo", "tui", "tuan", "tun"
, "na", "ne", "nai", "nei", "nao", "nou", "nan", "nen", "nang", "neng", "nong", "ni", "niao"
, "nie", "niu", "nian", "nin", "niang", "ning", "nu", "nuo", "nuan", "nü", "nüe"
, "la", "le", "lai", "lei", "lao", "lou", "lan", "lang", "leng", "long", "li", "lia", "liao", "lie"
, "liu", "lian", "lin", "liang", "ling", "lu", "luo", "luan", "lun", "lü", "lüe"
, "ga", "ge", "gai", "gei", "gao", "gou", "gan", "gen", "gang", "geng", "gong", "gu", "gua", "guo"
, "guai", "gui", "guan", "gun", "guang"
, "ka", "ke", "kai", "kei", "kao", "kou", "kan", "ken", "kang", "keng", "kong", "ku", "kua", "kuo"
, "kuai", "kui", "kuan", "kun", "kuang"
, "ha", "he", "hai", "hei", "hao", "hou", "han", "hen", "hang", "heng", "hong", "hu", "hua", "huo"
, "huai", "hui", "huan", "hun", "huang"
, "za", "ze", "zi", "zai", "zei", "zao", "zou", "zan", "zen", "zang", "zeng", "zong", "zu", "zuo"
, "zui", "zuan", "zun"
, "ca", "ce", "ci", "cai", "cao", "cou", "can", "cen", "cang", "ceng", "cong", "cu", "cuo", "cui"
, "cuan", "cun"
, "sa", "se", "si", "sai", "sao", "sou", "san", "sen", "sang", "seng", "song", "su", "suo", "sui"
, "suan", "sun"
, "zha", "zhe", "zhi", "zhai", "zhei", "zhao", "zhou", "zhan", "zhen", "zhang", "zheng", "zhong"
, "zhu", "zhua", "zhuo", "zhuai", "zhui", "zhuan", "zhun", "zhuang"
, "cha", "che", "chi", "chai", "chao", "chou", "chan", "chen", "chang", "cheng", "chong", "chu"
, "chua", "chuo", "chuai", "chui", "chuan", "chun", "chuang"
, "sha", "she", "shi", "shai", "shei", "shao", "shou", "shan", "shen", "shang", "sheng", "shu"
, "shua", "shuo", "shuai", "shui", "shuan", "shun", "shuang"
, "re", "ri", "rao", "rou", "ran", "ren", "rang", "reng", "rong", "ru", "rua", "ruo", "rui"
, "ruan", "run"
, "ji", "jia", "jiao", "jie", "jiPI:NAME:<NAME>END_PI", "jian", "jin", "jiang", "jing", "jiong", "ju", "jue", "juan", "jun"
, "qi", "qia", "qiao", "qie", "qiu", "qian", "qin", "qiang", "qing", "qiong", "qu", "que", "quan", "qun"
, "xi", "xia", "xiao", "xie", "xiu", "xian", "xin", "xiang", "xing", "xiong", "xu", "xue", "xuan", "xun"
] | elm |
[
{
"context": "\ngetUserNameView appState =\n strong [] [ text \"Andres\" ]\n\n\ngetStoreNameView : AppState -> Html Msg\ngetS",
"end": 2922,
"score": 0.999593854,
"start": 2916,
"tag": "NAME",
"value": "Andres"
}
] | src/elm/Views.elm | aotarola/whiz | 0 | module Views exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Models exposing (AppState, LineItem, unknownUser)
import Messages exposing (Msg(..))
import Json.Decode as Json
view : AppState -> Html Msg
view appState =
div []
[ headerView appState
, productSearchView appState
]
lineItemsView : AppState -> Html Msg
lineItemsView { lineItems } =
ul [ id "lineitems" ] (List.map lineItemsRowView lineItems)
lineItemsRowView : LineItem -> Html Msg
lineItemsRowView ( quantity, product ) =
li [] [ text product.title, text " ", text <| toString quantity ]
productSearchView : AppState -> Html Msg
productSearchView appState =
let
{ codeSearchInput } =
appState
in
div []
(productEntryView appState ++ [ lineItemsView appState ])
productEntryView : AppState -> List (Html Msg)
productEntryView appState =
let
{ codeSearchInput, currentProduct } =
appState
in
case currentProduct of
Just product ->
[ div []
[ strong [] [ text "producto" ] ]
, div [ id "product-info" ]
[ text product.title
, text " | "
, text <| toString product.price
, text " | "
, input
[ id "quantity-entry"
, type' "number"
, onInput UpdatePurchaseQuantity
, onEnter <| UpdateLineItems
]
[]
]
]
Nothing ->
[ div []
[ strong [] [ text "codigo barra" ] ]
, div []
[ input
[ id "search-by-code"
, type' "text"
, autofocus True
, onInput UpdateSearchByCode
, value codeSearchInput
, onEnter SearchProductByCode
]
[]
, button
[ id
"btn-search"
, onClick SearchProductByCode
]
[ text "buscar" ]
]
]
headerView : AppState -> Html Msg
headerView appState =
div []
[ p [] [ text "Bienvenid(a), ", getUserNameView appState, text " a nuestra sucursal ", getStoreNameView appState ]
, p [] [ text "Fecha inicio turno: Tuesday 25 October 2016 - 04:00:57" ]
, p [] [ text "Última venta registrada: No ha registrado ninguna venta." ]
]
getUserNameView : AppState -> Html Msg
getUserNameView appState =
strong [] [ text "Andres" ]
getStoreNameView : AppState -> Html Msg
getStoreNameView appState =
strong [] [ text "Playa Brava" ]
onEnter : Msg -> Attribute Msg
onEnter msg =
let
tagger code =
if code == 13 then
msg
else
NoOp
in
on "keydown" (Json.map tagger keyCode)
| 20471 | module Views exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Models exposing (AppState, LineItem, unknownUser)
import Messages exposing (Msg(..))
import Json.Decode as Json
view : AppState -> Html Msg
view appState =
div []
[ headerView appState
, productSearchView appState
]
lineItemsView : AppState -> Html Msg
lineItemsView { lineItems } =
ul [ id "lineitems" ] (List.map lineItemsRowView lineItems)
lineItemsRowView : LineItem -> Html Msg
lineItemsRowView ( quantity, product ) =
li [] [ text product.title, text " ", text <| toString quantity ]
productSearchView : AppState -> Html Msg
productSearchView appState =
let
{ codeSearchInput } =
appState
in
div []
(productEntryView appState ++ [ lineItemsView appState ])
productEntryView : AppState -> List (Html Msg)
productEntryView appState =
let
{ codeSearchInput, currentProduct } =
appState
in
case currentProduct of
Just product ->
[ div []
[ strong [] [ text "producto" ] ]
, div [ id "product-info" ]
[ text product.title
, text " | "
, text <| toString product.price
, text " | "
, input
[ id "quantity-entry"
, type' "number"
, onInput UpdatePurchaseQuantity
, onEnter <| UpdateLineItems
]
[]
]
]
Nothing ->
[ div []
[ strong [] [ text "codigo barra" ] ]
, div []
[ input
[ id "search-by-code"
, type' "text"
, autofocus True
, onInput UpdateSearchByCode
, value codeSearchInput
, onEnter SearchProductByCode
]
[]
, button
[ id
"btn-search"
, onClick SearchProductByCode
]
[ text "buscar" ]
]
]
headerView : AppState -> Html Msg
headerView appState =
div []
[ p [] [ text "Bienvenid(a), ", getUserNameView appState, text " a nuestra sucursal ", getStoreNameView appState ]
, p [] [ text "Fecha inicio turno: Tuesday 25 October 2016 - 04:00:57" ]
, p [] [ text "Última venta registrada: No ha registrado ninguna venta." ]
]
getUserNameView : AppState -> Html Msg
getUserNameView appState =
strong [] [ text "<NAME>" ]
getStoreNameView : AppState -> Html Msg
getStoreNameView appState =
strong [] [ text "Playa Brava" ]
onEnter : Msg -> Attribute Msg
onEnter msg =
let
tagger code =
if code == 13 then
msg
else
NoOp
in
on "keydown" (Json.map tagger keyCode)
| true | module Views exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Models exposing (AppState, LineItem, unknownUser)
import Messages exposing (Msg(..))
import Json.Decode as Json
view : AppState -> Html Msg
view appState =
div []
[ headerView appState
, productSearchView appState
]
lineItemsView : AppState -> Html Msg
lineItemsView { lineItems } =
ul [ id "lineitems" ] (List.map lineItemsRowView lineItems)
lineItemsRowView : LineItem -> Html Msg
lineItemsRowView ( quantity, product ) =
li [] [ text product.title, text " ", text <| toString quantity ]
productSearchView : AppState -> Html Msg
productSearchView appState =
let
{ codeSearchInput } =
appState
in
div []
(productEntryView appState ++ [ lineItemsView appState ])
productEntryView : AppState -> List (Html Msg)
productEntryView appState =
let
{ codeSearchInput, currentProduct } =
appState
in
case currentProduct of
Just product ->
[ div []
[ strong [] [ text "producto" ] ]
, div [ id "product-info" ]
[ text product.title
, text " | "
, text <| toString product.price
, text " | "
, input
[ id "quantity-entry"
, type' "number"
, onInput UpdatePurchaseQuantity
, onEnter <| UpdateLineItems
]
[]
]
]
Nothing ->
[ div []
[ strong [] [ text "codigo barra" ] ]
, div []
[ input
[ id "search-by-code"
, type' "text"
, autofocus True
, onInput UpdateSearchByCode
, value codeSearchInput
, onEnter SearchProductByCode
]
[]
, button
[ id
"btn-search"
, onClick SearchProductByCode
]
[ text "buscar" ]
]
]
headerView : AppState -> Html Msg
headerView appState =
div []
[ p [] [ text "Bienvenid(a), ", getUserNameView appState, text " a nuestra sucursal ", getStoreNameView appState ]
, p [] [ text "Fecha inicio turno: Tuesday 25 October 2016 - 04:00:57" ]
, p [] [ text "Última venta registrada: No ha registrado ninguna venta." ]
]
getUserNameView : AppState -> Html Msg
getUserNameView appState =
strong [] [ text "PI:NAME:<NAME>END_PI" ]
getStoreNameView : AppState -> Html Msg
getStoreNameView appState =
strong [] [ text "Playa Brava" ]
onEnter : Msg -> Attribute Msg
onEnter msg =
let
tagger code =
if code == 13 then
msg
else
NoOp
in
on "keydown" (Json.map tagger keyCode)
| elm |
[
{
"context": "= \"Password\"\n , value = password\n , onInput = actions.o",
"end": 3163,
"score": 0.6874414682,
"start": 3155,
"tag": "PASSWORD",
"value": "password"
}
] | examples/html/src/Components.elm | drshade/elm-spa | 0 | module Components exposing
( footer
, layout
, navbar
)
import Browser exposing (Document)
import Data.Modal as Modal exposing (Modal)
import Data.SignInForm exposing (SignInForm)
import Data.User as User exposing (User)
import Html exposing (..)
import Html.Attributes as Attr exposing (class, href)
import Html.Events as Events
import Generated.Route as Route
-- LAYOUT
layout :
{ page : Document msg
, global :
{ global
| modal : Maybe Modal
, user : Maybe User
}
, actions :
{ onSignOut : msg
, openSignInModal : msg
, closeModal : msg
, attemptSignIn : msg
, onSignInEmailInput : String -> msg
, onSignInPasswordInput : String -> msg
}
}
-> Document msg
layout { page, actions, global } =
{ title = page.title
, body =
[ div [ class "container pad--medium column spacing--large h--fill" ]
[ navbar { user = global.user, actions = actions }
, div [ class "column spacing--large", Attr.style "flex" "1 0 auto" ] page.body
, footer
, global.modal
|> Maybe.map (viewModal actions)
|> Maybe.withDefault (text "")
]
]
}
-- NAVBAR
navbar :
{ user : Maybe User
, actions : { actions | openSignInModal : msg, onSignOut : msg }
}
-> Html msg
navbar ({ actions } as options) =
header [ class "container" ]
[ div [ class "row spacing--between center-y" ]
[ a [ class "link font--h5 font--bold", href "/" ] [ text "home" ]
, div [ class "row spacing--medium center-y" ]
[ a [ class "link", href "/about" ] [ text "about" ]
, a [ class "link", href "/posts" ] [ text "posts" ]
, case options.user of
Just user ->
a [ class "link", href (Route.toHref Route.Profile) ] [ text "profile" ]
Nothing ->
button [ class "button", Events.onClick actions.openSignInModal ] [ text "sign in" ]
]
]
]
-- FOOTER
footer : Html msg
footer =
Html.footer [ class "container py--medium" ]
[ text "built with elm, 2020"
]
-- MODAL
viewModal :
{ actions
| closeModal : msg
, attemptSignIn : msg
, onSignInEmailInput : String -> msg
, onSignInPasswordInput : String -> msg
}
-> Modal
-> Html msg
viewModal actions modal_ =
case modal_ of
Modal.SignInModal { email, password } ->
modal
{ title = "Sign in"
, body =
form [ class "column spacing--medium", Events.onSubmit actions.attemptSignIn ]
[ emailField
{ label = "Email"
, value = email
, onInput = actions.onSignInEmailInput
}
, passwordField
{ label = "Password"
, value = password
, onInput = actions.onSignInPasswordInput
}
, button [ class "button" ] [ text "Sign in" ]
]
, actions = actions
}
modal :
{ title : String
, body : Html msg
, actions : { actions | closeModal : msg }
}
-> Html msg
modal ({ actions } as options) =
div [ class "fixed--full" ]
[ div [ class "absolute--full bg--overlay", Events.onClick actions.closeModal ] []
, div [ class "column spacing--large pad--large absolute--center min-width--480 bg--white" ]
[ div [ class "row spacing--between center-y" ]
[ h3 [ class "font--h3" ] [ text options.title ]
, button [ class "modal__close", Events.onClick actions.closeModal ] [ text "✖️" ]
]
, options.body
]
]
-- FORMS
inputField :
String
-> { label : String, value : String, onInput : String -> msg }
-> Html msg
inputField type_ options =
label [ class "column spacing--small" ]
[ span [] [ text options.label ]
, input [ Attr.type_ type_, Attr.value options.value, Events.onInput options.onInput ] []
]
emailField :
{ label : String, value : String, onInput : String -> msg }
-> Html msg
emailField =
inputField "email"
passwordField :
{ label : String, value : String, onInput : String -> msg }
-> Html msg
passwordField =
inputField "password"
| 30131 | module Components exposing
( footer
, layout
, navbar
)
import Browser exposing (Document)
import Data.Modal as Modal exposing (Modal)
import Data.SignInForm exposing (SignInForm)
import Data.User as User exposing (User)
import Html exposing (..)
import Html.Attributes as Attr exposing (class, href)
import Html.Events as Events
import Generated.Route as Route
-- LAYOUT
layout :
{ page : Document msg
, global :
{ global
| modal : Maybe Modal
, user : Maybe User
}
, actions :
{ onSignOut : msg
, openSignInModal : msg
, closeModal : msg
, attemptSignIn : msg
, onSignInEmailInput : String -> msg
, onSignInPasswordInput : String -> msg
}
}
-> Document msg
layout { page, actions, global } =
{ title = page.title
, body =
[ div [ class "container pad--medium column spacing--large h--fill" ]
[ navbar { user = global.user, actions = actions }
, div [ class "column spacing--large", Attr.style "flex" "1 0 auto" ] page.body
, footer
, global.modal
|> Maybe.map (viewModal actions)
|> Maybe.withDefault (text "")
]
]
}
-- NAVBAR
navbar :
{ user : Maybe User
, actions : { actions | openSignInModal : msg, onSignOut : msg }
}
-> Html msg
navbar ({ actions } as options) =
header [ class "container" ]
[ div [ class "row spacing--between center-y" ]
[ a [ class "link font--h5 font--bold", href "/" ] [ text "home" ]
, div [ class "row spacing--medium center-y" ]
[ a [ class "link", href "/about" ] [ text "about" ]
, a [ class "link", href "/posts" ] [ text "posts" ]
, case options.user of
Just user ->
a [ class "link", href (Route.toHref Route.Profile) ] [ text "profile" ]
Nothing ->
button [ class "button", Events.onClick actions.openSignInModal ] [ text "sign in" ]
]
]
]
-- FOOTER
footer : Html msg
footer =
Html.footer [ class "container py--medium" ]
[ text "built with elm, 2020"
]
-- MODAL
viewModal :
{ actions
| closeModal : msg
, attemptSignIn : msg
, onSignInEmailInput : String -> msg
, onSignInPasswordInput : String -> msg
}
-> Modal
-> Html msg
viewModal actions modal_ =
case modal_ of
Modal.SignInModal { email, password } ->
modal
{ title = "Sign in"
, body =
form [ class "column spacing--medium", Events.onSubmit actions.attemptSignIn ]
[ emailField
{ label = "Email"
, value = email
, onInput = actions.onSignInEmailInput
}
, passwordField
{ label = "Password"
, value = <PASSWORD>
, onInput = actions.onSignInPasswordInput
}
, button [ class "button" ] [ text "Sign in" ]
]
, actions = actions
}
modal :
{ title : String
, body : Html msg
, actions : { actions | closeModal : msg }
}
-> Html msg
modal ({ actions } as options) =
div [ class "fixed--full" ]
[ div [ class "absolute--full bg--overlay", Events.onClick actions.closeModal ] []
, div [ class "column spacing--large pad--large absolute--center min-width--480 bg--white" ]
[ div [ class "row spacing--between center-y" ]
[ h3 [ class "font--h3" ] [ text options.title ]
, button [ class "modal__close", Events.onClick actions.closeModal ] [ text "✖️" ]
]
, options.body
]
]
-- FORMS
inputField :
String
-> { label : String, value : String, onInput : String -> msg }
-> Html msg
inputField type_ options =
label [ class "column spacing--small" ]
[ span [] [ text options.label ]
, input [ Attr.type_ type_, Attr.value options.value, Events.onInput options.onInput ] []
]
emailField :
{ label : String, value : String, onInput : String -> msg }
-> Html msg
emailField =
inputField "email"
passwordField :
{ label : String, value : String, onInput : String -> msg }
-> Html msg
passwordField =
inputField "password"
| true | module Components exposing
( footer
, layout
, navbar
)
import Browser exposing (Document)
import Data.Modal as Modal exposing (Modal)
import Data.SignInForm exposing (SignInForm)
import Data.User as User exposing (User)
import Html exposing (..)
import Html.Attributes as Attr exposing (class, href)
import Html.Events as Events
import Generated.Route as Route
-- LAYOUT
layout :
{ page : Document msg
, global :
{ global
| modal : Maybe Modal
, user : Maybe User
}
, actions :
{ onSignOut : msg
, openSignInModal : msg
, closeModal : msg
, attemptSignIn : msg
, onSignInEmailInput : String -> msg
, onSignInPasswordInput : String -> msg
}
}
-> Document msg
layout { page, actions, global } =
{ title = page.title
, body =
[ div [ class "container pad--medium column spacing--large h--fill" ]
[ navbar { user = global.user, actions = actions }
, div [ class "column spacing--large", Attr.style "flex" "1 0 auto" ] page.body
, footer
, global.modal
|> Maybe.map (viewModal actions)
|> Maybe.withDefault (text "")
]
]
}
-- NAVBAR
navbar :
{ user : Maybe User
, actions : { actions | openSignInModal : msg, onSignOut : msg }
}
-> Html msg
navbar ({ actions } as options) =
header [ class "container" ]
[ div [ class "row spacing--between center-y" ]
[ a [ class "link font--h5 font--bold", href "/" ] [ text "home" ]
, div [ class "row spacing--medium center-y" ]
[ a [ class "link", href "/about" ] [ text "about" ]
, a [ class "link", href "/posts" ] [ text "posts" ]
, case options.user of
Just user ->
a [ class "link", href (Route.toHref Route.Profile) ] [ text "profile" ]
Nothing ->
button [ class "button", Events.onClick actions.openSignInModal ] [ text "sign in" ]
]
]
]
-- FOOTER
footer : Html msg
footer =
Html.footer [ class "container py--medium" ]
[ text "built with elm, 2020"
]
-- MODAL
viewModal :
{ actions
| closeModal : msg
, attemptSignIn : msg
, onSignInEmailInput : String -> msg
, onSignInPasswordInput : String -> msg
}
-> Modal
-> Html msg
viewModal actions modal_ =
case modal_ of
Modal.SignInModal { email, password } ->
modal
{ title = "Sign in"
, body =
form [ class "column spacing--medium", Events.onSubmit actions.attemptSignIn ]
[ emailField
{ label = "Email"
, value = email
, onInput = actions.onSignInEmailInput
}
, passwordField
{ label = "Password"
, value = PI:PASSWORD:<PASSWORD>END_PI
, onInput = actions.onSignInPasswordInput
}
, button [ class "button" ] [ text "Sign in" ]
]
, actions = actions
}
modal :
{ title : String
, body : Html msg
, actions : { actions | closeModal : msg }
}
-> Html msg
modal ({ actions } as options) =
div [ class "fixed--full" ]
[ div [ class "absolute--full bg--overlay", Events.onClick actions.closeModal ] []
, div [ class "column spacing--large pad--large absolute--center min-width--480 bg--white" ]
[ div [ class "row spacing--between center-y" ]
[ h3 [ class "font--h3" ] [ text options.title ]
, button [ class "modal__close", Events.onClick actions.closeModal ] [ text "✖️" ]
]
, options.body
]
]
-- FORMS
inputField :
String
-> { label : String, value : String, onInput : String -> msg }
-> Html msg
inputField type_ options =
label [ class "column spacing--small" ]
[ span [] [ text options.label ]
, input [ Attr.type_ type_, Attr.value options.value, Events.onInput options.onInput ] []
]
emailField :
{ label : String, value : String, onInput : String -> msg }
-> Html msg
emailField =
inputField "email"
passwordField :
{ label : String, value : String, onInput : String -> msg }
-> Html msg
passwordField =
inputField "password"
| elm |
[
{
"context": "OElig;\", 338 )\n , ( \"œ\", 339 )\n , ( \"Š\", 352 )\n , ( \"š\", 353 )\n , ( \"&Yuml",
"end": 173,
"score": 0.8548406959,
"start": 167,
"tag": "NAME",
"value": "Scaron"
}
] | src/ParseHtml/HtmlEntities.elm | dkodaj/simplerte | 3 | module ParseHtml.HtmlEntities exposing (htmlEntities)
htmlEntities : List ( String, Int )
htmlEntities =
[ ( "Œ", 338 )
, ( "œ", 339 )
, ( "Š", 352 )
, ( "š", 353 )
, ( "Ÿ", 376 )
, ( "ƒ", 402 )
, ( "ˆ", 710 )
, ( "˜", 732 )
, ( " ", 8194 )
, ( " ", 8195 )
, ( " ", 8201 )
, ( "‌", 8204 )
, ( "‍", 8205 )
, ( "‎", 8206 )
, ( "‏", 8207 )
, ( "–", 8211 )
, ( "—", 8212 )
, ( "‘", 8216 )
, ( "’", 8217 )
, ( "‚", 8218 )
, ( "“", 8220 )
, ( "”", 8221 )
, ( "„", 8222 )
, ( "†", 8224 )
, ( "‡", 8225 )
, ( "•", 8226 )
, ( "…", 8230 )
, ( "‰", 8240 )
, ( "′", 8242 )
, ( "″", 8243 )
, ( "‹", 8249 )
, ( "›", 8250 )
, ( "‾", 8254 )
, ( "€", 8364 )
, ( "™", 8482 )
, ( "←", 8592 )
, ( "↑", 8593 )
, ( "→", 8594 )
, ( "↓", 8595 )
, ( "↔", 8596 )
, ( "↵", 8629 )
, ( "⌈", 8968 )
, ( "⌉", 8969 )
, ( "⌊", 8970 )
, ( "⌋", 8971 )
, ( "◊", 9674 )
, ( "♠", 9824 )
, ( "♣", 9827 )
, ( "♥", 9829 )
, ( "♦", 9830 )
, ( "Α", 913 )
, ( "Β", 914 )
, ( "Γ", 915 )
, ( "Δ", 916 )
, ( "Ε", 917 )
, ( "Ζ", 918 )
, ( "Η", 919 )
, ( "Θ", 920 )
, ( "Ι", 921 )
, ( "Κ", 922 )
, ( "Λ", 923 )
, ( "Μ", 924 )
, ( "Ν", 925 )
, ( "Ξ", 926 )
, ( "Ο", 927 )
, ( "Π", 928 )
, ( "Ρ", 929 )
, ( "Σ", 931 )
, ( "Τ", 932 )
, ( "Υ", 933 )
, ( "Φ", 934 )
, ( "Χ", 935 )
, ( "Ψ", 936 )
, ( "Ω", 937 )
, ( "α", 945 )
, ( "β", 946 )
, ( "γ", 947 )
, ( "δ", 948 )
, ( "ε", 949 )
, ( "ζ", 950 )
, ( "η", 951 )
, ( "θ", 952 )
, ( "ι", 953 )
, ( "κ", 954 )
, ( "λ", 955 )
, ( "μ", 956 )
, ( "ν", 957 )
, ( "ξ", 958 )
, ( "ο", 959 )
, ( "π", 960 )
, ( "ρ", 961 )
, ( "ς", 962 )
, ( "σ", 963 )
, ( "τ", 964 )
, ( "υ", 965 )
, ( "φ", 966 )
, ( "χ", 967 )
, ( "ψ", 968 )
, ( "ω", 969 )
, ( "ϑ", 977 )
, ( "ϒ", 978 )
, ( "ϖ", 982 )
, ( "∀", 8704 )
, ( "∂", 8706 )
, ( "∃", 8707 )
, ( "∅", 8709 )
, ( "∇", 8711 )
, ( "∈", 8712 )
, ( "∉", 8713 )
, ( "∋", 8715 )
, ( "∏", 8719 )
, ( "∑", 8721 )
, ( "−", 8722 )
, ( "∗", 8727 )
, ( "√", 8730 )
, ( "∝", 8733 )
, ( "∞", 8734 )
, ( "∠", 8736 )
, ( "∧", 8743 )
, ( "∨", 8744 )
, ( "∩", 8745 )
, ( "∪", 8746 )
, ( "∫", 8747 )
, ( "∴", 8756 )
, ( "∼", 8764 )
, ( "≅", 8773 )
, ( "≈", 8776 )
, ( "≠", 8800 )
, ( "≡", 8801 )
, ( "≤", 8804 )
, ( "≥", 8805 )
, ( "⊂", 8834 )
, ( "⊃", 8835 )
, ( "⊄", 8836 )
, ( "⊆", 8838 )
, ( "⊇", 8839 )
, ( "⊕", 8853 )
, ( "⊗", 8855 )
, ( "⊥", 8869 )
, ( "⋅", 8901 )
, ( " ", 160 )
, ( "¡", 161 )
, ( "¢", 162 )
, ( "£", 163 )
, ( "¤", 164 )
, ( "¥", 165 )
, ( "¦", 166 )
, ( "§", 167 )
, ( "¨", 168 )
, ( "©", 169 )
, ( "ª", 170 )
, ( "«", 171 )
, ( "¬", 172 )
, ( "­", 173 )
, ( "®", 174 )
, ( "¯", 175 )
, ( "°", 176 )
, ( "±", 177 )
, ( "²", 178 )
, ( "³", 179 )
, ( "´", 180 )
, ( "µ", 181 )
, ( "¶", 182 )
, ( "¸", 184 )
, ( "¹", 185 )
, ( "º", 186 )
, ( "»", 187 )
, ( "¼", 188 )
, ( "½", 189 )
, ( "¾", 190 )
, ( "¿", 191 )
, ( "×", 215 )
, ( "÷", 247 )
, ( "À", 192 )
, ( "Á", 193 )
, ( "Â", 194 )
, ( "Ã", 195 )
, ( "Ä", 196 )
, ( "Å", 197 )
, ( "Æ", 198 )
, ( "Ç", 199 )
, ( "È", 200 )
, ( "É", 201 )
, ( "Ê", 202 )
, ( "Ë", 203 )
, ( "Ì", 204 )
, ( "Í", 205 )
, ( "Î", 206 )
, ( "Ï", 207 )
, ( "Ð", 208 )
, ( "Ñ", 209 )
, ( "Ò", 210 )
, ( "Ó", 211 )
, ( "Ô", 212 )
, ( "Õ", 213 )
, ( "Ö", 214 )
, ( "Ø", 216 )
, ( "Ù", 217 )
, ( "Ú", 218 )
, ( "Û", 219 )
, ( "Ü", 220 )
, ( "Ý", 221 )
, ( "Þ", 222 )
, ( "ß", 223 )
, ( "à", 224 )
, ( "á", 225 )
, ( "â", 226 )
, ( "ã", 227 )
, ( "ä", 228 )
, ( "å", 229 )
, ( "æ", 230 )
, ( "ç", 231 )
, ( "è", 232 )
, ( "é", 233 )
, ( "ê", 234 )
, ( "ë", 235 )
, ( "ì", 236 )
, ( "í", 237 )
, ( "î", 238 )
, ( "ï", 239 )
, ( "ð", 240 )
, ( "ñ", 241 )
, ( "ò", 242 )
, ( "ó", 243 )
, ( "ô", 244 )
, ( "õ", 245 )
, ( "ö", 246 )
, ( "ø", 248 )
, ( "ù", 249 )
, ( "ú", 250 )
, ( "û", 251 )
, ( "ü", 252 )
, ( "ý", 253 )
, ( "þ", 254 )
, ( "ÿ", 255 )
, ( "&", 38 )
, ( "<", 60 )
, ( ">", 62 )
, ( " ", 32 )
, ( "!", 33 )
, ( """, 34 )
, ( "#", 35 )
, ( "$", 36 )
, ( "%", 37 )
, ( "'", 39 )
, ( "(", 40 )
, ( ")", 41 )
, ( "*", 42 )
, ( "+", 43 )
, ( ",", 44 )
, ( "-", 45 )
, ( ".", 46 )
, ( "/", 47 )
, ( "0", 48 )
, ( "1", 49 )
, ( "2", 50 )
, ( "3", 51 )
, ( "4", 52 )
, ( "5", 53 )
, ( "6", 54 )
, ( "7", 55 )
, ( "8", 56 )
, ( "9", 57 )
, ( ":", 58 )
, ( ";", 59 )
, ( "=", 61 )
, ( "?", 63 )
, ( "@", 64 )
, ( "A", 65 )
, ( "B", 66 )
, ( "C", 67 )
, ( "D", 68 )
, ( "E", 69 )
, ( "F", 70 )
, ( "G", 71 )
, ( "H", 72 )
, ( "I", 73 )
, ( "J", 74 )
, ( "K", 75 )
, ( "L", 76 )
, ( "M", 77 )
, ( "N", 78 )
, ( "O", 79 )
, ( "P", 80 )
, ( "Q", 81 )
, ( "R", 82 )
, ( "S", 83 )
, ( "T", 84 )
, ( "U", 85 )
, ( "V", 86 )
, ( "W", 87 )
, ( "X", 88 )
, ( "Y", 89 )
, ( "Z", 90 )
, ( "[", 91 )
, ( "\", 92 )
, ( "]", 93 )
, ( "^", 94 )
, ( "_", 95 )
, ( "`", 96 )
, ( "a", 97 )
, ( "b", 98 )
, ( "c", 99 )
, ( "d", 100 )
, ( "e", 101 )
, ( "f", 102 )
, ( "g", 103 )
, ( "h", 104 )
, ( "i", 105 )
, ( "j", 106 )
, ( "k", 107 )
, ( "l", 108 )
, ( "m", 109 )
, ( "n", 110 )
, ( "o", 111 )
, ( "p", 112 )
, ( "q", 113 )
, ( "r", 114 )
, ( "s", 115 )
, ( "t", 116 )
, ( "u", 117 )
, ( "v", 118 )
, ( "w", 119 )
, ( "x", 120 )
, ( "y", 121 )
, ( "z", 122 )
, ( "{", 123 )
, ( "|", 124 )
, ( "}", 125 )
, ( "~", 126 )
]
| 52967 | module ParseHtml.HtmlEntities exposing (htmlEntities)
htmlEntities : List ( String, Int )
htmlEntities =
[ ( "Œ", 338 )
, ( "œ", 339 )
, ( "&<NAME>;", 352 )
, ( "š", 353 )
, ( "Ÿ", 376 )
, ( "ƒ", 402 )
, ( "ˆ", 710 )
, ( "˜", 732 )
, ( " ", 8194 )
, ( " ", 8195 )
, ( " ", 8201 )
, ( "‌", 8204 )
, ( "‍", 8205 )
, ( "‎", 8206 )
, ( "‏", 8207 )
, ( "–", 8211 )
, ( "—", 8212 )
, ( "‘", 8216 )
, ( "’", 8217 )
, ( "‚", 8218 )
, ( "“", 8220 )
, ( "”", 8221 )
, ( "„", 8222 )
, ( "†", 8224 )
, ( "‡", 8225 )
, ( "•", 8226 )
, ( "…", 8230 )
, ( "‰", 8240 )
, ( "′", 8242 )
, ( "″", 8243 )
, ( "‹", 8249 )
, ( "›", 8250 )
, ( "‾", 8254 )
, ( "€", 8364 )
, ( "™", 8482 )
, ( "←", 8592 )
, ( "↑", 8593 )
, ( "→", 8594 )
, ( "↓", 8595 )
, ( "↔", 8596 )
, ( "↵", 8629 )
, ( "⌈", 8968 )
, ( "⌉", 8969 )
, ( "⌊", 8970 )
, ( "⌋", 8971 )
, ( "◊", 9674 )
, ( "♠", 9824 )
, ( "♣", 9827 )
, ( "♥", 9829 )
, ( "♦", 9830 )
, ( "Α", 913 )
, ( "Β", 914 )
, ( "Γ", 915 )
, ( "Δ", 916 )
, ( "Ε", 917 )
, ( "Ζ", 918 )
, ( "Η", 919 )
, ( "Θ", 920 )
, ( "Ι", 921 )
, ( "Κ", 922 )
, ( "Λ", 923 )
, ( "Μ", 924 )
, ( "Ν", 925 )
, ( "Ξ", 926 )
, ( "Ο", 927 )
, ( "Π", 928 )
, ( "Ρ", 929 )
, ( "Σ", 931 )
, ( "Τ", 932 )
, ( "Υ", 933 )
, ( "Φ", 934 )
, ( "Χ", 935 )
, ( "Ψ", 936 )
, ( "Ω", 937 )
, ( "α", 945 )
, ( "β", 946 )
, ( "γ", 947 )
, ( "δ", 948 )
, ( "ε", 949 )
, ( "ζ", 950 )
, ( "η", 951 )
, ( "θ", 952 )
, ( "ι", 953 )
, ( "κ", 954 )
, ( "λ", 955 )
, ( "μ", 956 )
, ( "ν", 957 )
, ( "ξ", 958 )
, ( "ο", 959 )
, ( "π", 960 )
, ( "ρ", 961 )
, ( "ς", 962 )
, ( "σ", 963 )
, ( "τ", 964 )
, ( "υ", 965 )
, ( "φ", 966 )
, ( "χ", 967 )
, ( "ψ", 968 )
, ( "ω", 969 )
, ( "ϑ", 977 )
, ( "ϒ", 978 )
, ( "ϖ", 982 )
, ( "∀", 8704 )
, ( "∂", 8706 )
, ( "∃", 8707 )
, ( "∅", 8709 )
, ( "∇", 8711 )
, ( "∈", 8712 )
, ( "∉", 8713 )
, ( "∋", 8715 )
, ( "∏", 8719 )
, ( "∑", 8721 )
, ( "−", 8722 )
, ( "∗", 8727 )
, ( "√", 8730 )
, ( "∝", 8733 )
, ( "∞", 8734 )
, ( "∠", 8736 )
, ( "∧", 8743 )
, ( "∨", 8744 )
, ( "∩", 8745 )
, ( "∪", 8746 )
, ( "∫", 8747 )
, ( "∴", 8756 )
, ( "∼", 8764 )
, ( "≅", 8773 )
, ( "≈", 8776 )
, ( "≠", 8800 )
, ( "≡", 8801 )
, ( "≤", 8804 )
, ( "≥", 8805 )
, ( "⊂", 8834 )
, ( "⊃", 8835 )
, ( "⊄", 8836 )
, ( "⊆", 8838 )
, ( "⊇", 8839 )
, ( "⊕", 8853 )
, ( "⊗", 8855 )
, ( "⊥", 8869 )
, ( "⋅", 8901 )
, ( " ", 160 )
, ( "¡", 161 )
, ( "¢", 162 )
, ( "£", 163 )
, ( "¤", 164 )
, ( "¥", 165 )
, ( "¦", 166 )
, ( "§", 167 )
, ( "¨", 168 )
, ( "©", 169 )
, ( "ª", 170 )
, ( "«", 171 )
, ( "¬", 172 )
, ( "­", 173 )
, ( "®", 174 )
, ( "¯", 175 )
, ( "°", 176 )
, ( "±", 177 )
, ( "²", 178 )
, ( "³", 179 )
, ( "´", 180 )
, ( "µ", 181 )
, ( "¶", 182 )
, ( "¸", 184 )
, ( "¹", 185 )
, ( "º", 186 )
, ( "»", 187 )
, ( "¼", 188 )
, ( "½", 189 )
, ( "¾", 190 )
, ( "¿", 191 )
, ( "×", 215 )
, ( "÷", 247 )
, ( "À", 192 )
, ( "Á", 193 )
, ( "Â", 194 )
, ( "Ã", 195 )
, ( "Ä", 196 )
, ( "Å", 197 )
, ( "Æ", 198 )
, ( "Ç", 199 )
, ( "È", 200 )
, ( "É", 201 )
, ( "Ê", 202 )
, ( "Ë", 203 )
, ( "Ì", 204 )
, ( "Í", 205 )
, ( "Î", 206 )
, ( "Ï", 207 )
, ( "Ð", 208 )
, ( "Ñ", 209 )
, ( "Ò", 210 )
, ( "Ó", 211 )
, ( "Ô", 212 )
, ( "Õ", 213 )
, ( "Ö", 214 )
, ( "Ø", 216 )
, ( "Ù", 217 )
, ( "Ú", 218 )
, ( "Û", 219 )
, ( "Ü", 220 )
, ( "Ý", 221 )
, ( "Þ", 222 )
, ( "ß", 223 )
, ( "à", 224 )
, ( "á", 225 )
, ( "â", 226 )
, ( "ã", 227 )
, ( "ä", 228 )
, ( "å", 229 )
, ( "æ", 230 )
, ( "ç", 231 )
, ( "è", 232 )
, ( "é", 233 )
, ( "ê", 234 )
, ( "ë", 235 )
, ( "ì", 236 )
, ( "í", 237 )
, ( "î", 238 )
, ( "ï", 239 )
, ( "ð", 240 )
, ( "ñ", 241 )
, ( "ò", 242 )
, ( "ó", 243 )
, ( "ô", 244 )
, ( "õ", 245 )
, ( "ö", 246 )
, ( "ø", 248 )
, ( "ù", 249 )
, ( "ú", 250 )
, ( "û", 251 )
, ( "ü", 252 )
, ( "ý", 253 )
, ( "þ", 254 )
, ( "ÿ", 255 )
, ( "&", 38 )
, ( "<", 60 )
, ( ">", 62 )
, ( " ", 32 )
, ( "!", 33 )
, ( """, 34 )
, ( "#", 35 )
, ( "$", 36 )
, ( "%", 37 )
, ( "'", 39 )
, ( "(", 40 )
, ( ")", 41 )
, ( "*", 42 )
, ( "+", 43 )
, ( ",", 44 )
, ( "-", 45 )
, ( ".", 46 )
, ( "/", 47 )
, ( "0", 48 )
, ( "1", 49 )
, ( "2", 50 )
, ( "3", 51 )
, ( "4", 52 )
, ( "5", 53 )
, ( "6", 54 )
, ( "7", 55 )
, ( "8", 56 )
, ( "9", 57 )
, ( ":", 58 )
, ( ";", 59 )
, ( "=", 61 )
, ( "?", 63 )
, ( "@", 64 )
, ( "A", 65 )
, ( "B", 66 )
, ( "C", 67 )
, ( "D", 68 )
, ( "E", 69 )
, ( "F", 70 )
, ( "G", 71 )
, ( "H", 72 )
, ( "I", 73 )
, ( "J", 74 )
, ( "K", 75 )
, ( "L", 76 )
, ( "M", 77 )
, ( "N", 78 )
, ( "O", 79 )
, ( "P", 80 )
, ( "Q", 81 )
, ( "R", 82 )
, ( "S", 83 )
, ( "T", 84 )
, ( "U", 85 )
, ( "V", 86 )
, ( "W", 87 )
, ( "X", 88 )
, ( "Y", 89 )
, ( "Z", 90 )
, ( "[", 91 )
, ( "\", 92 )
, ( "]", 93 )
, ( "^", 94 )
, ( "_", 95 )
, ( "`", 96 )
, ( "a", 97 )
, ( "b", 98 )
, ( "c", 99 )
, ( "d", 100 )
, ( "e", 101 )
, ( "f", 102 )
, ( "g", 103 )
, ( "h", 104 )
, ( "i", 105 )
, ( "j", 106 )
, ( "k", 107 )
, ( "l", 108 )
, ( "m", 109 )
, ( "n", 110 )
, ( "o", 111 )
, ( "p", 112 )
, ( "q", 113 )
, ( "r", 114 )
, ( "s", 115 )
, ( "t", 116 )
, ( "u", 117 )
, ( "v", 118 )
, ( "w", 119 )
, ( "x", 120 )
, ( "y", 121 )
, ( "z", 122 )
, ( "{", 123 )
, ( "|", 124 )
, ( "}", 125 )
, ( "~", 126 )
]
| true | module ParseHtml.HtmlEntities exposing (htmlEntities)
htmlEntities : List ( String, Int )
htmlEntities =
[ ( "Œ", 338 )
, ( "œ", 339 )
, ( "&PI:NAME:<NAME>END_PI;", 352 )
, ( "š", 353 )
, ( "Ÿ", 376 )
, ( "ƒ", 402 )
, ( "ˆ", 710 )
, ( "˜", 732 )
, ( " ", 8194 )
, ( " ", 8195 )
, ( " ", 8201 )
, ( "‌", 8204 )
, ( "‍", 8205 )
, ( "‎", 8206 )
, ( "‏", 8207 )
, ( "–", 8211 )
, ( "—", 8212 )
, ( "‘", 8216 )
, ( "’", 8217 )
, ( "‚", 8218 )
, ( "“", 8220 )
, ( "”", 8221 )
, ( "„", 8222 )
, ( "†", 8224 )
, ( "‡", 8225 )
, ( "•", 8226 )
, ( "…", 8230 )
, ( "‰", 8240 )
, ( "′", 8242 )
, ( "″", 8243 )
, ( "‹", 8249 )
, ( "›", 8250 )
, ( "‾", 8254 )
, ( "€", 8364 )
, ( "™", 8482 )
, ( "←", 8592 )
, ( "↑", 8593 )
, ( "→", 8594 )
, ( "↓", 8595 )
, ( "↔", 8596 )
, ( "↵", 8629 )
, ( "⌈", 8968 )
, ( "⌉", 8969 )
, ( "⌊", 8970 )
, ( "⌋", 8971 )
, ( "◊", 9674 )
, ( "♠", 9824 )
, ( "♣", 9827 )
, ( "♥", 9829 )
, ( "♦", 9830 )
, ( "Α", 913 )
, ( "Β", 914 )
, ( "Γ", 915 )
, ( "Δ", 916 )
, ( "Ε", 917 )
, ( "Ζ", 918 )
, ( "Η", 919 )
, ( "Θ", 920 )
, ( "Ι", 921 )
, ( "Κ", 922 )
, ( "Λ", 923 )
, ( "Μ", 924 )
, ( "Ν", 925 )
, ( "Ξ", 926 )
, ( "Ο", 927 )
, ( "Π", 928 )
, ( "Ρ", 929 )
, ( "Σ", 931 )
, ( "Τ", 932 )
, ( "Υ", 933 )
, ( "Φ", 934 )
, ( "Χ", 935 )
, ( "Ψ", 936 )
, ( "Ω", 937 )
, ( "α", 945 )
, ( "β", 946 )
, ( "γ", 947 )
, ( "δ", 948 )
, ( "ε", 949 )
, ( "ζ", 950 )
, ( "η", 951 )
, ( "θ", 952 )
, ( "ι", 953 )
, ( "κ", 954 )
, ( "λ", 955 )
, ( "μ", 956 )
, ( "ν", 957 )
, ( "ξ", 958 )
, ( "ο", 959 )
, ( "π", 960 )
, ( "ρ", 961 )
, ( "ς", 962 )
, ( "σ", 963 )
, ( "τ", 964 )
, ( "υ", 965 )
, ( "φ", 966 )
, ( "χ", 967 )
, ( "ψ", 968 )
, ( "ω", 969 )
, ( "ϑ", 977 )
, ( "ϒ", 978 )
, ( "ϖ", 982 )
, ( "∀", 8704 )
, ( "∂", 8706 )
, ( "∃", 8707 )
, ( "∅", 8709 )
, ( "∇", 8711 )
, ( "∈", 8712 )
, ( "∉", 8713 )
, ( "∋", 8715 )
, ( "∏", 8719 )
, ( "∑", 8721 )
, ( "−", 8722 )
, ( "∗", 8727 )
, ( "√", 8730 )
, ( "∝", 8733 )
, ( "∞", 8734 )
, ( "∠", 8736 )
, ( "∧", 8743 )
, ( "∨", 8744 )
, ( "∩", 8745 )
, ( "∪", 8746 )
, ( "∫", 8747 )
, ( "∴", 8756 )
, ( "∼", 8764 )
, ( "≅", 8773 )
, ( "≈", 8776 )
, ( "≠", 8800 )
, ( "≡", 8801 )
, ( "≤", 8804 )
, ( "≥", 8805 )
, ( "⊂", 8834 )
, ( "⊃", 8835 )
, ( "⊄", 8836 )
, ( "⊆", 8838 )
, ( "⊇", 8839 )
, ( "⊕", 8853 )
, ( "⊗", 8855 )
, ( "⊥", 8869 )
, ( "⋅", 8901 )
, ( " ", 160 )
, ( "¡", 161 )
, ( "¢", 162 )
, ( "£", 163 )
, ( "¤", 164 )
, ( "¥", 165 )
, ( "¦", 166 )
, ( "§", 167 )
, ( "¨", 168 )
, ( "©", 169 )
, ( "ª", 170 )
, ( "«", 171 )
, ( "¬", 172 )
, ( "­", 173 )
, ( "®", 174 )
, ( "¯", 175 )
, ( "°", 176 )
, ( "±", 177 )
, ( "²", 178 )
, ( "³", 179 )
, ( "´", 180 )
, ( "µ", 181 )
, ( "¶", 182 )
, ( "¸", 184 )
, ( "¹", 185 )
, ( "º", 186 )
, ( "»", 187 )
, ( "¼", 188 )
, ( "½", 189 )
, ( "¾", 190 )
, ( "¿", 191 )
, ( "×", 215 )
, ( "÷", 247 )
, ( "À", 192 )
, ( "Á", 193 )
, ( "Â", 194 )
, ( "Ã", 195 )
, ( "Ä", 196 )
, ( "Å", 197 )
, ( "Æ", 198 )
, ( "Ç", 199 )
, ( "È", 200 )
, ( "É", 201 )
, ( "Ê", 202 )
, ( "Ë", 203 )
, ( "Ì", 204 )
, ( "Í", 205 )
, ( "Î", 206 )
, ( "Ï", 207 )
, ( "Ð", 208 )
, ( "Ñ", 209 )
, ( "Ò", 210 )
, ( "Ó", 211 )
, ( "Ô", 212 )
, ( "Õ", 213 )
, ( "Ö", 214 )
, ( "Ø", 216 )
, ( "Ù", 217 )
, ( "Ú", 218 )
, ( "Û", 219 )
, ( "Ü", 220 )
, ( "Ý", 221 )
, ( "Þ", 222 )
, ( "ß", 223 )
, ( "à", 224 )
, ( "á", 225 )
, ( "â", 226 )
, ( "ã", 227 )
, ( "ä", 228 )
, ( "å", 229 )
, ( "æ", 230 )
, ( "ç", 231 )
, ( "è", 232 )
, ( "é", 233 )
, ( "ê", 234 )
, ( "ë", 235 )
, ( "ì", 236 )
, ( "í", 237 )
, ( "î", 238 )
, ( "ï", 239 )
, ( "ð", 240 )
, ( "ñ", 241 )
, ( "ò", 242 )
, ( "ó", 243 )
, ( "ô", 244 )
, ( "õ", 245 )
, ( "ö", 246 )
, ( "ø", 248 )
, ( "ù", 249 )
, ( "ú", 250 )
, ( "û", 251 )
, ( "ü", 252 )
, ( "ý", 253 )
, ( "þ", 254 )
, ( "ÿ", 255 )
, ( "&", 38 )
, ( "<", 60 )
, ( ">", 62 )
, ( " ", 32 )
, ( "!", 33 )
, ( """, 34 )
, ( "#", 35 )
, ( "$", 36 )
, ( "%", 37 )
, ( "'", 39 )
, ( "(", 40 )
, ( ")", 41 )
, ( "*", 42 )
, ( "+", 43 )
, ( ",", 44 )
, ( "-", 45 )
, ( ".", 46 )
, ( "/", 47 )
, ( "0", 48 )
, ( "1", 49 )
, ( "2", 50 )
, ( "3", 51 )
, ( "4", 52 )
, ( "5", 53 )
, ( "6", 54 )
, ( "7", 55 )
, ( "8", 56 )
, ( "9", 57 )
, ( ":", 58 )
, ( ";", 59 )
, ( "=", 61 )
, ( "?", 63 )
, ( "@", 64 )
, ( "A", 65 )
, ( "B", 66 )
, ( "C", 67 )
, ( "D", 68 )
, ( "E", 69 )
, ( "F", 70 )
, ( "G", 71 )
, ( "H", 72 )
, ( "I", 73 )
, ( "J", 74 )
, ( "K", 75 )
, ( "L", 76 )
, ( "M", 77 )
, ( "N", 78 )
, ( "O", 79 )
, ( "P", 80 )
, ( "Q", 81 )
, ( "R", 82 )
, ( "S", 83 )
, ( "T", 84 )
, ( "U", 85 )
, ( "V", 86 )
, ( "W", 87 )
, ( "X", 88 )
, ( "Y", 89 )
, ( "Z", 90 )
, ( "[", 91 )
, ( "\", 92 )
, ( "]", 93 )
, ( "^", 94 )
, ( "_", 95 )
, ( "`", 96 )
, ( "a", 97 )
, ( "b", 98 )
, ( "c", 99 )
, ( "d", 100 )
, ( "e", 101 )
, ( "f", 102 )
, ( "g", 103 )
, ( "h", 104 )
, ( "i", 105 )
, ( "j", 106 )
, ( "k", 107 )
, ( "l", 108 )
, ( "m", 109 )
, ( "n", 110 )
, ( "o", 111 )
, ( "p", 112 )
, ( "q", 113 )
, ( "r", 114 )
, ( "s", 115 )
, ( "t", 116 )
, ( "u", 117 )
, ( "v", 118 )
, ( "w", 119 )
, ( "x", 120 )
, ( "y", 121 )
, ( "z", 122 )
, ( "{", 123 )
, ( "|", 124 )
, ( "}", 125 )
, ( "~", 126 )
]
| elm |
[
{
"context": "{-\nCopyright 2020 Morgan Stanley\n\nLicensed under the Apache License, Version 2.0 (",
"end": 32,
"score": 0.9997756481,
"start": 18,
"tag": "NAME",
"value": "Morgan Stanley"
}
] | draft/DevBot/Java/Ast.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 SlateX.DevBot.Java.Ast exposing (..)
{-| Java AST based on: https://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html
-}
type alias TODO = Never
type alias Identifier =
String
type alias QualifiedIdentifier =
List Identifier
type alias CompilationUnit =
{ filePath : List String
, fileName : String
, packageDecl : Maybe PackageDeclaration
, imports : List ImportDeclaration
, typeDecls : List TypeDeclaration
}
type alias PackageDeclaration =
{ annotations : List Annotation
, qualifiedName : QualifiedIdentifier
}
type ImportDeclaration
= Import QualifiedIdentifier Bool
| StaticImport QualifiedIdentifier Bool
type TypeDeclaration
= Class
{ modifiers : List Modifier
, name : Identifier
, typeParams : List Identifier
, extends : Maybe Type
, implements : List Type
, members : List MemberDecl
}
| Interface
{ modifiers : List Modifier
, name : Identifier
, typeParams : List Identifier
, extends : List Type
, members : List MemberDecl
}
| Enum
{ modifiers : List Modifier
, name : Identifier
, implements : List Type
, values : List Identifier
}
type Modifier
= Public
| Private
| Static
| Abstract
| Final
type MemberDecl
= Field
{ modifiers : List Modifier
, tpe : Type
, name : Identifier
}
| Constructor
{ modifiers : List Modifier
, args : List ( Identifier, Type )
, body : Maybe (List Exp)
}
| Method
{ modifiers : List Modifier
, typeParams : List Identifier
, returnType : Type
, name : Identifier
, args : List ( Identifier, Type )
, body : List Exp
}
type Type
= Void
| TypeRef QualifiedIdentifier
| TypeConst QualifiedIdentifier (List Type)
| TypeVar Identifier
| Predicate Type
| Function Type Type
type alias Annotation = TODO
type Exp
= VariableDecl (List Modifier) Type Identifier (Maybe Exp)
| Assign Exp Exp
| Return Exp
| Throw Exp
| Statements (List Exp)
| BooleanLit Bool
| StringLit String
| IntLit Int
| Variable Identifier
| This
| Select Exp Identifier
| BinOp Exp String Exp
| ValueRef QualifiedIdentifier
| Apply Exp (List Exp)
| Lambda (List Identifier) Exp
| Ternary Exp Exp Exp
| IfElse Exp (List Exp) (List Exp)
| ConstructorRef QualifiedIdentifier
| UnaryOp String Exp
| Cast Type Exp
| Null
--| Switch Exp (List ( Exp, Exp )) (Maybe Exp)
| 28797 | {-
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 SlateX.DevBot.Java.Ast exposing (..)
{-| Java AST based on: https://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html
-}
type alias TODO = Never
type alias Identifier =
String
type alias QualifiedIdentifier =
List Identifier
type alias CompilationUnit =
{ filePath : List String
, fileName : String
, packageDecl : Maybe PackageDeclaration
, imports : List ImportDeclaration
, typeDecls : List TypeDeclaration
}
type alias PackageDeclaration =
{ annotations : List Annotation
, qualifiedName : QualifiedIdentifier
}
type ImportDeclaration
= Import QualifiedIdentifier Bool
| StaticImport QualifiedIdentifier Bool
type TypeDeclaration
= Class
{ modifiers : List Modifier
, name : Identifier
, typeParams : List Identifier
, extends : Maybe Type
, implements : List Type
, members : List MemberDecl
}
| Interface
{ modifiers : List Modifier
, name : Identifier
, typeParams : List Identifier
, extends : List Type
, members : List MemberDecl
}
| Enum
{ modifiers : List Modifier
, name : Identifier
, implements : List Type
, values : List Identifier
}
type Modifier
= Public
| Private
| Static
| Abstract
| Final
type MemberDecl
= Field
{ modifiers : List Modifier
, tpe : Type
, name : Identifier
}
| Constructor
{ modifiers : List Modifier
, args : List ( Identifier, Type )
, body : Maybe (List Exp)
}
| Method
{ modifiers : List Modifier
, typeParams : List Identifier
, returnType : Type
, name : Identifier
, args : List ( Identifier, Type )
, body : List Exp
}
type Type
= Void
| TypeRef QualifiedIdentifier
| TypeConst QualifiedIdentifier (List Type)
| TypeVar Identifier
| Predicate Type
| Function Type Type
type alias Annotation = TODO
type Exp
= VariableDecl (List Modifier) Type Identifier (Maybe Exp)
| Assign Exp Exp
| Return Exp
| Throw Exp
| Statements (List Exp)
| BooleanLit Bool
| StringLit String
| IntLit Int
| Variable Identifier
| This
| Select Exp Identifier
| BinOp Exp String Exp
| ValueRef QualifiedIdentifier
| Apply Exp (List Exp)
| Lambda (List Identifier) Exp
| Ternary Exp Exp Exp
| IfElse Exp (List Exp) (List Exp)
| ConstructorRef QualifiedIdentifier
| UnaryOp String Exp
| Cast Type Exp
| Null
--| Switch Exp (List ( Exp, Exp )) (Maybe Exp)
| 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 SlateX.DevBot.Java.Ast exposing (..)
{-| Java AST based on: https://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html
-}
type alias TODO = Never
type alias Identifier =
String
type alias QualifiedIdentifier =
List Identifier
type alias CompilationUnit =
{ filePath : List String
, fileName : String
, packageDecl : Maybe PackageDeclaration
, imports : List ImportDeclaration
, typeDecls : List TypeDeclaration
}
type alias PackageDeclaration =
{ annotations : List Annotation
, qualifiedName : QualifiedIdentifier
}
type ImportDeclaration
= Import QualifiedIdentifier Bool
| StaticImport QualifiedIdentifier Bool
type TypeDeclaration
= Class
{ modifiers : List Modifier
, name : Identifier
, typeParams : List Identifier
, extends : Maybe Type
, implements : List Type
, members : List MemberDecl
}
| Interface
{ modifiers : List Modifier
, name : Identifier
, typeParams : List Identifier
, extends : List Type
, members : List MemberDecl
}
| Enum
{ modifiers : List Modifier
, name : Identifier
, implements : List Type
, values : List Identifier
}
type Modifier
= Public
| Private
| Static
| Abstract
| Final
type MemberDecl
= Field
{ modifiers : List Modifier
, tpe : Type
, name : Identifier
}
| Constructor
{ modifiers : List Modifier
, args : List ( Identifier, Type )
, body : Maybe (List Exp)
}
| Method
{ modifiers : List Modifier
, typeParams : List Identifier
, returnType : Type
, name : Identifier
, args : List ( Identifier, Type )
, body : List Exp
}
type Type
= Void
| TypeRef QualifiedIdentifier
| TypeConst QualifiedIdentifier (List Type)
| TypeVar Identifier
| Predicate Type
| Function Type Type
type alias Annotation = TODO
type Exp
= VariableDecl (List Modifier) Type Identifier (Maybe Exp)
| Assign Exp Exp
| Return Exp
| Throw Exp
| Statements (List Exp)
| BooleanLit Bool
| StringLit String
| IntLit Int
| Variable Identifier
| This
| Select Exp Identifier
| BinOp Exp String Exp
| ValueRef QualifiedIdentifier
| Apply Exp (List Exp)
| Lambda (List Identifier) Exp
| Ternary Exp Exp Exp
| IfElse Exp (List Exp) (List Exp)
| ConstructorRef QualifiedIdentifier
| UnaryOp String Exp
| Cast Type Exp
| Null
--| Switch Exp (List ( Exp, Exp )) (Maybe Exp)
| elm |
[
{
"context": "-\n Operations/Conversion/Automata.elm\n Author: Henrique da Cunha Buss\n Creation: October/2020\n This file contains f",
"end": 74,
"score": 0.9998477101,
"start": 52,
"tag": "NAME",
"value": "Henrique da Cunha Buss"
}
] | src/Operations/Conversion/Automata.elm | NeoVier/LFC01 | 0 | {-
Operations/Conversion/Automata.elm
Author: Henrique da Cunha Buss
Creation: October/2020
This file contains functions to convert between Automata
-}
module Operations.Conversion.Automata exposing (afdToGr, afndToAfd)
import Models.Alphabet as Alphabet
import Models.Automata as Automata
import Models.Grammars as Grammars
import Models.State as State
import Models.Transition as Transition
import Operations.Conversion.Alphabet as CAlphabet
import Operations.Conversion.Transition as CTransition
import Utils.Utils as Utils
-- AFND to AFD
{- Converts an AFND to AFD -}
afndToAfd : Automata.AFND -> Automata.AFD
afndToAfd afnd =
let
-- All combinations of states
newStates =
Utils.subsequences afnd.states
|> List.sortBy List.length
|> List.map Utils.listOfStatesToState
newTransitions : List Transition.DeterministicTransition
newTransitions =
List.concatMap
(\complexState ->
Utils.stateToListOfStates complexState
|> List.concatMap (getTransitions afnd)
|> List.map (\t -> { t | prevState = complexState })
|> List.filter (.nextState >> (/=) State.Dead)
|> Utils.removeDuplicates
)
newStates
|> Utils.removeDuplicates
|> Utils.sortTransitionsDeterministic
|> Utils.joinTransitionsDeterministic
newFinalStates =
List.filter
(\state ->
Utils.stateToListOfStates state
|> List.any (\st -> List.member st afnd.finalStates)
)
newStates
newInitialState =
Utils.followEpsilonStar afnd afnd.initialState
|> Utils.listOfStatesToState
in
{ states = newStates
, initialState = newInitialState
, finalStates = List.append afnd.finalStates newFinalStates
, alphabet = CAlphabet.nonDeterministicToDeterministic afnd.alphabet
, transitions = newTransitions
}
getTransitionThrough :
Automata.AFND
-> State.State
-> Alphabet.Symbol
-> Transition.DeterministicTransition
getTransitionThrough afnd state symbol =
let
epsilonStar =
Utils.followEpsilonStar afnd state
allStates =
List.concatMap (Utils.getFlatOutTransitionsNonDeterministic afnd)
epsilonStar
|> List.filter
(\t ->
t.conditions
== Transition.NoEpsilon [ symbol ]
&& t.nextStates
/= [ State.Dead ]
)
|> List.concatMap
(.nextStates
>> List.concatMap (Utils.followEpsilonStar afnd)
)
|> Utils.removeDuplicates
in
{ prevState = state
, conditions = [ symbol ]
, nextState = Utils.listOfStatesToState allStates
}
getTransitions :
Automata.AFND
-> State.State
-> List Transition.DeterministicTransition
getTransitions afnd origin =
CAlphabet.nonDeterministicToDeterministic afnd.alphabet
|> List.map (getTransitionThrough afnd origin)
-- AFD TO GR
{- Converts and AFD to a GR -}
afdToGr : Automata.AFD -> Grammars.RegularGrammar
afdToGr afd =
let
nonTerminals =
List.map stateToSymbol afd.states
|> Utils.listOfMaybesToMaybeList
|> Maybe.withDefault []
terminals =
afd.alphabet
initialSymbol =
stateToSymbol afd.initialState
|> Maybe.withDefault "S"
in
{ nonTerminals = nonTerminals
, terminals = terminals
, productions =
List.filterMap
(\transition ->
transitionToProduction transition afd.finalStates
)
afd.transitions
, initialSymbol = initialSymbol
, acceptsEmpty = List.member afd.initialState afd.finalStates
}
|> Utils.joinGrammarProductions
|> cleanGR
cleanGR : Grammars.RegularGrammar -> Grammars.RegularGrammar
cleanGR gr =
let
validNonTerminals =
List.filter
(\nonTerminal ->
List.map .fromSymbol gr.productions
|> List.member nonTerminal
)
gr.nonTerminals
cleanProduction : Grammars.Production -> Grammars.Production
cleanProduction prod =
{ prod
| productions =
List.filter
(\body ->
case body.toSymbol of
Nothing ->
True
Just s ->
List.member s validNonTerminals
)
prod.productions
}
in
{ gr
| nonTerminals = validNonTerminals
, productions =
List.map cleanProduction gr.productions
}
{- Convert a State to a Maybe Symbol -}
stateToSymbol : State.State -> Maybe Grammars.NonTerminalSymbol
stateToSymbol state =
case state of
State.Dead ->
Nothing
State.Valid label ->
Just label
{- Converts a Transition into a Maybe Grammars.Production -}
transitionToProduction :
Transition.DeterministicTransition
-> List State.State
-> Maybe Grammars.Production
transitionToProduction transition finalStates =
case transition.nextState of
State.Dead ->
Nothing
State.Valid _ ->
let
toSymbol =
stateToSymbol transition.nextState
isFinal =
List.member transition.nextState finalStates
productions =
List.concatMap
(\condition ->
if isFinal then
[ { consumed = condition, toSymbol = toSymbol }
, { consumed = condition, toSymbol = Nothing }
]
else
[ { consumed = condition, toSymbol = toSymbol } ]
)
transition.conditions
in
stateToSymbol transition.prevState
|> Maybe.map
(\fromSymbol ->
{ fromSymbol = fromSymbol
, productions = productions
}
)
| 44751 | {-
Operations/Conversion/Automata.elm
Author: <NAME>
Creation: October/2020
This file contains functions to convert between Automata
-}
module Operations.Conversion.Automata exposing (afdToGr, afndToAfd)
import Models.Alphabet as Alphabet
import Models.Automata as Automata
import Models.Grammars as Grammars
import Models.State as State
import Models.Transition as Transition
import Operations.Conversion.Alphabet as CAlphabet
import Operations.Conversion.Transition as CTransition
import Utils.Utils as Utils
-- AFND to AFD
{- Converts an AFND to AFD -}
afndToAfd : Automata.AFND -> Automata.AFD
afndToAfd afnd =
let
-- All combinations of states
newStates =
Utils.subsequences afnd.states
|> List.sortBy List.length
|> List.map Utils.listOfStatesToState
newTransitions : List Transition.DeterministicTransition
newTransitions =
List.concatMap
(\complexState ->
Utils.stateToListOfStates complexState
|> List.concatMap (getTransitions afnd)
|> List.map (\t -> { t | prevState = complexState })
|> List.filter (.nextState >> (/=) State.Dead)
|> Utils.removeDuplicates
)
newStates
|> Utils.removeDuplicates
|> Utils.sortTransitionsDeterministic
|> Utils.joinTransitionsDeterministic
newFinalStates =
List.filter
(\state ->
Utils.stateToListOfStates state
|> List.any (\st -> List.member st afnd.finalStates)
)
newStates
newInitialState =
Utils.followEpsilonStar afnd afnd.initialState
|> Utils.listOfStatesToState
in
{ states = newStates
, initialState = newInitialState
, finalStates = List.append afnd.finalStates newFinalStates
, alphabet = CAlphabet.nonDeterministicToDeterministic afnd.alphabet
, transitions = newTransitions
}
getTransitionThrough :
Automata.AFND
-> State.State
-> Alphabet.Symbol
-> Transition.DeterministicTransition
getTransitionThrough afnd state symbol =
let
epsilonStar =
Utils.followEpsilonStar afnd state
allStates =
List.concatMap (Utils.getFlatOutTransitionsNonDeterministic afnd)
epsilonStar
|> List.filter
(\t ->
t.conditions
== Transition.NoEpsilon [ symbol ]
&& t.nextStates
/= [ State.Dead ]
)
|> List.concatMap
(.nextStates
>> List.concatMap (Utils.followEpsilonStar afnd)
)
|> Utils.removeDuplicates
in
{ prevState = state
, conditions = [ symbol ]
, nextState = Utils.listOfStatesToState allStates
}
getTransitions :
Automata.AFND
-> State.State
-> List Transition.DeterministicTransition
getTransitions afnd origin =
CAlphabet.nonDeterministicToDeterministic afnd.alphabet
|> List.map (getTransitionThrough afnd origin)
-- AFD TO GR
{- Converts and AFD to a GR -}
afdToGr : Automata.AFD -> Grammars.RegularGrammar
afdToGr afd =
let
nonTerminals =
List.map stateToSymbol afd.states
|> Utils.listOfMaybesToMaybeList
|> Maybe.withDefault []
terminals =
afd.alphabet
initialSymbol =
stateToSymbol afd.initialState
|> Maybe.withDefault "S"
in
{ nonTerminals = nonTerminals
, terminals = terminals
, productions =
List.filterMap
(\transition ->
transitionToProduction transition afd.finalStates
)
afd.transitions
, initialSymbol = initialSymbol
, acceptsEmpty = List.member afd.initialState afd.finalStates
}
|> Utils.joinGrammarProductions
|> cleanGR
cleanGR : Grammars.RegularGrammar -> Grammars.RegularGrammar
cleanGR gr =
let
validNonTerminals =
List.filter
(\nonTerminal ->
List.map .fromSymbol gr.productions
|> List.member nonTerminal
)
gr.nonTerminals
cleanProduction : Grammars.Production -> Grammars.Production
cleanProduction prod =
{ prod
| productions =
List.filter
(\body ->
case body.toSymbol of
Nothing ->
True
Just s ->
List.member s validNonTerminals
)
prod.productions
}
in
{ gr
| nonTerminals = validNonTerminals
, productions =
List.map cleanProduction gr.productions
}
{- Convert a State to a Maybe Symbol -}
stateToSymbol : State.State -> Maybe Grammars.NonTerminalSymbol
stateToSymbol state =
case state of
State.Dead ->
Nothing
State.Valid label ->
Just label
{- Converts a Transition into a Maybe Grammars.Production -}
transitionToProduction :
Transition.DeterministicTransition
-> List State.State
-> Maybe Grammars.Production
transitionToProduction transition finalStates =
case transition.nextState of
State.Dead ->
Nothing
State.Valid _ ->
let
toSymbol =
stateToSymbol transition.nextState
isFinal =
List.member transition.nextState finalStates
productions =
List.concatMap
(\condition ->
if isFinal then
[ { consumed = condition, toSymbol = toSymbol }
, { consumed = condition, toSymbol = Nothing }
]
else
[ { consumed = condition, toSymbol = toSymbol } ]
)
transition.conditions
in
stateToSymbol transition.prevState
|> Maybe.map
(\fromSymbol ->
{ fromSymbol = fromSymbol
, productions = productions
}
)
| true | {-
Operations/Conversion/Automata.elm
Author: PI:NAME:<NAME>END_PI
Creation: October/2020
This file contains functions to convert between Automata
-}
module Operations.Conversion.Automata exposing (afdToGr, afndToAfd)
import Models.Alphabet as Alphabet
import Models.Automata as Automata
import Models.Grammars as Grammars
import Models.State as State
import Models.Transition as Transition
import Operations.Conversion.Alphabet as CAlphabet
import Operations.Conversion.Transition as CTransition
import Utils.Utils as Utils
-- AFND to AFD
{- Converts an AFND to AFD -}
afndToAfd : Automata.AFND -> Automata.AFD
afndToAfd afnd =
let
-- All combinations of states
newStates =
Utils.subsequences afnd.states
|> List.sortBy List.length
|> List.map Utils.listOfStatesToState
newTransitions : List Transition.DeterministicTransition
newTransitions =
List.concatMap
(\complexState ->
Utils.stateToListOfStates complexState
|> List.concatMap (getTransitions afnd)
|> List.map (\t -> { t | prevState = complexState })
|> List.filter (.nextState >> (/=) State.Dead)
|> Utils.removeDuplicates
)
newStates
|> Utils.removeDuplicates
|> Utils.sortTransitionsDeterministic
|> Utils.joinTransitionsDeterministic
newFinalStates =
List.filter
(\state ->
Utils.stateToListOfStates state
|> List.any (\st -> List.member st afnd.finalStates)
)
newStates
newInitialState =
Utils.followEpsilonStar afnd afnd.initialState
|> Utils.listOfStatesToState
in
{ states = newStates
, initialState = newInitialState
, finalStates = List.append afnd.finalStates newFinalStates
, alphabet = CAlphabet.nonDeterministicToDeterministic afnd.alphabet
, transitions = newTransitions
}
getTransitionThrough :
Automata.AFND
-> State.State
-> Alphabet.Symbol
-> Transition.DeterministicTransition
getTransitionThrough afnd state symbol =
let
epsilonStar =
Utils.followEpsilonStar afnd state
allStates =
List.concatMap (Utils.getFlatOutTransitionsNonDeterministic afnd)
epsilonStar
|> List.filter
(\t ->
t.conditions
== Transition.NoEpsilon [ symbol ]
&& t.nextStates
/= [ State.Dead ]
)
|> List.concatMap
(.nextStates
>> List.concatMap (Utils.followEpsilonStar afnd)
)
|> Utils.removeDuplicates
in
{ prevState = state
, conditions = [ symbol ]
, nextState = Utils.listOfStatesToState allStates
}
getTransitions :
Automata.AFND
-> State.State
-> List Transition.DeterministicTransition
getTransitions afnd origin =
CAlphabet.nonDeterministicToDeterministic afnd.alphabet
|> List.map (getTransitionThrough afnd origin)
-- AFD TO GR
{- Converts and AFD to a GR -}
afdToGr : Automata.AFD -> Grammars.RegularGrammar
afdToGr afd =
let
nonTerminals =
List.map stateToSymbol afd.states
|> Utils.listOfMaybesToMaybeList
|> Maybe.withDefault []
terminals =
afd.alphabet
initialSymbol =
stateToSymbol afd.initialState
|> Maybe.withDefault "S"
in
{ nonTerminals = nonTerminals
, terminals = terminals
, productions =
List.filterMap
(\transition ->
transitionToProduction transition afd.finalStates
)
afd.transitions
, initialSymbol = initialSymbol
, acceptsEmpty = List.member afd.initialState afd.finalStates
}
|> Utils.joinGrammarProductions
|> cleanGR
cleanGR : Grammars.RegularGrammar -> Grammars.RegularGrammar
cleanGR gr =
let
validNonTerminals =
List.filter
(\nonTerminal ->
List.map .fromSymbol gr.productions
|> List.member nonTerminal
)
gr.nonTerminals
cleanProduction : Grammars.Production -> Grammars.Production
cleanProduction prod =
{ prod
| productions =
List.filter
(\body ->
case body.toSymbol of
Nothing ->
True
Just s ->
List.member s validNonTerminals
)
prod.productions
}
in
{ gr
| nonTerminals = validNonTerminals
, productions =
List.map cleanProduction gr.productions
}
{- Convert a State to a Maybe Symbol -}
stateToSymbol : State.State -> Maybe Grammars.NonTerminalSymbol
stateToSymbol state =
case state of
State.Dead ->
Nothing
State.Valid label ->
Just label
{- Converts a Transition into a Maybe Grammars.Production -}
transitionToProduction :
Transition.DeterministicTransition
-> List State.State
-> Maybe Grammars.Production
transitionToProduction transition finalStates =
case transition.nextState of
State.Dead ->
Nothing
State.Valid _ ->
let
toSymbol =
stateToSymbol transition.nextState
isFinal =
List.member transition.nextState finalStates
productions =
List.concatMap
(\condition ->
if isFinal then
[ { consumed = condition, toSymbol = toSymbol }
, { consumed = condition, toSymbol = Nothing }
]
else
[ { consumed = condition, toSymbol = toSymbol } ]
)
transition.conditions
in
stateToSymbol transition.prevState
|> Maybe.map
(\fromSymbol ->
{ fromSymbol = fromSymbol
, productions = productions
}
)
| elm |
[
{
"context": "ing (..)\n\n\n{- Elm-Arduino-GBA-Multiboot-Cable! (by Andre Taulien)\n\n Some trivia about the Gameboy Advance:\n\n ",
"end": 231,
"score": 0.9998989105,
"start": 218,
"tag": "NAME",
"value": "Andre Taulien"
}
] | elm-flash.elm | ataulien/elm-gba-multiboot | 7 | port module Main exposing (..)
import Json.Decode exposing (..)
import Platform exposing (..)
import Bitwise exposing (..)
import Time exposing (..)
import List exposing (..)
{- Elm-Arduino-GBA-Multiboot-Cable! (by Andre Taulien)
Some trivia about the Gameboy Advance:
- The BIOS of each GBA has a section, which allows a small portion of
- arbitrary code (256K) to be downloaded through the Link-Port,
- called "multiboot".
About the GBAs Link-Cable:
- I found this information to be hard to find online, so here it is again:
- The protocol used by the GBA (all gameboys, really) to send data over the
- Link-Cable is just your usual SPI! Yes, the industry-standard SPI. I've
- come across too many websites describing what the protocol looks like as
- "some weird 16-bit"-protocol, so "let's roll our own solution for that".
- Well, since SPI is widely used, there are libraries for it. Almost every
- microcontroller supports it today. Please don't roll your own.
- To be more exact on the variant of SPI, here are settings that worked for me:
- SPI-Mode: 3
- Speed: 256000hz
- 32-Bit transfers
Here is an overview of the multiboot-process:
1. Search for the gameboy until it answers with a specific number
2. When found and configured for multibooting, transfer the ROM-header
3. Exchange some information regarding encryption
4. Send encrypted rest of the ROM-file
5. Exchange CRCs
For a detailed description, you can go here:
- <http://problemkaputt.de/gbatek.htm#biosfunctions> (Multiboot Transfer Protocol)
This elm-program talks to a connected Arduino over a serial port, which packs
the data and sends it over to a connected Gameboy-Advance.
-}
{- ------------------------------INPUT-PORTS---------------------------------- -}
{-| Called when the arduino sent us a message
-}
port port_on_remote_command : (Int -> msg) -> Sub msg
{-| Called when a file loaded using port_read_file_contents is ready
-}
port port_on_file_contents_loaded : (List Byte -> msg) -> Sub msg
{-| Called when nodejs has some commandline-arguments for us...
-}
port port_on_program_config : (List String -> msg) -> Sub msg
{- -----------------------------OUTPUT-PORTS---------------------------------- -}
{-| Writes data to the serialport connected to the arduino
-}
port port_write_serial : List Byte -> Cmd msg
{-| Requests to read a file from dist. Calls port_on_file_contents_loaded
when all data is loaded.
-}
port port_read_file_contents : String -> Cmd msg
{-| Writes data to the nodejs-console
-}
port port_write_console : String -> Cmd msg
{-| Writes data to the nodejs-console, but straight to stdout, saving us
from nodejs putting a newline behind our message.
-}
port port_write_stdout : String -> Cmd msg
{-| Initializes the serial-port used to talk to the arduino
-}
port port_initalize_serial_port : String -> Cmd msg
type Msg
= OnStateEntered
| OnProgramConfig (List String) -- Serial-port, rom-file
| OnCommandFromArduino Int
| OnFileContentsLoaded (List Byte)
| OnFileLoadFailed String -- reason
type State
= LoadRom
| WaitForArduino
| TransferRom
| Done
type alias Byte =
Int
type alias Model =
{ state : State
, rom : Result String (List Byte)
, serialport : Maybe String
, romfile : Maybe String
}
{-| Loads the ROM from a file.
-}
stateLoadRom : Msg -> Model -> ( Model, Cmd Msg )
stateLoadRom msg model =
case msg of
-- Commandline arguments arrived!
OnProgramConfig args ->
case args of
serialport :: romfile :: [] ->
( { model
| serialport = Just serialport
, romfile = Just romfile
}
, port_read_file_contents romfile
)
_ ->
( model, port_write_console "Invalid commandline-args..." )
-- ROM-File contents arrived!
OnFileContentsLoaded rom ->
case model.serialport of
Nothing ->
( model
, port_write_console "No serialport set!"
)
Just serialport ->
( { model
| state = WaitForArduino
, rom = Ok rom
}
, Cmd.batch
[ port_write_console ("Loaded ROM-File (" ++ (toString (length rom)) ++ " bytes)")
, port_write_console "Waiting for arduino to boot now..."
, port_initalize_serial_port serialport
]
)
OnFileLoadFailed reason ->
( { model | rom = Err reason }
, port_write_console ("Failed to read ROM-File: " ++ reason)
)
_ ->
( model, Cmd.none )
{-| Arduinos have the weird tendency to reboot when something connects to
their serial-port. The common workaround is to send a command over serial when
the arduino has finally rebooted, so we can continue.
The first actual transfer is:
1. The size of the ROM (4-Bytes Little Endian)
2. The ROM-Header (0xC0 Bytes)
That can be sent in one go. The next command from the arduino will indicate
that the rest of the ROM can now be sent, so go and wait for that afterwards!
-}
stateWaitForArduino : Msg -> Model -> ( Model, Cmd Msg )
stateWaitForArduino msg model =
case msg of
OnCommandFromArduino cmd ->
case cmd of
-- Arduino booted
0x01 ->
case model.rom of
Err _ ->
( model
, port_write_console "Can't send header, no ROM-Data available!"
)
Ok data ->
( { model | state = TransferRom, rom = Ok (List.drop 0xC0 data) }
, Cmd.batch
[ port_write_console "Arduino connected!"
, Cmd.batch
[ port_write_serial ((int32ToByteList (length data)) ++ (List.take 0xC0 data))
, port_write_console "Sending header..."
]
]
)
_ ->
( model, port_write_console ("Invalid command: " ++ (toString cmd)) )
_ ->
( model, Cmd.none )
{-| The Arduino will now exchange some information about the encryption with
the gameboy. Afterwards, it will send a command indicating that it is ready
to receive the rest of the ROM.
Then we send our ROM-File to the arduino. In small pieces, so the arduinos
serial-input-buffer doesn't run full. I'm not exactly sure how many bytes fit in
there, so one could probably up the block-size and still be fine...
-}
stateTransferRom : Msg -> Model -> ( Model, Cmd Msg )
stateTransferRom msg model =
case msg of
OnCommandFromArduino cmd ->
case cmd of
-- Write Done
0x03 ->
case model.rom of
Err _ ->
( model, port_write_console "Can't send block, no ROM-Data available!" )
Ok [] ->
( { model | state = Done }
, port_write_console "Transmission complete!"
)
Ok data ->
( { model | rom = Ok (List.drop 32 data) }
, Cmd.batch
[ port_write_serial (List.take 32 data)
]
)
_ ->
( model, port_write_console ("Invalid command: " ++ (toString cmd)) )
_ ->
( model, Cmd.none )
{-| All done, let's hope this worked!
-}
stateDone : Msg -> Model -> ( Model, Cmd Msg )
stateDone msg model =
( model, Cmd.none )
int32ToByteList : Int -> List Int
int32ToByteList v =
[ and 0xFF v
, and (shiftRightBy 8 v) 0xFF
, and (shiftRightBy 16 v) 0xFF
, and (shiftRightBy 24 v) 0xFF
]
{- -------------------------------------------------------------------------- -}
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case model.state of
LoadRom ->
stateLoadRom msg model
WaitForArduino ->
stateWaitForArduino msg model
TransferRom ->
stateTransferRom msg model
Done ->
stateDone msg model
init : ( Model, Cmd Msg )
init =
( { state = LoadRom
, rom = Err "ROM not loaded"
, serialport = Nothing
, romfile = Nothing
}
, Cmd.none
)
subscriptions : Model -> Sub Msg
subscriptions model =
case model.state of
LoadRom ->
Sub.batch
[ port_on_program_config OnProgramConfig
, port_on_file_contents_loaded OnFileContentsLoaded
]
WaitForArduino ->
Sub.batch
[ port_on_remote_command OnCommandFromArduino
]
TransferRom ->
Sub.batch
[ port_on_remote_command OnCommandFromArduino
]
Done ->
Sub.none
main =
Platform.program
{ init = init
, update = update
, subscriptions = subscriptions
}
| 29365 | port module Main exposing (..)
import Json.Decode exposing (..)
import Platform exposing (..)
import Bitwise exposing (..)
import Time exposing (..)
import List exposing (..)
{- Elm-Arduino-GBA-Multiboot-Cable! (by <NAME>)
Some trivia about the Gameboy Advance:
- The BIOS of each GBA has a section, which allows a small portion of
- arbitrary code (256K) to be downloaded through the Link-Port,
- called "multiboot".
About the GBAs Link-Cable:
- I found this information to be hard to find online, so here it is again:
- The protocol used by the GBA (all gameboys, really) to send data over the
- Link-Cable is just your usual SPI! Yes, the industry-standard SPI. I've
- come across too many websites describing what the protocol looks like as
- "some weird 16-bit"-protocol, so "let's roll our own solution for that".
- Well, since SPI is widely used, there are libraries for it. Almost every
- microcontroller supports it today. Please don't roll your own.
- To be more exact on the variant of SPI, here are settings that worked for me:
- SPI-Mode: 3
- Speed: 256000hz
- 32-Bit transfers
Here is an overview of the multiboot-process:
1. Search for the gameboy until it answers with a specific number
2. When found and configured for multibooting, transfer the ROM-header
3. Exchange some information regarding encryption
4. Send encrypted rest of the ROM-file
5. Exchange CRCs
For a detailed description, you can go here:
- <http://problemkaputt.de/gbatek.htm#biosfunctions> (Multiboot Transfer Protocol)
This elm-program talks to a connected Arduino over a serial port, which packs
the data and sends it over to a connected Gameboy-Advance.
-}
{- ------------------------------INPUT-PORTS---------------------------------- -}
{-| Called when the arduino sent us a message
-}
port port_on_remote_command : (Int -> msg) -> Sub msg
{-| Called when a file loaded using port_read_file_contents is ready
-}
port port_on_file_contents_loaded : (List Byte -> msg) -> Sub msg
{-| Called when nodejs has some commandline-arguments for us...
-}
port port_on_program_config : (List String -> msg) -> Sub msg
{- -----------------------------OUTPUT-PORTS---------------------------------- -}
{-| Writes data to the serialport connected to the arduino
-}
port port_write_serial : List Byte -> Cmd msg
{-| Requests to read a file from dist. Calls port_on_file_contents_loaded
when all data is loaded.
-}
port port_read_file_contents : String -> Cmd msg
{-| Writes data to the nodejs-console
-}
port port_write_console : String -> Cmd msg
{-| Writes data to the nodejs-console, but straight to stdout, saving us
from nodejs putting a newline behind our message.
-}
port port_write_stdout : String -> Cmd msg
{-| Initializes the serial-port used to talk to the arduino
-}
port port_initalize_serial_port : String -> Cmd msg
type Msg
= OnStateEntered
| OnProgramConfig (List String) -- Serial-port, rom-file
| OnCommandFromArduino Int
| OnFileContentsLoaded (List Byte)
| OnFileLoadFailed String -- reason
type State
= LoadRom
| WaitForArduino
| TransferRom
| Done
type alias Byte =
Int
type alias Model =
{ state : State
, rom : Result String (List Byte)
, serialport : Maybe String
, romfile : Maybe String
}
{-| Loads the ROM from a file.
-}
stateLoadRom : Msg -> Model -> ( Model, Cmd Msg )
stateLoadRom msg model =
case msg of
-- Commandline arguments arrived!
OnProgramConfig args ->
case args of
serialport :: romfile :: [] ->
( { model
| serialport = Just serialport
, romfile = Just romfile
}
, port_read_file_contents romfile
)
_ ->
( model, port_write_console "Invalid commandline-args..." )
-- ROM-File contents arrived!
OnFileContentsLoaded rom ->
case model.serialport of
Nothing ->
( model
, port_write_console "No serialport set!"
)
Just serialport ->
( { model
| state = WaitForArduino
, rom = Ok rom
}
, Cmd.batch
[ port_write_console ("Loaded ROM-File (" ++ (toString (length rom)) ++ " bytes)")
, port_write_console "Waiting for arduino to boot now..."
, port_initalize_serial_port serialport
]
)
OnFileLoadFailed reason ->
( { model | rom = Err reason }
, port_write_console ("Failed to read ROM-File: " ++ reason)
)
_ ->
( model, Cmd.none )
{-| Arduinos have the weird tendency to reboot when something connects to
their serial-port. The common workaround is to send a command over serial when
the arduino has finally rebooted, so we can continue.
The first actual transfer is:
1. The size of the ROM (4-Bytes Little Endian)
2. The ROM-Header (0xC0 Bytes)
That can be sent in one go. The next command from the arduino will indicate
that the rest of the ROM can now be sent, so go and wait for that afterwards!
-}
stateWaitForArduino : Msg -> Model -> ( Model, Cmd Msg )
stateWaitForArduino msg model =
case msg of
OnCommandFromArduino cmd ->
case cmd of
-- Arduino booted
0x01 ->
case model.rom of
Err _ ->
( model
, port_write_console "Can't send header, no ROM-Data available!"
)
Ok data ->
( { model | state = TransferRom, rom = Ok (List.drop 0xC0 data) }
, Cmd.batch
[ port_write_console "Arduino connected!"
, Cmd.batch
[ port_write_serial ((int32ToByteList (length data)) ++ (List.take 0xC0 data))
, port_write_console "Sending header..."
]
]
)
_ ->
( model, port_write_console ("Invalid command: " ++ (toString cmd)) )
_ ->
( model, Cmd.none )
{-| The Arduino will now exchange some information about the encryption with
the gameboy. Afterwards, it will send a command indicating that it is ready
to receive the rest of the ROM.
Then we send our ROM-File to the arduino. In small pieces, so the arduinos
serial-input-buffer doesn't run full. I'm not exactly sure how many bytes fit in
there, so one could probably up the block-size and still be fine...
-}
stateTransferRom : Msg -> Model -> ( Model, Cmd Msg )
stateTransferRom msg model =
case msg of
OnCommandFromArduino cmd ->
case cmd of
-- Write Done
0x03 ->
case model.rom of
Err _ ->
( model, port_write_console "Can't send block, no ROM-Data available!" )
Ok [] ->
( { model | state = Done }
, port_write_console "Transmission complete!"
)
Ok data ->
( { model | rom = Ok (List.drop 32 data) }
, Cmd.batch
[ port_write_serial (List.take 32 data)
]
)
_ ->
( model, port_write_console ("Invalid command: " ++ (toString cmd)) )
_ ->
( model, Cmd.none )
{-| All done, let's hope this worked!
-}
stateDone : Msg -> Model -> ( Model, Cmd Msg )
stateDone msg model =
( model, Cmd.none )
int32ToByteList : Int -> List Int
int32ToByteList v =
[ and 0xFF v
, and (shiftRightBy 8 v) 0xFF
, and (shiftRightBy 16 v) 0xFF
, and (shiftRightBy 24 v) 0xFF
]
{- -------------------------------------------------------------------------- -}
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case model.state of
LoadRom ->
stateLoadRom msg model
WaitForArduino ->
stateWaitForArduino msg model
TransferRom ->
stateTransferRom msg model
Done ->
stateDone msg model
init : ( Model, Cmd Msg )
init =
( { state = LoadRom
, rom = Err "ROM not loaded"
, serialport = Nothing
, romfile = Nothing
}
, Cmd.none
)
subscriptions : Model -> Sub Msg
subscriptions model =
case model.state of
LoadRom ->
Sub.batch
[ port_on_program_config OnProgramConfig
, port_on_file_contents_loaded OnFileContentsLoaded
]
WaitForArduino ->
Sub.batch
[ port_on_remote_command OnCommandFromArduino
]
TransferRom ->
Sub.batch
[ port_on_remote_command OnCommandFromArduino
]
Done ->
Sub.none
main =
Platform.program
{ init = init
, update = update
, subscriptions = subscriptions
}
| true | port module Main exposing (..)
import Json.Decode exposing (..)
import Platform exposing (..)
import Bitwise exposing (..)
import Time exposing (..)
import List exposing (..)
{- Elm-Arduino-GBA-Multiboot-Cable! (by PI:NAME:<NAME>END_PI)
Some trivia about the Gameboy Advance:
- The BIOS of each GBA has a section, which allows a small portion of
- arbitrary code (256K) to be downloaded through the Link-Port,
- called "multiboot".
About the GBAs Link-Cable:
- I found this information to be hard to find online, so here it is again:
- The protocol used by the GBA (all gameboys, really) to send data over the
- Link-Cable is just your usual SPI! Yes, the industry-standard SPI. I've
- come across too many websites describing what the protocol looks like as
- "some weird 16-bit"-protocol, so "let's roll our own solution for that".
- Well, since SPI is widely used, there are libraries for it. Almost every
- microcontroller supports it today. Please don't roll your own.
- To be more exact on the variant of SPI, here are settings that worked for me:
- SPI-Mode: 3
- Speed: 256000hz
- 32-Bit transfers
Here is an overview of the multiboot-process:
1. Search for the gameboy until it answers with a specific number
2. When found and configured for multibooting, transfer the ROM-header
3. Exchange some information regarding encryption
4. Send encrypted rest of the ROM-file
5. Exchange CRCs
For a detailed description, you can go here:
- <http://problemkaputt.de/gbatek.htm#biosfunctions> (Multiboot Transfer Protocol)
This elm-program talks to a connected Arduino over a serial port, which packs
the data and sends it over to a connected Gameboy-Advance.
-}
{- ------------------------------INPUT-PORTS---------------------------------- -}
{-| Called when the arduino sent us a message
-}
port port_on_remote_command : (Int -> msg) -> Sub msg
{-| Called when a file loaded using port_read_file_contents is ready
-}
port port_on_file_contents_loaded : (List Byte -> msg) -> Sub msg
{-| Called when nodejs has some commandline-arguments for us...
-}
port port_on_program_config : (List String -> msg) -> Sub msg
{- -----------------------------OUTPUT-PORTS---------------------------------- -}
{-| Writes data to the serialport connected to the arduino
-}
port port_write_serial : List Byte -> Cmd msg
{-| Requests to read a file from dist. Calls port_on_file_contents_loaded
when all data is loaded.
-}
port port_read_file_contents : String -> Cmd msg
{-| Writes data to the nodejs-console
-}
port port_write_console : String -> Cmd msg
{-| Writes data to the nodejs-console, but straight to stdout, saving us
from nodejs putting a newline behind our message.
-}
port port_write_stdout : String -> Cmd msg
{-| Initializes the serial-port used to talk to the arduino
-}
port port_initalize_serial_port : String -> Cmd msg
type Msg
= OnStateEntered
| OnProgramConfig (List String) -- Serial-port, rom-file
| OnCommandFromArduino Int
| OnFileContentsLoaded (List Byte)
| OnFileLoadFailed String -- reason
type State
= LoadRom
| WaitForArduino
| TransferRom
| Done
type alias Byte =
Int
type alias Model =
{ state : State
, rom : Result String (List Byte)
, serialport : Maybe String
, romfile : Maybe String
}
{-| Loads the ROM from a file.
-}
stateLoadRom : Msg -> Model -> ( Model, Cmd Msg )
stateLoadRom msg model =
case msg of
-- Commandline arguments arrived!
OnProgramConfig args ->
case args of
serialport :: romfile :: [] ->
( { model
| serialport = Just serialport
, romfile = Just romfile
}
, port_read_file_contents romfile
)
_ ->
( model, port_write_console "Invalid commandline-args..." )
-- ROM-File contents arrived!
OnFileContentsLoaded rom ->
case model.serialport of
Nothing ->
( model
, port_write_console "No serialport set!"
)
Just serialport ->
( { model
| state = WaitForArduino
, rom = Ok rom
}
, Cmd.batch
[ port_write_console ("Loaded ROM-File (" ++ (toString (length rom)) ++ " bytes)")
, port_write_console "Waiting for arduino to boot now..."
, port_initalize_serial_port serialport
]
)
OnFileLoadFailed reason ->
( { model | rom = Err reason }
, port_write_console ("Failed to read ROM-File: " ++ reason)
)
_ ->
( model, Cmd.none )
{-| Arduinos have the weird tendency to reboot when something connects to
their serial-port. The common workaround is to send a command over serial when
the arduino has finally rebooted, so we can continue.
The first actual transfer is:
1. The size of the ROM (4-Bytes Little Endian)
2. The ROM-Header (0xC0 Bytes)
That can be sent in one go. The next command from the arduino will indicate
that the rest of the ROM can now be sent, so go and wait for that afterwards!
-}
stateWaitForArduino : Msg -> Model -> ( Model, Cmd Msg )
stateWaitForArduino msg model =
case msg of
OnCommandFromArduino cmd ->
case cmd of
-- Arduino booted
0x01 ->
case model.rom of
Err _ ->
( model
, port_write_console "Can't send header, no ROM-Data available!"
)
Ok data ->
( { model | state = TransferRom, rom = Ok (List.drop 0xC0 data) }
, Cmd.batch
[ port_write_console "Arduino connected!"
, Cmd.batch
[ port_write_serial ((int32ToByteList (length data)) ++ (List.take 0xC0 data))
, port_write_console "Sending header..."
]
]
)
_ ->
( model, port_write_console ("Invalid command: " ++ (toString cmd)) )
_ ->
( model, Cmd.none )
{-| The Arduino will now exchange some information about the encryption with
the gameboy. Afterwards, it will send a command indicating that it is ready
to receive the rest of the ROM.
Then we send our ROM-File to the arduino. In small pieces, so the arduinos
serial-input-buffer doesn't run full. I'm not exactly sure how many bytes fit in
there, so one could probably up the block-size and still be fine...
-}
stateTransferRom : Msg -> Model -> ( Model, Cmd Msg )
stateTransferRom msg model =
case msg of
OnCommandFromArduino cmd ->
case cmd of
-- Write Done
0x03 ->
case model.rom of
Err _ ->
( model, port_write_console "Can't send block, no ROM-Data available!" )
Ok [] ->
( { model | state = Done }
, port_write_console "Transmission complete!"
)
Ok data ->
( { model | rom = Ok (List.drop 32 data) }
, Cmd.batch
[ port_write_serial (List.take 32 data)
]
)
_ ->
( model, port_write_console ("Invalid command: " ++ (toString cmd)) )
_ ->
( model, Cmd.none )
{-| All done, let's hope this worked!
-}
stateDone : Msg -> Model -> ( Model, Cmd Msg )
stateDone msg model =
( model, Cmd.none )
int32ToByteList : Int -> List Int
int32ToByteList v =
[ and 0xFF v
, and (shiftRightBy 8 v) 0xFF
, and (shiftRightBy 16 v) 0xFF
, and (shiftRightBy 24 v) 0xFF
]
{- -------------------------------------------------------------------------- -}
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case model.state of
LoadRom ->
stateLoadRom msg model
WaitForArduino ->
stateWaitForArduino msg model
TransferRom ->
stateTransferRom msg model
Done ->
stateDone msg model
init : ( Model, Cmd Msg )
init =
( { state = LoadRom
, rom = Err "ROM not loaded"
, serialport = Nothing
, romfile = Nothing
}
, Cmd.none
)
subscriptions : Model -> Sub Msg
subscriptions model =
case model.state of
LoadRom ->
Sub.batch
[ port_on_program_config OnProgramConfig
, port_on_file_contents_loaded OnFileContentsLoaded
]
WaitForArduino ->
Sub.batch
[ port_on_remote_command OnCommandFromArduino
]
TransferRom ->
Sub.batch
[ port_on_remote_command OnCommandFromArduino
]
Done ->
Sub.none
main =
Platform.program
{ init = init
, update = update
, subscriptions = subscriptions
}
| elm |
[
{
"context": "ello-world.md`\n\n```markdown\n---\ntype: blog\nauthor: Dillon Kearns\ntitle: Hello, World!\n---\n# Hello, World! 👋\n\n## Th",
"end": 899,
"score": 0.9998645186,
"start": 886,
"tag": "NAME",
"value": "Dillon Kearns"
},
{
"context": "{-| Register an [`elm-markup`](https://github.com/mdgriffith/elm-markup/)\nparser for your `.emu` files.\n-}\nmar",
"end": 4497,
"score": 0.998097837,
"start": 4487,
"tag": "USERNAME",
"value": "mdgriffith"
}
] | src/Pages/Document.elm | leojpod/elm-pages | 1 | module Pages.Document exposing
( Document, DocumentHandler
, parser, markupParser
, fromList, get
)
{-| The `Document` represents all the ways to handle the frontmatter metadata
and documents found in your `content` folder.
Frontmatter content is turned into JSON, so you can use the familiar Elm JSON decoding
to get frontmatter content. And you'll get helpful error messages if any of
your frontmatter is invalid (which will prevent an invalid production build from
being created!).
It's up to you how you parse your metadata and content. Here's a simple example of
a site that has two types of pages, `blog` posts and `page` (a regular page like `/about` or `/`).
`content/index.md`
```markdown
---
type: page
title: Welcome to my site!
---
# Here's my site!
I built it with `elm-pages`! 🚀
```
`content/blog/hello-world.md`
```markdown
---
type: blog
author: Dillon Kearns
title: Hello, World!
---
# Hello, World! 👋
## This will be parsed as markdown
Hello!!!
```
-- this example uses elm-explorations/markdown
import Html exposing (Html)
import Json.Decode as Decode exposing (Decoder)
import Markdown
import Pages.Document
type Metadata
= Blog { title : String, description : String, author : String }
| Page { title : String }
markdownDocument : ( String, Pages.Document.DocumentHandler Metadata (Html msg) )
markdownDocument =
Pages.Document.parser
{ extension = "md"
, metadata = frontmatterDecoder
, body = Markdown.toHtml []
}
frontmatterDecoder : Decoder Metadata
frontmatterDecoder =
Decode.field "type" Decode.string
|> Decode.andThen
(\metadataType ->
case metadataType of
"blog" ->
Decode.map3 (\title description author -> { title = title, description = description, author = author })
(Decode.field "title" Decode.string)
(Decode.field "description" Decode.string)
(Decode.field "author" Decode.string)
"page" ->
Decode.map (\title -> { title = title })
(Decode.field "title" Decode.string)
)
@docs Document, DocumentHandler
@docs parser, markupParser
## Functions for use by generated code
@docs fromList, get
-}
import Dict exposing (Dict)
import Html exposing (Html)
import Json.Decode
import Mark
import Mark.Error
{-| Represents all of the `DocumentHandler`s. You register a handler for each
extension that tells it how to parse frontmatter and content for that extension.
-}
type Document metadata view
= Document (Dict String (DocumentHandler metadata view))
{-| How to parse the frontmatter and content for a given extension. Build one
using `Document.parser` (see above for an example).
-}
type DocumentHandler metadata view
= DocumentHandler
{ frontmatterParser : String -> Result String metadata
, contentParser : String -> Result String view
}
{-| Used by the generated `Pages.elm` module. There's no need to use this
outside of the generated code.
-}
get :
String
-> Document metadata view
->
Maybe
{ frontmatterParser : String -> Result String metadata
, contentParser : String -> Result String view
}
get extension (Document document) =
document
|> Dict.get extension
|> Maybe.map (\(DocumentHandler handler) -> handler)
{-| Used by the generated `Pages.elm` module. There's no need to use this
outside of the generated code.
-}
fromList : List ( String, DocumentHandler metadata view ) -> Document metadata view
fromList list =
Document (Dict.fromList list)
{-| Create a Document Handler for the given extension.
-}
parser :
{ extension : String
, metadata : Json.Decode.Decoder metadata
, body : String -> Result String view
}
-> ( String, DocumentHandler metadata view )
parser { extension, body, metadata } =
( extension
, DocumentHandler
{ contentParser = body
, frontmatterParser =
\frontmatter ->
frontmatter
|> Json.Decode.decodeString metadata
|> Result.mapError Json.Decode.errorToString
}
)
{-| Register an [`elm-markup`](https://github.com/mdgriffith/elm-markup/)
parser for your `.emu` files.
-}
markupParser :
Mark.Document metadata
-> Mark.Document view
-> ( String, DocumentHandler metadata view )
markupParser metadataParser markBodyParser =
( "emu"
, DocumentHandler
{ contentParser = renderMarkup markBodyParser
, frontmatterParser =
\frontMatter ->
Mark.compile metadataParser
frontMatter
|> (\outcome ->
case outcome of
Mark.Success parsedMetadata ->
Ok parsedMetadata
Mark.Failure failure ->
Err "Failure"
Mark.Almost failure ->
Err "Almost failure"
)
}
)
renderMarkup : Mark.Document view -> String -> Result String view
renderMarkup markBodyParser markupBody =
Mark.compile
markBodyParser
(markupBody |> String.trimLeft)
|> (\outcome ->
case outcome of
Mark.Success renderedView ->
Ok renderedView
Mark.Failure failures ->
failures
|> List.map Mark.Error.toString
|> String.join "\n"
|> Err
Mark.Almost failure ->
Err "TODO almost failure"
)
| 44545 | module Pages.Document exposing
( Document, DocumentHandler
, parser, markupParser
, fromList, get
)
{-| The `Document` represents all the ways to handle the frontmatter metadata
and documents found in your `content` folder.
Frontmatter content is turned into JSON, so you can use the familiar Elm JSON decoding
to get frontmatter content. And you'll get helpful error messages if any of
your frontmatter is invalid (which will prevent an invalid production build from
being created!).
It's up to you how you parse your metadata and content. Here's a simple example of
a site that has two types of pages, `blog` posts and `page` (a regular page like `/about` or `/`).
`content/index.md`
```markdown
---
type: page
title: Welcome to my site!
---
# Here's my site!
I built it with `elm-pages`! 🚀
```
`content/blog/hello-world.md`
```markdown
---
type: blog
author: <NAME>
title: Hello, World!
---
# Hello, World! 👋
## This will be parsed as markdown
Hello!!!
```
-- this example uses elm-explorations/markdown
import Html exposing (Html)
import Json.Decode as Decode exposing (Decoder)
import Markdown
import Pages.Document
type Metadata
= Blog { title : String, description : String, author : String }
| Page { title : String }
markdownDocument : ( String, Pages.Document.DocumentHandler Metadata (Html msg) )
markdownDocument =
Pages.Document.parser
{ extension = "md"
, metadata = frontmatterDecoder
, body = Markdown.toHtml []
}
frontmatterDecoder : Decoder Metadata
frontmatterDecoder =
Decode.field "type" Decode.string
|> Decode.andThen
(\metadataType ->
case metadataType of
"blog" ->
Decode.map3 (\title description author -> { title = title, description = description, author = author })
(Decode.field "title" Decode.string)
(Decode.field "description" Decode.string)
(Decode.field "author" Decode.string)
"page" ->
Decode.map (\title -> { title = title })
(Decode.field "title" Decode.string)
)
@docs Document, DocumentHandler
@docs parser, markupParser
## Functions for use by generated code
@docs fromList, get
-}
import Dict exposing (Dict)
import Html exposing (Html)
import Json.Decode
import Mark
import Mark.Error
{-| Represents all of the `DocumentHandler`s. You register a handler for each
extension that tells it how to parse frontmatter and content for that extension.
-}
type Document metadata view
= Document (Dict String (DocumentHandler metadata view))
{-| How to parse the frontmatter and content for a given extension. Build one
using `Document.parser` (see above for an example).
-}
type DocumentHandler metadata view
= DocumentHandler
{ frontmatterParser : String -> Result String metadata
, contentParser : String -> Result String view
}
{-| Used by the generated `Pages.elm` module. There's no need to use this
outside of the generated code.
-}
get :
String
-> Document metadata view
->
Maybe
{ frontmatterParser : String -> Result String metadata
, contentParser : String -> Result String view
}
get extension (Document document) =
document
|> Dict.get extension
|> Maybe.map (\(DocumentHandler handler) -> handler)
{-| Used by the generated `Pages.elm` module. There's no need to use this
outside of the generated code.
-}
fromList : List ( String, DocumentHandler metadata view ) -> Document metadata view
fromList list =
Document (Dict.fromList list)
{-| Create a Document Handler for the given extension.
-}
parser :
{ extension : String
, metadata : Json.Decode.Decoder metadata
, body : String -> Result String view
}
-> ( String, DocumentHandler metadata view )
parser { extension, body, metadata } =
( extension
, DocumentHandler
{ contentParser = body
, frontmatterParser =
\frontmatter ->
frontmatter
|> Json.Decode.decodeString metadata
|> Result.mapError Json.Decode.errorToString
}
)
{-| Register an [`elm-markup`](https://github.com/mdgriffith/elm-markup/)
parser for your `.emu` files.
-}
markupParser :
Mark.Document metadata
-> Mark.Document view
-> ( String, DocumentHandler metadata view )
markupParser metadataParser markBodyParser =
( "emu"
, DocumentHandler
{ contentParser = renderMarkup markBodyParser
, frontmatterParser =
\frontMatter ->
Mark.compile metadataParser
frontMatter
|> (\outcome ->
case outcome of
Mark.Success parsedMetadata ->
Ok parsedMetadata
Mark.Failure failure ->
Err "Failure"
Mark.Almost failure ->
Err "Almost failure"
)
}
)
renderMarkup : Mark.Document view -> String -> Result String view
renderMarkup markBodyParser markupBody =
Mark.compile
markBodyParser
(markupBody |> String.trimLeft)
|> (\outcome ->
case outcome of
Mark.Success renderedView ->
Ok renderedView
Mark.Failure failures ->
failures
|> List.map Mark.Error.toString
|> String.join "\n"
|> Err
Mark.Almost failure ->
Err "TODO almost failure"
)
| true | module Pages.Document exposing
( Document, DocumentHandler
, parser, markupParser
, fromList, get
)
{-| The `Document` represents all the ways to handle the frontmatter metadata
and documents found in your `content` folder.
Frontmatter content is turned into JSON, so you can use the familiar Elm JSON decoding
to get frontmatter content. And you'll get helpful error messages if any of
your frontmatter is invalid (which will prevent an invalid production build from
being created!).
It's up to you how you parse your metadata and content. Here's a simple example of
a site that has two types of pages, `blog` posts and `page` (a regular page like `/about` or `/`).
`content/index.md`
```markdown
---
type: page
title: Welcome to my site!
---
# Here's my site!
I built it with `elm-pages`! 🚀
```
`content/blog/hello-world.md`
```markdown
---
type: blog
author: PI:NAME:<NAME>END_PI
title: Hello, World!
---
# Hello, World! 👋
## This will be parsed as markdown
Hello!!!
```
-- this example uses elm-explorations/markdown
import Html exposing (Html)
import Json.Decode as Decode exposing (Decoder)
import Markdown
import Pages.Document
type Metadata
= Blog { title : String, description : String, author : String }
| Page { title : String }
markdownDocument : ( String, Pages.Document.DocumentHandler Metadata (Html msg) )
markdownDocument =
Pages.Document.parser
{ extension = "md"
, metadata = frontmatterDecoder
, body = Markdown.toHtml []
}
frontmatterDecoder : Decoder Metadata
frontmatterDecoder =
Decode.field "type" Decode.string
|> Decode.andThen
(\metadataType ->
case metadataType of
"blog" ->
Decode.map3 (\title description author -> { title = title, description = description, author = author })
(Decode.field "title" Decode.string)
(Decode.field "description" Decode.string)
(Decode.field "author" Decode.string)
"page" ->
Decode.map (\title -> { title = title })
(Decode.field "title" Decode.string)
)
@docs Document, DocumentHandler
@docs parser, markupParser
## Functions for use by generated code
@docs fromList, get
-}
import Dict exposing (Dict)
import Html exposing (Html)
import Json.Decode
import Mark
import Mark.Error
{-| Represents all of the `DocumentHandler`s. You register a handler for each
extension that tells it how to parse frontmatter and content for that extension.
-}
type Document metadata view
= Document (Dict String (DocumentHandler metadata view))
{-| How to parse the frontmatter and content for a given extension. Build one
using `Document.parser` (see above for an example).
-}
type DocumentHandler metadata view
= DocumentHandler
{ frontmatterParser : String -> Result String metadata
, contentParser : String -> Result String view
}
{-| Used by the generated `Pages.elm` module. There's no need to use this
outside of the generated code.
-}
get :
String
-> Document metadata view
->
Maybe
{ frontmatterParser : String -> Result String metadata
, contentParser : String -> Result String view
}
get extension (Document document) =
document
|> Dict.get extension
|> Maybe.map (\(DocumentHandler handler) -> handler)
{-| Used by the generated `Pages.elm` module. There's no need to use this
outside of the generated code.
-}
fromList : List ( String, DocumentHandler metadata view ) -> Document metadata view
fromList list =
Document (Dict.fromList list)
{-| Create a Document Handler for the given extension.
-}
parser :
{ extension : String
, metadata : Json.Decode.Decoder metadata
, body : String -> Result String view
}
-> ( String, DocumentHandler metadata view )
parser { extension, body, metadata } =
( extension
, DocumentHandler
{ contentParser = body
, frontmatterParser =
\frontmatter ->
frontmatter
|> Json.Decode.decodeString metadata
|> Result.mapError Json.Decode.errorToString
}
)
{-| Register an [`elm-markup`](https://github.com/mdgriffith/elm-markup/)
parser for your `.emu` files.
-}
markupParser :
Mark.Document metadata
-> Mark.Document view
-> ( String, DocumentHandler metadata view )
markupParser metadataParser markBodyParser =
( "emu"
, DocumentHandler
{ contentParser = renderMarkup markBodyParser
, frontmatterParser =
\frontMatter ->
Mark.compile metadataParser
frontMatter
|> (\outcome ->
case outcome of
Mark.Success parsedMetadata ->
Ok parsedMetadata
Mark.Failure failure ->
Err "Failure"
Mark.Almost failure ->
Err "Almost failure"
)
}
)
renderMarkup : Mark.Document view -> String -> Result String view
renderMarkup markBodyParser markupBody =
Mark.compile
markBodyParser
(markupBody |> String.trimLeft)
|> (\outcome ->
case outcome of
Mark.Success renderedView ->
Ok renderedView
Mark.Failure failures ->
failures
|> List.map Mark.Error.toString
|> String.join "\n"
|> Err
Mark.Almost failure ->
Err "TODO almost failure"
)
| elm |
[
{
"context": "ap\n (\\item ->\n if item.name == \"Aged Brie\" || item.name == \"Backstage passes to a TAFKAL80E",
"end": 3030,
"score": 0.9997367263,
"start": 3021,
"tag": "NAME",
"value": "Aged Brie"
},
{
"context": "item.sell_by }\n\n else if item.name /= \"Aged Brie\" && item.name /= \"Sulfuras, Hand of Ragnaros\" the",
"end": 4011,
"score": 0.999648571,
"start": 4002,
"tag": "NAME",
"value": "Aged Brie"
},
{
"context": "else if item.name /= \"Aged Brie\" && item.name /= \"Sulfuras, Hand of Ragnaros\" then\n if it",
"end": 4034,
"score": 0.9993814826,
"start": 4030,
"tag": "NAME",
"value": "Sulf"
}
] | elm/src/GildedRose.elm | arnegoeteyn/GildedRose-Refactoring-Kata | 0 | module GildedRose exposing (Item, ItemType(..), typeFromName, updateItem, update_quality, update_quality_old, legendaryQuality, regularMaxQuality)
type alias Item =
{ name : String
, sell_by : Int
, quality : Int
}
type ItemType
= Legendary
| Brie
| Ticket
| Regular
| Conjured
legendaryQuality : number
legendaryQuality = 80
regularMaxQuality : number
regularMaxQuality = 50
typeFromName : String -> ItemType
typeFromName name =
case name of
"Sulfuras, Hand of Ragnaros" ->
Legendary
"Backstage passes to a TAFKAL80ETC concert" ->
Ticket
"Aged Brie" ->
Brie
_ ->
if String.startsWith "Conjured" name then
Conjured
else
Regular
updateSellBy : ( Item, Bool ) -> Item
updateSellBy ( item, shouldLower ) =
if shouldLower then
{ item
| sell_by = item.sell_by - 1
-- In the old code it was possible to get a ticket worth up to 52 quality.
-- This is not allowed according to the spec
-- This bug can be fixed by toggling the following line of code, but this is kept commented out
-- to make everything work exactly as it was before.
-- , quality = min regularMaxQuality item.quality
}
else
item
regularUpdate : Item -> Item
regularUpdate item =
if item.sell_by < 0 && item.quality >= 2 then
{ item | quality = item.quality - 2 }
else if item.quality >= 1 then
{ item | quality = item.quality - 1 }
else
{ item | quality = 0 }
brieUpdate : Item -> Item
brieUpdate item =
{ item | quality = item.quality + 1 }
ticketUpdate : Item -> Item
ticketUpdate item =
if item.sell_by < 0 then
{ item | quality = 0 }
else if item.sell_by < 6 then
{ item | quality = item.quality + 3 }
else if item.sell_by < 11 then
{ item | quality = item.quality + 2 }
else
{ item | quality = item.quality + 1 }
qualityUpdate : Item -> ( Item, Bool )
qualityUpdate item =
let
type_ =
typeFromName item.name
in
case type_ of
Legendary ->
( item, False )
Brie ->
if item.quality < 50 then
( brieUpdate item, True )
else
( item, False )
Ticket ->
if item.quality < 50 then
( ticketUpdate item, True )
else
( item, False )
Regular ->
( regularUpdate item, True )
Conjured ->
( (regularUpdate << regularUpdate) item, True )
updateItem : Item -> Item
updateItem =
qualityUpdate >> updateSellBy
update_quality : List Item -> List Item
update_quality =
List.map updateItem
update_quality_old : List Item -> List Item
update_quality_old items =
List.map
(\item ->
if item.name == "Aged Brie" || item.name == "Backstage passes to a TAFKAL80ETC concert" then
if item.quality < 50 then
if item.name == "Backstage passes to a TAFKAL80ETC concert" then
if item.sell_by < 0 then
{ item | sell_by = item.sell_by - 1, quality = 0 }
else if item.sell_by < 6 then
{ item | sell_by = item.sell_by - 1, quality = item.quality + 3 }
else if item.sell_by < 11 then
{ item | sell_by = item.sell_by - 1, quality = item.quality + 2 }
else
{ item | sell_by = item.sell_by - 1, quality = item.quality + 1 }
else
{ item | sell_by = item.sell_by - 1, quality = item.quality + 1 }
else
{ item | sell_by = item.sell_by }
else if item.name /= "Aged Brie" && item.name /= "Sulfuras, Hand of Ragnaros" then
if item.sell_by < 0 && item.quality > 0 then
if item.quality >= 2 then
{ item | sell_by = item.sell_by - 1, quality = item.quality - 2 }
else
{ item | sell_by = item.sell_by - 1, quality = 0 }
else if item.quality >= 1 then
{ item | sell_by = item.sell_by - 1, quality = item.quality - 1 }
else
{ item | sell_by = item.sell_by - 1, quality = 0 }
else
item
)
items
| 27510 | module GildedRose exposing (Item, ItemType(..), typeFromName, updateItem, update_quality, update_quality_old, legendaryQuality, regularMaxQuality)
type alias Item =
{ name : String
, sell_by : Int
, quality : Int
}
type ItemType
= Legendary
| Brie
| Ticket
| Regular
| Conjured
legendaryQuality : number
legendaryQuality = 80
regularMaxQuality : number
regularMaxQuality = 50
typeFromName : String -> ItemType
typeFromName name =
case name of
"Sulfuras, Hand of Ragnaros" ->
Legendary
"Backstage passes to a TAFKAL80ETC concert" ->
Ticket
"Aged Brie" ->
Brie
_ ->
if String.startsWith "Conjured" name then
Conjured
else
Regular
updateSellBy : ( Item, Bool ) -> Item
updateSellBy ( item, shouldLower ) =
if shouldLower then
{ item
| sell_by = item.sell_by - 1
-- In the old code it was possible to get a ticket worth up to 52 quality.
-- This is not allowed according to the spec
-- This bug can be fixed by toggling the following line of code, but this is kept commented out
-- to make everything work exactly as it was before.
-- , quality = min regularMaxQuality item.quality
}
else
item
regularUpdate : Item -> Item
regularUpdate item =
if item.sell_by < 0 && item.quality >= 2 then
{ item | quality = item.quality - 2 }
else if item.quality >= 1 then
{ item | quality = item.quality - 1 }
else
{ item | quality = 0 }
brieUpdate : Item -> Item
brieUpdate item =
{ item | quality = item.quality + 1 }
ticketUpdate : Item -> Item
ticketUpdate item =
if item.sell_by < 0 then
{ item | quality = 0 }
else if item.sell_by < 6 then
{ item | quality = item.quality + 3 }
else if item.sell_by < 11 then
{ item | quality = item.quality + 2 }
else
{ item | quality = item.quality + 1 }
qualityUpdate : Item -> ( Item, Bool )
qualityUpdate item =
let
type_ =
typeFromName item.name
in
case type_ of
Legendary ->
( item, False )
Brie ->
if item.quality < 50 then
( brieUpdate item, True )
else
( item, False )
Ticket ->
if item.quality < 50 then
( ticketUpdate item, True )
else
( item, False )
Regular ->
( regularUpdate item, True )
Conjured ->
( (regularUpdate << regularUpdate) item, True )
updateItem : Item -> Item
updateItem =
qualityUpdate >> updateSellBy
update_quality : List Item -> List Item
update_quality =
List.map updateItem
update_quality_old : List Item -> List Item
update_quality_old items =
List.map
(\item ->
if item.name == "<NAME>" || item.name == "Backstage passes to a TAFKAL80ETC concert" then
if item.quality < 50 then
if item.name == "Backstage passes to a TAFKAL80ETC concert" then
if item.sell_by < 0 then
{ item | sell_by = item.sell_by - 1, quality = 0 }
else if item.sell_by < 6 then
{ item | sell_by = item.sell_by - 1, quality = item.quality + 3 }
else if item.sell_by < 11 then
{ item | sell_by = item.sell_by - 1, quality = item.quality + 2 }
else
{ item | sell_by = item.sell_by - 1, quality = item.quality + 1 }
else
{ item | sell_by = item.sell_by - 1, quality = item.quality + 1 }
else
{ item | sell_by = item.sell_by }
else if item.name /= "<NAME>" && item.name /= "<NAME>uras, Hand of Ragnaros" then
if item.sell_by < 0 && item.quality > 0 then
if item.quality >= 2 then
{ item | sell_by = item.sell_by - 1, quality = item.quality - 2 }
else
{ item | sell_by = item.sell_by - 1, quality = 0 }
else if item.quality >= 1 then
{ item | sell_by = item.sell_by - 1, quality = item.quality - 1 }
else
{ item | sell_by = item.sell_by - 1, quality = 0 }
else
item
)
items
| true | module GildedRose exposing (Item, ItemType(..), typeFromName, updateItem, update_quality, update_quality_old, legendaryQuality, regularMaxQuality)
type alias Item =
{ name : String
, sell_by : Int
, quality : Int
}
type ItemType
= Legendary
| Brie
| Ticket
| Regular
| Conjured
legendaryQuality : number
legendaryQuality = 80
regularMaxQuality : number
regularMaxQuality = 50
typeFromName : String -> ItemType
typeFromName name =
case name of
"Sulfuras, Hand of Ragnaros" ->
Legendary
"Backstage passes to a TAFKAL80ETC concert" ->
Ticket
"Aged Brie" ->
Brie
_ ->
if String.startsWith "Conjured" name then
Conjured
else
Regular
updateSellBy : ( Item, Bool ) -> Item
updateSellBy ( item, shouldLower ) =
if shouldLower then
{ item
| sell_by = item.sell_by - 1
-- In the old code it was possible to get a ticket worth up to 52 quality.
-- This is not allowed according to the spec
-- This bug can be fixed by toggling the following line of code, but this is kept commented out
-- to make everything work exactly as it was before.
-- , quality = min regularMaxQuality item.quality
}
else
item
regularUpdate : Item -> Item
regularUpdate item =
if item.sell_by < 0 && item.quality >= 2 then
{ item | quality = item.quality - 2 }
else if item.quality >= 1 then
{ item | quality = item.quality - 1 }
else
{ item | quality = 0 }
brieUpdate : Item -> Item
brieUpdate item =
{ item | quality = item.quality + 1 }
ticketUpdate : Item -> Item
ticketUpdate item =
if item.sell_by < 0 then
{ item | quality = 0 }
else if item.sell_by < 6 then
{ item | quality = item.quality + 3 }
else if item.sell_by < 11 then
{ item | quality = item.quality + 2 }
else
{ item | quality = item.quality + 1 }
qualityUpdate : Item -> ( Item, Bool )
qualityUpdate item =
let
type_ =
typeFromName item.name
in
case type_ of
Legendary ->
( item, False )
Brie ->
if item.quality < 50 then
( brieUpdate item, True )
else
( item, False )
Ticket ->
if item.quality < 50 then
( ticketUpdate item, True )
else
( item, False )
Regular ->
( regularUpdate item, True )
Conjured ->
( (regularUpdate << regularUpdate) item, True )
updateItem : Item -> Item
updateItem =
qualityUpdate >> updateSellBy
update_quality : List Item -> List Item
update_quality =
List.map updateItem
update_quality_old : List Item -> List Item
update_quality_old items =
List.map
(\item ->
if item.name == "PI:NAME:<NAME>END_PI" || item.name == "Backstage passes to a TAFKAL80ETC concert" then
if item.quality < 50 then
if item.name == "Backstage passes to a TAFKAL80ETC concert" then
if item.sell_by < 0 then
{ item | sell_by = item.sell_by - 1, quality = 0 }
else if item.sell_by < 6 then
{ item | sell_by = item.sell_by - 1, quality = item.quality + 3 }
else if item.sell_by < 11 then
{ item | sell_by = item.sell_by - 1, quality = item.quality + 2 }
else
{ item | sell_by = item.sell_by - 1, quality = item.quality + 1 }
else
{ item | sell_by = item.sell_by - 1, quality = item.quality + 1 }
else
{ item | sell_by = item.sell_by }
else if item.name /= "PI:NAME:<NAME>END_PI" && item.name /= "PI:NAME:<NAME>END_PIuras, Hand of Ragnaros" then
if item.sell_by < 0 && item.quality > 0 then
if item.quality >= 2 then
{ item | sell_by = item.sell_by - 1, quality = item.quality - 2 }
else
{ item | sell_by = item.sell_by - 1, quality = 0 }
else if item.quality >= 1 then
{ item | sell_by = item.sell_by - 1, quality = item.quality - 1 }
else
{ item | sell_by = item.sell_by - 1, quality = 0 }
else
item
)
items
| elm |
[
{
"context": "ically in it's entirety from: <https://github.com/the-sett/elm-syntax-dsl/blob/master/src/Elm/Pretty.elm>\n\nT",
"end": 260,
"score": 0.9995657206,
"start": 252,
"tag": "USERNAME",
"value": "the-sett"
},
{
"context": "tax-dsl/blob/master/src/Elm/Pretty.elm>\n\nThank you Rupert!\n\n-}\n\nimport Dict\nimport Elm.Syntax.Declaration\ni",
"end": 325,
"score": 0.9991977811,
"start": 319,
"tag": "NAME",
"value": "Rupert"
}
] | src/Internal/Write.elm | absynce/elm-codegen | 0 | module Internal.Write exposing
( write
, writeAnnotation
, writeDeclaration
, writeExpression
, writeImports
, writeInference
, writeSignature
)
{-| This is borrowed basically in it's entirety from: <https://github.com/the-sett/elm-syntax-dsl/blob/master/src/Elm/Pretty.elm>
Thank you Rupert!
-}
import Dict
import Elm.Syntax.Declaration
import Elm.Syntax.Documentation exposing (Documentation)
import Elm.Syntax.Exposing exposing (ExposedType, Exposing(..), TopLevelExpose(..))
import Elm.Syntax.Expression exposing (Case, CaseBlock, Expression(..), Function, FunctionImplementation, Lambda, LetBlock, LetDeclaration(..), RecordSetter)
import Elm.Syntax.File
import Elm.Syntax.Import exposing (Import)
import Elm.Syntax.Infix exposing (Infix, InfixDirection(..))
import Elm.Syntax.Module exposing (DefaultModuleData, EffectModuleData, Module(..))
import Elm.Syntax.ModuleName exposing (ModuleName)
import Elm.Syntax.Node as Node exposing (Node(..))
import Elm.Syntax.Pattern exposing (Pattern(..), QualifiedNameRef)
import Elm.Syntax.Range exposing (Location, Range, emptyRange)
import Elm.Syntax.Signature exposing (Signature)
import Elm.Syntax.Type exposing (Type, ValueConstructor)
import Elm.Syntax.TypeAlias exposing (TypeAlias)
import Elm.Syntax.TypeAnnotation exposing (RecordDefinition, RecordField, TypeAnnotation(..))
import Hex
import Internal.Comments as Comments
import Internal.Compiler as Util exposing (denode, denodeAll, denodeMaybe, nodify, nodifyAll, nodifyMaybe)
import Internal.ImportsAndExposing as ImportsAndExposing
import Pretty exposing (Doc)
type alias File =
{ moduleDefinition : Module
, aliases : List ( Util.Module, String )
, imports : List Import
, declarations : List Util.Declaration
, comments : Maybe (Comments.Comment Comments.FileComment)
}
type alias Aliases =
List ( Util.Module, String )
{-| Prepares a file of Elm code for layout by the pretty printer.
Note that the `Doc` type returned by this is a `Pretty.Doc`. This can be printed
to a string by the `the-sett/elm-pretty-printer` package.
These `Doc` based functions are exposed in case you want to pretty print some
Elm inside something else with the pretty printer. The `pretty` function can be
used to go directly from a `File` to a `String`, if that is more convenient.
-}
prepareLayout : Int -> File -> Doc t
prepareLayout width file =
prettyModule file.moduleDefinition
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> (\doc ->
case file.comments of
Nothing ->
doc
Just fileComment ->
let
( fileCommentStr, innerTags ) =
Comments.prettyFileComment width fileComment
in
doc
|> Pretty.a (prettyComments [ fileCommentStr ])
|> Pretty.a Pretty.line
)
|> Pretty.a (importsPretty file.imports)
|> Pretty.a (prettyDeclarations file.aliases file.declarations)
importsPretty : List Import -> Doc t
importsPretty imports =
case imports of
[] ->
Pretty.line
_ ->
prettyImports imports
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
write : File -> String
write =
pretty 80
writeExpression : Expression -> String
writeExpression exp =
prettyExpression noAliases exp
|> Pretty.pretty 80
writeSignature : Signature -> String
writeSignature sig =
prettySignature noAliases sig
|> Pretty.pretty 80
writeAnnotation : TypeAnnotation -> String
writeAnnotation sig =
prettyTypeAnnotation noAliases sig
|> Pretty.pretty 80
writeInference : Util.Inference -> String
writeInference inf =
"--TYPE:\n "
++ (writeAnnotation inf.type_
|> String.lines
|> String.join "\n "
)
++ "\n\n-- INFERRED\n\n "
++ (Dict.toList inf.inferences
|> List.map
(\( key, val ) ->
key
++ ":\n "
++ (writeAnnotation val
|> String.lines
|> String.join "\n "
)
)
|> String.join "\n\n "
)
++ "\n\n----END-----\n\n"
writeImports : List Import -> String
writeImports imports =
prettyImports imports
|> Pretty.pretty 80
writeDeclaration : Util.Declaration -> String
writeDeclaration exp =
prettyDeclaration 80 exp
|> Pretty.pretty 80
{-| Prints a file of Elm code to the given page width, making use of the pretty
printer.
-}
pretty : Int -> File -> String
pretty width file =
prepareLayout width file
|> Pretty.pretty width
prettyModule : Module -> Doc t
prettyModule mod =
case mod of
NormalModule defaultModuleData ->
prettyDefaultModuleData defaultModuleData
PortModule defaultModuleData ->
prettyPortModuleData defaultModuleData
EffectModule effectModuleData ->
prettyEffectModuleData effectModuleData
prettyModuleName : ModuleName -> Doc t
prettyModuleName name =
List.map Pretty.string name
|> Pretty.join dot
prettyModuleNameDot : Aliases -> ModuleName -> Doc t
prettyModuleNameDot aliases name =
case name of
[] ->
Pretty.empty
_ ->
case Util.findAlias name aliases of
Nothing ->
List.map Pretty.string name
|> Pretty.join dot
|> Pretty.a dot
Just alias ->
Pretty.string alias
|> Pretty.a dot
prettyModuleNameAlias : ModuleName -> Doc t
prettyModuleNameAlias name =
case name of
[] ->
Pretty.empty
_ ->
Pretty.string "as "
|> Pretty.a (List.map Pretty.string name |> Pretty.join dot)
prettyDefaultModuleData : DefaultModuleData -> Doc t
prettyDefaultModuleData moduleData =
Pretty.words
[ Pretty.string "module"
, prettyModuleName (denode moduleData.moduleName)
, prettyExposing (denode moduleData.exposingList)
]
prettyPortModuleData : DefaultModuleData -> Doc t
prettyPortModuleData moduleData =
Pretty.words
[ Pretty.string "port module"
, prettyModuleName (denode moduleData.moduleName)
, prettyExposing (denode moduleData.exposingList)
]
prettyEffectModuleData : EffectModuleData -> Doc t
prettyEffectModuleData moduleData =
let
prettyCmdAndSub maybeCmd maybeSub =
case ( maybeCmd, maybeSub ) of
( Nothing, Nothing ) ->
Nothing
( Just cmdName, Just subName ) ->
[ Pretty.string "where { command ="
, Pretty.string cmdName
, Pretty.string ","
, Pretty.string "subscription ="
, Pretty.string subName
, Pretty.string "}"
]
|> Pretty.words
|> Just
( Just cmdName, Nothing ) ->
[ Pretty.string "where { command ="
, Pretty.string cmdName
, Pretty.string "}"
]
|> Pretty.words
|> Just
( Nothing, Just subName ) ->
[ Pretty.string "where { subscription ="
, Pretty.string subName
, Pretty.string "}"
]
|> Pretty.words
|> Just
in
Pretty.words
[ Pretty.string "effect module"
, prettyModuleName (denode moduleData.moduleName)
, prettyCmdAndSub (denodeMaybe moduleData.command) (denodeMaybe moduleData.subscription)
|> prettyMaybe identity
, prettyExposing (denode moduleData.exposingList)
]
prettyComments : List String -> Doc t
prettyComments comments =
case comments of
[] ->
Pretty.empty
_ ->
List.map Pretty.string comments
|> Pretty.lines
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
{-| Pretty prints a list of import statements.
The list will be de-duplicated and sorted.
-}
prettyImports : List Import -> Doc t
prettyImports imports =
ImportsAndExposing.sortAndDedupImports imports
|> List.map prettyImport
|> Pretty.lines
prettyImport : Import -> Doc t
prettyImport import_ =
Pretty.join Pretty.space
[ Pretty.string "import"
, prettyModuleName (denode import_.moduleName)
, prettyMaybe prettyModuleNameAlias (denodeMaybe import_.moduleAlias)
, prettyMaybe prettyExposing (denodeMaybe import_.exposingList)
]
{-| Pretty prints the contents of an exposing statement, as found on a module or import
statement.
The exposed values will be de-duplicated and sorted.
-}
prettyExposing : Exposing -> Doc t
prettyExposing exposing_ =
let
exposings =
case exposing_ of
All _ ->
Pretty.string ".." |> Pretty.parens
Explicit tll ->
ImportsAndExposing.sortAndDedupExposings (denodeAll tll)
|> prettyTopLevelExposes
|> Pretty.parens
in
Pretty.string "exposing"
|> Pretty.a Pretty.space
|> Pretty.a exposings
prettyTopLevelExposes : List TopLevelExpose -> Doc t
prettyTopLevelExposes exposes =
List.map prettyTopLevelExpose exposes
|> Pretty.join (Pretty.string ", ")
prettyTopLevelExpose : TopLevelExpose -> Doc t
prettyTopLevelExpose tlExpose =
case tlExpose of
InfixExpose val ->
Pretty.string val
|> Pretty.parens
FunctionExpose val ->
Pretty.string val
TypeOrAliasExpose val ->
Pretty.string val
TypeExpose exposedType ->
case exposedType.open of
Nothing ->
Pretty.string exposedType.name
Just _ ->
Pretty.string exposedType.name
|> Pretty.a (Pretty.string "(..)")
{-| Pretty prints a single top-level declaration.
-}
prettyDeclaration : Int -> Util.Declaration -> Doc t
prettyDeclaration width decl =
case decl of
Util.Declaration exp mods innerDecl ->
prettyElmSyntaxDeclaration noAliases innerDecl
Util.Comment content ->
Pretty.string content
Util.Block source ->
Pretty.string source
noAliases : Aliases
noAliases =
[]
{-| Pretty prints an elm-syntax declaration.
-}
prettyElmSyntaxDeclaration : Aliases -> Elm.Syntax.Declaration.Declaration -> Doc t
prettyElmSyntaxDeclaration aliases decl =
case decl of
Elm.Syntax.Declaration.FunctionDeclaration fn ->
prettyFun aliases fn
Elm.Syntax.Declaration.AliasDeclaration tAlias ->
prettyTypeAlias aliases tAlias
Elm.Syntax.Declaration.CustomTypeDeclaration type_ ->
prettyCustomType aliases type_
Elm.Syntax.Declaration.PortDeclaration sig ->
prettyPortDeclaration aliases sig
Elm.Syntax.Declaration.InfixDeclaration infix_ ->
prettyInfix infix_
Elm.Syntax.Declaration.Destructuring pattern expr ->
prettyDestructuring aliases (denode pattern) (denode expr)
prettyDeclarations : Aliases -> List Util.Declaration -> Doc t
prettyDeclarations aliases decls =
List.foldl
(\decl doc ->
case decl of
Util.Comment content ->
doc
|> Pretty.a (Pretty.string (content ++ "\n"))
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
Util.Block source ->
doc
|> Pretty.a (Pretty.string source)
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
Util.Declaration _ _ innerDecl ->
doc
|> Pretty.a (prettyElmSyntaxDeclaration aliases innerDecl)
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
)
Pretty.empty
decls
{-| Pretty prints an Elm function, which may include documentation and a signature too.
-}
prettyFun : Aliases -> Function -> Doc t
prettyFun aliases fn =
[ prettyMaybe prettyDocumentation (denodeMaybe fn.documentation)
, prettyMaybe (prettySignature aliases) (denodeMaybe fn.signature)
, prettyFunctionImplementation aliases (denode fn.declaration)
]
|> Pretty.lines
{-| Pretty prints a type alias definition, which may include documentation too.
-}
prettyTypeAlias : Aliases -> TypeAlias -> Doc t
prettyTypeAlias aliases tAlias =
let
typeAliasPretty =
[ Pretty.string "type alias"
, Pretty.string (denode tAlias.name)
, List.map Pretty.string (denodeAll tAlias.generics) |> Pretty.words
, Pretty.string "="
]
|> Pretty.words
|> Pretty.a Pretty.line
|> Pretty.a (prettyTypeAnnotation aliases (denode tAlias.typeAnnotation))
|> Pretty.nest 4
in
[ prettyMaybe prettyDocumentation (denodeMaybe tAlias.documentation)
, typeAliasPretty
]
|> Pretty.lines
{-| Pretty prints a custom type declaration, which may include documentation too.
-}
prettyCustomType : Aliases -> Type -> Doc t
prettyCustomType aliases type_ =
let
customTypePretty =
[ Pretty.string "type"
, Pretty.string (denode type_.name)
, List.map Pretty.string (denodeAll type_.generics) |> Pretty.words
]
|> Pretty.words
|> Pretty.a Pretty.line
|> Pretty.a (Pretty.string "= ")
|> Pretty.a (prettyValueConstructors aliases (denodeAll type_.constructors))
|> Pretty.nest 4
in
[ prettyMaybe prettyDocumentation (denodeMaybe type_.documentation)
, customTypePretty
]
|> Pretty.lines
prettyValueConstructors : Aliases -> List ValueConstructor -> Doc t
prettyValueConstructors aliases constructors =
List.map (prettyValueConstructor aliases) constructors
|> Pretty.join (Pretty.line |> Pretty.a (Pretty.string "| "))
prettyValueConstructor : Aliases -> ValueConstructor -> Doc t
prettyValueConstructor aliases cons =
[ Pretty.string (denode cons.name)
, List.map (prettyTypeAnnotationParens aliases) (denodeAll cons.arguments) |> Pretty.lines
]
|> Pretty.lines
|> Pretty.group
|> Pretty.nest 4
{-| Pretty prints a port declaration.
-}
prettyPortDeclaration : Aliases -> Signature -> Doc t
prettyPortDeclaration aliases sig =
[ Pretty.string "port"
, prettySignature aliases sig
]
|> Pretty.words
prettyInfix : Infix -> Doc t
prettyInfix infix_ =
let
dirToString direction =
case direction of
Left ->
"left"
Right ->
"right"
Non ->
"non"
in
[ Pretty.string "infix"
, Pretty.string (dirToString (denode infix_.direction))
, Pretty.string (String.fromInt (denode infix_.precedence))
, Pretty.string (denode infix_.operator) |> Pretty.parens
, Pretty.string "="
, Pretty.string (denode infix_.function)
]
|> Pretty.words
{-| Pretty prints a desctructuring declaration.
-}
prettyDestructuring : Aliases -> Pattern -> Expression -> Doc t
prettyDestructuring aliases pattern expr =
[ [ prettyPattern aliases pattern
, Pretty.string "="
]
|> Pretty.words
, prettyExpression aliases expr
]
|> Pretty.lines
|> Pretty.nest 4
prettyDocumentation : Documentation -> Doc t
prettyDocumentation docs =
Pretty.string ("{-|" ++ docs ++ "-}")
{-| Pretty prints a type signature.
-}
prettySignature : Aliases -> Signature -> Doc t
prettySignature aliases sig =
[ [ Pretty.string (denode sig.name)
, Pretty.string ":"
]
|> Pretty.words
, prettyTypeAnnotation aliases (denode sig.typeAnnotation)
]
|> Pretty.lines
|> Pretty.nest 4
|> Pretty.group
prettyFunctionImplementation : Aliases -> FunctionImplementation -> Doc t
prettyFunctionImplementation aliases impl =
Pretty.words
[ Pretty.string (denode impl.name)
, prettyArgs aliases (denodeAll impl.arguments)
, Pretty.string "="
]
|> Pretty.a Pretty.line
|> Pretty.a (prettyExpression aliases (denode impl.expression))
|> Pretty.nest 4
prettyArgs : Aliases -> List Pattern -> Doc t
prettyArgs aliases args =
List.map (prettyPatternInner aliases False) args
|> Pretty.words
--== Patterns
{-| Pretty prints a pattern.
-}
prettyPattern : Aliases -> Pattern -> Doc t
prettyPattern aliases pattern =
prettyPatternInner aliases True pattern
adjustPatternParentheses : Bool -> Pattern -> Pattern
adjustPatternParentheses isTop pattern =
let
addParens pat =
case ( isTop, pat ) of
( False, NamedPattern _ (_ :: _) ) ->
nodify pat |> ParenthesizedPattern
( False, AsPattern _ _ ) ->
nodify pat |> ParenthesizedPattern
( _, _ ) ->
pat
removeParens pat =
case pat of
ParenthesizedPattern innerPat ->
if shouldRemove (denode innerPat) then
denode innerPat
|> removeParens
else
pat
_ ->
pat
shouldRemove pat =
case ( isTop, pat ) of
( False, NamedPattern _ _ ) ->
False
( _, AsPattern _ _ ) ->
False
( _, _ ) ->
isTop
in
removeParens pattern
|> addParens
prettyPatternInner : Aliases -> Bool -> Pattern -> Doc t
prettyPatternInner aliases isTop pattern =
case adjustPatternParentheses isTop pattern of
AllPattern ->
Pretty.string "_"
UnitPattern ->
Pretty.string "()"
CharPattern val ->
Pretty.string (escapeChar val)
|> singleQuotes
StringPattern val ->
Pretty.string val
|> quotes
IntPattern val ->
Pretty.string (String.fromInt val)
HexPattern val ->
Pretty.string (Hex.toString val)
FloatPattern val ->
Pretty.string (String.fromFloat val)
TuplePattern vals ->
Pretty.space
|> Pretty.a
(List.map (prettyPatternInner aliases True) (denodeAll vals)
|> Pretty.join (Pretty.string ", ")
)
|> Pretty.a Pretty.space
|> Pretty.parens
RecordPattern fields ->
List.map Pretty.string (denodeAll fields)
|> Pretty.join (Pretty.string ", ")
|> Pretty.surround Pretty.space Pretty.space
|> Pretty.braces
UnConsPattern hdPat tlPat ->
[ prettyPatternInner aliases False (denode hdPat)
, Pretty.string "::"
, prettyPatternInner aliases False (denode tlPat)
]
|> Pretty.words
ListPattern listPats ->
case listPats of
[] ->
Pretty.string "[]"
_ ->
let
open =
Pretty.a Pretty.space (Pretty.string "[")
close =
Pretty.a (Pretty.string "]") Pretty.space
in
List.map (prettyPatternInner aliases False) (denodeAll listPats)
|> Pretty.join (Pretty.string ", ")
|> Pretty.surround open close
VarPattern var ->
Pretty.string var
NamedPattern qnRef listPats ->
(prettyModuleNameDot aliases qnRef.moduleName
|> Pretty.a (Pretty.string qnRef.name)
)
:: List.map (prettyPatternInner aliases False) (denodeAll listPats)
|> Pretty.words
AsPattern pat name ->
[ prettyPatternInner aliases False (denode pat)
, Pretty.string "as"
, Pretty.string (denode name)
]
|> Pretty.words
ParenthesizedPattern pat ->
prettyPatternInner aliases True (denode pat)
|> Pretty.parens
--== Expressions
type alias Context =
{ precedence : Int
, isTop : Bool
, isLeftPipe : Bool
}
topContext =
{ precedence = 11
, isTop = True
, isLeftPipe = False
}
adjustExpressionParentheses : Context -> Expression -> Expression
adjustExpressionParentheses context expression =
let
addParens expr =
case ( context.isTop, context.isLeftPipe, expr ) of
( False, False, LetExpression _ ) ->
nodify expr |> ParenthesizedExpression
( False, False, CaseExpression _ ) ->
nodify expr |> ParenthesizedExpression
( False, False, LambdaExpression _ ) ->
nodify expr |> ParenthesizedExpression
( False, False, IfBlock _ _ _ ) ->
nodify expr |> ParenthesizedExpression
( _, _, _ ) ->
expr
removeParens expr =
case expr of
ParenthesizedExpression innerExpr ->
if shouldRemove (denode innerExpr) then
denode innerExpr
|> removeParens
else
expr
_ ->
expr
shouldRemove expr =
case ( context.isTop, context.isLeftPipe, expr ) of
( True, _, _ ) ->
True
( _, True, _ ) ->
True
( False, _, Application _ ) ->
if context.precedence < 11 then
True
else
False
( False, _, FunctionOrValue _ _ ) ->
True
( False, _, Integer _ ) ->
True
( False, _, Hex _ ) ->
True
( False, _, Floatable _ ) ->
True
( False, _, Negation _ ) ->
True
( False, _, Literal _ ) ->
True
( False, _, CharLiteral _ ) ->
True
( False, _, TupledExpression _ ) ->
True
( False, _, RecordExpr _ ) ->
True
( False, _, ListExpr _ ) ->
True
( False, _, RecordAccess _ _ ) ->
True
( False, _, RecordAccessFunction _ ) ->
True
( False, _, RecordUpdateExpression _ _ ) ->
True
( _, _, _ ) ->
False
in
removeParens expression
|> addParens
{-| Pretty prints an expression.
-}
prettyExpression : Aliases -> Expression -> Doc t
prettyExpression aliases expression =
prettyExpressionInner aliases topContext 4 expression
|> Tuple.first
prettyExpressionInner : Aliases -> Context -> Int -> Expression -> ( Doc t, Bool )
prettyExpressionInner aliases context indent expression =
case adjustExpressionParentheses context expression of
UnitExpr ->
( Pretty.string "()"
, False
)
Application exprs ->
prettyApplication aliases indent exprs
OperatorApplication symbol dir exprl exprr ->
prettyOperatorApplication aliases indent symbol dir exprl exprr
FunctionOrValue modl val ->
( prettyModuleNameDot aliases modl
|> Pretty.a (Pretty.string val)
, False
)
IfBlock exprBool exprTrue exprFalse ->
prettyIfBlock aliases indent exprBool exprTrue exprFalse
PrefixOperator symbol ->
( Pretty.string symbol |> Pretty.parens
, False
)
Operator symbol ->
( Pretty.string symbol
, False
)
Integer val ->
( Pretty.string (String.fromInt val)
, False
)
Hex val ->
( Pretty.string (toHexString val)
, False
)
Floatable val ->
( Pretty.string (String.fromFloat val)
, False
)
Negation expr ->
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode expr)
in
( Pretty.string "-"
|> Pretty.a prettyExpr
, alwaysBreak
)
Literal val ->
( prettyLiteral val
, False
)
CharLiteral val ->
( Pretty.string (escapeChar val)
|> singleQuotes
, False
)
TupledExpression exprs ->
prettyTupledExpression aliases indent exprs
ParenthesizedExpression expr ->
prettyParenthesizedExpression aliases indent expr
LetExpression letBlock ->
prettyLetBlock aliases indent letBlock
CaseExpression caseBlock ->
prettyCaseBlock aliases indent caseBlock
LambdaExpression lambda ->
prettyLambdaExpression aliases indent lambda
RecordExpr setters ->
prettyRecordExpr aliases setters
ListExpr exprs ->
prettyList aliases indent exprs
RecordAccess expr field ->
prettyRecordAccess aliases expr field
RecordAccessFunction field ->
( Pretty.string field
, False
)
RecordUpdateExpression var setters ->
prettyRecordUpdateExpression aliases indent var setters
GLSLExpression val ->
( Pretty.string "glsl"
, True
)
prettyApplication : Aliases -> Int -> List (Node Expression) -> ( Doc t, Bool )
prettyApplication aliases indent exprs =
let
( prettyExpressions, alwaysBreak ) =
List.map
(prettyExpressionInner aliases
{ precedence = 11
, isTop = False
, isLeftPipe = False
}
4
)
(denodeAll exprs)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.lines
|> Pretty.nest indent
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
isEndLineOperator : String -> Bool
isEndLineOperator op =
case op of
"<|" ->
True
_ ->
False
prettyOperatorApplication : Aliases -> Int -> String -> InfixDirection -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyOperatorApplication aliases indent symbol dir exprl exprr =
if symbol == "<|" then
prettyOperatorApplicationLeft aliases indent symbol dir exprl exprr
else
prettyOperatorApplicationRight aliases indent symbol dir exprl exprr
prettyOperatorApplicationLeft : Aliases -> Int -> String -> InfixDirection -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyOperatorApplicationLeft aliases indent symbol _ exprl exprr =
let
context =
{ precedence = precedence symbol
, isTop = False
, isLeftPipe = True
}
( prettyExpressionLeft, alwaysBreakLeft ) =
prettyExpressionInner aliases context 4 (denode exprl)
( prettyExpressionRight, alwaysBreakRight ) =
prettyExpressionInner aliases context 4 (denode exprr)
alwaysBreak =
alwaysBreakLeft || alwaysBreakRight
in
( [ [ prettyExpressionLeft, Pretty.string symbol ] |> Pretty.words
, prettyExpressionRight
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest 4
, alwaysBreak
)
prettyOperatorApplicationRight : Aliases -> Int -> String -> InfixDirection -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyOperatorApplicationRight aliases indent symbol _ exprl exprr =
let
expandExpr : Int -> Context -> Expression -> List ( Doc t, Bool )
expandExpr innerIndent context expr =
case expr of
OperatorApplication sym _ left right ->
innerOpApply False sym left right
_ ->
[ prettyExpressionInner aliases context innerIndent expr ]
innerOpApply : Bool -> String -> Node Expression -> Node Expression -> List ( Doc t, Bool )
innerOpApply isTop sym left right =
let
context =
{ precedence = precedence sym
, isTop = False
, isLeftPipe = "<|" == sym
}
innerIndent =
decrementIndent 4 (String.length symbol + 1)
leftIndent =
if isTop then
indent
else
innerIndent
rightSide =
denode right |> expandExpr innerIndent context
in
case rightSide of
( hdExpr, hdBreak ) :: tl ->
List.append (denode left |> expandExpr leftIndent context)
(( Pretty.string sym |> Pretty.a Pretty.space |> Pretty.a hdExpr, hdBreak ) :: tl)
[] ->
[]
( prettyExpressions, alwaysBreak ) =
innerOpApply True symbol exprl exprr
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.join (Pretty.nest indent Pretty.line)
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyIfBlock : Aliases -> Int -> Node Expression -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyIfBlock aliases indent exprBool exprTrue exprFalse =
let
innerIfBlock : Node Expression -> Node Expression -> Node Expression -> List (Doc t)
innerIfBlock innerExprBool innerExprTrue innerExprFalse =
let
context =
topContext
ifPart =
let
( prettyBoolExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode innerExprBool)
in
[ [ Pretty.string "if"
, prettyExpressionInner aliases topContext 4 (denode innerExprBool) |> Tuple.first
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest indent
, Pretty.string "then"
]
|> Pretty.lines
|> optionalGroup alwaysBreak
truePart =
prettyExpressionInner aliases topContext 4 (denode innerExprTrue)
|> Tuple.first
|> Pretty.indent indent
elsePart =
Pretty.line
|> Pretty.a (Pretty.string "else")
falsePart =
case denode innerExprFalse of
IfBlock nestedExprBool nestedExprTrue nestedExprFalse ->
innerIfBlock nestedExprBool nestedExprTrue nestedExprFalse
_ ->
[ prettyExpressionInner aliases topContext 4 (denode innerExprFalse)
|> Tuple.first
|> Pretty.indent indent
]
in
case falsePart of
[] ->
[]
[ falseExpr ] ->
[ ifPart
, truePart
, elsePart
, falseExpr
]
hd :: tl ->
List.append
[ ifPart
, truePart
, [ elsePart, hd ] |> Pretty.words
]
tl
prettyExpressions =
innerIfBlock exprBool exprTrue exprFalse
in
( prettyExpressions
|> Pretty.lines
|> Pretty.align
, True
)
prettyLiteral : String -> Doc t
prettyLiteral val =
if String.contains "\n" val then
Pretty.string val
|> tripleQuotes
else
Pretty.string (escape val)
|> quotes
prettyTupledExpression : Aliases -> Int -> List (Node Expression) -> ( Doc t, Bool )
prettyTupledExpression aliases indent exprs =
let
open =
Pretty.a Pretty.space (Pretty.string "(")
close =
Pretty.a (Pretty.string ")") Pretty.line
in
case exprs of
[] ->
( Pretty.string "()", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettyExpressionInner aliases topContext (decrementIndent indent 2)) (denodeAll exprs)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyParenthesizedExpression : Aliases -> Int -> Node Expression -> ( Doc t, Bool )
prettyParenthesizedExpression aliases indent expr =
let
open =
Pretty.string "("
close =
Pretty.a (Pretty.string ")") Pretty.tightline
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext (decrementIndent indent 1) (denode expr)
in
( prettyExpr
|> Pretty.nest 1
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyLetBlock : Aliases -> Int -> LetBlock -> ( Doc t, Bool )
prettyLetBlock aliases indent letBlock =
( [ Pretty.string "let"
, List.map (prettyLetDeclaration aliases indent) (denodeAll letBlock.declarations)
|> doubleLines
|> Pretty.indent indent
, Pretty.string "in"
, prettyExpressionInner aliases topContext 4 (denode letBlock.expression) |> Tuple.first
]
|> Pretty.lines
|> Pretty.align
, True
)
prettyLetDeclaration : Aliases -> Int -> LetDeclaration -> Doc t
prettyLetDeclaration aliases indent letDecl =
case letDecl of
LetFunction fn ->
prettyFun aliases fn
LetDestructuring pattern expr ->
[ prettyPatternInner aliases False (denode pattern)
, Pretty.string "="
]
|> Pretty.words
|> Pretty.a Pretty.line
|> Pretty.a
(prettyExpressionInner aliases topContext 4 (denode expr)
|> Tuple.first
|> Pretty.indent indent
)
prettyCaseBlock : Aliases -> Int -> CaseBlock -> ( Doc t, Bool )
prettyCaseBlock aliases indent caseBlock =
let
casePart =
let
( caseExpression, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode caseBlock.expression)
in
[ [ Pretty.string "case"
, caseExpression
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest indent
, Pretty.string "of"
]
|> Pretty.lines
|> optionalGroup alwaysBreak
prettyCase ( pattern, expr ) =
prettyPattern aliases (denode pattern)
|> Pretty.a (Pretty.string " ->")
|> Pretty.a Pretty.line
|> Pretty.a (prettyExpressionInner aliases topContext 4 (denode expr) |> Tuple.first |> Pretty.indent 4)
|> Pretty.indent indent
patternsPart =
List.map prettyCase caseBlock.cases
|> doubleLines
in
( [ casePart, patternsPart ]
|> Pretty.lines
|> Pretty.align
, True
)
prettyLambdaExpression : Aliases -> Int -> Lambda -> ( Doc t, Bool )
prettyLambdaExpression aliases indent lambda =
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode lambda.expression)
in
( [ Pretty.string "\\"
|> Pretty.a (List.map (prettyPatternInner aliases False) (denodeAll lambda.args) |> Pretty.words)
|> Pretty.a (Pretty.string " ->")
, prettyExpr
]
|> Pretty.lines
|> Pretty.nest indent
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyRecordExpr : Aliases -> List (Node RecordSetter) -> ( Doc t, Bool )
prettyRecordExpr aliases setters =
let
open =
Pretty.a Pretty.space (Pretty.string "{")
close =
Pretty.a (Pretty.string "}")
Pretty.line
in
case setters of
[] ->
( Pretty.string "{}", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettySetter aliases) (denodeAll setters)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettySetter : Aliases -> ( Node String, Node Expression ) -> ( Doc t, Bool )
prettySetter aliases ( fld, val ) =
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode val)
in
( [ [ Pretty.string (denode fld)
, Pretty.string "="
]
|> Pretty.words
, prettyExpr
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest 4
, alwaysBreak
)
prettyList : Aliases -> Int -> List (Node Expression) -> ( Doc t, Bool )
prettyList aliases indent exprs =
let
open =
Pretty.a Pretty.space (Pretty.string "[")
close =
Pretty.a (Pretty.string "]") Pretty.line
in
case exprs of
[] ->
( Pretty.string "[]", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettyExpressionInner aliases topContext (decrementIndent indent 2)) (denodeAll exprs)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyRecordAccess : Aliases -> Node Expression -> Node String -> ( Doc t, Bool )
prettyRecordAccess aliases expr field =
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode expr)
in
( prettyExpr
|> Pretty.a dot
|> Pretty.a (Pretty.string (denode field))
, alwaysBreak
)
prettyRecordUpdateExpression : Aliases -> Int -> Node String -> List (Node RecordSetter) -> ( Doc t, Bool )
prettyRecordUpdateExpression aliases indent var setters =
let
open =
[ Pretty.string "{"
, Pretty.string (denode var)
]
|> Pretty.words
|> Pretty.a Pretty.line
close =
Pretty.a (Pretty.string "}")
Pretty.line
addBarToFirst exprs =
case exprs of
[] ->
[]
hd :: tl ->
Pretty.a hd (Pretty.string "| ") :: tl
in
case setters of
[] ->
( Pretty.string "{}", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettySetter aliases) (denodeAll setters)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( open
|> Pretty.a
(prettyExpressions
|> addBarToFirst
|> Pretty.separators ", "
)
|> Pretty.nest indent
|> Pretty.surround Pretty.empty close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
--== Type Annotations
{-| Pretty prints a type annotation.
-}
prettyTypeAnnotation : Aliases -> TypeAnnotation -> Doc t
prettyTypeAnnotation aliases typeAnn =
case typeAnn of
GenericType val ->
Pretty.string val
Typed fqName anns ->
prettyTyped aliases fqName anns
Unit ->
Pretty.string "()"
Tupled anns ->
prettyTupled aliases anns
Record recordDef ->
prettyRecord aliases (denodeAll recordDef)
GenericRecord paramName recordDef ->
prettyGenericRecord aliases (denode paramName) (denodeAll (denode recordDef))
FunctionTypeAnnotation fromAnn toAnn ->
prettyFunctionTypeAnnotation aliases fromAnn toAnn
prettyTyped : Aliases -> Node ( ModuleName, String ) -> List (Node TypeAnnotation) -> Doc t
prettyTyped aliases fqName anns =
let
( moduleName, typeName ) =
denode fqName
typeDoc =
prettyModuleNameDot aliases moduleName
|> Pretty.a (Pretty.string typeName)
argsDoc =
List.map (prettyTypeAnnotationParens aliases) (denodeAll anns)
|> Pretty.words
in
[ typeDoc
, argsDoc
]
|> Pretty.words
prettyTupled : Aliases -> List (Node TypeAnnotation) -> Doc t
prettyTupled aliases anns =
Pretty.space
|> Pretty.a
(List.map (prettyTypeAnnotation aliases) (denodeAll anns)
|> Pretty.join (Pretty.string ", ")
)
|> Pretty.a Pretty.space
|> Pretty.parens
prettyTypeAnnotationParens : Aliases -> TypeAnnotation -> Doc t
prettyTypeAnnotationParens aliases typeAnn =
if isNakedCompound typeAnn then
prettyTypeAnnotation aliases typeAnn |> Pretty.parens
else
prettyTypeAnnotation aliases typeAnn
prettyRecord : Aliases -> List RecordField -> Doc t
prettyRecord aliases fields =
let
open =
Pretty.a Pretty.space (Pretty.string "{")
close =
Pretty.a (Pretty.string "}") Pretty.line
in
case fields of
[] ->
Pretty.string "{}"
_ ->
fields
|> List.map (Tuple.mapBoth denode denode)
|> List.map (prettyFieldTypeAnn aliases)
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.group
prettyGenericRecord : Aliases -> String -> List RecordField -> Doc t
prettyGenericRecord aliases paramName fields =
let
open =
[ Pretty.string "{"
, Pretty.string paramName
]
|> Pretty.words
|> Pretty.a Pretty.line
close =
Pretty.a (Pretty.string "}")
Pretty.line
addBarToFirst exprs =
case exprs of
[] ->
[]
hd :: tl ->
Pretty.a hd (Pretty.string "| ") :: tl
in
case fields of
[] ->
Pretty.string "{}"
_ ->
open
|> Pretty.a
(fields
|> List.map (Tuple.mapBoth denode denode)
|> List.map (prettyFieldTypeAnn aliases)
|> addBarToFirst
|> Pretty.separators ", "
)
|> Pretty.nest 4
|> Pretty.surround Pretty.empty close
|> Pretty.group
prettyFieldTypeAnn : Aliases -> ( String, TypeAnnotation ) -> Doc t
prettyFieldTypeAnn aliases ( name, ann ) =
[ [ Pretty.string name
, Pretty.string ":"
]
|> Pretty.words
, prettyTypeAnnotation aliases ann
]
|> Pretty.lines
|> Pretty.nest 4
|> Pretty.group
prettyFunctionTypeAnnotation : Aliases -> Node TypeAnnotation -> Node TypeAnnotation -> Doc t
prettyFunctionTypeAnnotation aliases left right =
let
expandLeft : TypeAnnotation -> Doc t
expandLeft ann =
case ann of
FunctionTypeAnnotation _ _ ->
prettyTypeAnnotationParens aliases ann
_ ->
prettyTypeAnnotation aliases ann
expandRight : TypeAnnotation -> List (Doc t)
expandRight ann =
case ann of
FunctionTypeAnnotation innerLeft innerRight ->
innerFnTypeAnn innerLeft innerRight
_ ->
[ prettyTypeAnnotation aliases ann ]
innerFnTypeAnn : Node TypeAnnotation -> Node TypeAnnotation -> List (Doc t)
innerFnTypeAnn innerLeft innerRight =
let
rightSide =
denode innerRight |> expandRight
in
case rightSide of
hd :: tl ->
(denode innerLeft |> expandLeft)
:: ([ Pretty.string "->", hd ] |> Pretty.words)
:: tl
[] ->
[]
in
innerFnTypeAnn left right
|> Pretty.lines
|> Pretty.group
{-| A type annotation is a naked compound if it is made up of multiple parts that
are not enclosed in brackets or braces. This means either a type or type alias with
arguments or a function type; records and tuples are compound but enclosed in brackets
or braces.
Naked type annotations need to be bracketed in situations type argument bindings are
ambiguous otherwise.
-}
isNakedCompound : TypeAnnotation -> Bool
isNakedCompound typeAnn =
case typeAnn of
Typed _ [] ->
False
Typed _ args ->
True
FunctionTypeAnnotation _ _ ->
True
_ ->
False
--== Helpers
prettyMaybe : (a -> Doc t) -> Maybe a -> Doc t
prettyMaybe prettyFn maybeVal =
Maybe.map prettyFn maybeVal
|> Maybe.withDefault Pretty.empty
decrementIndent : Int -> Int -> Int
decrementIndent currentIndent spaces =
let
modded =
modBy 4 (currentIndent - spaces)
in
if modded == 0 then
4
else
modded
dot : Doc t
dot =
Pretty.string "."
quotes : Doc t -> Doc t
quotes doc =
Pretty.surround (Pretty.char '"') (Pretty.char '"') doc
tripleQuotes : Doc t -> Doc t
tripleQuotes doc =
Pretty.surround (Pretty.string "\"\"\"") (Pretty.string "\"\"\"") doc
singleQuotes : Doc t -> Doc t
singleQuotes doc =
Pretty.surround (Pretty.char '\'') (Pretty.char '\'') doc
sqParens : Doc t -> Doc t
sqParens doc =
Pretty.surround (Pretty.string "[") (Pretty.string "]") doc
doubleLines : List (Doc t) -> Doc t
doubleLines =
Pretty.join (Pretty.a Pretty.line Pretty.line)
escape : String -> String
escape val =
val
|> String.replace "\\" "\\\\"
|> String.replace "\"" "\\\""
|> String.replace "\n" "\\n"
|> String.replace "\t" "\\t"
escapeChar : Char -> String
escapeChar val =
case val of
'\\' ->
"\\\\"
'\'' ->
"\\'"
'\t' ->
"\\t"
'\n' ->
"\\n"
c ->
String.fromChar c
optionalGroup : Bool -> Doc t -> Doc t
optionalGroup flag doc =
if flag then
doc
else
Pretty.group doc
optionalParens : Bool -> Doc t -> Doc t
optionalParens flag doc =
if flag then
Pretty.parens doc
else
doc
toHexString : Int -> String
toHexString val =
let
padWithZeros str =
let
length =
String.length str
in
if length < 2 then
String.padLeft 2 '0' str
else if length > 2 && length < 4 then
String.padLeft 4 '0' str
else if length > 4 && length < 8 then
String.padLeft 8 '0' str
else
str
in
"0x" ++ (Hex.toString val |> String.toUpper |> padWithZeros)
{-| Calculate a precedence for any operator to be able to know when
parenthesis are needed or not.
When a lower precedence expression appears beneath a higher one, its needs
parenthesis.
When a higher precedence expression appears beneath a lower one, if should
not have parenthesis.
-}
precedence : String -> Int
precedence symbol =
case symbol of
">>" ->
9
"<<" ->
9
"^" ->
8
"*" ->
7
"/" ->
7
"//" ->
7
"%" ->
7
"rem" ->
7
"+" ->
6
"-" ->
6
"++" ->
5
"::" ->
5
"==" ->
4
"/=" ->
4
"<" ->
4
">" ->
4
"<=" ->
4
">=" ->
4
"&&" ->
3
"||" ->
2
"|>" ->
0
"<|" ->
0
_ ->
0
| 7132 | module Internal.Write exposing
( write
, writeAnnotation
, writeDeclaration
, writeExpression
, writeImports
, writeInference
, writeSignature
)
{-| This is borrowed basically in it's entirety from: <https://github.com/the-sett/elm-syntax-dsl/blob/master/src/Elm/Pretty.elm>
Thank you <NAME>!
-}
import Dict
import Elm.Syntax.Declaration
import Elm.Syntax.Documentation exposing (Documentation)
import Elm.Syntax.Exposing exposing (ExposedType, Exposing(..), TopLevelExpose(..))
import Elm.Syntax.Expression exposing (Case, CaseBlock, Expression(..), Function, FunctionImplementation, Lambda, LetBlock, LetDeclaration(..), RecordSetter)
import Elm.Syntax.File
import Elm.Syntax.Import exposing (Import)
import Elm.Syntax.Infix exposing (Infix, InfixDirection(..))
import Elm.Syntax.Module exposing (DefaultModuleData, EffectModuleData, Module(..))
import Elm.Syntax.ModuleName exposing (ModuleName)
import Elm.Syntax.Node as Node exposing (Node(..))
import Elm.Syntax.Pattern exposing (Pattern(..), QualifiedNameRef)
import Elm.Syntax.Range exposing (Location, Range, emptyRange)
import Elm.Syntax.Signature exposing (Signature)
import Elm.Syntax.Type exposing (Type, ValueConstructor)
import Elm.Syntax.TypeAlias exposing (TypeAlias)
import Elm.Syntax.TypeAnnotation exposing (RecordDefinition, RecordField, TypeAnnotation(..))
import Hex
import Internal.Comments as Comments
import Internal.Compiler as Util exposing (denode, denodeAll, denodeMaybe, nodify, nodifyAll, nodifyMaybe)
import Internal.ImportsAndExposing as ImportsAndExposing
import Pretty exposing (Doc)
type alias File =
{ moduleDefinition : Module
, aliases : List ( Util.Module, String )
, imports : List Import
, declarations : List Util.Declaration
, comments : Maybe (Comments.Comment Comments.FileComment)
}
type alias Aliases =
List ( Util.Module, String )
{-| Prepares a file of Elm code for layout by the pretty printer.
Note that the `Doc` type returned by this is a `Pretty.Doc`. This can be printed
to a string by the `the-sett/elm-pretty-printer` package.
These `Doc` based functions are exposed in case you want to pretty print some
Elm inside something else with the pretty printer. The `pretty` function can be
used to go directly from a `File` to a `String`, if that is more convenient.
-}
prepareLayout : Int -> File -> Doc t
prepareLayout width file =
prettyModule file.moduleDefinition
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> (\doc ->
case file.comments of
Nothing ->
doc
Just fileComment ->
let
( fileCommentStr, innerTags ) =
Comments.prettyFileComment width fileComment
in
doc
|> Pretty.a (prettyComments [ fileCommentStr ])
|> Pretty.a Pretty.line
)
|> Pretty.a (importsPretty file.imports)
|> Pretty.a (prettyDeclarations file.aliases file.declarations)
importsPretty : List Import -> Doc t
importsPretty imports =
case imports of
[] ->
Pretty.line
_ ->
prettyImports imports
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
write : File -> String
write =
pretty 80
writeExpression : Expression -> String
writeExpression exp =
prettyExpression noAliases exp
|> Pretty.pretty 80
writeSignature : Signature -> String
writeSignature sig =
prettySignature noAliases sig
|> Pretty.pretty 80
writeAnnotation : TypeAnnotation -> String
writeAnnotation sig =
prettyTypeAnnotation noAliases sig
|> Pretty.pretty 80
writeInference : Util.Inference -> String
writeInference inf =
"--TYPE:\n "
++ (writeAnnotation inf.type_
|> String.lines
|> String.join "\n "
)
++ "\n\n-- INFERRED\n\n "
++ (Dict.toList inf.inferences
|> List.map
(\( key, val ) ->
key
++ ":\n "
++ (writeAnnotation val
|> String.lines
|> String.join "\n "
)
)
|> String.join "\n\n "
)
++ "\n\n----END-----\n\n"
writeImports : List Import -> String
writeImports imports =
prettyImports imports
|> Pretty.pretty 80
writeDeclaration : Util.Declaration -> String
writeDeclaration exp =
prettyDeclaration 80 exp
|> Pretty.pretty 80
{-| Prints a file of Elm code to the given page width, making use of the pretty
printer.
-}
pretty : Int -> File -> String
pretty width file =
prepareLayout width file
|> Pretty.pretty width
prettyModule : Module -> Doc t
prettyModule mod =
case mod of
NormalModule defaultModuleData ->
prettyDefaultModuleData defaultModuleData
PortModule defaultModuleData ->
prettyPortModuleData defaultModuleData
EffectModule effectModuleData ->
prettyEffectModuleData effectModuleData
prettyModuleName : ModuleName -> Doc t
prettyModuleName name =
List.map Pretty.string name
|> Pretty.join dot
prettyModuleNameDot : Aliases -> ModuleName -> Doc t
prettyModuleNameDot aliases name =
case name of
[] ->
Pretty.empty
_ ->
case Util.findAlias name aliases of
Nothing ->
List.map Pretty.string name
|> Pretty.join dot
|> Pretty.a dot
Just alias ->
Pretty.string alias
|> Pretty.a dot
prettyModuleNameAlias : ModuleName -> Doc t
prettyModuleNameAlias name =
case name of
[] ->
Pretty.empty
_ ->
Pretty.string "as "
|> Pretty.a (List.map Pretty.string name |> Pretty.join dot)
prettyDefaultModuleData : DefaultModuleData -> Doc t
prettyDefaultModuleData moduleData =
Pretty.words
[ Pretty.string "module"
, prettyModuleName (denode moduleData.moduleName)
, prettyExposing (denode moduleData.exposingList)
]
prettyPortModuleData : DefaultModuleData -> Doc t
prettyPortModuleData moduleData =
Pretty.words
[ Pretty.string "port module"
, prettyModuleName (denode moduleData.moduleName)
, prettyExposing (denode moduleData.exposingList)
]
prettyEffectModuleData : EffectModuleData -> Doc t
prettyEffectModuleData moduleData =
let
prettyCmdAndSub maybeCmd maybeSub =
case ( maybeCmd, maybeSub ) of
( Nothing, Nothing ) ->
Nothing
( Just cmdName, Just subName ) ->
[ Pretty.string "where { command ="
, Pretty.string cmdName
, Pretty.string ","
, Pretty.string "subscription ="
, Pretty.string subName
, Pretty.string "}"
]
|> Pretty.words
|> Just
( Just cmdName, Nothing ) ->
[ Pretty.string "where { command ="
, Pretty.string cmdName
, Pretty.string "}"
]
|> Pretty.words
|> Just
( Nothing, Just subName ) ->
[ Pretty.string "where { subscription ="
, Pretty.string subName
, Pretty.string "}"
]
|> Pretty.words
|> Just
in
Pretty.words
[ Pretty.string "effect module"
, prettyModuleName (denode moduleData.moduleName)
, prettyCmdAndSub (denodeMaybe moduleData.command) (denodeMaybe moduleData.subscription)
|> prettyMaybe identity
, prettyExposing (denode moduleData.exposingList)
]
prettyComments : List String -> Doc t
prettyComments comments =
case comments of
[] ->
Pretty.empty
_ ->
List.map Pretty.string comments
|> Pretty.lines
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
{-| Pretty prints a list of import statements.
The list will be de-duplicated and sorted.
-}
prettyImports : List Import -> Doc t
prettyImports imports =
ImportsAndExposing.sortAndDedupImports imports
|> List.map prettyImport
|> Pretty.lines
prettyImport : Import -> Doc t
prettyImport import_ =
Pretty.join Pretty.space
[ Pretty.string "import"
, prettyModuleName (denode import_.moduleName)
, prettyMaybe prettyModuleNameAlias (denodeMaybe import_.moduleAlias)
, prettyMaybe prettyExposing (denodeMaybe import_.exposingList)
]
{-| Pretty prints the contents of an exposing statement, as found on a module or import
statement.
The exposed values will be de-duplicated and sorted.
-}
prettyExposing : Exposing -> Doc t
prettyExposing exposing_ =
let
exposings =
case exposing_ of
All _ ->
Pretty.string ".." |> Pretty.parens
Explicit tll ->
ImportsAndExposing.sortAndDedupExposings (denodeAll tll)
|> prettyTopLevelExposes
|> Pretty.parens
in
Pretty.string "exposing"
|> Pretty.a Pretty.space
|> Pretty.a exposings
prettyTopLevelExposes : List TopLevelExpose -> Doc t
prettyTopLevelExposes exposes =
List.map prettyTopLevelExpose exposes
|> Pretty.join (Pretty.string ", ")
prettyTopLevelExpose : TopLevelExpose -> Doc t
prettyTopLevelExpose tlExpose =
case tlExpose of
InfixExpose val ->
Pretty.string val
|> Pretty.parens
FunctionExpose val ->
Pretty.string val
TypeOrAliasExpose val ->
Pretty.string val
TypeExpose exposedType ->
case exposedType.open of
Nothing ->
Pretty.string exposedType.name
Just _ ->
Pretty.string exposedType.name
|> Pretty.a (Pretty.string "(..)")
{-| Pretty prints a single top-level declaration.
-}
prettyDeclaration : Int -> Util.Declaration -> Doc t
prettyDeclaration width decl =
case decl of
Util.Declaration exp mods innerDecl ->
prettyElmSyntaxDeclaration noAliases innerDecl
Util.Comment content ->
Pretty.string content
Util.Block source ->
Pretty.string source
noAliases : Aliases
noAliases =
[]
{-| Pretty prints an elm-syntax declaration.
-}
prettyElmSyntaxDeclaration : Aliases -> Elm.Syntax.Declaration.Declaration -> Doc t
prettyElmSyntaxDeclaration aliases decl =
case decl of
Elm.Syntax.Declaration.FunctionDeclaration fn ->
prettyFun aliases fn
Elm.Syntax.Declaration.AliasDeclaration tAlias ->
prettyTypeAlias aliases tAlias
Elm.Syntax.Declaration.CustomTypeDeclaration type_ ->
prettyCustomType aliases type_
Elm.Syntax.Declaration.PortDeclaration sig ->
prettyPortDeclaration aliases sig
Elm.Syntax.Declaration.InfixDeclaration infix_ ->
prettyInfix infix_
Elm.Syntax.Declaration.Destructuring pattern expr ->
prettyDestructuring aliases (denode pattern) (denode expr)
prettyDeclarations : Aliases -> List Util.Declaration -> Doc t
prettyDeclarations aliases decls =
List.foldl
(\decl doc ->
case decl of
Util.Comment content ->
doc
|> Pretty.a (Pretty.string (content ++ "\n"))
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
Util.Block source ->
doc
|> Pretty.a (Pretty.string source)
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
Util.Declaration _ _ innerDecl ->
doc
|> Pretty.a (prettyElmSyntaxDeclaration aliases innerDecl)
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
)
Pretty.empty
decls
{-| Pretty prints an Elm function, which may include documentation and a signature too.
-}
prettyFun : Aliases -> Function -> Doc t
prettyFun aliases fn =
[ prettyMaybe prettyDocumentation (denodeMaybe fn.documentation)
, prettyMaybe (prettySignature aliases) (denodeMaybe fn.signature)
, prettyFunctionImplementation aliases (denode fn.declaration)
]
|> Pretty.lines
{-| Pretty prints a type alias definition, which may include documentation too.
-}
prettyTypeAlias : Aliases -> TypeAlias -> Doc t
prettyTypeAlias aliases tAlias =
let
typeAliasPretty =
[ Pretty.string "type alias"
, Pretty.string (denode tAlias.name)
, List.map Pretty.string (denodeAll tAlias.generics) |> Pretty.words
, Pretty.string "="
]
|> Pretty.words
|> Pretty.a Pretty.line
|> Pretty.a (prettyTypeAnnotation aliases (denode tAlias.typeAnnotation))
|> Pretty.nest 4
in
[ prettyMaybe prettyDocumentation (denodeMaybe tAlias.documentation)
, typeAliasPretty
]
|> Pretty.lines
{-| Pretty prints a custom type declaration, which may include documentation too.
-}
prettyCustomType : Aliases -> Type -> Doc t
prettyCustomType aliases type_ =
let
customTypePretty =
[ Pretty.string "type"
, Pretty.string (denode type_.name)
, List.map Pretty.string (denodeAll type_.generics) |> Pretty.words
]
|> Pretty.words
|> Pretty.a Pretty.line
|> Pretty.a (Pretty.string "= ")
|> Pretty.a (prettyValueConstructors aliases (denodeAll type_.constructors))
|> Pretty.nest 4
in
[ prettyMaybe prettyDocumentation (denodeMaybe type_.documentation)
, customTypePretty
]
|> Pretty.lines
prettyValueConstructors : Aliases -> List ValueConstructor -> Doc t
prettyValueConstructors aliases constructors =
List.map (prettyValueConstructor aliases) constructors
|> Pretty.join (Pretty.line |> Pretty.a (Pretty.string "| "))
prettyValueConstructor : Aliases -> ValueConstructor -> Doc t
prettyValueConstructor aliases cons =
[ Pretty.string (denode cons.name)
, List.map (prettyTypeAnnotationParens aliases) (denodeAll cons.arguments) |> Pretty.lines
]
|> Pretty.lines
|> Pretty.group
|> Pretty.nest 4
{-| Pretty prints a port declaration.
-}
prettyPortDeclaration : Aliases -> Signature -> Doc t
prettyPortDeclaration aliases sig =
[ Pretty.string "port"
, prettySignature aliases sig
]
|> Pretty.words
prettyInfix : Infix -> Doc t
prettyInfix infix_ =
let
dirToString direction =
case direction of
Left ->
"left"
Right ->
"right"
Non ->
"non"
in
[ Pretty.string "infix"
, Pretty.string (dirToString (denode infix_.direction))
, Pretty.string (String.fromInt (denode infix_.precedence))
, Pretty.string (denode infix_.operator) |> Pretty.parens
, Pretty.string "="
, Pretty.string (denode infix_.function)
]
|> Pretty.words
{-| Pretty prints a desctructuring declaration.
-}
prettyDestructuring : Aliases -> Pattern -> Expression -> Doc t
prettyDestructuring aliases pattern expr =
[ [ prettyPattern aliases pattern
, Pretty.string "="
]
|> Pretty.words
, prettyExpression aliases expr
]
|> Pretty.lines
|> Pretty.nest 4
prettyDocumentation : Documentation -> Doc t
prettyDocumentation docs =
Pretty.string ("{-|" ++ docs ++ "-}")
{-| Pretty prints a type signature.
-}
prettySignature : Aliases -> Signature -> Doc t
prettySignature aliases sig =
[ [ Pretty.string (denode sig.name)
, Pretty.string ":"
]
|> Pretty.words
, prettyTypeAnnotation aliases (denode sig.typeAnnotation)
]
|> Pretty.lines
|> Pretty.nest 4
|> Pretty.group
prettyFunctionImplementation : Aliases -> FunctionImplementation -> Doc t
prettyFunctionImplementation aliases impl =
Pretty.words
[ Pretty.string (denode impl.name)
, prettyArgs aliases (denodeAll impl.arguments)
, Pretty.string "="
]
|> Pretty.a Pretty.line
|> Pretty.a (prettyExpression aliases (denode impl.expression))
|> Pretty.nest 4
prettyArgs : Aliases -> List Pattern -> Doc t
prettyArgs aliases args =
List.map (prettyPatternInner aliases False) args
|> Pretty.words
--== Patterns
{-| Pretty prints a pattern.
-}
prettyPattern : Aliases -> Pattern -> Doc t
prettyPattern aliases pattern =
prettyPatternInner aliases True pattern
adjustPatternParentheses : Bool -> Pattern -> Pattern
adjustPatternParentheses isTop pattern =
let
addParens pat =
case ( isTop, pat ) of
( False, NamedPattern _ (_ :: _) ) ->
nodify pat |> ParenthesizedPattern
( False, AsPattern _ _ ) ->
nodify pat |> ParenthesizedPattern
( _, _ ) ->
pat
removeParens pat =
case pat of
ParenthesizedPattern innerPat ->
if shouldRemove (denode innerPat) then
denode innerPat
|> removeParens
else
pat
_ ->
pat
shouldRemove pat =
case ( isTop, pat ) of
( False, NamedPattern _ _ ) ->
False
( _, AsPattern _ _ ) ->
False
( _, _ ) ->
isTop
in
removeParens pattern
|> addParens
prettyPatternInner : Aliases -> Bool -> Pattern -> Doc t
prettyPatternInner aliases isTop pattern =
case adjustPatternParentheses isTop pattern of
AllPattern ->
Pretty.string "_"
UnitPattern ->
Pretty.string "()"
CharPattern val ->
Pretty.string (escapeChar val)
|> singleQuotes
StringPattern val ->
Pretty.string val
|> quotes
IntPattern val ->
Pretty.string (String.fromInt val)
HexPattern val ->
Pretty.string (Hex.toString val)
FloatPattern val ->
Pretty.string (String.fromFloat val)
TuplePattern vals ->
Pretty.space
|> Pretty.a
(List.map (prettyPatternInner aliases True) (denodeAll vals)
|> Pretty.join (Pretty.string ", ")
)
|> Pretty.a Pretty.space
|> Pretty.parens
RecordPattern fields ->
List.map Pretty.string (denodeAll fields)
|> Pretty.join (Pretty.string ", ")
|> Pretty.surround Pretty.space Pretty.space
|> Pretty.braces
UnConsPattern hdPat tlPat ->
[ prettyPatternInner aliases False (denode hdPat)
, Pretty.string "::"
, prettyPatternInner aliases False (denode tlPat)
]
|> Pretty.words
ListPattern listPats ->
case listPats of
[] ->
Pretty.string "[]"
_ ->
let
open =
Pretty.a Pretty.space (Pretty.string "[")
close =
Pretty.a (Pretty.string "]") Pretty.space
in
List.map (prettyPatternInner aliases False) (denodeAll listPats)
|> Pretty.join (Pretty.string ", ")
|> Pretty.surround open close
VarPattern var ->
Pretty.string var
NamedPattern qnRef listPats ->
(prettyModuleNameDot aliases qnRef.moduleName
|> Pretty.a (Pretty.string qnRef.name)
)
:: List.map (prettyPatternInner aliases False) (denodeAll listPats)
|> Pretty.words
AsPattern pat name ->
[ prettyPatternInner aliases False (denode pat)
, Pretty.string "as"
, Pretty.string (denode name)
]
|> Pretty.words
ParenthesizedPattern pat ->
prettyPatternInner aliases True (denode pat)
|> Pretty.parens
--== Expressions
type alias Context =
{ precedence : Int
, isTop : Bool
, isLeftPipe : Bool
}
topContext =
{ precedence = 11
, isTop = True
, isLeftPipe = False
}
adjustExpressionParentheses : Context -> Expression -> Expression
adjustExpressionParentheses context expression =
let
addParens expr =
case ( context.isTop, context.isLeftPipe, expr ) of
( False, False, LetExpression _ ) ->
nodify expr |> ParenthesizedExpression
( False, False, CaseExpression _ ) ->
nodify expr |> ParenthesizedExpression
( False, False, LambdaExpression _ ) ->
nodify expr |> ParenthesizedExpression
( False, False, IfBlock _ _ _ ) ->
nodify expr |> ParenthesizedExpression
( _, _, _ ) ->
expr
removeParens expr =
case expr of
ParenthesizedExpression innerExpr ->
if shouldRemove (denode innerExpr) then
denode innerExpr
|> removeParens
else
expr
_ ->
expr
shouldRemove expr =
case ( context.isTop, context.isLeftPipe, expr ) of
( True, _, _ ) ->
True
( _, True, _ ) ->
True
( False, _, Application _ ) ->
if context.precedence < 11 then
True
else
False
( False, _, FunctionOrValue _ _ ) ->
True
( False, _, Integer _ ) ->
True
( False, _, Hex _ ) ->
True
( False, _, Floatable _ ) ->
True
( False, _, Negation _ ) ->
True
( False, _, Literal _ ) ->
True
( False, _, CharLiteral _ ) ->
True
( False, _, TupledExpression _ ) ->
True
( False, _, RecordExpr _ ) ->
True
( False, _, ListExpr _ ) ->
True
( False, _, RecordAccess _ _ ) ->
True
( False, _, RecordAccessFunction _ ) ->
True
( False, _, RecordUpdateExpression _ _ ) ->
True
( _, _, _ ) ->
False
in
removeParens expression
|> addParens
{-| Pretty prints an expression.
-}
prettyExpression : Aliases -> Expression -> Doc t
prettyExpression aliases expression =
prettyExpressionInner aliases topContext 4 expression
|> Tuple.first
prettyExpressionInner : Aliases -> Context -> Int -> Expression -> ( Doc t, Bool )
prettyExpressionInner aliases context indent expression =
case adjustExpressionParentheses context expression of
UnitExpr ->
( Pretty.string "()"
, False
)
Application exprs ->
prettyApplication aliases indent exprs
OperatorApplication symbol dir exprl exprr ->
prettyOperatorApplication aliases indent symbol dir exprl exprr
FunctionOrValue modl val ->
( prettyModuleNameDot aliases modl
|> Pretty.a (Pretty.string val)
, False
)
IfBlock exprBool exprTrue exprFalse ->
prettyIfBlock aliases indent exprBool exprTrue exprFalse
PrefixOperator symbol ->
( Pretty.string symbol |> Pretty.parens
, False
)
Operator symbol ->
( Pretty.string symbol
, False
)
Integer val ->
( Pretty.string (String.fromInt val)
, False
)
Hex val ->
( Pretty.string (toHexString val)
, False
)
Floatable val ->
( Pretty.string (String.fromFloat val)
, False
)
Negation expr ->
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode expr)
in
( Pretty.string "-"
|> Pretty.a prettyExpr
, alwaysBreak
)
Literal val ->
( prettyLiteral val
, False
)
CharLiteral val ->
( Pretty.string (escapeChar val)
|> singleQuotes
, False
)
TupledExpression exprs ->
prettyTupledExpression aliases indent exprs
ParenthesizedExpression expr ->
prettyParenthesizedExpression aliases indent expr
LetExpression letBlock ->
prettyLetBlock aliases indent letBlock
CaseExpression caseBlock ->
prettyCaseBlock aliases indent caseBlock
LambdaExpression lambda ->
prettyLambdaExpression aliases indent lambda
RecordExpr setters ->
prettyRecordExpr aliases setters
ListExpr exprs ->
prettyList aliases indent exprs
RecordAccess expr field ->
prettyRecordAccess aliases expr field
RecordAccessFunction field ->
( Pretty.string field
, False
)
RecordUpdateExpression var setters ->
prettyRecordUpdateExpression aliases indent var setters
GLSLExpression val ->
( Pretty.string "glsl"
, True
)
prettyApplication : Aliases -> Int -> List (Node Expression) -> ( Doc t, Bool )
prettyApplication aliases indent exprs =
let
( prettyExpressions, alwaysBreak ) =
List.map
(prettyExpressionInner aliases
{ precedence = 11
, isTop = False
, isLeftPipe = False
}
4
)
(denodeAll exprs)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.lines
|> Pretty.nest indent
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
isEndLineOperator : String -> Bool
isEndLineOperator op =
case op of
"<|" ->
True
_ ->
False
prettyOperatorApplication : Aliases -> Int -> String -> InfixDirection -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyOperatorApplication aliases indent symbol dir exprl exprr =
if symbol == "<|" then
prettyOperatorApplicationLeft aliases indent symbol dir exprl exprr
else
prettyOperatorApplicationRight aliases indent symbol dir exprl exprr
prettyOperatorApplicationLeft : Aliases -> Int -> String -> InfixDirection -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyOperatorApplicationLeft aliases indent symbol _ exprl exprr =
let
context =
{ precedence = precedence symbol
, isTop = False
, isLeftPipe = True
}
( prettyExpressionLeft, alwaysBreakLeft ) =
prettyExpressionInner aliases context 4 (denode exprl)
( prettyExpressionRight, alwaysBreakRight ) =
prettyExpressionInner aliases context 4 (denode exprr)
alwaysBreak =
alwaysBreakLeft || alwaysBreakRight
in
( [ [ prettyExpressionLeft, Pretty.string symbol ] |> Pretty.words
, prettyExpressionRight
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest 4
, alwaysBreak
)
prettyOperatorApplicationRight : Aliases -> Int -> String -> InfixDirection -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyOperatorApplicationRight aliases indent symbol _ exprl exprr =
let
expandExpr : Int -> Context -> Expression -> List ( Doc t, Bool )
expandExpr innerIndent context expr =
case expr of
OperatorApplication sym _ left right ->
innerOpApply False sym left right
_ ->
[ prettyExpressionInner aliases context innerIndent expr ]
innerOpApply : Bool -> String -> Node Expression -> Node Expression -> List ( Doc t, Bool )
innerOpApply isTop sym left right =
let
context =
{ precedence = precedence sym
, isTop = False
, isLeftPipe = "<|" == sym
}
innerIndent =
decrementIndent 4 (String.length symbol + 1)
leftIndent =
if isTop then
indent
else
innerIndent
rightSide =
denode right |> expandExpr innerIndent context
in
case rightSide of
( hdExpr, hdBreak ) :: tl ->
List.append (denode left |> expandExpr leftIndent context)
(( Pretty.string sym |> Pretty.a Pretty.space |> Pretty.a hdExpr, hdBreak ) :: tl)
[] ->
[]
( prettyExpressions, alwaysBreak ) =
innerOpApply True symbol exprl exprr
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.join (Pretty.nest indent Pretty.line)
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyIfBlock : Aliases -> Int -> Node Expression -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyIfBlock aliases indent exprBool exprTrue exprFalse =
let
innerIfBlock : Node Expression -> Node Expression -> Node Expression -> List (Doc t)
innerIfBlock innerExprBool innerExprTrue innerExprFalse =
let
context =
topContext
ifPart =
let
( prettyBoolExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode innerExprBool)
in
[ [ Pretty.string "if"
, prettyExpressionInner aliases topContext 4 (denode innerExprBool) |> Tuple.first
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest indent
, Pretty.string "then"
]
|> Pretty.lines
|> optionalGroup alwaysBreak
truePart =
prettyExpressionInner aliases topContext 4 (denode innerExprTrue)
|> Tuple.first
|> Pretty.indent indent
elsePart =
Pretty.line
|> Pretty.a (Pretty.string "else")
falsePart =
case denode innerExprFalse of
IfBlock nestedExprBool nestedExprTrue nestedExprFalse ->
innerIfBlock nestedExprBool nestedExprTrue nestedExprFalse
_ ->
[ prettyExpressionInner aliases topContext 4 (denode innerExprFalse)
|> Tuple.first
|> Pretty.indent indent
]
in
case falsePart of
[] ->
[]
[ falseExpr ] ->
[ ifPart
, truePart
, elsePart
, falseExpr
]
hd :: tl ->
List.append
[ ifPart
, truePart
, [ elsePart, hd ] |> Pretty.words
]
tl
prettyExpressions =
innerIfBlock exprBool exprTrue exprFalse
in
( prettyExpressions
|> Pretty.lines
|> Pretty.align
, True
)
prettyLiteral : String -> Doc t
prettyLiteral val =
if String.contains "\n" val then
Pretty.string val
|> tripleQuotes
else
Pretty.string (escape val)
|> quotes
prettyTupledExpression : Aliases -> Int -> List (Node Expression) -> ( Doc t, Bool )
prettyTupledExpression aliases indent exprs =
let
open =
Pretty.a Pretty.space (Pretty.string "(")
close =
Pretty.a (Pretty.string ")") Pretty.line
in
case exprs of
[] ->
( Pretty.string "()", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettyExpressionInner aliases topContext (decrementIndent indent 2)) (denodeAll exprs)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyParenthesizedExpression : Aliases -> Int -> Node Expression -> ( Doc t, Bool )
prettyParenthesizedExpression aliases indent expr =
let
open =
Pretty.string "("
close =
Pretty.a (Pretty.string ")") Pretty.tightline
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext (decrementIndent indent 1) (denode expr)
in
( prettyExpr
|> Pretty.nest 1
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyLetBlock : Aliases -> Int -> LetBlock -> ( Doc t, Bool )
prettyLetBlock aliases indent letBlock =
( [ Pretty.string "let"
, List.map (prettyLetDeclaration aliases indent) (denodeAll letBlock.declarations)
|> doubleLines
|> Pretty.indent indent
, Pretty.string "in"
, prettyExpressionInner aliases topContext 4 (denode letBlock.expression) |> Tuple.first
]
|> Pretty.lines
|> Pretty.align
, True
)
prettyLetDeclaration : Aliases -> Int -> LetDeclaration -> Doc t
prettyLetDeclaration aliases indent letDecl =
case letDecl of
LetFunction fn ->
prettyFun aliases fn
LetDestructuring pattern expr ->
[ prettyPatternInner aliases False (denode pattern)
, Pretty.string "="
]
|> Pretty.words
|> Pretty.a Pretty.line
|> Pretty.a
(prettyExpressionInner aliases topContext 4 (denode expr)
|> Tuple.first
|> Pretty.indent indent
)
prettyCaseBlock : Aliases -> Int -> CaseBlock -> ( Doc t, Bool )
prettyCaseBlock aliases indent caseBlock =
let
casePart =
let
( caseExpression, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode caseBlock.expression)
in
[ [ Pretty.string "case"
, caseExpression
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest indent
, Pretty.string "of"
]
|> Pretty.lines
|> optionalGroup alwaysBreak
prettyCase ( pattern, expr ) =
prettyPattern aliases (denode pattern)
|> Pretty.a (Pretty.string " ->")
|> Pretty.a Pretty.line
|> Pretty.a (prettyExpressionInner aliases topContext 4 (denode expr) |> Tuple.first |> Pretty.indent 4)
|> Pretty.indent indent
patternsPart =
List.map prettyCase caseBlock.cases
|> doubleLines
in
( [ casePart, patternsPart ]
|> Pretty.lines
|> Pretty.align
, True
)
prettyLambdaExpression : Aliases -> Int -> Lambda -> ( Doc t, Bool )
prettyLambdaExpression aliases indent lambda =
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode lambda.expression)
in
( [ Pretty.string "\\"
|> Pretty.a (List.map (prettyPatternInner aliases False) (denodeAll lambda.args) |> Pretty.words)
|> Pretty.a (Pretty.string " ->")
, prettyExpr
]
|> Pretty.lines
|> Pretty.nest indent
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyRecordExpr : Aliases -> List (Node RecordSetter) -> ( Doc t, Bool )
prettyRecordExpr aliases setters =
let
open =
Pretty.a Pretty.space (Pretty.string "{")
close =
Pretty.a (Pretty.string "}")
Pretty.line
in
case setters of
[] ->
( Pretty.string "{}", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettySetter aliases) (denodeAll setters)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettySetter : Aliases -> ( Node String, Node Expression ) -> ( Doc t, Bool )
prettySetter aliases ( fld, val ) =
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode val)
in
( [ [ Pretty.string (denode fld)
, Pretty.string "="
]
|> Pretty.words
, prettyExpr
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest 4
, alwaysBreak
)
prettyList : Aliases -> Int -> List (Node Expression) -> ( Doc t, Bool )
prettyList aliases indent exprs =
let
open =
Pretty.a Pretty.space (Pretty.string "[")
close =
Pretty.a (Pretty.string "]") Pretty.line
in
case exprs of
[] ->
( Pretty.string "[]", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettyExpressionInner aliases topContext (decrementIndent indent 2)) (denodeAll exprs)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyRecordAccess : Aliases -> Node Expression -> Node String -> ( Doc t, Bool )
prettyRecordAccess aliases expr field =
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode expr)
in
( prettyExpr
|> Pretty.a dot
|> Pretty.a (Pretty.string (denode field))
, alwaysBreak
)
prettyRecordUpdateExpression : Aliases -> Int -> Node String -> List (Node RecordSetter) -> ( Doc t, Bool )
prettyRecordUpdateExpression aliases indent var setters =
let
open =
[ Pretty.string "{"
, Pretty.string (denode var)
]
|> Pretty.words
|> Pretty.a Pretty.line
close =
Pretty.a (Pretty.string "}")
Pretty.line
addBarToFirst exprs =
case exprs of
[] ->
[]
hd :: tl ->
Pretty.a hd (Pretty.string "| ") :: tl
in
case setters of
[] ->
( Pretty.string "{}", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettySetter aliases) (denodeAll setters)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( open
|> Pretty.a
(prettyExpressions
|> addBarToFirst
|> Pretty.separators ", "
)
|> Pretty.nest indent
|> Pretty.surround Pretty.empty close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
--== Type Annotations
{-| Pretty prints a type annotation.
-}
prettyTypeAnnotation : Aliases -> TypeAnnotation -> Doc t
prettyTypeAnnotation aliases typeAnn =
case typeAnn of
GenericType val ->
Pretty.string val
Typed fqName anns ->
prettyTyped aliases fqName anns
Unit ->
Pretty.string "()"
Tupled anns ->
prettyTupled aliases anns
Record recordDef ->
prettyRecord aliases (denodeAll recordDef)
GenericRecord paramName recordDef ->
prettyGenericRecord aliases (denode paramName) (denodeAll (denode recordDef))
FunctionTypeAnnotation fromAnn toAnn ->
prettyFunctionTypeAnnotation aliases fromAnn toAnn
prettyTyped : Aliases -> Node ( ModuleName, String ) -> List (Node TypeAnnotation) -> Doc t
prettyTyped aliases fqName anns =
let
( moduleName, typeName ) =
denode fqName
typeDoc =
prettyModuleNameDot aliases moduleName
|> Pretty.a (Pretty.string typeName)
argsDoc =
List.map (prettyTypeAnnotationParens aliases) (denodeAll anns)
|> Pretty.words
in
[ typeDoc
, argsDoc
]
|> Pretty.words
prettyTupled : Aliases -> List (Node TypeAnnotation) -> Doc t
prettyTupled aliases anns =
Pretty.space
|> Pretty.a
(List.map (prettyTypeAnnotation aliases) (denodeAll anns)
|> Pretty.join (Pretty.string ", ")
)
|> Pretty.a Pretty.space
|> Pretty.parens
prettyTypeAnnotationParens : Aliases -> TypeAnnotation -> Doc t
prettyTypeAnnotationParens aliases typeAnn =
if isNakedCompound typeAnn then
prettyTypeAnnotation aliases typeAnn |> Pretty.parens
else
prettyTypeAnnotation aliases typeAnn
prettyRecord : Aliases -> List RecordField -> Doc t
prettyRecord aliases fields =
let
open =
Pretty.a Pretty.space (Pretty.string "{")
close =
Pretty.a (Pretty.string "}") Pretty.line
in
case fields of
[] ->
Pretty.string "{}"
_ ->
fields
|> List.map (Tuple.mapBoth denode denode)
|> List.map (prettyFieldTypeAnn aliases)
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.group
prettyGenericRecord : Aliases -> String -> List RecordField -> Doc t
prettyGenericRecord aliases paramName fields =
let
open =
[ Pretty.string "{"
, Pretty.string paramName
]
|> Pretty.words
|> Pretty.a Pretty.line
close =
Pretty.a (Pretty.string "}")
Pretty.line
addBarToFirst exprs =
case exprs of
[] ->
[]
hd :: tl ->
Pretty.a hd (Pretty.string "| ") :: tl
in
case fields of
[] ->
Pretty.string "{}"
_ ->
open
|> Pretty.a
(fields
|> List.map (Tuple.mapBoth denode denode)
|> List.map (prettyFieldTypeAnn aliases)
|> addBarToFirst
|> Pretty.separators ", "
)
|> Pretty.nest 4
|> Pretty.surround Pretty.empty close
|> Pretty.group
prettyFieldTypeAnn : Aliases -> ( String, TypeAnnotation ) -> Doc t
prettyFieldTypeAnn aliases ( name, ann ) =
[ [ Pretty.string name
, Pretty.string ":"
]
|> Pretty.words
, prettyTypeAnnotation aliases ann
]
|> Pretty.lines
|> Pretty.nest 4
|> Pretty.group
prettyFunctionTypeAnnotation : Aliases -> Node TypeAnnotation -> Node TypeAnnotation -> Doc t
prettyFunctionTypeAnnotation aliases left right =
let
expandLeft : TypeAnnotation -> Doc t
expandLeft ann =
case ann of
FunctionTypeAnnotation _ _ ->
prettyTypeAnnotationParens aliases ann
_ ->
prettyTypeAnnotation aliases ann
expandRight : TypeAnnotation -> List (Doc t)
expandRight ann =
case ann of
FunctionTypeAnnotation innerLeft innerRight ->
innerFnTypeAnn innerLeft innerRight
_ ->
[ prettyTypeAnnotation aliases ann ]
innerFnTypeAnn : Node TypeAnnotation -> Node TypeAnnotation -> List (Doc t)
innerFnTypeAnn innerLeft innerRight =
let
rightSide =
denode innerRight |> expandRight
in
case rightSide of
hd :: tl ->
(denode innerLeft |> expandLeft)
:: ([ Pretty.string "->", hd ] |> Pretty.words)
:: tl
[] ->
[]
in
innerFnTypeAnn left right
|> Pretty.lines
|> Pretty.group
{-| A type annotation is a naked compound if it is made up of multiple parts that
are not enclosed in brackets or braces. This means either a type or type alias with
arguments or a function type; records and tuples are compound but enclosed in brackets
or braces.
Naked type annotations need to be bracketed in situations type argument bindings are
ambiguous otherwise.
-}
isNakedCompound : TypeAnnotation -> Bool
isNakedCompound typeAnn =
case typeAnn of
Typed _ [] ->
False
Typed _ args ->
True
FunctionTypeAnnotation _ _ ->
True
_ ->
False
--== Helpers
prettyMaybe : (a -> Doc t) -> Maybe a -> Doc t
prettyMaybe prettyFn maybeVal =
Maybe.map prettyFn maybeVal
|> Maybe.withDefault Pretty.empty
decrementIndent : Int -> Int -> Int
decrementIndent currentIndent spaces =
let
modded =
modBy 4 (currentIndent - spaces)
in
if modded == 0 then
4
else
modded
dot : Doc t
dot =
Pretty.string "."
quotes : Doc t -> Doc t
quotes doc =
Pretty.surround (Pretty.char '"') (Pretty.char '"') doc
tripleQuotes : Doc t -> Doc t
tripleQuotes doc =
Pretty.surround (Pretty.string "\"\"\"") (Pretty.string "\"\"\"") doc
singleQuotes : Doc t -> Doc t
singleQuotes doc =
Pretty.surround (Pretty.char '\'') (Pretty.char '\'') doc
sqParens : Doc t -> Doc t
sqParens doc =
Pretty.surround (Pretty.string "[") (Pretty.string "]") doc
doubleLines : List (Doc t) -> Doc t
doubleLines =
Pretty.join (Pretty.a Pretty.line Pretty.line)
escape : String -> String
escape val =
val
|> String.replace "\\" "\\\\"
|> String.replace "\"" "\\\""
|> String.replace "\n" "\\n"
|> String.replace "\t" "\\t"
escapeChar : Char -> String
escapeChar val =
case val of
'\\' ->
"\\\\"
'\'' ->
"\\'"
'\t' ->
"\\t"
'\n' ->
"\\n"
c ->
String.fromChar c
optionalGroup : Bool -> Doc t -> Doc t
optionalGroup flag doc =
if flag then
doc
else
Pretty.group doc
optionalParens : Bool -> Doc t -> Doc t
optionalParens flag doc =
if flag then
Pretty.parens doc
else
doc
toHexString : Int -> String
toHexString val =
let
padWithZeros str =
let
length =
String.length str
in
if length < 2 then
String.padLeft 2 '0' str
else if length > 2 && length < 4 then
String.padLeft 4 '0' str
else if length > 4 && length < 8 then
String.padLeft 8 '0' str
else
str
in
"0x" ++ (Hex.toString val |> String.toUpper |> padWithZeros)
{-| Calculate a precedence for any operator to be able to know when
parenthesis are needed or not.
When a lower precedence expression appears beneath a higher one, its needs
parenthesis.
When a higher precedence expression appears beneath a lower one, if should
not have parenthesis.
-}
precedence : String -> Int
precedence symbol =
case symbol of
">>" ->
9
"<<" ->
9
"^" ->
8
"*" ->
7
"/" ->
7
"//" ->
7
"%" ->
7
"rem" ->
7
"+" ->
6
"-" ->
6
"++" ->
5
"::" ->
5
"==" ->
4
"/=" ->
4
"<" ->
4
">" ->
4
"<=" ->
4
">=" ->
4
"&&" ->
3
"||" ->
2
"|>" ->
0
"<|" ->
0
_ ->
0
| true | module Internal.Write exposing
( write
, writeAnnotation
, writeDeclaration
, writeExpression
, writeImports
, writeInference
, writeSignature
)
{-| This is borrowed basically in it's entirety from: <https://github.com/the-sett/elm-syntax-dsl/blob/master/src/Elm/Pretty.elm>
Thank you PI:NAME:<NAME>END_PI!
-}
import Dict
import Elm.Syntax.Declaration
import Elm.Syntax.Documentation exposing (Documentation)
import Elm.Syntax.Exposing exposing (ExposedType, Exposing(..), TopLevelExpose(..))
import Elm.Syntax.Expression exposing (Case, CaseBlock, Expression(..), Function, FunctionImplementation, Lambda, LetBlock, LetDeclaration(..), RecordSetter)
import Elm.Syntax.File
import Elm.Syntax.Import exposing (Import)
import Elm.Syntax.Infix exposing (Infix, InfixDirection(..))
import Elm.Syntax.Module exposing (DefaultModuleData, EffectModuleData, Module(..))
import Elm.Syntax.ModuleName exposing (ModuleName)
import Elm.Syntax.Node as Node exposing (Node(..))
import Elm.Syntax.Pattern exposing (Pattern(..), QualifiedNameRef)
import Elm.Syntax.Range exposing (Location, Range, emptyRange)
import Elm.Syntax.Signature exposing (Signature)
import Elm.Syntax.Type exposing (Type, ValueConstructor)
import Elm.Syntax.TypeAlias exposing (TypeAlias)
import Elm.Syntax.TypeAnnotation exposing (RecordDefinition, RecordField, TypeAnnotation(..))
import Hex
import Internal.Comments as Comments
import Internal.Compiler as Util exposing (denode, denodeAll, denodeMaybe, nodify, nodifyAll, nodifyMaybe)
import Internal.ImportsAndExposing as ImportsAndExposing
import Pretty exposing (Doc)
type alias File =
{ moduleDefinition : Module
, aliases : List ( Util.Module, String )
, imports : List Import
, declarations : List Util.Declaration
, comments : Maybe (Comments.Comment Comments.FileComment)
}
type alias Aliases =
List ( Util.Module, String )
{-| Prepares a file of Elm code for layout by the pretty printer.
Note that the `Doc` type returned by this is a `Pretty.Doc`. This can be printed
to a string by the `the-sett/elm-pretty-printer` package.
These `Doc` based functions are exposed in case you want to pretty print some
Elm inside something else with the pretty printer. The `pretty` function can be
used to go directly from a `File` to a `String`, if that is more convenient.
-}
prepareLayout : Int -> File -> Doc t
prepareLayout width file =
prettyModule file.moduleDefinition
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> (\doc ->
case file.comments of
Nothing ->
doc
Just fileComment ->
let
( fileCommentStr, innerTags ) =
Comments.prettyFileComment width fileComment
in
doc
|> Pretty.a (prettyComments [ fileCommentStr ])
|> Pretty.a Pretty.line
)
|> Pretty.a (importsPretty file.imports)
|> Pretty.a (prettyDeclarations file.aliases file.declarations)
importsPretty : List Import -> Doc t
importsPretty imports =
case imports of
[] ->
Pretty.line
_ ->
prettyImports imports
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
write : File -> String
write =
pretty 80
writeExpression : Expression -> String
writeExpression exp =
prettyExpression noAliases exp
|> Pretty.pretty 80
writeSignature : Signature -> String
writeSignature sig =
prettySignature noAliases sig
|> Pretty.pretty 80
writeAnnotation : TypeAnnotation -> String
writeAnnotation sig =
prettyTypeAnnotation noAliases sig
|> Pretty.pretty 80
writeInference : Util.Inference -> String
writeInference inf =
"--TYPE:\n "
++ (writeAnnotation inf.type_
|> String.lines
|> String.join "\n "
)
++ "\n\n-- INFERRED\n\n "
++ (Dict.toList inf.inferences
|> List.map
(\( key, val ) ->
key
++ ":\n "
++ (writeAnnotation val
|> String.lines
|> String.join "\n "
)
)
|> String.join "\n\n "
)
++ "\n\n----END-----\n\n"
writeImports : List Import -> String
writeImports imports =
prettyImports imports
|> Pretty.pretty 80
writeDeclaration : Util.Declaration -> String
writeDeclaration exp =
prettyDeclaration 80 exp
|> Pretty.pretty 80
{-| Prints a file of Elm code to the given page width, making use of the pretty
printer.
-}
pretty : Int -> File -> String
pretty width file =
prepareLayout width file
|> Pretty.pretty width
prettyModule : Module -> Doc t
prettyModule mod =
case mod of
NormalModule defaultModuleData ->
prettyDefaultModuleData defaultModuleData
PortModule defaultModuleData ->
prettyPortModuleData defaultModuleData
EffectModule effectModuleData ->
prettyEffectModuleData effectModuleData
prettyModuleName : ModuleName -> Doc t
prettyModuleName name =
List.map Pretty.string name
|> Pretty.join dot
prettyModuleNameDot : Aliases -> ModuleName -> Doc t
prettyModuleNameDot aliases name =
case name of
[] ->
Pretty.empty
_ ->
case Util.findAlias name aliases of
Nothing ->
List.map Pretty.string name
|> Pretty.join dot
|> Pretty.a dot
Just alias ->
Pretty.string alias
|> Pretty.a dot
prettyModuleNameAlias : ModuleName -> Doc t
prettyModuleNameAlias name =
case name of
[] ->
Pretty.empty
_ ->
Pretty.string "as "
|> Pretty.a (List.map Pretty.string name |> Pretty.join dot)
prettyDefaultModuleData : DefaultModuleData -> Doc t
prettyDefaultModuleData moduleData =
Pretty.words
[ Pretty.string "module"
, prettyModuleName (denode moduleData.moduleName)
, prettyExposing (denode moduleData.exposingList)
]
prettyPortModuleData : DefaultModuleData -> Doc t
prettyPortModuleData moduleData =
Pretty.words
[ Pretty.string "port module"
, prettyModuleName (denode moduleData.moduleName)
, prettyExposing (denode moduleData.exposingList)
]
prettyEffectModuleData : EffectModuleData -> Doc t
prettyEffectModuleData moduleData =
let
prettyCmdAndSub maybeCmd maybeSub =
case ( maybeCmd, maybeSub ) of
( Nothing, Nothing ) ->
Nothing
( Just cmdName, Just subName ) ->
[ Pretty.string "where { command ="
, Pretty.string cmdName
, Pretty.string ","
, Pretty.string "subscription ="
, Pretty.string subName
, Pretty.string "}"
]
|> Pretty.words
|> Just
( Just cmdName, Nothing ) ->
[ Pretty.string "where { command ="
, Pretty.string cmdName
, Pretty.string "}"
]
|> Pretty.words
|> Just
( Nothing, Just subName ) ->
[ Pretty.string "where { subscription ="
, Pretty.string subName
, Pretty.string "}"
]
|> Pretty.words
|> Just
in
Pretty.words
[ Pretty.string "effect module"
, prettyModuleName (denode moduleData.moduleName)
, prettyCmdAndSub (denodeMaybe moduleData.command) (denodeMaybe moduleData.subscription)
|> prettyMaybe identity
, prettyExposing (denode moduleData.exposingList)
]
prettyComments : List String -> Doc t
prettyComments comments =
case comments of
[] ->
Pretty.empty
_ ->
List.map Pretty.string comments
|> Pretty.lines
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
{-| Pretty prints a list of import statements.
The list will be de-duplicated and sorted.
-}
prettyImports : List Import -> Doc t
prettyImports imports =
ImportsAndExposing.sortAndDedupImports imports
|> List.map prettyImport
|> Pretty.lines
prettyImport : Import -> Doc t
prettyImport import_ =
Pretty.join Pretty.space
[ Pretty.string "import"
, prettyModuleName (denode import_.moduleName)
, prettyMaybe prettyModuleNameAlias (denodeMaybe import_.moduleAlias)
, prettyMaybe prettyExposing (denodeMaybe import_.exposingList)
]
{-| Pretty prints the contents of an exposing statement, as found on a module or import
statement.
The exposed values will be de-duplicated and sorted.
-}
prettyExposing : Exposing -> Doc t
prettyExposing exposing_ =
let
exposings =
case exposing_ of
All _ ->
Pretty.string ".." |> Pretty.parens
Explicit tll ->
ImportsAndExposing.sortAndDedupExposings (denodeAll tll)
|> prettyTopLevelExposes
|> Pretty.parens
in
Pretty.string "exposing"
|> Pretty.a Pretty.space
|> Pretty.a exposings
prettyTopLevelExposes : List TopLevelExpose -> Doc t
prettyTopLevelExposes exposes =
List.map prettyTopLevelExpose exposes
|> Pretty.join (Pretty.string ", ")
prettyTopLevelExpose : TopLevelExpose -> Doc t
prettyTopLevelExpose tlExpose =
case tlExpose of
InfixExpose val ->
Pretty.string val
|> Pretty.parens
FunctionExpose val ->
Pretty.string val
TypeOrAliasExpose val ->
Pretty.string val
TypeExpose exposedType ->
case exposedType.open of
Nothing ->
Pretty.string exposedType.name
Just _ ->
Pretty.string exposedType.name
|> Pretty.a (Pretty.string "(..)")
{-| Pretty prints a single top-level declaration.
-}
prettyDeclaration : Int -> Util.Declaration -> Doc t
prettyDeclaration width decl =
case decl of
Util.Declaration exp mods innerDecl ->
prettyElmSyntaxDeclaration noAliases innerDecl
Util.Comment content ->
Pretty.string content
Util.Block source ->
Pretty.string source
noAliases : Aliases
noAliases =
[]
{-| Pretty prints an elm-syntax declaration.
-}
prettyElmSyntaxDeclaration : Aliases -> Elm.Syntax.Declaration.Declaration -> Doc t
prettyElmSyntaxDeclaration aliases decl =
case decl of
Elm.Syntax.Declaration.FunctionDeclaration fn ->
prettyFun aliases fn
Elm.Syntax.Declaration.AliasDeclaration tAlias ->
prettyTypeAlias aliases tAlias
Elm.Syntax.Declaration.CustomTypeDeclaration type_ ->
prettyCustomType aliases type_
Elm.Syntax.Declaration.PortDeclaration sig ->
prettyPortDeclaration aliases sig
Elm.Syntax.Declaration.InfixDeclaration infix_ ->
prettyInfix infix_
Elm.Syntax.Declaration.Destructuring pattern expr ->
prettyDestructuring aliases (denode pattern) (denode expr)
prettyDeclarations : Aliases -> List Util.Declaration -> Doc t
prettyDeclarations aliases decls =
List.foldl
(\decl doc ->
case decl of
Util.Comment content ->
doc
|> Pretty.a (Pretty.string (content ++ "\n"))
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
Util.Block source ->
doc
|> Pretty.a (Pretty.string source)
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
Util.Declaration _ _ innerDecl ->
doc
|> Pretty.a (prettyElmSyntaxDeclaration aliases innerDecl)
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
|> Pretty.a Pretty.line
)
Pretty.empty
decls
{-| Pretty prints an Elm function, which may include documentation and a signature too.
-}
prettyFun : Aliases -> Function -> Doc t
prettyFun aliases fn =
[ prettyMaybe prettyDocumentation (denodeMaybe fn.documentation)
, prettyMaybe (prettySignature aliases) (denodeMaybe fn.signature)
, prettyFunctionImplementation aliases (denode fn.declaration)
]
|> Pretty.lines
{-| Pretty prints a type alias definition, which may include documentation too.
-}
prettyTypeAlias : Aliases -> TypeAlias -> Doc t
prettyTypeAlias aliases tAlias =
let
typeAliasPretty =
[ Pretty.string "type alias"
, Pretty.string (denode tAlias.name)
, List.map Pretty.string (denodeAll tAlias.generics) |> Pretty.words
, Pretty.string "="
]
|> Pretty.words
|> Pretty.a Pretty.line
|> Pretty.a (prettyTypeAnnotation aliases (denode tAlias.typeAnnotation))
|> Pretty.nest 4
in
[ prettyMaybe prettyDocumentation (denodeMaybe tAlias.documentation)
, typeAliasPretty
]
|> Pretty.lines
{-| Pretty prints a custom type declaration, which may include documentation too.
-}
prettyCustomType : Aliases -> Type -> Doc t
prettyCustomType aliases type_ =
let
customTypePretty =
[ Pretty.string "type"
, Pretty.string (denode type_.name)
, List.map Pretty.string (denodeAll type_.generics) |> Pretty.words
]
|> Pretty.words
|> Pretty.a Pretty.line
|> Pretty.a (Pretty.string "= ")
|> Pretty.a (prettyValueConstructors aliases (denodeAll type_.constructors))
|> Pretty.nest 4
in
[ prettyMaybe prettyDocumentation (denodeMaybe type_.documentation)
, customTypePretty
]
|> Pretty.lines
prettyValueConstructors : Aliases -> List ValueConstructor -> Doc t
prettyValueConstructors aliases constructors =
List.map (prettyValueConstructor aliases) constructors
|> Pretty.join (Pretty.line |> Pretty.a (Pretty.string "| "))
prettyValueConstructor : Aliases -> ValueConstructor -> Doc t
prettyValueConstructor aliases cons =
[ Pretty.string (denode cons.name)
, List.map (prettyTypeAnnotationParens aliases) (denodeAll cons.arguments) |> Pretty.lines
]
|> Pretty.lines
|> Pretty.group
|> Pretty.nest 4
{-| Pretty prints a port declaration.
-}
prettyPortDeclaration : Aliases -> Signature -> Doc t
prettyPortDeclaration aliases sig =
[ Pretty.string "port"
, prettySignature aliases sig
]
|> Pretty.words
prettyInfix : Infix -> Doc t
prettyInfix infix_ =
let
dirToString direction =
case direction of
Left ->
"left"
Right ->
"right"
Non ->
"non"
in
[ Pretty.string "infix"
, Pretty.string (dirToString (denode infix_.direction))
, Pretty.string (String.fromInt (denode infix_.precedence))
, Pretty.string (denode infix_.operator) |> Pretty.parens
, Pretty.string "="
, Pretty.string (denode infix_.function)
]
|> Pretty.words
{-| Pretty prints a desctructuring declaration.
-}
prettyDestructuring : Aliases -> Pattern -> Expression -> Doc t
prettyDestructuring aliases pattern expr =
[ [ prettyPattern aliases pattern
, Pretty.string "="
]
|> Pretty.words
, prettyExpression aliases expr
]
|> Pretty.lines
|> Pretty.nest 4
prettyDocumentation : Documentation -> Doc t
prettyDocumentation docs =
Pretty.string ("{-|" ++ docs ++ "-}")
{-| Pretty prints a type signature.
-}
prettySignature : Aliases -> Signature -> Doc t
prettySignature aliases sig =
[ [ Pretty.string (denode sig.name)
, Pretty.string ":"
]
|> Pretty.words
, prettyTypeAnnotation aliases (denode sig.typeAnnotation)
]
|> Pretty.lines
|> Pretty.nest 4
|> Pretty.group
prettyFunctionImplementation : Aliases -> FunctionImplementation -> Doc t
prettyFunctionImplementation aliases impl =
Pretty.words
[ Pretty.string (denode impl.name)
, prettyArgs aliases (denodeAll impl.arguments)
, Pretty.string "="
]
|> Pretty.a Pretty.line
|> Pretty.a (prettyExpression aliases (denode impl.expression))
|> Pretty.nest 4
prettyArgs : Aliases -> List Pattern -> Doc t
prettyArgs aliases args =
List.map (prettyPatternInner aliases False) args
|> Pretty.words
--== Patterns
{-| Pretty prints a pattern.
-}
prettyPattern : Aliases -> Pattern -> Doc t
prettyPattern aliases pattern =
prettyPatternInner aliases True pattern
adjustPatternParentheses : Bool -> Pattern -> Pattern
adjustPatternParentheses isTop pattern =
let
addParens pat =
case ( isTop, pat ) of
( False, NamedPattern _ (_ :: _) ) ->
nodify pat |> ParenthesizedPattern
( False, AsPattern _ _ ) ->
nodify pat |> ParenthesizedPattern
( _, _ ) ->
pat
removeParens pat =
case pat of
ParenthesizedPattern innerPat ->
if shouldRemove (denode innerPat) then
denode innerPat
|> removeParens
else
pat
_ ->
pat
shouldRemove pat =
case ( isTop, pat ) of
( False, NamedPattern _ _ ) ->
False
( _, AsPattern _ _ ) ->
False
( _, _ ) ->
isTop
in
removeParens pattern
|> addParens
prettyPatternInner : Aliases -> Bool -> Pattern -> Doc t
prettyPatternInner aliases isTop pattern =
case adjustPatternParentheses isTop pattern of
AllPattern ->
Pretty.string "_"
UnitPattern ->
Pretty.string "()"
CharPattern val ->
Pretty.string (escapeChar val)
|> singleQuotes
StringPattern val ->
Pretty.string val
|> quotes
IntPattern val ->
Pretty.string (String.fromInt val)
HexPattern val ->
Pretty.string (Hex.toString val)
FloatPattern val ->
Pretty.string (String.fromFloat val)
TuplePattern vals ->
Pretty.space
|> Pretty.a
(List.map (prettyPatternInner aliases True) (denodeAll vals)
|> Pretty.join (Pretty.string ", ")
)
|> Pretty.a Pretty.space
|> Pretty.parens
RecordPattern fields ->
List.map Pretty.string (denodeAll fields)
|> Pretty.join (Pretty.string ", ")
|> Pretty.surround Pretty.space Pretty.space
|> Pretty.braces
UnConsPattern hdPat tlPat ->
[ prettyPatternInner aliases False (denode hdPat)
, Pretty.string "::"
, prettyPatternInner aliases False (denode tlPat)
]
|> Pretty.words
ListPattern listPats ->
case listPats of
[] ->
Pretty.string "[]"
_ ->
let
open =
Pretty.a Pretty.space (Pretty.string "[")
close =
Pretty.a (Pretty.string "]") Pretty.space
in
List.map (prettyPatternInner aliases False) (denodeAll listPats)
|> Pretty.join (Pretty.string ", ")
|> Pretty.surround open close
VarPattern var ->
Pretty.string var
NamedPattern qnRef listPats ->
(prettyModuleNameDot aliases qnRef.moduleName
|> Pretty.a (Pretty.string qnRef.name)
)
:: List.map (prettyPatternInner aliases False) (denodeAll listPats)
|> Pretty.words
AsPattern pat name ->
[ prettyPatternInner aliases False (denode pat)
, Pretty.string "as"
, Pretty.string (denode name)
]
|> Pretty.words
ParenthesizedPattern pat ->
prettyPatternInner aliases True (denode pat)
|> Pretty.parens
--== Expressions
type alias Context =
{ precedence : Int
, isTop : Bool
, isLeftPipe : Bool
}
topContext =
{ precedence = 11
, isTop = True
, isLeftPipe = False
}
adjustExpressionParentheses : Context -> Expression -> Expression
adjustExpressionParentheses context expression =
let
addParens expr =
case ( context.isTop, context.isLeftPipe, expr ) of
( False, False, LetExpression _ ) ->
nodify expr |> ParenthesizedExpression
( False, False, CaseExpression _ ) ->
nodify expr |> ParenthesizedExpression
( False, False, LambdaExpression _ ) ->
nodify expr |> ParenthesizedExpression
( False, False, IfBlock _ _ _ ) ->
nodify expr |> ParenthesizedExpression
( _, _, _ ) ->
expr
removeParens expr =
case expr of
ParenthesizedExpression innerExpr ->
if shouldRemove (denode innerExpr) then
denode innerExpr
|> removeParens
else
expr
_ ->
expr
shouldRemove expr =
case ( context.isTop, context.isLeftPipe, expr ) of
( True, _, _ ) ->
True
( _, True, _ ) ->
True
( False, _, Application _ ) ->
if context.precedence < 11 then
True
else
False
( False, _, FunctionOrValue _ _ ) ->
True
( False, _, Integer _ ) ->
True
( False, _, Hex _ ) ->
True
( False, _, Floatable _ ) ->
True
( False, _, Negation _ ) ->
True
( False, _, Literal _ ) ->
True
( False, _, CharLiteral _ ) ->
True
( False, _, TupledExpression _ ) ->
True
( False, _, RecordExpr _ ) ->
True
( False, _, ListExpr _ ) ->
True
( False, _, RecordAccess _ _ ) ->
True
( False, _, RecordAccessFunction _ ) ->
True
( False, _, RecordUpdateExpression _ _ ) ->
True
( _, _, _ ) ->
False
in
removeParens expression
|> addParens
{-| Pretty prints an expression.
-}
prettyExpression : Aliases -> Expression -> Doc t
prettyExpression aliases expression =
prettyExpressionInner aliases topContext 4 expression
|> Tuple.first
prettyExpressionInner : Aliases -> Context -> Int -> Expression -> ( Doc t, Bool )
prettyExpressionInner aliases context indent expression =
case adjustExpressionParentheses context expression of
UnitExpr ->
( Pretty.string "()"
, False
)
Application exprs ->
prettyApplication aliases indent exprs
OperatorApplication symbol dir exprl exprr ->
prettyOperatorApplication aliases indent symbol dir exprl exprr
FunctionOrValue modl val ->
( prettyModuleNameDot aliases modl
|> Pretty.a (Pretty.string val)
, False
)
IfBlock exprBool exprTrue exprFalse ->
prettyIfBlock aliases indent exprBool exprTrue exprFalse
PrefixOperator symbol ->
( Pretty.string symbol |> Pretty.parens
, False
)
Operator symbol ->
( Pretty.string symbol
, False
)
Integer val ->
( Pretty.string (String.fromInt val)
, False
)
Hex val ->
( Pretty.string (toHexString val)
, False
)
Floatable val ->
( Pretty.string (String.fromFloat val)
, False
)
Negation expr ->
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode expr)
in
( Pretty.string "-"
|> Pretty.a prettyExpr
, alwaysBreak
)
Literal val ->
( prettyLiteral val
, False
)
CharLiteral val ->
( Pretty.string (escapeChar val)
|> singleQuotes
, False
)
TupledExpression exprs ->
prettyTupledExpression aliases indent exprs
ParenthesizedExpression expr ->
prettyParenthesizedExpression aliases indent expr
LetExpression letBlock ->
prettyLetBlock aliases indent letBlock
CaseExpression caseBlock ->
prettyCaseBlock aliases indent caseBlock
LambdaExpression lambda ->
prettyLambdaExpression aliases indent lambda
RecordExpr setters ->
prettyRecordExpr aliases setters
ListExpr exprs ->
prettyList aliases indent exprs
RecordAccess expr field ->
prettyRecordAccess aliases expr field
RecordAccessFunction field ->
( Pretty.string field
, False
)
RecordUpdateExpression var setters ->
prettyRecordUpdateExpression aliases indent var setters
GLSLExpression val ->
( Pretty.string "glsl"
, True
)
prettyApplication : Aliases -> Int -> List (Node Expression) -> ( Doc t, Bool )
prettyApplication aliases indent exprs =
let
( prettyExpressions, alwaysBreak ) =
List.map
(prettyExpressionInner aliases
{ precedence = 11
, isTop = False
, isLeftPipe = False
}
4
)
(denodeAll exprs)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.lines
|> Pretty.nest indent
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
isEndLineOperator : String -> Bool
isEndLineOperator op =
case op of
"<|" ->
True
_ ->
False
prettyOperatorApplication : Aliases -> Int -> String -> InfixDirection -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyOperatorApplication aliases indent symbol dir exprl exprr =
if symbol == "<|" then
prettyOperatorApplicationLeft aliases indent symbol dir exprl exprr
else
prettyOperatorApplicationRight aliases indent symbol dir exprl exprr
prettyOperatorApplicationLeft : Aliases -> Int -> String -> InfixDirection -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyOperatorApplicationLeft aliases indent symbol _ exprl exprr =
let
context =
{ precedence = precedence symbol
, isTop = False
, isLeftPipe = True
}
( prettyExpressionLeft, alwaysBreakLeft ) =
prettyExpressionInner aliases context 4 (denode exprl)
( prettyExpressionRight, alwaysBreakRight ) =
prettyExpressionInner aliases context 4 (denode exprr)
alwaysBreak =
alwaysBreakLeft || alwaysBreakRight
in
( [ [ prettyExpressionLeft, Pretty.string symbol ] |> Pretty.words
, prettyExpressionRight
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest 4
, alwaysBreak
)
prettyOperatorApplicationRight : Aliases -> Int -> String -> InfixDirection -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyOperatorApplicationRight aliases indent symbol _ exprl exprr =
let
expandExpr : Int -> Context -> Expression -> List ( Doc t, Bool )
expandExpr innerIndent context expr =
case expr of
OperatorApplication sym _ left right ->
innerOpApply False sym left right
_ ->
[ prettyExpressionInner aliases context innerIndent expr ]
innerOpApply : Bool -> String -> Node Expression -> Node Expression -> List ( Doc t, Bool )
innerOpApply isTop sym left right =
let
context =
{ precedence = precedence sym
, isTop = False
, isLeftPipe = "<|" == sym
}
innerIndent =
decrementIndent 4 (String.length symbol + 1)
leftIndent =
if isTop then
indent
else
innerIndent
rightSide =
denode right |> expandExpr innerIndent context
in
case rightSide of
( hdExpr, hdBreak ) :: tl ->
List.append (denode left |> expandExpr leftIndent context)
(( Pretty.string sym |> Pretty.a Pretty.space |> Pretty.a hdExpr, hdBreak ) :: tl)
[] ->
[]
( prettyExpressions, alwaysBreak ) =
innerOpApply True symbol exprl exprr
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.join (Pretty.nest indent Pretty.line)
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyIfBlock : Aliases -> Int -> Node Expression -> Node Expression -> Node Expression -> ( Doc t, Bool )
prettyIfBlock aliases indent exprBool exprTrue exprFalse =
let
innerIfBlock : Node Expression -> Node Expression -> Node Expression -> List (Doc t)
innerIfBlock innerExprBool innerExprTrue innerExprFalse =
let
context =
topContext
ifPart =
let
( prettyBoolExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode innerExprBool)
in
[ [ Pretty.string "if"
, prettyExpressionInner aliases topContext 4 (denode innerExprBool) |> Tuple.first
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest indent
, Pretty.string "then"
]
|> Pretty.lines
|> optionalGroup alwaysBreak
truePart =
prettyExpressionInner aliases topContext 4 (denode innerExprTrue)
|> Tuple.first
|> Pretty.indent indent
elsePart =
Pretty.line
|> Pretty.a (Pretty.string "else")
falsePart =
case denode innerExprFalse of
IfBlock nestedExprBool nestedExprTrue nestedExprFalse ->
innerIfBlock nestedExprBool nestedExprTrue nestedExprFalse
_ ->
[ prettyExpressionInner aliases topContext 4 (denode innerExprFalse)
|> Tuple.first
|> Pretty.indent indent
]
in
case falsePart of
[] ->
[]
[ falseExpr ] ->
[ ifPart
, truePart
, elsePart
, falseExpr
]
hd :: tl ->
List.append
[ ifPart
, truePart
, [ elsePart, hd ] |> Pretty.words
]
tl
prettyExpressions =
innerIfBlock exprBool exprTrue exprFalse
in
( prettyExpressions
|> Pretty.lines
|> Pretty.align
, True
)
prettyLiteral : String -> Doc t
prettyLiteral val =
if String.contains "\n" val then
Pretty.string val
|> tripleQuotes
else
Pretty.string (escape val)
|> quotes
prettyTupledExpression : Aliases -> Int -> List (Node Expression) -> ( Doc t, Bool )
prettyTupledExpression aliases indent exprs =
let
open =
Pretty.a Pretty.space (Pretty.string "(")
close =
Pretty.a (Pretty.string ")") Pretty.line
in
case exprs of
[] ->
( Pretty.string "()", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettyExpressionInner aliases topContext (decrementIndent indent 2)) (denodeAll exprs)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyParenthesizedExpression : Aliases -> Int -> Node Expression -> ( Doc t, Bool )
prettyParenthesizedExpression aliases indent expr =
let
open =
Pretty.string "("
close =
Pretty.a (Pretty.string ")") Pretty.tightline
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext (decrementIndent indent 1) (denode expr)
in
( prettyExpr
|> Pretty.nest 1
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyLetBlock : Aliases -> Int -> LetBlock -> ( Doc t, Bool )
prettyLetBlock aliases indent letBlock =
( [ Pretty.string "let"
, List.map (prettyLetDeclaration aliases indent) (denodeAll letBlock.declarations)
|> doubleLines
|> Pretty.indent indent
, Pretty.string "in"
, prettyExpressionInner aliases topContext 4 (denode letBlock.expression) |> Tuple.first
]
|> Pretty.lines
|> Pretty.align
, True
)
prettyLetDeclaration : Aliases -> Int -> LetDeclaration -> Doc t
prettyLetDeclaration aliases indent letDecl =
case letDecl of
LetFunction fn ->
prettyFun aliases fn
LetDestructuring pattern expr ->
[ prettyPatternInner aliases False (denode pattern)
, Pretty.string "="
]
|> Pretty.words
|> Pretty.a Pretty.line
|> Pretty.a
(prettyExpressionInner aliases topContext 4 (denode expr)
|> Tuple.first
|> Pretty.indent indent
)
prettyCaseBlock : Aliases -> Int -> CaseBlock -> ( Doc t, Bool )
prettyCaseBlock aliases indent caseBlock =
let
casePart =
let
( caseExpression, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode caseBlock.expression)
in
[ [ Pretty.string "case"
, caseExpression
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest indent
, Pretty.string "of"
]
|> Pretty.lines
|> optionalGroup alwaysBreak
prettyCase ( pattern, expr ) =
prettyPattern aliases (denode pattern)
|> Pretty.a (Pretty.string " ->")
|> Pretty.a Pretty.line
|> Pretty.a (prettyExpressionInner aliases topContext 4 (denode expr) |> Tuple.first |> Pretty.indent 4)
|> Pretty.indent indent
patternsPart =
List.map prettyCase caseBlock.cases
|> doubleLines
in
( [ casePart, patternsPart ]
|> Pretty.lines
|> Pretty.align
, True
)
prettyLambdaExpression : Aliases -> Int -> Lambda -> ( Doc t, Bool )
prettyLambdaExpression aliases indent lambda =
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode lambda.expression)
in
( [ Pretty.string "\\"
|> Pretty.a (List.map (prettyPatternInner aliases False) (denodeAll lambda.args) |> Pretty.words)
|> Pretty.a (Pretty.string " ->")
, prettyExpr
]
|> Pretty.lines
|> Pretty.nest indent
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyRecordExpr : Aliases -> List (Node RecordSetter) -> ( Doc t, Bool )
prettyRecordExpr aliases setters =
let
open =
Pretty.a Pretty.space (Pretty.string "{")
close =
Pretty.a (Pretty.string "}")
Pretty.line
in
case setters of
[] ->
( Pretty.string "{}", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettySetter aliases) (denodeAll setters)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettySetter : Aliases -> ( Node String, Node Expression ) -> ( Doc t, Bool )
prettySetter aliases ( fld, val ) =
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode val)
in
( [ [ Pretty.string (denode fld)
, Pretty.string "="
]
|> Pretty.words
, prettyExpr
]
|> Pretty.lines
|> optionalGroup alwaysBreak
|> Pretty.nest 4
, alwaysBreak
)
prettyList : Aliases -> Int -> List (Node Expression) -> ( Doc t, Bool )
prettyList aliases indent exprs =
let
open =
Pretty.a Pretty.space (Pretty.string "[")
close =
Pretty.a (Pretty.string "]") Pretty.line
in
case exprs of
[] ->
( Pretty.string "[]", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettyExpressionInner aliases topContext (decrementIndent indent 2)) (denodeAll exprs)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( prettyExpressions
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
prettyRecordAccess : Aliases -> Node Expression -> Node String -> ( Doc t, Bool )
prettyRecordAccess aliases expr field =
let
( prettyExpr, alwaysBreak ) =
prettyExpressionInner aliases topContext 4 (denode expr)
in
( prettyExpr
|> Pretty.a dot
|> Pretty.a (Pretty.string (denode field))
, alwaysBreak
)
prettyRecordUpdateExpression : Aliases -> Int -> Node String -> List (Node RecordSetter) -> ( Doc t, Bool )
prettyRecordUpdateExpression aliases indent var setters =
let
open =
[ Pretty.string "{"
, Pretty.string (denode var)
]
|> Pretty.words
|> Pretty.a Pretty.line
close =
Pretty.a (Pretty.string "}")
Pretty.line
addBarToFirst exprs =
case exprs of
[] ->
[]
hd :: tl ->
Pretty.a hd (Pretty.string "| ") :: tl
in
case setters of
[] ->
( Pretty.string "{}", False )
_ ->
let
( prettyExpressions, alwaysBreak ) =
List.map (prettySetter aliases) (denodeAll setters)
|> List.unzip
|> Tuple.mapSecond (List.any identity)
in
( open
|> Pretty.a
(prettyExpressions
|> addBarToFirst
|> Pretty.separators ", "
)
|> Pretty.nest indent
|> Pretty.surround Pretty.empty close
|> Pretty.align
|> optionalGroup alwaysBreak
, alwaysBreak
)
--== Type Annotations
{-| Pretty prints a type annotation.
-}
prettyTypeAnnotation : Aliases -> TypeAnnotation -> Doc t
prettyTypeAnnotation aliases typeAnn =
case typeAnn of
GenericType val ->
Pretty.string val
Typed fqName anns ->
prettyTyped aliases fqName anns
Unit ->
Pretty.string "()"
Tupled anns ->
prettyTupled aliases anns
Record recordDef ->
prettyRecord aliases (denodeAll recordDef)
GenericRecord paramName recordDef ->
prettyGenericRecord aliases (denode paramName) (denodeAll (denode recordDef))
FunctionTypeAnnotation fromAnn toAnn ->
prettyFunctionTypeAnnotation aliases fromAnn toAnn
prettyTyped : Aliases -> Node ( ModuleName, String ) -> List (Node TypeAnnotation) -> Doc t
prettyTyped aliases fqName anns =
let
( moduleName, typeName ) =
denode fqName
typeDoc =
prettyModuleNameDot aliases moduleName
|> Pretty.a (Pretty.string typeName)
argsDoc =
List.map (prettyTypeAnnotationParens aliases) (denodeAll anns)
|> Pretty.words
in
[ typeDoc
, argsDoc
]
|> Pretty.words
prettyTupled : Aliases -> List (Node TypeAnnotation) -> Doc t
prettyTupled aliases anns =
Pretty.space
|> Pretty.a
(List.map (prettyTypeAnnotation aliases) (denodeAll anns)
|> Pretty.join (Pretty.string ", ")
)
|> Pretty.a Pretty.space
|> Pretty.parens
prettyTypeAnnotationParens : Aliases -> TypeAnnotation -> Doc t
prettyTypeAnnotationParens aliases typeAnn =
if isNakedCompound typeAnn then
prettyTypeAnnotation aliases typeAnn |> Pretty.parens
else
prettyTypeAnnotation aliases typeAnn
prettyRecord : Aliases -> List RecordField -> Doc t
prettyRecord aliases fields =
let
open =
Pretty.a Pretty.space (Pretty.string "{")
close =
Pretty.a (Pretty.string "}") Pretty.line
in
case fields of
[] ->
Pretty.string "{}"
_ ->
fields
|> List.map (Tuple.mapBoth denode denode)
|> List.map (prettyFieldTypeAnn aliases)
|> Pretty.separators ", "
|> Pretty.surround open close
|> Pretty.group
prettyGenericRecord : Aliases -> String -> List RecordField -> Doc t
prettyGenericRecord aliases paramName fields =
let
open =
[ Pretty.string "{"
, Pretty.string paramName
]
|> Pretty.words
|> Pretty.a Pretty.line
close =
Pretty.a (Pretty.string "}")
Pretty.line
addBarToFirst exprs =
case exprs of
[] ->
[]
hd :: tl ->
Pretty.a hd (Pretty.string "| ") :: tl
in
case fields of
[] ->
Pretty.string "{}"
_ ->
open
|> Pretty.a
(fields
|> List.map (Tuple.mapBoth denode denode)
|> List.map (prettyFieldTypeAnn aliases)
|> addBarToFirst
|> Pretty.separators ", "
)
|> Pretty.nest 4
|> Pretty.surround Pretty.empty close
|> Pretty.group
prettyFieldTypeAnn : Aliases -> ( String, TypeAnnotation ) -> Doc t
prettyFieldTypeAnn aliases ( name, ann ) =
[ [ Pretty.string name
, Pretty.string ":"
]
|> Pretty.words
, prettyTypeAnnotation aliases ann
]
|> Pretty.lines
|> Pretty.nest 4
|> Pretty.group
prettyFunctionTypeAnnotation : Aliases -> Node TypeAnnotation -> Node TypeAnnotation -> Doc t
prettyFunctionTypeAnnotation aliases left right =
let
expandLeft : TypeAnnotation -> Doc t
expandLeft ann =
case ann of
FunctionTypeAnnotation _ _ ->
prettyTypeAnnotationParens aliases ann
_ ->
prettyTypeAnnotation aliases ann
expandRight : TypeAnnotation -> List (Doc t)
expandRight ann =
case ann of
FunctionTypeAnnotation innerLeft innerRight ->
innerFnTypeAnn innerLeft innerRight
_ ->
[ prettyTypeAnnotation aliases ann ]
innerFnTypeAnn : Node TypeAnnotation -> Node TypeAnnotation -> List (Doc t)
innerFnTypeAnn innerLeft innerRight =
let
rightSide =
denode innerRight |> expandRight
in
case rightSide of
hd :: tl ->
(denode innerLeft |> expandLeft)
:: ([ Pretty.string "->", hd ] |> Pretty.words)
:: tl
[] ->
[]
in
innerFnTypeAnn left right
|> Pretty.lines
|> Pretty.group
{-| A type annotation is a naked compound if it is made up of multiple parts that
are not enclosed in brackets or braces. This means either a type or type alias with
arguments or a function type; records and tuples are compound but enclosed in brackets
or braces.
Naked type annotations need to be bracketed in situations type argument bindings are
ambiguous otherwise.
-}
isNakedCompound : TypeAnnotation -> Bool
isNakedCompound typeAnn =
case typeAnn of
Typed _ [] ->
False
Typed _ args ->
True
FunctionTypeAnnotation _ _ ->
True
_ ->
False
--== Helpers
prettyMaybe : (a -> Doc t) -> Maybe a -> Doc t
prettyMaybe prettyFn maybeVal =
Maybe.map prettyFn maybeVal
|> Maybe.withDefault Pretty.empty
decrementIndent : Int -> Int -> Int
decrementIndent currentIndent spaces =
let
modded =
modBy 4 (currentIndent - spaces)
in
if modded == 0 then
4
else
modded
dot : Doc t
dot =
Pretty.string "."
quotes : Doc t -> Doc t
quotes doc =
Pretty.surround (Pretty.char '"') (Pretty.char '"') doc
tripleQuotes : Doc t -> Doc t
tripleQuotes doc =
Pretty.surround (Pretty.string "\"\"\"") (Pretty.string "\"\"\"") doc
singleQuotes : Doc t -> Doc t
singleQuotes doc =
Pretty.surround (Pretty.char '\'') (Pretty.char '\'') doc
sqParens : Doc t -> Doc t
sqParens doc =
Pretty.surround (Pretty.string "[") (Pretty.string "]") doc
doubleLines : List (Doc t) -> Doc t
doubleLines =
Pretty.join (Pretty.a Pretty.line Pretty.line)
escape : String -> String
escape val =
val
|> String.replace "\\" "\\\\"
|> String.replace "\"" "\\\""
|> String.replace "\n" "\\n"
|> String.replace "\t" "\\t"
escapeChar : Char -> String
escapeChar val =
case val of
'\\' ->
"\\\\"
'\'' ->
"\\'"
'\t' ->
"\\t"
'\n' ->
"\\n"
c ->
String.fromChar c
optionalGroup : Bool -> Doc t -> Doc t
optionalGroup flag doc =
if flag then
doc
else
Pretty.group doc
optionalParens : Bool -> Doc t -> Doc t
optionalParens flag doc =
if flag then
Pretty.parens doc
else
doc
toHexString : Int -> String
toHexString val =
let
padWithZeros str =
let
length =
String.length str
in
if length < 2 then
String.padLeft 2 '0' str
else if length > 2 && length < 4 then
String.padLeft 4 '0' str
else if length > 4 && length < 8 then
String.padLeft 8 '0' str
else
str
in
"0x" ++ (Hex.toString val |> String.toUpper |> padWithZeros)
{-| Calculate a precedence for any operator to be able to know when
parenthesis are needed or not.
When a lower precedence expression appears beneath a higher one, its needs
parenthesis.
When a higher precedence expression appears beneath a lower one, if should
not have parenthesis.
-}
precedence : String -> Int
precedence symbol =
case symbol of
">>" ->
9
"<<" ->
9
"^" ->
8
"*" ->
7
"/" ->
7
"//" ->
7
"%" ->
7
"rem" ->
7
"+" ->
6
"-" ->
6
"++" ->
5
"::" ->
5
"==" ->
4
"/=" ->
4
"<" ->
4
">" ->
4
"<=" ->
4
">=" ->
4
"&&" ->
3
"||" ->
2
"|>" ->
0
"<|" ->
0
_ ->
0
| elm |
[
{
"context": "Vertex { id, label } =\n { key = id\n , position = label.position\n ",
"end": 3462,
"score": 0.9933300614,
"start": 3460,
"tag": "KEY",
"value": "id"
}
] | src/Graph/Force.elm | lydell/kite | 446 | module Graph.Force exposing
( Force(..)
, ForceGraph
, State
, alphaTarget
, defaultForceState
, isCompleted
, tick
)
import Graph exposing (Edge, Graph, Node, NodeId)
import Graph.Extra
import Graph.Force.Gravity as Gravity
import Graph.Force.Link as Link
import Graph.Force.ManyBody as ManyBody
import Point2d exposing (Point2d)
import Vector2d exposing (Vector2d)
type State
= State
{ alpha : Float
, minAlpha : Float
, alphaDecay : Float
, alphaTarget : Float
, velocityDecay : Float
}
type Force
= Link
| ManyBody Float
| Gravity
type alias ForceVertex n =
{ n
| position : Point2d
, velocity : Velocity
, manyBodyStrength : Float
, gravityCenter : Point2d
, gravityStrengthX : Float
, gravityStrengthY : Float
, fixed : Bool
}
type alias Velocity =
Vector2d
type alias ForceEdge e =
{ e
| distance : Float
, strength : Float
}
type alias ForceGraph n e =
Graph (ForceVertex n) (ForceEdge e)
defaultForceState : State
defaultForceState =
State
{ alpha = 1.0
, minAlpha = 0.001
, alphaDecay = 1 - 0.001 ^ (1 / 300)
, alphaTarget = 0.0
, velocityDecay = 0.6
}
updateVelocities : List ( NodeId, Velocity ) -> ForceGraph n e -> ForceGraph n e
updateVelocities newVelocities =
let
applyVelocity : Velocity -> ForceVertex n -> ForceVertex n
applyVelocity velocity forceVertex =
{ forceVertex | velocity = velocity }
in
Graph.Extra.updateNodesBy newVelocities applyVelocity
{-| This ONLY UPDATES THE VERTEX VELOCITIES but does not touch the positions.
-}
applyForce : Float -> Force -> ForceGraph n e -> ForceGraph n e
applyForce alpha force forceGraph =
case force of
Link ->
let
getData id =
case forceGraph |> Graph.get id of
Just ctx ->
{ id = id
, degree = forceGraph |> Graph.Extra.degree id
, position = ctx.node.label.position
, velocity = ctx.node.label.velocity
}
_ ->
--Debug.todo "This shouldn't happen!" <|
{ id = 0
, degree = 0
, position = Point2d.origin
, velocity = Vector2d.zero
}
toLinkParam : Edge (ForceEdge e) -> Link.Param
toLinkParam { from, to, label } =
{ source = getData from
, target = getData to
, distance = label.distance
, strength = label.strength
}
newVelocities : List ( NodeId, Velocity )
newVelocities =
forceGraph
|> Graph.edges
|> List.map toLinkParam
|> Link.run alpha
in
forceGraph |> updateVelocities newVelocities
ManyBody theta ->
let
toManyBodyVertex : Node (ForceVertex n) -> ManyBody.Vertex NodeId
toManyBodyVertex { id, label } =
{ key = id
, position = label.position
, velocity = label.velocity
, strength = label.manyBodyStrength
}
newVelocities : List ( NodeId, Velocity )
newVelocities =
forceGraph
|> Graph.nodes
|> List.map toManyBodyVertex
|> ManyBody.run alpha theta
|> List.map (\{ key, velocity } -> ( key, velocity ))
in
forceGraph |> updateVelocities newVelocities
Gravity ->
let
toGravityVertex : Node (ForceVertex n) -> Gravity.Vertex
toGravityVertex { id, label } =
{ id = id
, position = label.position
, velocity = label.velocity
, gravityCenter = label.gravityCenter
, gravityStrengthX = label.gravityStrengthX
, gravityStrengthY = label.gravityStrengthY
}
newVelocities : List ( NodeId, Velocity )
newVelocities =
forceGraph
|> Graph.nodes
|> List.map toGravityVertex
|> Gravity.run alpha
in
forceGraph |> updateVelocities newVelocities
tick : State -> ForceGraph n e -> ( State, ForceGraph n e )
tick (State state) forceGraph =
let
newAlpha =
state.alpha + (state.alphaTarget - state.alpha) * state.alphaDecay
applyVelocity forceVertex =
let
sV =
forceVertex.velocity |> Vector2d.scaleBy state.velocityDecay
in
if forceVertex.fixed then
{ forceVertex
| velocity = Vector2d.zero
}
else
{ forceVertex
| position = forceVertex.position |> Point2d.translateBy sV
, velocity = sV
}
in
( State { state | alpha = newAlpha }
, [ Link, ManyBody 0.9, Gravity ]
|> List.foldl (applyForce newAlpha) forceGraph
|> Graph.mapNodes applyVelocity
)
alphaTarget : Float -> State -> State
alphaTarget aT (State config) =
State { config | alphaTarget = aT }
isCompleted : State -> Bool
isCompleted (State { alpha, minAlpha }) =
alpha <= minAlpha
{- You can set this to control how quickly the simulation should converge. The default value is 300 iterations.
Lower number of iterations will produce a layout quicker, but risk getting stuck in a local minimum. Higher values take
longer, but typically produce better results.
-}
-- iterations : Int -> State -> State
-- iterations iters (State config) =
-- State { config | alphaDecay = 1 - config.minAlpha ^ (1 / toFloat iters) }
| 46286 | module Graph.Force exposing
( Force(..)
, ForceGraph
, State
, alphaTarget
, defaultForceState
, isCompleted
, tick
)
import Graph exposing (Edge, Graph, Node, NodeId)
import Graph.Extra
import Graph.Force.Gravity as Gravity
import Graph.Force.Link as Link
import Graph.Force.ManyBody as ManyBody
import Point2d exposing (Point2d)
import Vector2d exposing (Vector2d)
type State
= State
{ alpha : Float
, minAlpha : Float
, alphaDecay : Float
, alphaTarget : Float
, velocityDecay : Float
}
type Force
= Link
| ManyBody Float
| Gravity
type alias ForceVertex n =
{ n
| position : Point2d
, velocity : Velocity
, manyBodyStrength : Float
, gravityCenter : Point2d
, gravityStrengthX : Float
, gravityStrengthY : Float
, fixed : Bool
}
type alias Velocity =
Vector2d
type alias ForceEdge e =
{ e
| distance : Float
, strength : Float
}
type alias ForceGraph n e =
Graph (ForceVertex n) (ForceEdge e)
defaultForceState : State
defaultForceState =
State
{ alpha = 1.0
, minAlpha = 0.001
, alphaDecay = 1 - 0.001 ^ (1 / 300)
, alphaTarget = 0.0
, velocityDecay = 0.6
}
updateVelocities : List ( NodeId, Velocity ) -> ForceGraph n e -> ForceGraph n e
updateVelocities newVelocities =
let
applyVelocity : Velocity -> ForceVertex n -> ForceVertex n
applyVelocity velocity forceVertex =
{ forceVertex | velocity = velocity }
in
Graph.Extra.updateNodesBy newVelocities applyVelocity
{-| This ONLY UPDATES THE VERTEX VELOCITIES but does not touch the positions.
-}
applyForce : Float -> Force -> ForceGraph n e -> ForceGraph n e
applyForce alpha force forceGraph =
case force of
Link ->
let
getData id =
case forceGraph |> Graph.get id of
Just ctx ->
{ id = id
, degree = forceGraph |> Graph.Extra.degree id
, position = ctx.node.label.position
, velocity = ctx.node.label.velocity
}
_ ->
--Debug.todo "This shouldn't happen!" <|
{ id = 0
, degree = 0
, position = Point2d.origin
, velocity = Vector2d.zero
}
toLinkParam : Edge (ForceEdge e) -> Link.Param
toLinkParam { from, to, label } =
{ source = getData from
, target = getData to
, distance = label.distance
, strength = label.strength
}
newVelocities : List ( NodeId, Velocity )
newVelocities =
forceGraph
|> Graph.edges
|> List.map toLinkParam
|> Link.run alpha
in
forceGraph |> updateVelocities newVelocities
ManyBody theta ->
let
toManyBodyVertex : Node (ForceVertex n) -> ManyBody.Vertex NodeId
toManyBodyVertex { id, label } =
{ key = <KEY>
, position = label.position
, velocity = label.velocity
, strength = label.manyBodyStrength
}
newVelocities : List ( NodeId, Velocity )
newVelocities =
forceGraph
|> Graph.nodes
|> List.map toManyBodyVertex
|> ManyBody.run alpha theta
|> List.map (\{ key, velocity } -> ( key, velocity ))
in
forceGraph |> updateVelocities newVelocities
Gravity ->
let
toGravityVertex : Node (ForceVertex n) -> Gravity.Vertex
toGravityVertex { id, label } =
{ id = id
, position = label.position
, velocity = label.velocity
, gravityCenter = label.gravityCenter
, gravityStrengthX = label.gravityStrengthX
, gravityStrengthY = label.gravityStrengthY
}
newVelocities : List ( NodeId, Velocity )
newVelocities =
forceGraph
|> Graph.nodes
|> List.map toGravityVertex
|> Gravity.run alpha
in
forceGraph |> updateVelocities newVelocities
tick : State -> ForceGraph n e -> ( State, ForceGraph n e )
tick (State state) forceGraph =
let
newAlpha =
state.alpha + (state.alphaTarget - state.alpha) * state.alphaDecay
applyVelocity forceVertex =
let
sV =
forceVertex.velocity |> Vector2d.scaleBy state.velocityDecay
in
if forceVertex.fixed then
{ forceVertex
| velocity = Vector2d.zero
}
else
{ forceVertex
| position = forceVertex.position |> Point2d.translateBy sV
, velocity = sV
}
in
( State { state | alpha = newAlpha }
, [ Link, ManyBody 0.9, Gravity ]
|> List.foldl (applyForce newAlpha) forceGraph
|> Graph.mapNodes applyVelocity
)
alphaTarget : Float -> State -> State
alphaTarget aT (State config) =
State { config | alphaTarget = aT }
isCompleted : State -> Bool
isCompleted (State { alpha, minAlpha }) =
alpha <= minAlpha
{- You can set this to control how quickly the simulation should converge. The default value is 300 iterations.
Lower number of iterations will produce a layout quicker, but risk getting stuck in a local minimum. Higher values take
longer, but typically produce better results.
-}
-- iterations : Int -> State -> State
-- iterations iters (State config) =
-- State { config | alphaDecay = 1 - config.minAlpha ^ (1 / toFloat iters) }
| true | module Graph.Force exposing
( Force(..)
, ForceGraph
, State
, alphaTarget
, defaultForceState
, isCompleted
, tick
)
import Graph exposing (Edge, Graph, Node, NodeId)
import Graph.Extra
import Graph.Force.Gravity as Gravity
import Graph.Force.Link as Link
import Graph.Force.ManyBody as ManyBody
import Point2d exposing (Point2d)
import Vector2d exposing (Vector2d)
type State
= State
{ alpha : Float
, minAlpha : Float
, alphaDecay : Float
, alphaTarget : Float
, velocityDecay : Float
}
type Force
= Link
| ManyBody Float
| Gravity
type alias ForceVertex n =
{ n
| position : Point2d
, velocity : Velocity
, manyBodyStrength : Float
, gravityCenter : Point2d
, gravityStrengthX : Float
, gravityStrengthY : Float
, fixed : Bool
}
type alias Velocity =
Vector2d
type alias ForceEdge e =
{ e
| distance : Float
, strength : Float
}
type alias ForceGraph n e =
Graph (ForceVertex n) (ForceEdge e)
defaultForceState : State
defaultForceState =
State
{ alpha = 1.0
, minAlpha = 0.001
, alphaDecay = 1 - 0.001 ^ (1 / 300)
, alphaTarget = 0.0
, velocityDecay = 0.6
}
updateVelocities : List ( NodeId, Velocity ) -> ForceGraph n e -> ForceGraph n e
updateVelocities newVelocities =
let
applyVelocity : Velocity -> ForceVertex n -> ForceVertex n
applyVelocity velocity forceVertex =
{ forceVertex | velocity = velocity }
in
Graph.Extra.updateNodesBy newVelocities applyVelocity
{-| This ONLY UPDATES THE VERTEX VELOCITIES but does not touch the positions.
-}
applyForce : Float -> Force -> ForceGraph n e -> ForceGraph n e
applyForce alpha force forceGraph =
case force of
Link ->
let
getData id =
case forceGraph |> Graph.get id of
Just ctx ->
{ id = id
, degree = forceGraph |> Graph.Extra.degree id
, position = ctx.node.label.position
, velocity = ctx.node.label.velocity
}
_ ->
--Debug.todo "This shouldn't happen!" <|
{ id = 0
, degree = 0
, position = Point2d.origin
, velocity = Vector2d.zero
}
toLinkParam : Edge (ForceEdge e) -> Link.Param
toLinkParam { from, to, label } =
{ source = getData from
, target = getData to
, distance = label.distance
, strength = label.strength
}
newVelocities : List ( NodeId, Velocity )
newVelocities =
forceGraph
|> Graph.edges
|> List.map toLinkParam
|> Link.run alpha
in
forceGraph |> updateVelocities newVelocities
ManyBody theta ->
let
toManyBodyVertex : Node (ForceVertex n) -> ManyBody.Vertex NodeId
toManyBodyVertex { id, label } =
{ key = PI:KEY:<KEY>END_PI
, position = label.position
, velocity = label.velocity
, strength = label.manyBodyStrength
}
newVelocities : List ( NodeId, Velocity )
newVelocities =
forceGraph
|> Graph.nodes
|> List.map toManyBodyVertex
|> ManyBody.run alpha theta
|> List.map (\{ key, velocity } -> ( key, velocity ))
in
forceGraph |> updateVelocities newVelocities
Gravity ->
let
toGravityVertex : Node (ForceVertex n) -> Gravity.Vertex
toGravityVertex { id, label } =
{ id = id
, position = label.position
, velocity = label.velocity
, gravityCenter = label.gravityCenter
, gravityStrengthX = label.gravityStrengthX
, gravityStrengthY = label.gravityStrengthY
}
newVelocities : List ( NodeId, Velocity )
newVelocities =
forceGraph
|> Graph.nodes
|> List.map toGravityVertex
|> Gravity.run alpha
in
forceGraph |> updateVelocities newVelocities
tick : State -> ForceGraph n e -> ( State, ForceGraph n e )
tick (State state) forceGraph =
let
newAlpha =
state.alpha + (state.alphaTarget - state.alpha) * state.alphaDecay
applyVelocity forceVertex =
let
sV =
forceVertex.velocity |> Vector2d.scaleBy state.velocityDecay
in
if forceVertex.fixed then
{ forceVertex
| velocity = Vector2d.zero
}
else
{ forceVertex
| position = forceVertex.position |> Point2d.translateBy sV
, velocity = sV
}
in
( State { state | alpha = newAlpha }
, [ Link, ManyBody 0.9, Gravity ]
|> List.foldl (applyForce newAlpha) forceGraph
|> Graph.mapNodes applyVelocity
)
alphaTarget : Float -> State -> State
alphaTarget aT (State config) =
State { config | alphaTarget = aT }
isCompleted : State -> Bool
isCompleted (State { alpha, minAlpha }) =
alpha <= minAlpha
{- You can set this to control how quickly the simulation should converge. The default value is 300 iterations.
Lower number of iterations will produce a layout quicker, but risk getting stuck in a local minimum. Higher values take
longer, but typically produce better results.
-}
-- iterations : Int -> State -> State
-- iterations iters (State config) =
-- State { config | alphaDecay = 1 - config.minAlpha ^ (1 / toFloat iters) }
| elm |
[
{
"context": "cks\r\n@docs getTimezoneOffset\r\n\r\nCopyright (c) 2016 Robin Luiten\r\n-}\r\n\r\nimport Date exposing (Date, Month (..))\r\n\r",
"end": 187,
"score": 0.9997745752,
"start": 175,
"tag": "NAME",
"value": "Robin Luiten"
}
] | src/Date/Create.elm | altworx/elm-date-extra | 0 | module Date.Create
( makeDateTicks
, getTimezoneOffset
) where
{-| Create dates and offsets.
@docs makeDateTicks
@docs getTimezoneOffset
Copyright (c) 2016 Robin Luiten
-}
import Date exposing (Date, Month (..))
import Date.Core as Core
{-| Return raw epoch ticks since Unix epoch for given date.
Result can be positive or negative.
Unix epoch. Thursday, 1 January 1970 at 00:00:00.000 in UTC is 0 ticks.
This can be fed to Date.fromTime to create a time, but be careful this
function does nothing about time zone offsets so you may not get you
would expect.
TODO ? not sure should pass in Date as source of the parameters, it is
missleading as to whats doing the work this way I think. It also means
the date offset has an impact...
-}
makeDateTicks : Date -> Int
makeDateTicks date =
let
year = Date.year date
in
if year < 1970 then
makeDateTicksNegative date
else
makeDateTicksPositive date
makeDateTicksPositive date =
let
year = Date.year date
month = Date.month date
day = Date.day date
restTicks
= (Date.millisecond date) * Core.ticksAMillisecond
+ (Date.second date) * Core.ticksASecond
+ (Date.minute date) * Core.ticksAMinute
+ (Date.hour date) * Core.ticksAnHour
+ (day - 1) * Core.ticksADay -- day of month is 1 based
yearTicks = getYearTicksFrom1970 year
monthTicks = getMonthTicksSinceStartOfYear year month
in
yearTicks + monthTicks + restTicks
{- Return the ticks for start of year since unix epoch (1970). -}
getYearTicksFrom1970 year =
iterateSum ((+)1) yearToTicks year 1970 0
yearToTicks year =
(Core.yearToDayLength year) * Core.ticksADay
{- Return days in year upto start of given year and month. -}
getMonthTicksSinceStartOfYear : Int -> Month -> Int
getMonthTicksSinceStartOfYear year month =
iterateSum Core.nextMonth (monthToTicks year) month Jan 0
{- Return ticks in a given year month. -}
monthToTicks : Int -> Month -> Int
monthToTicks year month =
(Core.daysInMonth year month) * Core.ticksADay
makeDateTicksNegative date =
let
year = Date.year date
month = Date.month date
yearTicks = getYearTicksTo1970 year
monthTicks = getMonthTicksToEndYear year month
daysToEndOfMonth = (Core.daysInMonth year month) - (Date.day date)
dayTicks = daysToEndOfMonth * Core.ticksADay
hoursToEndOfDay = 24 - (Date.hour date) - 1
hourTicks = hoursToEndOfDay * Core.ticksAnHour
minutesToEndOfHour = 60 - (Date.minute date) - 1
minuteTicks = minutesToEndOfHour * Core.ticksAMinute
secondsToEndOfMinute = 60 - (Date.second date) - 1
secondTicks = secondsToEndOfMinute * Core.ticksASecond
millisecondsToEndOfSecond = 1000 - (Date.millisecond date)
millisecondTicks = millisecondsToEndOfSecond * Core.ticksAMillisecond
-- _ = Debug.log("makeDateTicksNegative element counts")
-- ( year, month
-- , (Date.day date, daysToEndOfMonth)
-- , (Date.hour date, hoursToEndOfDay)
-- , (Date.minute date, minutesToEndOfHour)
-- , (Date.second date, secondsToEndOfMinute)
-- , (Date.millisecond date, millisecondsToEndOfSecond)
-- )
-- _ = Debug.log("makeDateTicksNegative ticks")
-- ( (yearTicks, yearTicks // Core.ticksADay)
-- , (monthTicks, monthTicks // Core.ticksADay), dayTicks
-- , hourTicks, minuteTicks, secondTicks, millisecondTicks)
in
negate (yearTicks + monthTicks + dayTicks
+ hourTicks + minuteTicks + secondTicks + millisecondTicks)
{- Return days to end of year, end of Dec.
This does not include days in the starting month given.
-}
getMonthTicksToEndYear year month =
iterateSum
Core.nextMonth (monthToTicks year) Jan
(Core.nextMonth month) 0
{- Return the ticks for start of year up to unix epoch (1970).
Note if our date is in a given year we start counting full years after it.
-}
getYearTicksTo1970 year =
iterateSum ((+)1) yearToTicks 1970 (year + 1) 0
{-| A general iterate for sum accumulator.
-}
iterateSum : (a -> a) -> (a -> number) -> a -> a -> number -> number
iterateSum getNext getValue target current accumulator =
if current == target then
accumulator
else
iterateSum getNext getValue target
(getNext current) (accumulator + (getValue current))
{-| Return the time zone offset of current javascript environment underneath
Elm in Minutes. This should produce the same result getTimezoneOffset()
for a given date in the same javascript VM.
Time zone offset is always for a given date and time so an input date is required.
Given that timezones change (though slowly) this is not strictly pure, but
I suspect it is sufficiently pure. Is is dependent on the timezone mechanics
of the javascript VM.
### Example zone stuff.
For an offset of -600 minutes, in +10:00 time zone offset.
In javascript date parsing of "1970-01-01T00:00:00Z" produces a
javascript localised date.
Converting this date to a string in javascript
* toISOString() produces "1970-01-01T00:00:00.000Z"
* toLocalString() produces "01/01/1970, 10:00:00"
The 10 in hours field due to the +10:00 offset.
Thats how the time zone offset can be figured out, by creating the date
using makeDateTicks
The offset is picked up in Elm using makeDateTicks which creates a
UTC date in ticks from the fields pulled from the date we want to
compare with.
-}
getTimezoneOffset : Date -> Int
getTimezoneOffset date =
let
date =
{-
DO NOT USE `DateUtils.fromString` or `DateUtils.usafeFromString` here.
It will cause unbounded recursion and give interesting javascript
console errors about functions not existing.
-}
case (Date.fromString Core.epochDateStr) of
Ok aDate -> aDate
Err _ -> Debug.crash("Failed to parse unix epoch date something is very wrong.")
dateTicks = Core.toTime date
newTicks = makeDateTicks date
timezoneOffset = (dateTicks - newTicks) // Core.ticksAMinute
-- _ = Debug.log("Date.Create getTimezoneOffset") (timezoneOffset)
in
timezoneOffset
| 5510 | module Date.Create
( makeDateTicks
, getTimezoneOffset
) where
{-| Create dates and offsets.
@docs makeDateTicks
@docs getTimezoneOffset
Copyright (c) 2016 <NAME>
-}
import Date exposing (Date, Month (..))
import Date.Core as Core
{-| Return raw epoch ticks since Unix epoch for given date.
Result can be positive or negative.
Unix epoch. Thursday, 1 January 1970 at 00:00:00.000 in UTC is 0 ticks.
This can be fed to Date.fromTime to create a time, but be careful this
function does nothing about time zone offsets so you may not get you
would expect.
TODO ? not sure should pass in Date as source of the parameters, it is
missleading as to whats doing the work this way I think. It also means
the date offset has an impact...
-}
makeDateTicks : Date -> Int
makeDateTicks date =
let
year = Date.year date
in
if year < 1970 then
makeDateTicksNegative date
else
makeDateTicksPositive date
makeDateTicksPositive date =
let
year = Date.year date
month = Date.month date
day = Date.day date
restTicks
= (Date.millisecond date) * Core.ticksAMillisecond
+ (Date.second date) * Core.ticksASecond
+ (Date.minute date) * Core.ticksAMinute
+ (Date.hour date) * Core.ticksAnHour
+ (day - 1) * Core.ticksADay -- day of month is 1 based
yearTicks = getYearTicksFrom1970 year
monthTicks = getMonthTicksSinceStartOfYear year month
in
yearTicks + monthTicks + restTicks
{- Return the ticks for start of year since unix epoch (1970). -}
getYearTicksFrom1970 year =
iterateSum ((+)1) yearToTicks year 1970 0
yearToTicks year =
(Core.yearToDayLength year) * Core.ticksADay
{- Return days in year upto start of given year and month. -}
getMonthTicksSinceStartOfYear : Int -> Month -> Int
getMonthTicksSinceStartOfYear year month =
iterateSum Core.nextMonth (monthToTicks year) month Jan 0
{- Return ticks in a given year month. -}
monthToTicks : Int -> Month -> Int
monthToTicks year month =
(Core.daysInMonth year month) * Core.ticksADay
makeDateTicksNegative date =
let
year = Date.year date
month = Date.month date
yearTicks = getYearTicksTo1970 year
monthTicks = getMonthTicksToEndYear year month
daysToEndOfMonth = (Core.daysInMonth year month) - (Date.day date)
dayTicks = daysToEndOfMonth * Core.ticksADay
hoursToEndOfDay = 24 - (Date.hour date) - 1
hourTicks = hoursToEndOfDay * Core.ticksAnHour
minutesToEndOfHour = 60 - (Date.minute date) - 1
minuteTicks = minutesToEndOfHour * Core.ticksAMinute
secondsToEndOfMinute = 60 - (Date.second date) - 1
secondTicks = secondsToEndOfMinute * Core.ticksASecond
millisecondsToEndOfSecond = 1000 - (Date.millisecond date)
millisecondTicks = millisecondsToEndOfSecond * Core.ticksAMillisecond
-- _ = Debug.log("makeDateTicksNegative element counts")
-- ( year, month
-- , (Date.day date, daysToEndOfMonth)
-- , (Date.hour date, hoursToEndOfDay)
-- , (Date.minute date, minutesToEndOfHour)
-- , (Date.second date, secondsToEndOfMinute)
-- , (Date.millisecond date, millisecondsToEndOfSecond)
-- )
-- _ = Debug.log("makeDateTicksNegative ticks")
-- ( (yearTicks, yearTicks // Core.ticksADay)
-- , (monthTicks, monthTicks // Core.ticksADay), dayTicks
-- , hourTicks, minuteTicks, secondTicks, millisecondTicks)
in
negate (yearTicks + monthTicks + dayTicks
+ hourTicks + minuteTicks + secondTicks + millisecondTicks)
{- Return days to end of year, end of Dec.
This does not include days in the starting month given.
-}
getMonthTicksToEndYear year month =
iterateSum
Core.nextMonth (monthToTicks year) Jan
(Core.nextMonth month) 0
{- Return the ticks for start of year up to unix epoch (1970).
Note if our date is in a given year we start counting full years after it.
-}
getYearTicksTo1970 year =
iterateSum ((+)1) yearToTicks 1970 (year + 1) 0
{-| A general iterate for sum accumulator.
-}
iterateSum : (a -> a) -> (a -> number) -> a -> a -> number -> number
iterateSum getNext getValue target current accumulator =
if current == target then
accumulator
else
iterateSum getNext getValue target
(getNext current) (accumulator + (getValue current))
{-| Return the time zone offset of current javascript environment underneath
Elm in Minutes. This should produce the same result getTimezoneOffset()
for a given date in the same javascript VM.
Time zone offset is always for a given date and time so an input date is required.
Given that timezones change (though slowly) this is not strictly pure, but
I suspect it is sufficiently pure. Is is dependent on the timezone mechanics
of the javascript VM.
### Example zone stuff.
For an offset of -600 minutes, in +10:00 time zone offset.
In javascript date parsing of "1970-01-01T00:00:00Z" produces a
javascript localised date.
Converting this date to a string in javascript
* toISOString() produces "1970-01-01T00:00:00.000Z"
* toLocalString() produces "01/01/1970, 10:00:00"
The 10 in hours field due to the +10:00 offset.
Thats how the time zone offset can be figured out, by creating the date
using makeDateTicks
The offset is picked up in Elm using makeDateTicks which creates a
UTC date in ticks from the fields pulled from the date we want to
compare with.
-}
getTimezoneOffset : Date -> Int
getTimezoneOffset date =
let
date =
{-
DO NOT USE `DateUtils.fromString` or `DateUtils.usafeFromString` here.
It will cause unbounded recursion and give interesting javascript
console errors about functions not existing.
-}
case (Date.fromString Core.epochDateStr) of
Ok aDate -> aDate
Err _ -> Debug.crash("Failed to parse unix epoch date something is very wrong.")
dateTicks = Core.toTime date
newTicks = makeDateTicks date
timezoneOffset = (dateTicks - newTicks) // Core.ticksAMinute
-- _ = Debug.log("Date.Create getTimezoneOffset") (timezoneOffset)
in
timezoneOffset
| true | module Date.Create
( makeDateTicks
, getTimezoneOffset
) where
{-| Create dates and offsets.
@docs makeDateTicks
@docs getTimezoneOffset
Copyright (c) 2016 PI:NAME:<NAME>END_PI
-}
import Date exposing (Date, Month (..))
import Date.Core as Core
{-| Return raw epoch ticks since Unix epoch for given date.
Result can be positive or negative.
Unix epoch. Thursday, 1 January 1970 at 00:00:00.000 in UTC is 0 ticks.
This can be fed to Date.fromTime to create a time, but be careful this
function does nothing about time zone offsets so you may not get you
would expect.
TODO ? not sure should pass in Date as source of the parameters, it is
missleading as to whats doing the work this way I think. It also means
the date offset has an impact...
-}
makeDateTicks : Date -> Int
makeDateTicks date =
let
year = Date.year date
in
if year < 1970 then
makeDateTicksNegative date
else
makeDateTicksPositive date
makeDateTicksPositive date =
let
year = Date.year date
month = Date.month date
day = Date.day date
restTicks
= (Date.millisecond date) * Core.ticksAMillisecond
+ (Date.second date) * Core.ticksASecond
+ (Date.minute date) * Core.ticksAMinute
+ (Date.hour date) * Core.ticksAnHour
+ (day - 1) * Core.ticksADay -- day of month is 1 based
yearTicks = getYearTicksFrom1970 year
monthTicks = getMonthTicksSinceStartOfYear year month
in
yearTicks + monthTicks + restTicks
{- Return the ticks for start of year since unix epoch (1970). -}
getYearTicksFrom1970 year =
iterateSum ((+)1) yearToTicks year 1970 0
yearToTicks year =
(Core.yearToDayLength year) * Core.ticksADay
{- Return days in year upto start of given year and month. -}
getMonthTicksSinceStartOfYear : Int -> Month -> Int
getMonthTicksSinceStartOfYear year month =
iterateSum Core.nextMonth (monthToTicks year) month Jan 0
{- Return ticks in a given year month. -}
monthToTicks : Int -> Month -> Int
monthToTicks year month =
(Core.daysInMonth year month) * Core.ticksADay
makeDateTicksNegative date =
let
year = Date.year date
month = Date.month date
yearTicks = getYearTicksTo1970 year
monthTicks = getMonthTicksToEndYear year month
daysToEndOfMonth = (Core.daysInMonth year month) - (Date.day date)
dayTicks = daysToEndOfMonth * Core.ticksADay
hoursToEndOfDay = 24 - (Date.hour date) - 1
hourTicks = hoursToEndOfDay * Core.ticksAnHour
minutesToEndOfHour = 60 - (Date.minute date) - 1
minuteTicks = minutesToEndOfHour * Core.ticksAMinute
secondsToEndOfMinute = 60 - (Date.second date) - 1
secondTicks = secondsToEndOfMinute * Core.ticksASecond
millisecondsToEndOfSecond = 1000 - (Date.millisecond date)
millisecondTicks = millisecondsToEndOfSecond * Core.ticksAMillisecond
-- _ = Debug.log("makeDateTicksNegative element counts")
-- ( year, month
-- , (Date.day date, daysToEndOfMonth)
-- , (Date.hour date, hoursToEndOfDay)
-- , (Date.minute date, minutesToEndOfHour)
-- , (Date.second date, secondsToEndOfMinute)
-- , (Date.millisecond date, millisecondsToEndOfSecond)
-- )
-- _ = Debug.log("makeDateTicksNegative ticks")
-- ( (yearTicks, yearTicks // Core.ticksADay)
-- , (monthTicks, monthTicks // Core.ticksADay), dayTicks
-- , hourTicks, minuteTicks, secondTicks, millisecondTicks)
in
negate (yearTicks + monthTicks + dayTicks
+ hourTicks + minuteTicks + secondTicks + millisecondTicks)
{- Return days to end of year, end of Dec.
This does not include days in the starting month given.
-}
getMonthTicksToEndYear year month =
iterateSum
Core.nextMonth (monthToTicks year) Jan
(Core.nextMonth month) 0
{- Return the ticks for start of year up to unix epoch (1970).
Note if our date is in a given year we start counting full years after it.
-}
getYearTicksTo1970 year =
iterateSum ((+)1) yearToTicks 1970 (year + 1) 0
{-| A general iterate for sum accumulator.
-}
iterateSum : (a -> a) -> (a -> number) -> a -> a -> number -> number
iterateSum getNext getValue target current accumulator =
if current == target then
accumulator
else
iterateSum getNext getValue target
(getNext current) (accumulator + (getValue current))
{-| Return the time zone offset of current javascript environment underneath
Elm in Minutes. This should produce the same result getTimezoneOffset()
for a given date in the same javascript VM.
Time zone offset is always for a given date and time so an input date is required.
Given that timezones change (though slowly) this is not strictly pure, but
I suspect it is sufficiently pure. Is is dependent on the timezone mechanics
of the javascript VM.
### Example zone stuff.
For an offset of -600 minutes, in +10:00 time zone offset.
In javascript date parsing of "1970-01-01T00:00:00Z" produces a
javascript localised date.
Converting this date to a string in javascript
* toISOString() produces "1970-01-01T00:00:00.000Z"
* toLocalString() produces "01/01/1970, 10:00:00"
The 10 in hours field due to the +10:00 offset.
Thats how the time zone offset can be figured out, by creating the date
using makeDateTicks
The offset is picked up in Elm using makeDateTicks which creates a
UTC date in ticks from the fields pulled from the date we want to
compare with.
-}
getTimezoneOffset : Date -> Int
getTimezoneOffset date =
let
date =
{-
DO NOT USE `DateUtils.fromString` or `DateUtils.usafeFromString` here.
It will cause unbounded recursion and give interesting javascript
console errors about functions not existing.
-}
case (Date.fromString Core.epochDateStr) of
Ok aDate -> aDate
Err _ -> Debug.crash("Failed to parse unix epoch date something is very wrong.")
dateTicks = Core.toTime date
newTicks = makeDateTicks date
timezoneOffset = (dateTicks - newTicks) // Core.ticksAMinute
-- _ = Debug.log("Date.Create getTimezoneOffset") (timezoneOffset)
in
timezoneOffset
| elm |
[
{
"context": "he version of the OpenAPI document: v1\n Contact: support@coinapi.io\n\n NOTE: This file is auto generated by the open",
"end": 343,
"score": 0.9999232292,
"start": 325,
"tag": "EMAIL",
"value": "support@coinapi.io"
},
{
"context": "d by the openapi-generator.\n https://github.com/openapitools/openapi-generator.git\n Do not edit this file ma",
"end": 442,
"score": 0.9995568395,
"start": 430,
"tag": "USERNAME",
"value": "openapitools"
}
] | oeml-sdk/elm/src/Data/OrderNewSingleRequest.elm | oskaralfons/coinapi-sdk | 1 | {-
OEML - REST API
This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a>
The version of the OpenAPI document: v1
Contact: support@coinapi.io
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.OrderNewSingleRequest exposing (OrderNewSingleRequest, ExecInst(..), decoder, encode, encodeWithTag, toString)
import Data.OrdSide as OrdSide exposing (OrdSide)
import Data.OrdType as OrdType exposing (OrdType)
import Data.TimeInForce as TimeInForce exposing (TimeInForce)
import DateOnly exposing (DateOnly)
import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (optional, required)
import Json.Encode as Encode
{-| The new order message.
-}
type alias OrderNewSingleRequest =
{ exchangeId : String
, clientOrderId : String
, symbolIdExchange : Maybe (String)
, symbolIdCoinapi : Maybe (String)
, amountOrder : Float
, price : Float
, side : OrdSide
, orderType : OrdType
, timeInForce : TimeInForce
, expireTime : Maybe (DateOnly)
, execInst : Maybe ((List ExecInst))
}
type ExecInst
= MAKERORCANCEL
| AUCTIONONLY
| INDICATIONOFINTEREST
decoder : Decoder OrderNewSingleRequest
decoder =
Decode.succeed OrderNewSingleRequest
|> required "exchange_id" Decode.string
|> required "client_order_id" Decode.string
|> optional "symbol_id_exchange" (Decode.nullable Decode.string) Nothing
|> optional "symbol_id_coinapi" (Decode.nullable Decode.string) Nothing
|> required "amount_order" Decode.float
|> required "price" Decode.float
|> required "side" OrdSide.decoder
|> required "order_type" OrdType.decoder
|> required "time_in_force" TimeInForce.decoder
|> optional "expire_time" (Decode.nullable DateOnly.decoder) Nothing
|> optional "exec_inst" (Decode.nullable (Decode.list execInstDecoder)) Nothing
encode : OrderNewSingleRequest -> Encode.Value
encode =
Encode.object << encodePairs
encodeWithTag : ( String, String ) -> OrderNewSingleRequest -> Encode.Value
encodeWithTag (tagField, tag) model =
Encode.object <| encodePairs model ++ [ ( tagField, Encode.string tag ) ]
encodePairs : OrderNewSingleRequest -> List (String, Encode.Value)
encodePairs model =
[ ( "exchange_id", Encode.string model.exchangeId )
, ( "client_order_id", Encode.string model.clientOrderId )
, ( "symbol_id_exchange", Maybe.withDefault Encode.null (Maybe.map Encode.string model.symbolIdExchange) )
, ( "symbol_id_coinapi", Maybe.withDefault Encode.null (Maybe.map Encode.string model.symbolIdCoinapi) )
, ( "amount_order", Encode.float model.amountOrder )
, ( "price", Encode.float model.price )
, ( "side", OrdSide.encode model.side )
, ( "order_type", OrdType.encode model.orderType )
, ( "time_in_force", TimeInForce.encode model.timeInForce )
, ( "expire_time", Maybe.withDefault Encode.null (Maybe.map DateOnly.encode model.expireTime) )
, ( "exec_inst", Maybe.withDefault Encode.null (Maybe.map (Encode.list encodeExecInst) model.execInst) )
]
toString : OrderNewSingleRequest -> String
toString =
Encode.encode 0 << encode
execInstDecoder : Decoder ExecInst
execInstDecoder =
Decode.string
|> Decode.andThen
(\str ->
case str of
"MAKER_OR_CANCEL" ->
Decode.succeed MAKERORCANCEL
"AUCTION_ONLY" ->
Decode.succeed AUCTIONONLY
"INDICATION_OF_INTEREST" ->
Decode.succeed INDICATIONOFINTEREST
other ->
Decode.fail <| "Unknown type: " ++ other
)
encodeExecInst : ExecInst -> Encode.Value
encodeExecInst model =
case model of
MAKERORCANCEL ->
Encode.string "MAKER_OR_CANCEL"
AUCTIONONLY ->
Encode.string "AUCTION_ONLY"
INDICATIONOFINTEREST ->
Encode.string "INDICATION_OF_INTEREST"
| 29498 | {-
OEML - REST API
This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a>
The version of the OpenAPI document: v1
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.OrderNewSingleRequest exposing (OrderNewSingleRequest, ExecInst(..), decoder, encode, encodeWithTag, toString)
import Data.OrdSide as OrdSide exposing (OrdSide)
import Data.OrdType as OrdType exposing (OrdType)
import Data.TimeInForce as TimeInForce exposing (TimeInForce)
import DateOnly exposing (DateOnly)
import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (optional, required)
import Json.Encode as Encode
{-| The new order message.
-}
type alias OrderNewSingleRequest =
{ exchangeId : String
, clientOrderId : String
, symbolIdExchange : Maybe (String)
, symbolIdCoinapi : Maybe (String)
, amountOrder : Float
, price : Float
, side : OrdSide
, orderType : OrdType
, timeInForce : TimeInForce
, expireTime : Maybe (DateOnly)
, execInst : Maybe ((List ExecInst))
}
type ExecInst
= MAKERORCANCEL
| AUCTIONONLY
| INDICATIONOFINTEREST
decoder : Decoder OrderNewSingleRequest
decoder =
Decode.succeed OrderNewSingleRequest
|> required "exchange_id" Decode.string
|> required "client_order_id" Decode.string
|> optional "symbol_id_exchange" (Decode.nullable Decode.string) Nothing
|> optional "symbol_id_coinapi" (Decode.nullable Decode.string) Nothing
|> required "amount_order" Decode.float
|> required "price" Decode.float
|> required "side" OrdSide.decoder
|> required "order_type" OrdType.decoder
|> required "time_in_force" TimeInForce.decoder
|> optional "expire_time" (Decode.nullable DateOnly.decoder) Nothing
|> optional "exec_inst" (Decode.nullable (Decode.list execInstDecoder)) Nothing
encode : OrderNewSingleRequest -> Encode.Value
encode =
Encode.object << encodePairs
encodeWithTag : ( String, String ) -> OrderNewSingleRequest -> Encode.Value
encodeWithTag (tagField, tag) model =
Encode.object <| encodePairs model ++ [ ( tagField, Encode.string tag ) ]
encodePairs : OrderNewSingleRequest -> List (String, Encode.Value)
encodePairs model =
[ ( "exchange_id", Encode.string model.exchangeId )
, ( "client_order_id", Encode.string model.clientOrderId )
, ( "symbol_id_exchange", Maybe.withDefault Encode.null (Maybe.map Encode.string model.symbolIdExchange) )
, ( "symbol_id_coinapi", Maybe.withDefault Encode.null (Maybe.map Encode.string model.symbolIdCoinapi) )
, ( "amount_order", Encode.float model.amountOrder )
, ( "price", Encode.float model.price )
, ( "side", OrdSide.encode model.side )
, ( "order_type", OrdType.encode model.orderType )
, ( "time_in_force", TimeInForce.encode model.timeInForce )
, ( "expire_time", Maybe.withDefault Encode.null (Maybe.map DateOnly.encode model.expireTime) )
, ( "exec_inst", Maybe.withDefault Encode.null (Maybe.map (Encode.list encodeExecInst) model.execInst) )
]
toString : OrderNewSingleRequest -> String
toString =
Encode.encode 0 << encode
execInstDecoder : Decoder ExecInst
execInstDecoder =
Decode.string
|> Decode.andThen
(\str ->
case str of
"MAKER_OR_CANCEL" ->
Decode.succeed MAKERORCANCEL
"AUCTION_ONLY" ->
Decode.succeed AUCTIONONLY
"INDICATION_OF_INTEREST" ->
Decode.succeed INDICATIONOFINTEREST
other ->
Decode.fail <| "Unknown type: " ++ other
)
encodeExecInst : ExecInst -> Encode.Value
encodeExecInst model =
case model of
MAKERORCANCEL ->
Encode.string "MAKER_OR_CANCEL"
AUCTIONONLY ->
Encode.string "AUCTION_ONLY"
INDICATIONOFINTEREST ->
Encode.string "INDICATION_OF_INTEREST"
| true | {-
OEML - REST API
This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a>
The version of the OpenAPI document: v1
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.OrderNewSingleRequest exposing (OrderNewSingleRequest, ExecInst(..), decoder, encode, encodeWithTag, toString)
import Data.OrdSide as OrdSide exposing (OrdSide)
import Data.OrdType as OrdType exposing (OrdType)
import Data.TimeInForce as TimeInForce exposing (TimeInForce)
import DateOnly exposing (DateOnly)
import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (optional, required)
import Json.Encode as Encode
{-| The new order message.
-}
type alias OrderNewSingleRequest =
{ exchangeId : String
, clientOrderId : String
, symbolIdExchange : Maybe (String)
, symbolIdCoinapi : Maybe (String)
, amountOrder : Float
, price : Float
, side : OrdSide
, orderType : OrdType
, timeInForce : TimeInForce
, expireTime : Maybe (DateOnly)
, execInst : Maybe ((List ExecInst))
}
type ExecInst
= MAKERORCANCEL
| AUCTIONONLY
| INDICATIONOFINTEREST
decoder : Decoder OrderNewSingleRequest
decoder =
Decode.succeed OrderNewSingleRequest
|> required "exchange_id" Decode.string
|> required "client_order_id" Decode.string
|> optional "symbol_id_exchange" (Decode.nullable Decode.string) Nothing
|> optional "symbol_id_coinapi" (Decode.nullable Decode.string) Nothing
|> required "amount_order" Decode.float
|> required "price" Decode.float
|> required "side" OrdSide.decoder
|> required "order_type" OrdType.decoder
|> required "time_in_force" TimeInForce.decoder
|> optional "expire_time" (Decode.nullable DateOnly.decoder) Nothing
|> optional "exec_inst" (Decode.nullable (Decode.list execInstDecoder)) Nothing
encode : OrderNewSingleRequest -> Encode.Value
encode =
Encode.object << encodePairs
encodeWithTag : ( String, String ) -> OrderNewSingleRequest -> Encode.Value
encodeWithTag (tagField, tag) model =
Encode.object <| encodePairs model ++ [ ( tagField, Encode.string tag ) ]
encodePairs : OrderNewSingleRequest -> List (String, Encode.Value)
encodePairs model =
[ ( "exchange_id", Encode.string model.exchangeId )
, ( "client_order_id", Encode.string model.clientOrderId )
, ( "symbol_id_exchange", Maybe.withDefault Encode.null (Maybe.map Encode.string model.symbolIdExchange) )
, ( "symbol_id_coinapi", Maybe.withDefault Encode.null (Maybe.map Encode.string model.symbolIdCoinapi) )
, ( "amount_order", Encode.float model.amountOrder )
, ( "price", Encode.float model.price )
, ( "side", OrdSide.encode model.side )
, ( "order_type", OrdType.encode model.orderType )
, ( "time_in_force", TimeInForce.encode model.timeInForce )
, ( "expire_time", Maybe.withDefault Encode.null (Maybe.map DateOnly.encode model.expireTime) )
, ( "exec_inst", Maybe.withDefault Encode.null (Maybe.map (Encode.list encodeExecInst) model.execInst) )
]
toString : OrderNewSingleRequest -> String
toString =
Encode.encode 0 << encode
execInstDecoder : Decoder ExecInst
execInstDecoder =
Decode.string
|> Decode.andThen
(\str ->
case str of
"MAKER_OR_CANCEL" ->
Decode.succeed MAKERORCANCEL
"AUCTION_ONLY" ->
Decode.succeed AUCTIONONLY
"INDICATION_OF_INTEREST" ->
Decode.succeed INDICATIONOFINTEREST
other ->
Decode.fail <| "Unknown type: " ++ other
)
encodeExecInst : ExecInst -> Encode.Value
encodeExecInst model =
case model of
MAKERORCANCEL ->
Encode.string "MAKER_OR_CANCEL"
AUCTIONONLY ->
Encode.string "AUCTION_ONLY"
INDICATIONOFINTEREST ->
Encode.string "INDICATION_OF_INTEREST"
| elm |
[
{
"context": "t user.name ] ]\n , Table.td [] [ text \"Monkey\" ]\n , Table.td [] [ text \"monkey@examp",
"end": 5845,
"score": 0.818338871,
"start": 5839,
"tag": "NAME",
"value": "Monkey"
},
{
"context": "text \"Monkey\" ]\n , Table.td [] [ text \"monkey@example.com\" ]\n , Table.td [] [ text \"3h 28m\" ]\n ",
"end": 5901,
"score": 0.9999219775,
"start": 5883,
"tag": "EMAIL",
"value": "monkey@example.com"
}
] | elm/src/View/Users.elm | knewter/time-tracker | 382 | module View.Users exposing (view, header)
import Model exposing (UsersModel)
import Types exposing (User, UserSortableField(..), Sorted(..), UsersListView(..), Paginated)
import Msg exposing (Msg(..), UserMsg(..))
import Route exposing (Location(..))
import Html exposing (Html, text, div, a, img, span, h3, ul, li)
import Html.Attributes exposing (href, src, style, colspan, class)
import Html.Events exposing (onClick)
import Material.List as List
import Material.Button as Button
import Material.Icon as Icon
import Material.Table as Table
import Material.Card as Card
import Material.Elevation as Elevation
import Material.Color as Color
import Material.Options as Options
import Material.Layout as Layout
import Material.Textfield as Textfield
import Material
import Material.Grid exposing (grid, size, cell, Device(..))
import View.Helpers as Helpers
import View.Pieces.PaginatedTable as PaginatedTable
import Util exposing (onEnter)
import RemoteData exposing (RemoteData(..))
view : Material.Model -> UsersModel -> Html Msg
view mdl usersModel =
let
body =
case usersModel.usersListView of
UsersTable ->
usersTable mdl usersModel
UsersCards ->
usersCards usersModel
in
div [] [ body ]
usersCards : UsersModel -> Html Msg
usersCards usersModel =
case usersModel.users.current of
NotAsked ->
text "Initialising..."
Loading ->
text "Loading..."
Failure err ->
text <| "There was a problem fetching the users: " ++ toString err
Success paginatedUsers ->
grid [] <|
List.map
(\user -> cell [ size All 3 ] [ userCard user ])
paginatedUsers.items
userCard : User -> Html Msg
userCard user =
let
userPhotoUrl =
"https://api.adorable.io/avatars/400/" ++ user.name ++ ".png"
in
Card.view
[ Options.css "width" "100%"
, Options.css "cursor" "pointer"
, Options.attribute <| onClick <| NavigateTo <| Maybe.map ShowUser user.id
, Elevation.e2
]
[ Card.title
[ Options.css "background" ("url('" ++ userPhotoUrl ++ "') center / cover")
, Options.css "min-height" "250px"
, Options.css "padding" "0"
]
[]
, Card.text []
[ h3 [] [ text user.name ]
, text "Software Zealot"
]
]
renderTable : Material.Model -> Maybe ( Sorted, UserSortableField ) -> String -> Paginated User -> Html Msg
renderTable mdl sort searchQuery paginatedUsers =
Table.table
[ Options.css "width" "100%"
, Elevation.e2
]
[ Table.thead []
[ Table.th [] []
, Table.th
(thOptions UserName sort)
[ text "Name" ]
, Table.th [] [ text "Position" ]
, Table.th [] [ text "Email" ]
, Table.th [] [ text "Today" ]
, Table.th [] [ text "Last 7 days" ]
, Table.th [] [ text "Projects" ]
, Table.th [] [ text "Open Tasks" ]
, Table.th []
[ Textfield.render Mdl
[ 0, 4 ]
mdl
[ Textfield.label "Search"
, Textfield.floatingLabel
, Textfield.text'
, Textfield.value searchQuery
, Textfield.onInput <| UserMsg' << SetUserSearchQuery
, onEnter <| UserMsg' <| FetchUsers <| "/users?q=" ++ searchQuery
]
]
]
, Table.tbody []
(List.indexedMap (viewUserRow mdl) paginatedUsers.items)
, Table.tfoot []
[ Html.td [ colspan 999, class "mdl-data-table__cell--non-numeric" ]
[ PaginatedTable.paginationData [ 0, 3 ] (UserMsg' << FetchUsers) mdl paginatedUsers ]
]
]
usersTable : Material.Model -> UsersModel -> Html Msg
usersTable mdl usersModel =
case usersModel.users.current of
NotAsked ->
text "Initialising..."
Loading ->
case usersModel.users.previous of
Nothing ->
text "Loading..."
Just previousUsers ->
div [ class "loading" ]
[ renderTable mdl usersModel.usersSort usersModel.userSearchQuery previousUsers
]
Failure err ->
case usersModel.users.previous of
Nothing ->
text <| "There was a problem fetching the users: " ++ toString err
Just previousUsers ->
div []
[ text <| "There was a problem fetching the users: " ++ toString err
, renderTable mdl usersModel.usersSort usersModel.userSearchQuery previousUsers
]
Success paginatedUsers ->
renderTable mdl usersModel.usersSort usersModel.userSearchQuery paginatedUsers
viewUserRow : Material.Model -> Int -> User -> Html Msg
viewUserRow mdl index user =
let
attributes =
case user.id of
Nothing ->
[]
Just id ->
[ href (Route.urlFor (ShowUser id)) ]
in
Table.tr []
[ Table.td []
[ img
[ src ("https://api.adorable.io/avatars/30/" ++ user.name ++ ".png"), style [ ( "border-radius", "50%" ) ] ]
[]
]
, Table.td [] [ a attributes [ text user.name ] ]
, Table.td [] [ text "Monkey" ]
, Table.td [] [ text "monkey@example.com" ]
, Table.td [] [ text "3h 28m" ]
, Table.td [] [ text "57h 12m" ]
, Table.td [] [ text "20" ]
, Table.td [] [ text "8" ]
, Table.td []
[ editButton mdl index user
, deleteButton mdl index user
]
]
addUserButton : Material.Model -> Html Msg
addUserButton mdl =
Button.render Mdl
[ 0, 0 ]
mdl
[ Options.css "position" "fixed"
, Options.css "display" "block"
, Options.css "right" "0"
, Options.css "top" "0"
, Options.css "margin-right" "35px"
, Options.css "margin-top" "35px"
, Options.css "z-index" "900"
, Button.fab
, Button.colored
, Button.ripple
, Button.onClick <| NavigateTo <| Just NewUser
]
[ Icon.i "add" ]
deleteButton : Material.Model -> Int -> User -> Html Msg
deleteButton mdl index user =
Button.render Mdl
[ 0, 1, index ]
mdl
[ Button.minifab
, Button.colored
, Button.ripple
, Button.onClick <| UserMsg' <| DeleteUser user
]
[ Icon.i "delete" ]
editButton : Material.Model -> Int -> User -> Html Msg
editButton mdl index user =
case user.id of
Nothing ->
text ""
Just id ->
Button.render Mdl
[ 0, 2, index ]
mdl
[ Button.minifab
, Button.colored
, Button.ripple
, Button.onClick <| NavigateTo <| Just <| EditUser id
]
[ Icon.i "edit" ]
header : Material.Model -> UsersListView -> List (Html Msg)
header mdl usersListView =
Helpers.defaultHeaderWithNavigation
"Users"
[ switchViewButton usersListView mdl
, addUserButton mdl
]
switchViewButton : UsersListView -> Material.Model -> Html Msg
switchViewButton listView mdl =
let
( msg, icon ) =
case listView of
UsersTable ->
( SwitchUsersListView UsersCards, "insert_photo" )
UsersCards ->
( SwitchUsersListView UsersTable, "list" )
in
Button.render Mdl
[ 0, 3 ]
mdl
[ Button.icon
, Button.ripple
, Button.onClick <| UserMsg' msg
, Options.css "margin-right" "6rem"
]
[ Icon.i icon ]
thOptions : UserSortableField -> Maybe ( Sorted, UserSortableField ) -> List (Options.Property (Util.MaterialTableHeader Msg) Msg)
thOptions sortableField usersSort =
[ Table.onClick <| UserMsg' <| ReorderUsers sortableField
, Options.css "cursor" "pointer"
]
++ case usersSort of
Nothing ->
[]
Just ( sorted, sortedField ) ->
case sortedField == sortableField of
True ->
case sorted of
Ascending ->
[ Table.sorted Table.Ascending ]
Descending ->
[ Table.sorted Table.Descending ]
False ->
[]
| 41541 | module View.Users exposing (view, header)
import Model exposing (UsersModel)
import Types exposing (User, UserSortableField(..), Sorted(..), UsersListView(..), Paginated)
import Msg exposing (Msg(..), UserMsg(..))
import Route exposing (Location(..))
import Html exposing (Html, text, div, a, img, span, h3, ul, li)
import Html.Attributes exposing (href, src, style, colspan, class)
import Html.Events exposing (onClick)
import Material.List as List
import Material.Button as Button
import Material.Icon as Icon
import Material.Table as Table
import Material.Card as Card
import Material.Elevation as Elevation
import Material.Color as Color
import Material.Options as Options
import Material.Layout as Layout
import Material.Textfield as Textfield
import Material
import Material.Grid exposing (grid, size, cell, Device(..))
import View.Helpers as Helpers
import View.Pieces.PaginatedTable as PaginatedTable
import Util exposing (onEnter)
import RemoteData exposing (RemoteData(..))
view : Material.Model -> UsersModel -> Html Msg
view mdl usersModel =
let
body =
case usersModel.usersListView of
UsersTable ->
usersTable mdl usersModel
UsersCards ->
usersCards usersModel
in
div [] [ body ]
usersCards : UsersModel -> Html Msg
usersCards usersModel =
case usersModel.users.current of
NotAsked ->
text "Initialising..."
Loading ->
text "Loading..."
Failure err ->
text <| "There was a problem fetching the users: " ++ toString err
Success paginatedUsers ->
grid [] <|
List.map
(\user -> cell [ size All 3 ] [ userCard user ])
paginatedUsers.items
userCard : User -> Html Msg
userCard user =
let
userPhotoUrl =
"https://api.adorable.io/avatars/400/" ++ user.name ++ ".png"
in
Card.view
[ Options.css "width" "100%"
, Options.css "cursor" "pointer"
, Options.attribute <| onClick <| NavigateTo <| Maybe.map ShowUser user.id
, Elevation.e2
]
[ Card.title
[ Options.css "background" ("url('" ++ userPhotoUrl ++ "') center / cover")
, Options.css "min-height" "250px"
, Options.css "padding" "0"
]
[]
, Card.text []
[ h3 [] [ text user.name ]
, text "Software Zealot"
]
]
renderTable : Material.Model -> Maybe ( Sorted, UserSortableField ) -> String -> Paginated User -> Html Msg
renderTable mdl sort searchQuery paginatedUsers =
Table.table
[ Options.css "width" "100%"
, Elevation.e2
]
[ Table.thead []
[ Table.th [] []
, Table.th
(thOptions UserName sort)
[ text "Name" ]
, Table.th [] [ text "Position" ]
, Table.th [] [ text "Email" ]
, Table.th [] [ text "Today" ]
, Table.th [] [ text "Last 7 days" ]
, Table.th [] [ text "Projects" ]
, Table.th [] [ text "Open Tasks" ]
, Table.th []
[ Textfield.render Mdl
[ 0, 4 ]
mdl
[ Textfield.label "Search"
, Textfield.floatingLabel
, Textfield.text'
, Textfield.value searchQuery
, Textfield.onInput <| UserMsg' << SetUserSearchQuery
, onEnter <| UserMsg' <| FetchUsers <| "/users?q=" ++ searchQuery
]
]
]
, Table.tbody []
(List.indexedMap (viewUserRow mdl) paginatedUsers.items)
, Table.tfoot []
[ Html.td [ colspan 999, class "mdl-data-table__cell--non-numeric" ]
[ PaginatedTable.paginationData [ 0, 3 ] (UserMsg' << FetchUsers) mdl paginatedUsers ]
]
]
usersTable : Material.Model -> UsersModel -> Html Msg
usersTable mdl usersModel =
case usersModel.users.current of
NotAsked ->
text "Initialising..."
Loading ->
case usersModel.users.previous of
Nothing ->
text "Loading..."
Just previousUsers ->
div [ class "loading" ]
[ renderTable mdl usersModel.usersSort usersModel.userSearchQuery previousUsers
]
Failure err ->
case usersModel.users.previous of
Nothing ->
text <| "There was a problem fetching the users: " ++ toString err
Just previousUsers ->
div []
[ text <| "There was a problem fetching the users: " ++ toString err
, renderTable mdl usersModel.usersSort usersModel.userSearchQuery previousUsers
]
Success paginatedUsers ->
renderTable mdl usersModel.usersSort usersModel.userSearchQuery paginatedUsers
viewUserRow : Material.Model -> Int -> User -> Html Msg
viewUserRow mdl index user =
let
attributes =
case user.id of
Nothing ->
[]
Just id ->
[ href (Route.urlFor (ShowUser id)) ]
in
Table.tr []
[ Table.td []
[ img
[ src ("https://api.adorable.io/avatars/30/" ++ user.name ++ ".png"), style [ ( "border-radius", "50%" ) ] ]
[]
]
, Table.td [] [ a attributes [ text user.name ] ]
, Table.td [] [ text "<NAME>" ]
, Table.td [] [ text "<EMAIL>" ]
, Table.td [] [ text "3h 28m" ]
, Table.td [] [ text "57h 12m" ]
, Table.td [] [ text "20" ]
, Table.td [] [ text "8" ]
, Table.td []
[ editButton mdl index user
, deleteButton mdl index user
]
]
addUserButton : Material.Model -> Html Msg
addUserButton mdl =
Button.render Mdl
[ 0, 0 ]
mdl
[ Options.css "position" "fixed"
, Options.css "display" "block"
, Options.css "right" "0"
, Options.css "top" "0"
, Options.css "margin-right" "35px"
, Options.css "margin-top" "35px"
, Options.css "z-index" "900"
, Button.fab
, Button.colored
, Button.ripple
, Button.onClick <| NavigateTo <| Just NewUser
]
[ Icon.i "add" ]
deleteButton : Material.Model -> Int -> User -> Html Msg
deleteButton mdl index user =
Button.render Mdl
[ 0, 1, index ]
mdl
[ Button.minifab
, Button.colored
, Button.ripple
, Button.onClick <| UserMsg' <| DeleteUser user
]
[ Icon.i "delete" ]
editButton : Material.Model -> Int -> User -> Html Msg
editButton mdl index user =
case user.id of
Nothing ->
text ""
Just id ->
Button.render Mdl
[ 0, 2, index ]
mdl
[ Button.minifab
, Button.colored
, Button.ripple
, Button.onClick <| NavigateTo <| Just <| EditUser id
]
[ Icon.i "edit" ]
header : Material.Model -> UsersListView -> List (Html Msg)
header mdl usersListView =
Helpers.defaultHeaderWithNavigation
"Users"
[ switchViewButton usersListView mdl
, addUserButton mdl
]
switchViewButton : UsersListView -> Material.Model -> Html Msg
switchViewButton listView mdl =
let
( msg, icon ) =
case listView of
UsersTable ->
( SwitchUsersListView UsersCards, "insert_photo" )
UsersCards ->
( SwitchUsersListView UsersTable, "list" )
in
Button.render Mdl
[ 0, 3 ]
mdl
[ Button.icon
, Button.ripple
, Button.onClick <| UserMsg' msg
, Options.css "margin-right" "6rem"
]
[ Icon.i icon ]
thOptions : UserSortableField -> Maybe ( Sorted, UserSortableField ) -> List (Options.Property (Util.MaterialTableHeader Msg) Msg)
thOptions sortableField usersSort =
[ Table.onClick <| UserMsg' <| ReorderUsers sortableField
, Options.css "cursor" "pointer"
]
++ case usersSort of
Nothing ->
[]
Just ( sorted, sortedField ) ->
case sortedField == sortableField of
True ->
case sorted of
Ascending ->
[ Table.sorted Table.Ascending ]
Descending ->
[ Table.sorted Table.Descending ]
False ->
[]
| true | module View.Users exposing (view, header)
import Model exposing (UsersModel)
import Types exposing (User, UserSortableField(..), Sorted(..), UsersListView(..), Paginated)
import Msg exposing (Msg(..), UserMsg(..))
import Route exposing (Location(..))
import Html exposing (Html, text, div, a, img, span, h3, ul, li)
import Html.Attributes exposing (href, src, style, colspan, class)
import Html.Events exposing (onClick)
import Material.List as List
import Material.Button as Button
import Material.Icon as Icon
import Material.Table as Table
import Material.Card as Card
import Material.Elevation as Elevation
import Material.Color as Color
import Material.Options as Options
import Material.Layout as Layout
import Material.Textfield as Textfield
import Material
import Material.Grid exposing (grid, size, cell, Device(..))
import View.Helpers as Helpers
import View.Pieces.PaginatedTable as PaginatedTable
import Util exposing (onEnter)
import RemoteData exposing (RemoteData(..))
view : Material.Model -> UsersModel -> Html Msg
view mdl usersModel =
let
body =
case usersModel.usersListView of
UsersTable ->
usersTable mdl usersModel
UsersCards ->
usersCards usersModel
in
div [] [ body ]
usersCards : UsersModel -> Html Msg
usersCards usersModel =
case usersModel.users.current of
NotAsked ->
text "Initialising..."
Loading ->
text "Loading..."
Failure err ->
text <| "There was a problem fetching the users: " ++ toString err
Success paginatedUsers ->
grid [] <|
List.map
(\user -> cell [ size All 3 ] [ userCard user ])
paginatedUsers.items
userCard : User -> Html Msg
userCard user =
let
userPhotoUrl =
"https://api.adorable.io/avatars/400/" ++ user.name ++ ".png"
in
Card.view
[ Options.css "width" "100%"
, Options.css "cursor" "pointer"
, Options.attribute <| onClick <| NavigateTo <| Maybe.map ShowUser user.id
, Elevation.e2
]
[ Card.title
[ Options.css "background" ("url('" ++ userPhotoUrl ++ "') center / cover")
, Options.css "min-height" "250px"
, Options.css "padding" "0"
]
[]
, Card.text []
[ h3 [] [ text user.name ]
, text "Software Zealot"
]
]
renderTable : Material.Model -> Maybe ( Sorted, UserSortableField ) -> String -> Paginated User -> Html Msg
renderTable mdl sort searchQuery paginatedUsers =
Table.table
[ Options.css "width" "100%"
, Elevation.e2
]
[ Table.thead []
[ Table.th [] []
, Table.th
(thOptions UserName sort)
[ text "Name" ]
, Table.th [] [ text "Position" ]
, Table.th [] [ text "Email" ]
, Table.th [] [ text "Today" ]
, Table.th [] [ text "Last 7 days" ]
, Table.th [] [ text "Projects" ]
, Table.th [] [ text "Open Tasks" ]
, Table.th []
[ Textfield.render Mdl
[ 0, 4 ]
mdl
[ Textfield.label "Search"
, Textfield.floatingLabel
, Textfield.text'
, Textfield.value searchQuery
, Textfield.onInput <| UserMsg' << SetUserSearchQuery
, onEnter <| UserMsg' <| FetchUsers <| "/users?q=" ++ searchQuery
]
]
]
, Table.tbody []
(List.indexedMap (viewUserRow mdl) paginatedUsers.items)
, Table.tfoot []
[ Html.td [ colspan 999, class "mdl-data-table__cell--non-numeric" ]
[ PaginatedTable.paginationData [ 0, 3 ] (UserMsg' << FetchUsers) mdl paginatedUsers ]
]
]
usersTable : Material.Model -> UsersModel -> Html Msg
usersTable mdl usersModel =
case usersModel.users.current of
NotAsked ->
text "Initialising..."
Loading ->
case usersModel.users.previous of
Nothing ->
text "Loading..."
Just previousUsers ->
div [ class "loading" ]
[ renderTable mdl usersModel.usersSort usersModel.userSearchQuery previousUsers
]
Failure err ->
case usersModel.users.previous of
Nothing ->
text <| "There was a problem fetching the users: " ++ toString err
Just previousUsers ->
div []
[ text <| "There was a problem fetching the users: " ++ toString err
, renderTable mdl usersModel.usersSort usersModel.userSearchQuery previousUsers
]
Success paginatedUsers ->
renderTable mdl usersModel.usersSort usersModel.userSearchQuery paginatedUsers
viewUserRow : Material.Model -> Int -> User -> Html Msg
viewUserRow mdl index user =
let
attributes =
case user.id of
Nothing ->
[]
Just id ->
[ href (Route.urlFor (ShowUser id)) ]
in
Table.tr []
[ Table.td []
[ img
[ src ("https://api.adorable.io/avatars/30/" ++ user.name ++ ".png"), style [ ( "border-radius", "50%" ) ] ]
[]
]
, Table.td [] [ a attributes [ text user.name ] ]
, Table.td [] [ text "PI:NAME:<NAME>END_PI" ]
, Table.td [] [ text "PI:EMAIL:<EMAIL>END_PI" ]
, Table.td [] [ text "3h 28m" ]
, Table.td [] [ text "57h 12m" ]
, Table.td [] [ text "20" ]
, Table.td [] [ text "8" ]
, Table.td []
[ editButton mdl index user
, deleteButton mdl index user
]
]
addUserButton : Material.Model -> Html Msg
addUserButton mdl =
Button.render Mdl
[ 0, 0 ]
mdl
[ Options.css "position" "fixed"
, Options.css "display" "block"
, Options.css "right" "0"
, Options.css "top" "0"
, Options.css "margin-right" "35px"
, Options.css "margin-top" "35px"
, Options.css "z-index" "900"
, Button.fab
, Button.colored
, Button.ripple
, Button.onClick <| NavigateTo <| Just NewUser
]
[ Icon.i "add" ]
deleteButton : Material.Model -> Int -> User -> Html Msg
deleteButton mdl index user =
Button.render Mdl
[ 0, 1, index ]
mdl
[ Button.minifab
, Button.colored
, Button.ripple
, Button.onClick <| UserMsg' <| DeleteUser user
]
[ Icon.i "delete" ]
editButton : Material.Model -> Int -> User -> Html Msg
editButton mdl index user =
case user.id of
Nothing ->
text ""
Just id ->
Button.render Mdl
[ 0, 2, index ]
mdl
[ Button.minifab
, Button.colored
, Button.ripple
, Button.onClick <| NavigateTo <| Just <| EditUser id
]
[ Icon.i "edit" ]
header : Material.Model -> UsersListView -> List (Html Msg)
header mdl usersListView =
Helpers.defaultHeaderWithNavigation
"Users"
[ switchViewButton usersListView mdl
, addUserButton mdl
]
switchViewButton : UsersListView -> Material.Model -> Html Msg
switchViewButton listView mdl =
let
( msg, icon ) =
case listView of
UsersTable ->
( SwitchUsersListView UsersCards, "insert_photo" )
UsersCards ->
( SwitchUsersListView UsersTable, "list" )
in
Button.render Mdl
[ 0, 3 ]
mdl
[ Button.icon
, Button.ripple
, Button.onClick <| UserMsg' msg
, Options.css "margin-right" "6rem"
]
[ Icon.i icon ]
thOptions : UserSortableField -> Maybe ( Sorted, UserSortableField ) -> List (Options.Property (Util.MaterialTableHeader Msg) Msg)
thOptions sortableField usersSort =
[ Table.onClick <| UserMsg' <| ReorderUsers sortableField
, Options.css "cursor" "pointer"
]
++ case usersSort of
Nothing ->
[]
Just ( sorted, sortedField ) ->
case sortedField == sortableField of
True ->
case sorted of
Ascending ->
[ Table.sorted Table.Ascending ]
Descending ->
[ Table.sorted Table.Descending ]
False ->
[]
| elm |
[
{
"context": "{--\n\nCopyright (c) 2016, William Whitacre\nAll rights reserved.\n\nRedistribution and use in s",
"end": 41,
"score": 0.9998533726,
"start": 25,
"tag": "NAME",
"value": "William Whitacre"
}
] | src/Scaffold/Resource.elm | williamwhitacre/scaffold | 8 | {--
Copyright (c) 2016, William Whitacre
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--}
module Scaffold.Resource
(Resource,
ResourceTask, UserTask,
ResourceRef,
ResourcePath,
userTask, deltaTask, toProgramTask,
defResource, forbiddenResource, pendingResource, undecidedResource,
unknownResource, voidResource, operationResource, groupResource,
maybeOr, resultOr,
assumeIf, assumeIfNot, assumeIfNow, assumeInCase, assumeInCaseNow,
dispatchIf, dispatchIfNot, dispatchInCase, dispatchInCaseNow,
deriveIf, deriveIfNow, decideBy, maybeKnownNow, otherwise,
therefore, therefore',
comprehend, comprehend',
interpret, interpret',
within,
throughout, throughoutNow,
flatten, flattenDict, collapse,
routeTo, catchError,
isUnknown, isNotUnknown,
isPending, isNotPending,
isUndecided, isNotUndecided,
isForbidden, isNotForbidden,
isVoid, isNotVoid,
isNil, isNotNil,
isKnown, isNotKnown,
isOperation, isNotOperation,
isGroup, isNotGroup,
prefixPath,
atPath,
putPath,
getPath,
deletePath,
writePath,
movePath,
copyPath,
chooseLeft,
chooseRight,
chooseVoid,
chooseNeither,
merge, mergeMany,
update, updateList,
update', updateList',
dispatch, integrate,
deltaTo, deltaOf,
toProgram)
where
{-| Resource system.
# Types
@docs Resource, ResourceTask, ResourceRef, ResourcePath, UserTask
# Define Resources
@docs defResource, forbiddenResource, pendingResource, undecidedResource, unknownResource, voidResource, operationResource, groupResource
# Interpret `Maybe` or `Result` as Resources
@docs maybeOr, resultOr
# Conditional Assumptions
@docs assumeIf, assumeIfNot, assumeIfNow, assumeInCase, assumeInCaseNow
# Conditional Derivations
`deriveIf` and `deriveIfNow` are given as more flexible and readable versions of `assumeInCase`
and `assumeInCaseNow`. Neither muddies the waters with the Maybe type, and the transformation
can be any `Resource euser v -> Resource euser v`, which makes these highly nestable by comparison
to their respective older counterparts.
@docs deriveIf, deriveIfNow
# Resource Output
@docs otherwise, maybeKnownNow
# Bulk Operations
@docs decideBy, flatten, flattenDict, collapse, throughout, throughoutNow, therefore, therefore', within
# Handling `UserTask` and `ResourceTask`
@docs userTask, deltaTask, toProgramTask, comprehend, comprehend', interpret, interpret', routeTo, catchError
# Conditional Operations
@docs dispatchIf, dispatchIfNot, dispatchInCase, dispatchInCaseNow
# Resource Introspection Predicates
@docs isUnknown, isNotUnknown, isPending, isNotPending, isUndecided, isNotUndecided, isForbidden, isNotForbidden, isVoid, isNotVoid, isNil, isNotNil, isKnown, isNotKnown, isOperation, isNotOperation, isGroup, isNotGroup
# Manipulate and Use `ResourcePath`
@docs prefixPath, atPath, putPath, getPath, deletePath, writePath, movePath, copyPath
# Built-in Conflict Operators
For use with `merge` and `mergeMany`.
@docs chooseLeft, chooseRight, chooseVoid, chooseNeither
# Merge Resource Groups
@docs merge, mergeMany
# Update Resources
@docs update, updateList, update', updateList', dispatch, integrate, deltaTo, deltaOf
# Program Resources
@docs toProgram
-}
-- TODO: determine cause of the path reversal strangeness in the example.
import Scaffold.App exposing (..)
import Scaffold.Error as Error
import Signal
import Task exposing (Task, andThen, onError)
import Trampoline exposing (Trampoline)
import Dict exposing (Dict)
import Set exposing (Set)
import Lazy.List exposing (LazyList, (+++))
{-| This is a Task which represents some kind of synchronization with optask data. It can also easily
be used for long running arbitrary computations, too. It produces a Gigan Error or a Resource. -}
type alias ResourceTask euser v = Task (ResourcePath, Error.Error euser) (ResourceRef euser v)
{-| This task simplifies routing out for the user. -}
type alias UserTask euser v = Task (Error.Error euser) (Resource euser v)
{-| A reference to a resource, including it's path. -}
type alias ResourceRef euser v =
{ path : ResourcePath, resource : Resource euser v }
{-| Used as the resource path type. -}
type alias ResourcePath = List String
type alias GroupStruct_ euser v =
{ curr : Dict String (Resource euser v)
, chgs : Dict String (Resource euser v)
}
groupStructMap_ f stct =
{ stct | chgs = groupStructMapped_ f stct }
groupStructKeyMap_ f stct =
{ stct | chgs = groupStructKeyMapped_ f stct }
groupStructMapped_ f stct =
groupStructKeyMapped_ (always f) stct
groupStructKeyMapped_ f stct =
let
curr' = groupStructChanged_ stct |> .curr
in
Dict.map f curr'
groupStructChanged_ stct =
{ curr =
Dict.foldl
(\key value -> case value of
Unknown -> Dict.remove key
Group stct -> Dict.insert key (groupStructChanged_ stct |> Group)
_ -> Dict.insert key value)
stct.curr
stct.chgs
, chgs = Dict.empty
}
groupStructMapChange_ f stct =
groupStructChanged_ { stct | chgs = Dict.map (always f) stct.chgs }
groupStructFoldHelper_ foldf f data stct =
foldf f data (groupStructChanged_ stct |> .curr)
groupStructFoldl_ f data stct =
groupStructFoldHelper_ Dict.foldl f data stct
groupStructFoldr_ f data stct =
groupStructFoldHelper_ Dict.foldr f data stct
groupGet_ key stct =
Maybe.oneOf [Dict.get key stct.chgs, Dict.get key stct.curr]
|> Maybe.withDefault Unknown
groupPut_ key value stct =
{ stct | chgs = Dict.insert key value stct.chgs }
groupUpdate_ key op stct =
groupGet_ key stct
|> \value -> groupPut_ key (op value) stct
groupNew_ =
{ curr = Dict.empty
, chgs = Dict.empty
}
{-| A resource item. -}
type Resource euser v =
Unknown
| Pending
-- No such datum exists.
| Void
-- Gives reason as to why this data are still unknown after a retrieval attempt. If a resource
-- enters in to this state, it's time to intervene, whether automatically or with the aid of user
-- feedback of some kind.
| Undecided (Error.Error euser)
-- This is what is done if the result from the optask operation for the data is an error explaining why
-- access to the data was denied.
| Forbidden (Error.Error euser)
-- If a resource is an Operation, then any primitives not suffixed with Now will result in an operation
| Operation (ResourceTask euser v)
-- known value of type v.
| Known v
-- known to be a collection of string keyed v things.
| Group (GroupStruct_ euser v)
{-| True if the resource is unknownResource. -}
isUnknown : Resource euser v -> Bool
isUnknown res =
case res of
Unknown -> True
_ -> False
{-| False if the resource is unknownResource. -}
isNotUnknown : Resource euser v -> Bool
isNotUnknown = isUnknown >> not
{-| True if the resource is pendingResource. -}
isPending : Resource euser v -> Bool
isPending res =
case res of
Pending -> True
_ -> False
{-| False if the resource is pendingResource. -}
isNotPending : Resource euser v -> Bool
isNotPending = isPending >> not
{-| True if the resource is voidResource. -}
isVoid : Resource euser v -> Bool
isVoid res =
case res of
Void -> True
_ -> False
{-| False if the resource is voidResource. -}
isNotVoid : Resource euser v -> Bool
isNotVoid = isVoid >> not
{-| True if the resource is unknownResource or voidResource. -}
isNil : Resource euser v -> Bool
isNil res =
case res of
Unknown -> True
Void -> True
_ -> False
{-| False if the resource is unknownResource or voidResource. -}
isNotNil : Resource euser v -> Bool
isNotNil = isNil >> not
{-| True if the resource is undecidedResource. -}
isUndecided : Resource euser v -> Bool
isUndecided res =
case res of
Undecided _ -> True
_ -> False
{-| False if the resource is undecidedResource. -}
isNotUndecided : Resource euser v -> Bool
isNotUndecided = isUndecided >> not
{-| True if the resource is forbiddenResource. -}
isForbidden : Resource euser v -> Bool
isForbidden res =
case res of
Forbidden _ -> True
_ -> False
{-| False if the resource is forbiddenResource. -}
isNotForbidden : Resource euser v -> Bool
isNotForbidden = isForbidden >> not
{-| True if the resource is a pending operation. -}
isOperation : Resource euser v -> Bool
isOperation res =
case res of
Operation _ -> True
_ -> False
{-| False if the resource is a pending operation. -}
isNotOperation : Resource euser v -> Bool
isNotOperation = isOperation >> not
{-| True if the resource is known. -}
isKnown : Resource euser v -> Bool
isKnown res =
case res of
Known _ -> True
_ -> False
{-| False if the resource is known. -}
isNotKnown : Resource euser v -> Bool
isNotKnown = isKnown >> not
{-| True if the resource is unknownResource. -}
isGroup : Resource euser v -> Bool
isGroup res =
case res of
Group stct -> True
_ -> False
{-| False if the resource is unknownResource. -}
isNotGroup : Resource euser v -> Bool
isNotGroup = isGroup >> not
{-| Create a task which will route the resulting resource to the given path. -}
userTask : UserTask euser v -> ResourceTask euser v
userTask usertask =
usertask
`andThen` (\res -> Task.succeed { resource = res, path = [ ] })
`onError` (\err' -> Task.fail ([ ], err'))
{-| Transform a `ResourceTask` back in to a `UserTask`, which will produce a nested `Resource`
finger reflecting the final path output of the given `ResourceTask`. This output resource can be
treated just like a delta using the `Resource.merge` and `Resource.mergeMany` functions to inject it
in to the working set. -}
deltaTask : ResourceTask euser v -> UserTask euser v
deltaTask optask =
optask
`andThen` (\{resource, path} -> prefixPath path resource |> Task.succeed)
`onError` (\(path', err') -> undecidedResource err' |> prefixPath path' |> Task.succeed)
{-| Convert a `UserTask euser v` in to an `App.ProgramTask bad a` -}
toProgramTask : (Error.Error euser -> List a) -> (Resource euser v -> List a) -> UserTask euser v -> ProgramTask bad a
toProgramTask errorActions resourceActions =
agent
(resourceActions >> agentSuccess)
(errorActions >> agentSuccess)
{-| The equivalent of therefore for ResourceTasks. This allows you to map fetched data to multiple
models with ease, as long as operations which should effect all of the models are all sunk in to
ResourceTasks producing the base model's type. -}
comprehend : (v -> v') -> ResourceTask euser v -> ResourceTask euser v'
comprehend xdcr optask =
optask `andThen` (\ref -> { ref | resource = therefore xdcr ref.resource } |> Task.succeed)
{-| Like `comprehend`, but accounts for the path of the leaves effected by the transformation
by using `therefore'` on the result of the task. This prepends the reference path of the resource
task, such that global context for the resource's location is available if desired.
Note that you may specify a prefix path to the existing one to provide additional context in large
resource group structures.
-}
comprehend' : (ResourcePath -> v -> v') -> ResourceTask euser v -> ResourceTask euser v'
comprehend' xdcr optask =
optask `andThen` (\ref -> { ref | resource = therefore' xdcr ref.path ref.resource } |> Task.succeed)
-- adapter for therefore implementation
comprehendImpl_r : (ResourcePath -> v -> v') -> ResourcePath -> ResourceTask euser v -> ResourceTask euser v'
comprehendImpl_r rxdcr rpath optask =
optask `andThen` (\ref -> { ref | resource = thereforeImpl_r rxdcr (List.reverse ref.path ++ rpath) ref.resource } |> Task.succeed)
{-| Interpret the given `ResourceTask`'s resource output by a given transform function. NOTE that this
can be literally any function whose signature ends in `ResourceTask euser v -> ResourceTask euser v'`,
which is of course inclusive of `ResourceTask euser v -> ResourceTask euser v'` in the case that
`v` is the same type as `v'`. -}
interpret : (Resource euser v -> Resource euser v') -> ResourceTask euser v -> ResourceTask euser v'
interpret f optask =
optask `andThen` (\ref -> { ref | resource = f ref.resource } |> Task.succeed)
{-| Like `interpret`, but the prefix path of the resource is passed to the given function, and the
user can optionally specify their own prefix path. `interpret'` is to `interpret` what `comprehend'`
is to `comprehend`. -}
interpret' : (ResourcePath -> Resource euser v -> Resource euser v') -> ResourcePath -> ResourceTask euser v -> ResourceTask euser v'
interpret' f prepath optask =
optask `andThen` (\ref -> { ref | resource = f (prepath ++ ref.path) ref.resource } |> Task.succeed)
{-| Route the results of a given `ResourceTask` to a given `ResourcePath`. -}
routeTo : ResourcePath -> ResourceTask euser v -> ResourceTask euser v
routeTo path' optask =
optask `andThen` (\ref -> { ref | path = path' } |> Task.succeed)
{-| Provide a decider that turns an error of type `Error.Error euser` in to a resource of `Resource euser v`. -}
catchError : (Error.Error euser -> Resource euser v) -> ResourceTask euser v -> ResourceTask euser v
catchError decider optask =
optask `onError` (\(path', err') -> Task.succeed { path = path', resource = decider err' })
{-| Collapses a resource tree made of group resources in to a single resource of the same type. -}
collapse : (List (ResourcePath, Resource euser v) -> Resource euser v) -> Resource euser v -> Resource euser v
collapse f res =
collapse_ f [] res
collapse_ : (List (ResourcePath, Resource euser v) -> Resource euser v) -> ResourcePath -> Resource euser v -> Resource euser v
collapse_ frecurse rpath res =
let
cfold key res ls = (List.reverse rpath, collapse_ frecurse (key :: rpath) res) :: ls
in
case res of
Group stct -> groupStructFoldr_ cfold [] stct |> frecurse
_ -> res
{-| Flatten the given resource if it is a group to a resource of the same type. Note that unlike
`collapse`, this function does not recursively collapse the entire tree automatically. This grants
a greater degree of flexibility. -}
flatten : (List (String, Resource euser v) -> Resource euser v) -> Resource euser v -> Resource euser v
flatten fgrp res =
let
cfold key res ls = (key, res) :: ls
in
case res of
Group stct -> groupStructFoldr_ cfold [] stct |> fgrp
_ -> res
{-| Variant of `flatten` whose argument function takes a dictionary instead of a list of pairs. -}
flattenDict : (Dict String (Resource euser v) -> Resource euser v) -> Resource euser v -> Resource euser v
flattenDict fgrp res =
case res of
Group stct ->
stct
|> groupStructChanged_
|> .curr
|> fgrp
_ -> res
{-| Use the given function to transform all leaf resources throughout a group structure. This
applies to the result of any pending resource operations. -}
throughout : (Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v
throughout f res =
case res of
Group stct ->
groupStructMap_ (throughout f) stct
|> Group
Operation optask -> Operation (interpret (throughout f) optask)
_ -> f res
{-| Use the given function to transform all leaf resources throughout a group structure. This version
applies the transformation function now, even if the resource is a pending operation. This should be
used in contexts where we are rendering some resulting view of the resources most of the time. -}
throughoutNow : (Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v
throughoutNow f res =
case res of
Group stct ->
groupStructMap_ (throughout f) stct
|> Group
_ -> f res
{-| Given a resource of value type v, create a resource of value type v' by transforming the
known value or group using some function (v -> v'). NOTE that this will create an entirely new
resouce structure, and thus any pending changes will be integrated immediately. If you wish to
preserve deltas for the purpose of mirroring and efficient data flow, then one should be using
deltaTo in order to transform just the changes. -}
therefore : (v -> v') -> Resource euser v -> Resource euser v'
therefore xdcr =
thereforeImpl_r (always xdcr) [ ]
{-| `therefore`, but which includes the current path as the first argument. -}
therefore' : (ResourcePath -> v -> v') -> ResourcePath -> Resource euser v -> Resource euser v'
therefore' xdcr path =
thereforeImpl_r (List.reverse >> xdcr) (List.reverse path)
-- The implementation deals with reversed paths. This is because during path construction, it is
-- obviously more efficient to push path elements to the head of a list. The given reversed path
-- transducer reverses said path, yielding the path itself, and does so once per concrete leaf in
-- the resource group tree structure. This would only result in poor runtime performance in practice
-- in the unlikely case that we have very large deltas which further consist of very deep trees.
-- Since this scenario is highly unlikely and can easily be avoided by design from an engineering
-- standpoint, that theoretical weakness does not have a substantial concrete cost.
thereforeImpl_r : (ResourcePath -> v -> v') -> ResourcePath -> Resource euser v -> Resource euser v'
thereforeImpl_r rxdcr rpath res =
let
stepIn_ key = thereforeImpl_r rxdcr (key :: rpath)
in
case res of
Unknown -> Unknown
Pending -> Pending
Void -> Void
Undecided err' -> Undecided err'
Forbidden err' -> Forbidden err'
Known x' -> Known (rxdcr rpath x')
Operation optask -> Operation (comprehendImpl_r rxdcr rpath optask)
Group stct -> { curr = Dict.empty, chgs = groupStructKeyMapped_ stepIn_ stct } |> Group
{-| DEPRECIATED version of therefore, not supporting type transformation.
NOTE : removed in version 5.
-}
within : (sub -> sub) -> Resource euser sub -> Resource euser sub
within = therefore
{-| Manipulate an item at the given path, or else do nothing if the path does not exist. -}
atPath : (Resource euser v -> Resource euser v) -> ResourcePath -> Resource euser v -> Resource euser v
atPath operation path res =
case path of
[ ] -> operation res
element :: path' ->
case res of
Group stct ->
groupUpdate_ element (atPath operation path') stct
|> Group
_ -> res
{-| Delete the item at the given path. This equivalency holds:
atPath (always unknownResource) path res == deletePath path res
-}
deletePath : ResourcePath -> Resource euser v -> Resource euser v
deletePath = atPath (always Unknown)
{-| Put a resource in to a group resource at the given path. In the case that something is already
there, use the `choice` function to determine which should be used. See the `choose*` family for some
built-in functions. -}
putPath : (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> Resource euser v -> Resource euser v -> Resource euser v
putPath choice path res' res =
prefixPath path res'
|> \res'' -> merge choice res'' res
{-| Equivalent to `putPath chooseLeft`, this is a simple write which will always blindly overwrite the
current resource at the given path. -}
writePath : ResourcePath -> Resource euser v -> Resource euser v -> Resource euser v
writePath = putPath chooseLeft
{-| Move the resource at a given path `path` in the resource group structure to a target path `path'`. -}
movePath : (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> ResourcePath -> Resource euser v -> Resource euser v
movePath = cpPathImpl_ True
{-| Copy the resource at a given path `path` in the resource group structure to a target path `path'`. -}
copyPath : (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> ResourcePath -> Resource euser v -> Resource euser v
copyPath = cpPathImpl_ False
cpPathImpl_ : Bool -> (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> ResourcePath -> Resource euser v -> Resource euser v
cpPathImpl_ bDoMove choice path path' res =
if path /= path' then
putPath choice path' (getPath path res) res
|> \res'' -> if bDoMove then putPath chooseLeft path Unknown res'' else res''
else
res
{-| Collision handler for nested Resources that always chooses the left hand side. -}
chooseLeft : Resource euser v -> Resource euser v -> Resource euser v
chooseLeft x _ = x
{-| Collision handler for nested Resources that always chooses the right hand side. -}
chooseRight : Resource euser v -> Resource euser v -> Resource euser v
chooseRight _ x = x
{-| Collision handler for nested Resources that voids collision keys. -}
chooseVoid : Resource euser v -> Resource euser v -> Resource euser v
chooseVoid _ _ = Void
{-| Collision handler that removes collision keys entirely. -}
chooseNeither : Resource euser v -> Resource euser v -> Resource euser v
chooseNeither _ _ = Unknown
{-| Create a path before the given resource. This has the effect of prefixing whatever is there
whether concrete or a group with the given path. Thus, creating a resource path ["foo", "bar"] and
another at ["foo", "baz"] would result in two resources that can be merged without conflicts
guaranteed because their contents are in the `foo -> bar -> ...` and `foo -> baz -> ...` subtries
respectively. -}
prefixPath : ResourcePath -> Resource euser v -> Resource euser v
prefixPath path res =
List.foldr
(\element res' -> Group (groupPut_ element res' groupNew_))
res
path
{-| Merge can be used to assemble path fingers or existing group structures arbitrarily. A common
usage would be to put many different resources at their own prefix paths, then merge them all by
folding on this if your data structure is odd, otherwise use mergeMany if you are already working
with a list. This takes a choice function that determines the outcome of two different resources
existing at the same path, _at least one of which is concrete and not a group_. Groups merge
automatically with eachother. -}
merge : (Resource euser v -> Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v -> Resource euser v
merge choice left' right' =
-- right' is the current group, left' is what's being merged in.
case (left', right') of
(Group lhs, Group rhs) ->
Dict.foldl
(\key res' rhs' ->
groupGet_ key rhs'
|> \res -> groupPut_ key (merge choice res' res) rhs'
)
rhs
(Dict.union lhs.chgs lhs.curr)
|> Group
(Group lhs, old) ->
choice (Group { curr = Dict.empty, chgs = (Dict.union lhs.chgs lhs.curr) }) old
(_, _) -> choice left' right'
{-| Merge many folds from the left over the given list of resources with merge. -}
mergeMany : (Resource euser v -> Resource euser v -> Resource euser v) -> List (Resource euser v) -> Resource euser v
mergeMany choice gs =
case gs of
g :: gs' ->
List.foldl (merge choice) g gs'
[ ] -> Void
{-| Get the item at the given path. Returns unknownResource if the item _might_ exist, but the hierarchy
does not show knowledge at the fringe (i.e., the fringe is unknown at the last known location in
the path), but may also return voidResource to a path which is known not to exist. For example,
if foo is a resource, then foo/bar cannot be a valid path because foo is not a collection. Pending
will be given in the case that an operation is pending. -}
getPath : ResourcePath -> Resource euser v -> Resource euser v
getPath path res =
case path of
[ ] -> res
element :: path' ->
case res of
Group stct ->
groupGet_ element stct
|> getPath path'
Known x' -> Void
Void -> Void
Pending -> Pending
Operation optask -> Pending
_ -> Unknown
{-| Offer a decision on some `undecidedResource res`. Undecided resource is the result of some
problem which may or may not be in control of the client. Such resource may be the result of
anything that can result in an error in your application. If this resource is an operation, then
the assumption will be applied to the result of that operation. -}
decideBy : (Error.Error euser -> Resource euser v) -> Resource euser v -> Resource euser v
decideBy decider res =
case res of
Undecided err' -> decider err'
Operation optask -> Operation (catchError decider optask)
_ -> res
{-| If some predicate `satisfies` is satisfied by the resource `res`, then we make the following
assumption. If this resource is an operation, then the assumption will be applied to
the result of that operation. -}
assumeIf : (Resource euser v -> Bool) -> v -> Resource euser v -> Resource euser v
assumeIf satisfies assume res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = assumeIf satisfies assume ref.resource } |> Task.succeed))
_ ->
if satisfies res then therefore (always assume) res else res
{-| Negation of assumeIf. -}
assumeIfNot : (Resource euser v -> Bool) -> v -> Resource euser v -> Resource euser v
assumeIfNot satisfies assume res =
assumeIf (satisfies >> not) assume res
{-| If `possibleAssumption` yields some value `value'` when a Resource is applied, then that
value is used to overwrite the resource with an assumption `Known value'`, otherwise the Resource
is unaffected. If this resource is an operation, then the assumption will be applied conditionally
to the result of that operation. -}
assumeInCase : (Resource euser v -> Maybe v) -> Resource euser v -> Resource euser v
assumeInCase possibleAssumption res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = assumeInCase possibleAssumption ref.resource } |> Task.succeed))
_ ->
Maybe.map Known (possibleAssumption res)
|> Maybe.withDefault res
{-| If some predicate `satisfies` is satisfied by the resource `res`, then we make the following
optask. -}
dispatchIf : (Resource euser v -> Bool) -> ResourceTask euser v -> Resource euser v -> Resource euser v
dispatchIf satisfies optask res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = dispatchIf satisfies optask ref.resource } |> Task.succeed))
_ ->
dispatchInCase (if satisfies res then always (Just optask) else always Nothing) res
{-| Negation of dispatchIf -}
dispatchIfNot : (Resource euser v -> Bool) -> ResourceTask euser v -> Resource euser v -> Resource euser v
dispatchIfNot satisfies optask res =
dispatchIf (satisfies >> not) optask res
{-| If `possibleOperation` yields some ResourceTask task `optask` when a Resource is applied, then
the resource is replaced by the resource `operationResource optask`, otherwise the resource is
unaffected. If this resource is an operation, then the result of that operation will be used as
the input to the provided function. In this way, operations can be chained arbitrarily deep,
but in a manner that helpfully abstracts away whether we are still waiting or already have the
result in the composition. -}
dispatchInCase : (Resource euser v -> Maybe (ResourceTask euser v)) -> Resource euser v -> Resource euser v
dispatchInCase possibleOperation res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = dispatchInCase possibleOperation ref.resource } |> Task.succeed))
_ ->
Maybe.map operationResource (possibleOperation res)
|> Maybe.withDefault res
{-| If the predicate is satisfied, apply the given transformation function. If this is a pending
operationResource, then apply deriveIf with the same arguments to the result. -}
deriveIf : (Resource euser v' -> Bool) -> (Resource euser v' -> Resource euser v') -> Resource euser v' -> Resource euser v'
deriveIf satisfies f res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = deriveIf satisfies f ref.resource } |> Task.succeed))
_ ->
deriveIfNow satisfies f res
{-| If the predicate is satisfied, apply the given transformation function. -}
deriveIfNow : (Resource euser v' -> Bool) -> (Resource euser v' -> Resource euser v') -> Resource euser v' -> Resource euser v'
deriveIfNow satisfies f res' =
if satisfies res' then f res' else res'
-- NOTE : These primitives force a reduction now even for an optask operation type
-- convenient conversion to a maybe after all mappings are given. This is intended for use when
-- mapping the state of the content to an actual display.
{-| If a resource is known, then give Just it's value, otherwise Nothing. -}
maybeKnownNow : Resource euser v' -> Maybe v'
maybeKnownNow res' =
case res' of
Known x' -> Just x'
_ -> Nothing
{-| If the predicate is satisfied, replace the resource with some known value. -}
assumeIfNow : (Resource euser v' -> Bool) -> v' -> Resource euser v' -> Resource euser v'
assumeIfNow satisfies assumption res' =
if satisfies res' then Known assumption else res'
{-| This is the counterpart to assumeInCase which does _not_ abstract away whether or not this is
some pending optask operation. Concretely, we want this in the case that we are doing model to view
reductions because a pending operation should still have some concrete visible representation, such
as an ajax loader symbol. Of course, one should still correctly call *Integrate so that an operation
is always a `pendingResource` by the time it gets past the `stage` step. -}
assumeInCaseNow : (Resource euser v' -> Maybe v') -> Resource euser v' -> Resource euser v'
assumeInCaseNow possibleAssumption res' =
Maybe.map Known (possibleAssumption res')
|> Maybe.withDefault res'
{-| -}
dispatchInCaseNow : (Resource euser v -> Maybe (ResourceTask euser v)) -> Resource euser v -> Resource euser v
dispatchInCaseNow possibleOperation res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = dispatchInCase possibleOperation ref.resource } |> Task.succeed))
_ ->
Maybe.map operationResource (possibleOperation res)
|> Maybe.withDefault res
{-| In the event that the given resource is not a simple `defResource`, we replace it with a different simple
resource. -}
otherwise : v' -> Resource euser v' -> v'
otherwise assumption res' =
case res' of
Known x' -> x'
_ -> assumption
{-| -}
unknownResource : Resource euser v
unknownResource = Unknown
{-| -}
pendingResource : Resource euser v
pendingResource = Pending
{-| -}
voidResource : Resource euser v
voidResource = Void
{-| -}
undecidedResource : Error.Error euser -> Resource euser v
undecidedResource = Undecided
{-| -}
forbiddenResource : Error.Error euser -> Resource euser v
forbiddenResource = Forbidden
{-| -}
operationResource : ResourceTask euser v -> Resource euser v
operationResource = Operation
{-| -}
defResource : v -> Resource euser v
defResource = Known
{-| -}
groupResource : List (String, Resource euser v) -> Resource euser v
groupResource members =
Group { curr = Dict.empty, chgs = Dict.fromList members }
{-| -}
resultOr : (Error.Error euser -> Resource euser v) -> Result (Error.Error euser) v -> Resource euser v
resultOr errorResource result =
case result of
Result.Ok data -> defResource data
Result.Err err' -> errorResource err'
{-| -}
maybeOr : Resource euser v -> Maybe v -> Resource euser v
maybeOr nothingResource maybeValue =
Maybe.map Known maybeValue
|> Maybe.withDefault nothingResource
{-| Given some configuration and a resource, produce Just an opaque query task or Nothing
when the resource is an operation or the resource is not an operation respectively. -}
dispatch : Resource euser v -> List (ResourceTask euser v)
dispatch res =
dispatch_ [] res
|> Lazy.List.toList -- crunch to a normal list at top level.
dispatch_ : List String -> Resource euser v -> LazyList (ResourceTask euser v)
dispatch_ rpath res =
case res of
Group stct -> groupStructFoldr_ (\key res' ls -> (dispatch_ (key :: rpath) res') +++ ls) Lazy.List.empty stct
Operation optask ->
Lazy.List.singleton
(routeTo (List.reverse rpath) optask
|> catchError undecidedResource)
_ -> Lazy.List.empty
{-| Update the second `Resource` argument by merging the first argument's delta `Resource`. Chooses
the left `Resource` on a conflict, mechanically speaking. -}
update : Resource euser v -> Resource euser v -> Resource euser v
update = update' chooseLeft
{-| Same as `update`, but apply a list of delta resources sequentially. This resolves all conflicts
by `chooseLeft`, which favors the deltas always. -}
updateList : List (Resource euser v) -> Resource euser v -> Resource euser v
updateList = updateList' chooseLeft
{-| Same as `update`, but pass the given conflict resolution choice function to `merge` instead of
`chooseLeft`, which is the default. This allows one to make a selection as to whether or not the
given delta is still relevant. -}
update' : (Resource euser v -> Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v -> Resource euser v
update' mergeChoice = merge mergeChoice
{-| Same as `updateList`, but uses the provided conflict resolution choice function instead of
`chooseLeft` as in `updateList`. This allows one to make a selection as to whether or not the
given delta is still relevant. -}
updateList' : (Resource euser v -> Resource euser v -> Resource euser v) -> List (Resource euser v) -> Resource euser v -> Resource euser v
updateList' mergeChoice deltas res =
mergeMany (flip mergeChoice) (res :: deltas)
{-| Given some configuration and a resource, produce a pendingResource in the case that the
resource is an operation, otherwise give the same resource. -}
integrate : Resource euser v -> Resource euser v
integrate res =
case res of
Group stct -> groupStructMapChange_ integrate stct |> Group
Operation optask -> Pending
_ -> res
{-| `deltaTo` applies the given transformation function to the pending changes to the
`Resource` structure, producing a partial structure representing only what has changed since the
last call to `integrate`. The resulting partial structure is intended for use as a delta, to be
passed to `update` for some other Resource structure. This results in a simple one-way data binding.
To introduce k-way data binding, one need only use the `interpret` function to transform the
`ResourceTask` output of the subordinate views back in to deltas that transform the origin
`Resource` structure. NOTE that this implies when one wishes for the origin structure to reflect
changes to one of it's subordinates, one must dispatch UserTasks that succeed with the intended
changes. This can be very clean as long as there is a bijection between the origin structure
and each of it's subordinates. The complexity of the mapping is of course dependent on your record
design, so one must still take care. -}
deltaTo : (Resource euser v -> Resource euser v') -> Resource euser v -> Resource euser v'
deltaTo f res =
case res of
Group stct ->
Dict.foldl
(\key res' -> deltaTo f res' |> Dict.insert key)
Dict.empty
stct.chgs
|> \chgs' -> { curr = chgs', chgs = Dict.empty }
|> Group
_ -> f res
{-| Like `deltaTo`, but without the transformation. The following equivalency holds -}
deltaOf : Resource euser v -> Resource euser v
deltaOf = deltaTo identity
{-| Convert a resource to program input. I've found that this is a very un-Elm-like way
of doing things that makes the Elm Architecture harder to stick to. If anyone else finds a
counterexample, please let me know! If it does turn out to be useful, I will complete the set.
NOTE : DEPRECIATED, removed from v5.
-}
toProgram : (b -> ProgramInput a b c bad) -> Resource euser b -> Resource euser (ProgramInput a b c bad)
toProgram modelInput model' = therefore modelInput model'
| 25095 | {--
Copyright (c) 2016, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--}
module Scaffold.Resource
(Resource,
ResourceTask, UserTask,
ResourceRef,
ResourcePath,
userTask, deltaTask, toProgramTask,
defResource, forbiddenResource, pendingResource, undecidedResource,
unknownResource, voidResource, operationResource, groupResource,
maybeOr, resultOr,
assumeIf, assumeIfNot, assumeIfNow, assumeInCase, assumeInCaseNow,
dispatchIf, dispatchIfNot, dispatchInCase, dispatchInCaseNow,
deriveIf, deriveIfNow, decideBy, maybeKnownNow, otherwise,
therefore, therefore',
comprehend, comprehend',
interpret, interpret',
within,
throughout, throughoutNow,
flatten, flattenDict, collapse,
routeTo, catchError,
isUnknown, isNotUnknown,
isPending, isNotPending,
isUndecided, isNotUndecided,
isForbidden, isNotForbidden,
isVoid, isNotVoid,
isNil, isNotNil,
isKnown, isNotKnown,
isOperation, isNotOperation,
isGroup, isNotGroup,
prefixPath,
atPath,
putPath,
getPath,
deletePath,
writePath,
movePath,
copyPath,
chooseLeft,
chooseRight,
chooseVoid,
chooseNeither,
merge, mergeMany,
update, updateList,
update', updateList',
dispatch, integrate,
deltaTo, deltaOf,
toProgram)
where
{-| Resource system.
# Types
@docs Resource, ResourceTask, ResourceRef, ResourcePath, UserTask
# Define Resources
@docs defResource, forbiddenResource, pendingResource, undecidedResource, unknownResource, voidResource, operationResource, groupResource
# Interpret `Maybe` or `Result` as Resources
@docs maybeOr, resultOr
# Conditional Assumptions
@docs assumeIf, assumeIfNot, assumeIfNow, assumeInCase, assumeInCaseNow
# Conditional Derivations
`deriveIf` and `deriveIfNow` are given as more flexible and readable versions of `assumeInCase`
and `assumeInCaseNow`. Neither muddies the waters with the Maybe type, and the transformation
can be any `Resource euser v -> Resource euser v`, which makes these highly nestable by comparison
to their respective older counterparts.
@docs deriveIf, deriveIfNow
# Resource Output
@docs otherwise, maybeKnownNow
# Bulk Operations
@docs decideBy, flatten, flattenDict, collapse, throughout, throughoutNow, therefore, therefore', within
# Handling `UserTask` and `ResourceTask`
@docs userTask, deltaTask, toProgramTask, comprehend, comprehend', interpret, interpret', routeTo, catchError
# Conditional Operations
@docs dispatchIf, dispatchIfNot, dispatchInCase, dispatchInCaseNow
# Resource Introspection Predicates
@docs isUnknown, isNotUnknown, isPending, isNotPending, isUndecided, isNotUndecided, isForbidden, isNotForbidden, isVoid, isNotVoid, isNil, isNotNil, isKnown, isNotKnown, isOperation, isNotOperation, isGroup, isNotGroup
# Manipulate and Use `ResourcePath`
@docs prefixPath, atPath, putPath, getPath, deletePath, writePath, movePath, copyPath
# Built-in Conflict Operators
For use with `merge` and `mergeMany`.
@docs chooseLeft, chooseRight, chooseVoid, chooseNeither
# Merge Resource Groups
@docs merge, mergeMany
# Update Resources
@docs update, updateList, update', updateList', dispatch, integrate, deltaTo, deltaOf
# Program Resources
@docs toProgram
-}
-- TODO: determine cause of the path reversal strangeness in the example.
import Scaffold.App exposing (..)
import Scaffold.Error as Error
import Signal
import Task exposing (Task, andThen, onError)
import Trampoline exposing (Trampoline)
import Dict exposing (Dict)
import Set exposing (Set)
import Lazy.List exposing (LazyList, (+++))
{-| This is a Task which represents some kind of synchronization with optask data. It can also easily
be used for long running arbitrary computations, too. It produces a Gigan Error or a Resource. -}
type alias ResourceTask euser v = Task (ResourcePath, Error.Error euser) (ResourceRef euser v)
{-| This task simplifies routing out for the user. -}
type alias UserTask euser v = Task (Error.Error euser) (Resource euser v)
{-| A reference to a resource, including it's path. -}
type alias ResourceRef euser v =
{ path : ResourcePath, resource : Resource euser v }
{-| Used as the resource path type. -}
type alias ResourcePath = List String
type alias GroupStruct_ euser v =
{ curr : Dict String (Resource euser v)
, chgs : Dict String (Resource euser v)
}
groupStructMap_ f stct =
{ stct | chgs = groupStructMapped_ f stct }
groupStructKeyMap_ f stct =
{ stct | chgs = groupStructKeyMapped_ f stct }
groupStructMapped_ f stct =
groupStructKeyMapped_ (always f) stct
groupStructKeyMapped_ f stct =
let
curr' = groupStructChanged_ stct |> .curr
in
Dict.map f curr'
groupStructChanged_ stct =
{ curr =
Dict.foldl
(\key value -> case value of
Unknown -> Dict.remove key
Group stct -> Dict.insert key (groupStructChanged_ stct |> Group)
_ -> Dict.insert key value)
stct.curr
stct.chgs
, chgs = Dict.empty
}
groupStructMapChange_ f stct =
groupStructChanged_ { stct | chgs = Dict.map (always f) stct.chgs }
groupStructFoldHelper_ foldf f data stct =
foldf f data (groupStructChanged_ stct |> .curr)
groupStructFoldl_ f data stct =
groupStructFoldHelper_ Dict.foldl f data stct
groupStructFoldr_ f data stct =
groupStructFoldHelper_ Dict.foldr f data stct
groupGet_ key stct =
Maybe.oneOf [Dict.get key stct.chgs, Dict.get key stct.curr]
|> Maybe.withDefault Unknown
groupPut_ key value stct =
{ stct | chgs = Dict.insert key value stct.chgs }
groupUpdate_ key op stct =
groupGet_ key stct
|> \value -> groupPut_ key (op value) stct
groupNew_ =
{ curr = Dict.empty
, chgs = Dict.empty
}
{-| A resource item. -}
type Resource euser v =
Unknown
| Pending
-- No such datum exists.
| Void
-- Gives reason as to why this data are still unknown after a retrieval attempt. If a resource
-- enters in to this state, it's time to intervene, whether automatically or with the aid of user
-- feedback of some kind.
| Undecided (Error.Error euser)
-- This is what is done if the result from the optask operation for the data is an error explaining why
-- access to the data was denied.
| Forbidden (Error.Error euser)
-- If a resource is an Operation, then any primitives not suffixed with Now will result in an operation
| Operation (ResourceTask euser v)
-- known value of type v.
| Known v
-- known to be a collection of string keyed v things.
| Group (GroupStruct_ euser v)
{-| True if the resource is unknownResource. -}
isUnknown : Resource euser v -> Bool
isUnknown res =
case res of
Unknown -> True
_ -> False
{-| False if the resource is unknownResource. -}
isNotUnknown : Resource euser v -> Bool
isNotUnknown = isUnknown >> not
{-| True if the resource is pendingResource. -}
isPending : Resource euser v -> Bool
isPending res =
case res of
Pending -> True
_ -> False
{-| False if the resource is pendingResource. -}
isNotPending : Resource euser v -> Bool
isNotPending = isPending >> not
{-| True if the resource is voidResource. -}
isVoid : Resource euser v -> Bool
isVoid res =
case res of
Void -> True
_ -> False
{-| False if the resource is voidResource. -}
isNotVoid : Resource euser v -> Bool
isNotVoid = isVoid >> not
{-| True if the resource is unknownResource or voidResource. -}
isNil : Resource euser v -> Bool
isNil res =
case res of
Unknown -> True
Void -> True
_ -> False
{-| False if the resource is unknownResource or voidResource. -}
isNotNil : Resource euser v -> Bool
isNotNil = isNil >> not
{-| True if the resource is undecidedResource. -}
isUndecided : Resource euser v -> Bool
isUndecided res =
case res of
Undecided _ -> True
_ -> False
{-| False if the resource is undecidedResource. -}
isNotUndecided : Resource euser v -> Bool
isNotUndecided = isUndecided >> not
{-| True if the resource is forbiddenResource. -}
isForbidden : Resource euser v -> Bool
isForbidden res =
case res of
Forbidden _ -> True
_ -> False
{-| False if the resource is forbiddenResource. -}
isNotForbidden : Resource euser v -> Bool
isNotForbidden = isForbidden >> not
{-| True if the resource is a pending operation. -}
isOperation : Resource euser v -> Bool
isOperation res =
case res of
Operation _ -> True
_ -> False
{-| False if the resource is a pending operation. -}
isNotOperation : Resource euser v -> Bool
isNotOperation = isOperation >> not
{-| True if the resource is known. -}
isKnown : Resource euser v -> Bool
isKnown res =
case res of
Known _ -> True
_ -> False
{-| False if the resource is known. -}
isNotKnown : Resource euser v -> Bool
isNotKnown = isKnown >> not
{-| True if the resource is unknownResource. -}
isGroup : Resource euser v -> Bool
isGroup res =
case res of
Group stct -> True
_ -> False
{-| False if the resource is unknownResource. -}
isNotGroup : Resource euser v -> Bool
isNotGroup = isGroup >> not
{-| Create a task which will route the resulting resource to the given path. -}
userTask : UserTask euser v -> ResourceTask euser v
userTask usertask =
usertask
`andThen` (\res -> Task.succeed { resource = res, path = [ ] })
`onError` (\err' -> Task.fail ([ ], err'))
{-| Transform a `ResourceTask` back in to a `UserTask`, which will produce a nested `Resource`
finger reflecting the final path output of the given `ResourceTask`. This output resource can be
treated just like a delta using the `Resource.merge` and `Resource.mergeMany` functions to inject it
in to the working set. -}
deltaTask : ResourceTask euser v -> UserTask euser v
deltaTask optask =
optask
`andThen` (\{resource, path} -> prefixPath path resource |> Task.succeed)
`onError` (\(path', err') -> undecidedResource err' |> prefixPath path' |> Task.succeed)
{-| Convert a `UserTask euser v` in to an `App.ProgramTask bad a` -}
toProgramTask : (Error.Error euser -> List a) -> (Resource euser v -> List a) -> UserTask euser v -> ProgramTask bad a
toProgramTask errorActions resourceActions =
agent
(resourceActions >> agentSuccess)
(errorActions >> agentSuccess)
{-| The equivalent of therefore for ResourceTasks. This allows you to map fetched data to multiple
models with ease, as long as operations which should effect all of the models are all sunk in to
ResourceTasks producing the base model's type. -}
comprehend : (v -> v') -> ResourceTask euser v -> ResourceTask euser v'
comprehend xdcr optask =
optask `andThen` (\ref -> { ref | resource = therefore xdcr ref.resource } |> Task.succeed)
{-| Like `comprehend`, but accounts for the path of the leaves effected by the transformation
by using `therefore'` on the result of the task. This prepends the reference path of the resource
task, such that global context for the resource's location is available if desired.
Note that you may specify a prefix path to the existing one to provide additional context in large
resource group structures.
-}
comprehend' : (ResourcePath -> v -> v') -> ResourceTask euser v -> ResourceTask euser v'
comprehend' xdcr optask =
optask `andThen` (\ref -> { ref | resource = therefore' xdcr ref.path ref.resource } |> Task.succeed)
-- adapter for therefore implementation
comprehendImpl_r : (ResourcePath -> v -> v') -> ResourcePath -> ResourceTask euser v -> ResourceTask euser v'
comprehendImpl_r rxdcr rpath optask =
optask `andThen` (\ref -> { ref | resource = thereforeImpl_r rxdcr (List.reverse ref.path ++ rpath) ref.resource } |> Task.succeed)
{-| Interpret the given `ResourceTask`'s resource output by a given transform function. NOTE that this
can be literally any function whose signature ends in `ResourceTask euser v -> ResourceTask euser v'`,
which is of course inclusive of `ResourceTask euser v -> ResourceTask euser v'` in the case that
`v` is the same type as `v'`. -}
interpret : (Resource euser v -> Resource euser v') -> ResourceTask euser v -> ResourceTask euser v'
interpret f optask =
optask `andThen` (\ref -> { ref | resource = f ref.resource } |> Task.succeed)
{-| Like `interpret`, but the prefix path of the resource is passed to the given function, and the
user can optionally specify their own prefix path. `interpret'` is to `interpret` what `comprehend'`
is to `comprehend`. -}
interpret' : (ResourcePath -> Resource euser v -> Resource euser v') -> ResourcePath -> ResourceTask euser v -> ResourceTask euser v'
interpret' f prepath optask =
optask `andThen` (\ref -> { ref | resource = f (prepath ++ ref.path) ref.resource } |> Task.succeed)
{-| Route the results of a given `ResourceTask` to a given `ResourcePath`. -}
routeTo : ResourcePath -> ResourceTask euser v -> ResourceTask euser v
routeTo path' optask =
optask `andThen` (\ref -> { ref | path = path' } |> Task.succeed)
{-| Provide a decider that turns an error of type `Error.Error euser` in to a resource of `Resource euser v`. -}
catchError : (Error.Error euser -> Resource euser v) -> ResourceTask euser v -> ResourceTask euser v
catchError decider optask =
optask `onError` (\(path', err') -> Task.succeed { path = path', resource = decider err' })
{-| Collapses a resource tree made of group resources in to a single resource of the same type. -}
collapse : (List (ResourcePath, Resource euser v) -> Resource euser v) -> Resource euser v -> Resource euser v
collapse f res =
collapse_ f [] res
collapse_ : (List (ResourcePath, Resource euser v) -> Resource euser v) -> ResourcePath -> Resource euser v -> Resource euser v
collapse_ frecurse rpath res =
let
cfold key res ls = (List.reverse rpath, collapse_ frecurse (key :: rpath) res) :: ls
in
case res of
Group stct -> groupStructFoldr_ cfold [] stct |> frecurse
_ -> res
{-| Flatten the given resource if it is a group to a resource of the same type. Note that unlike
`collapse`, this function does not recursively collapse the entire tree automatically. This grants
a greater degree of flexibility. -}
flatten : (List (String, Resource euser v) -> Resource euser v) -> Resource euser v -> Resource euser v
flatten fgrp res =
let
cfold key res ls = (key, res) :: ls
in
case res of
Group stct -> groupStructFoldr_ cfold [] stct |> fgrp
_ -> res
{-| Variant of `flatten` whose argument function takes a dictionary instead of a list of pairs. -}
flattenDict : (Dict String (Resource euser v) -> Resource euser v) -> Resource euser v -> Resource euser v
flattenDict fgrp res =
case res of
Group stct ->
stct
|> groupStructChanged_
|> .curr
|> fgrp
_ -> res
{-| Use the given function to transform all leaf resources throughout a group structure. This
applies to the result of any pending resource operations. -}
throughout : (Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v
throughout f res =
case res of
Group stct ->
groupStructMap_ (throughout f) stct
|> Group
Operation optask -> Operation (interpret (throughout f) optask)
_ -> f res
{-| Use the given function to transform all leaf resources throughout a group structure. This version
applies the transformation function now, even if the resource is a pending operation. This should be
used in contexts where we are rendering some resulting view of the resources most of the time. -}
throughoutNow : (Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v
throughoutNow f res =
case res of
Group stct ->
groupStructMap_ (throughout f) stct
|> Group
_ -> f res
{-| Given a resource of value type v, create a resource of value type v' by transforming the
known value or group using some function (v -> v'). NOTE that this will create an entirely new
resouce structure, and thus any pending changes will be integrated immediately. If you wish to
preserve deltas for the purpose of mirroring and efficient data flow, then one should be using
deltaTo in order to transform just the changes. -}
therefore : (v -> v') -> Resource euser v -> Resource euser v'
therefore xdcr =
thereforeImpl_r (always xdcr) [ ]
{-| `therefore`, but which includes the current path as the first argument. -}
therefore' : (ResourcePath -> v -> v') -> ResourcePath -> Resource euser v -> Resource euser v'
therefore' xdcr path =
thereforeImpl_r (List.reverse >> xdcr) (List.reverse path)
-- The implementation deals with reversed paths. This is because during path construction, it is
-- obviously more efficient to push path elements to the head of a list. The given reversed path
-- transducer reverses said path, yielding the path itself, and does so once per concrete leaf in
-- the resource group tree structure. This would only result in poor runtime performance in practice
-- in the unlikely case that we have very large deltas which further consist of very deep trees.
-- Since this scenario is highly unlikely and can easily be avoided by design from an engineering
-- standpoint, that theoretical weakness does not have a substantial concrete cost.
thereforeImpl_r : (ResourcePath -> v -> v') -> ResourcePath -> Resource euser v -> Resource euser v'
thereforeImpl_r rxdcr rpath res =
let
stepIn_ key = thereforeImpl_r rxdcr (key :: rpath)
in
case res of
Unknown -> Unknown
Pending -> Pending
Void -> Void
Undecided err' -> Undecided err'
Forbidden err' -> Forbidden err'
Known x' -> Known (rxdcr rpath x')
Operation optask -> Operation (comprehendImpl_r rxdcr rpath optask)
Group stct -> { curr = Dict.empty, chgs = groupStructKeyMapped_ stepIn_ stct } |> Group
{-| DEPRECIATED version of therefore, not supporting type transformation.
NOTE : removed in version 5.
-}
within : (sub -> sub) -> Resource euser sub -> Resource euser sub
within = therefore
{-| Manipulate an item at the given path, or else do nothing if the path does not exist. -}
atPath : (Resource euser v -> Resource euser v) -> ResourcePath -> Resource euser v -> Resource euser v
atPath operation path res =
case path of
[ ] -> operation res
element :: path' ->
case res of
Group stct ->
groupUpdate_ element (atPath operation path') stct
|> Group
_ -> res
{-| Delete the item at the given path. This equivalency holds:
atPath (always unknownResource) path res == deletePath path res
-}
deletePath : ResourcePath -> Resource euser v -> Resource euser v
deletePath = atPath (always Unknown)
{-| Put a resource in to a group resource at the given path. In the case that something is already
there, use the `choice` function to determine which should be used. See the `choose*` family for some
built-in functions. -}
putPath : (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> Resource euser v -> Resource euser v -> Resource euser v
putPath choice path res' res =
prefixPath path res'
|> \res'' -> merge choice res'' res
{-| Equivalent to `putPath chooseLeft`, this is a simple write which will always blindly overwrite the
current resource at the given path. -}
writePath : ResourcePath -> Resource euser v -> Resource euser v -> Resource euser v
writePath = putPath chooseLeft
{-| Move the resource at a given path `path` in the resource group structure to a target path `path'`. -}
movePath : (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> ResourcePath -> Resource euser v -> Resource euser v
movePath = cpPathImpl_ True
{-| Copy the resource at a given path `path` in the resource group structure to a target path `path'`. -}
copyPath : (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> ResourcePath -> Resource euser v -> Resource euser v
copyPath = cpPathImpl_ False
cpPathImpl_ : Bool -> (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> ResourcePath -> Resource euser v -> Resource euser v
cpPathImpl_ bDoMove choice path path' res =
if path /= path' then
putPath choice path' (getPath path res) res
|> \res'' -> if bDoMove then putPath chooseLeft path Unknown res'' else res''
else
res
{-| Collision handler for nested Resources that always chooses the left hand side. -}
chooseLeft : Resource euser v -> Resource euser v -> Resource euser v
chooseLeft x _ = x
{-| Collision handler for nested Resources that always chooses the right hand side. -}
chooseRight : Resource euser v -> Resource euser v -> Resource euser v
chooseRight _ x = x
{-| Collision handler for nested Resources that voids collision keys. -}
chooseVoid : Resource euser v -> Resource euser v -> Resource euser v
chooseVoid _ _ = Void
{-| Collision handler that removes collision keys entirely. -}
chooseNeither : Resource euser v -> Resource euser v -> Resource euser v
chooseNeither _ _ = Unknown
{-| Create a path before the given resource. This has the effect of prefixing whatever is there
whether concrete or a group with the given path. Thus, creating a resource path ["foo", "bar"] and
another at ["foo", "baz"] would result in two resources that can be merged without conflicts
guaranteed because their contents are in the `foo -> bar -> ...` and `foo -> baz -> ...` subtries
respectively. -}
prefixPath : ResourcePath -> Resource euser v -> Resource euser v
prefixPath path res =
List.foldr
(\element res' -> Group (groupPut_ element res' groupNew_))
res
path
{-| Merge can be used to assemble path fingers or existing group structures arbitrarily. A common
usage would be to put many different resources at their own prefix paths, then merge them all by
folding on this if your data structure is odd, otherwise use mergeMany if you are already working
with a list. This takes a choice function that determines the outcome of two different resources
existing at the same path, _at least one of which is concrete and not a group_. Groups merge
automatically with eachother. -}
merge : (Resource euser v -> Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v -> Resource euser v
merge choice left' right' =
-- right' is the current group, left' is what's being merged in.
case (left', right') of
(Group lhs, Group rhs) ->
Dict.foldl
(\key res' rhs' ->
groupGet_ key rhs'
|> \res -> groupPut_ key (merge choice res' res) rhs'
)
rhs
(Dict.union lhs.chgs lhs.curr)
|> Group
(Group lhs, old) ->
choice (Group { curr = Dict.empty, chgs = (Dict.union lhs.chgs lhs.curr) }) old
(_, _) -> choice left' right'
{-| Merge many folds from the left over the given list of resources with merge. -}
mergeMany : (Resource euser v -> Resource euser v -> Resource euser v) -> List (Resource euser v) -> Resource euser v
mergeMany choice gs =
case gs of
g :: gs' ->
List.foldl (merge choice) g gs'
[ ] -> Void
{-| Get the item at the given path. Returns unknownResource if the item _might_ exist, but the hierarchy
does not show knowledge at the fringe (i.e., the fringe is unknown at the last known location in
the path), but may also return voidResource to a path which is known not to exist. For example,
if foo is a resource, then foo/bar cannot be a valid path because foo is not a collection. Pending
will be given in the case that an operation is pending. -}
getPath : ResourcePath -> Resource euser v -> Resource euser v
getPath path res =
case path of
[ ] -> res
element :: path' ->
case res of
Group stct ->
groupGet_ element stct
|> getPath path'
Known x' -> Void
Void -> Void
Pending -> Pending
Operation optask -> Pending
_ -> Unknown
{-| Offer a decision on some `undecidedResource res`. Undecided resource is the result of some
problem which may or may not be in control of the client. Such resource may be the result of
anything that can result in an error in your application. If this resource is an operation, then
the assumption will be applied to the result of that operation. -}
decideBy : (Error.Error euser -> Resource euser v) -> Resource euser v -> Resource euser v
decideBy decider res =
case res of
Undecided err' -> decider err'
Operation optask -> Operation (catchError decider optask)
_ -> res
{-| If some predicate `satisfies` is satisfied by the resource `res`, then we make the following
assumption. If this resource is an operation, then the assumption will be applied to
the result of that operation. -}
assumeIf : (Resource euser v -> Bool) -> v -> Resource euser v -> Resource euser v
assumeIf satisfies assume res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = assumeIf satisfies assume ref.resource } |> Task.succeed))
_ ->
if satisfies res then therefore (always assume) res else res
{-| Negation of assumeIf. -}
assumeIfNot : (Resource euser v -> Bool) -> v -> Resource euser v -> Resource euser v
assumeIfNot satisfies assume res =
assumeIf (satisfies >> not) assume res
{-| If `possibleAssumption` yields some value `value'` when a Resource is applied, then that
value is used to overwrite the resource with an assumption `Known value'`, otherwise the Resource
is unaffected. If this resource is an operation, then the assumption will be applied conditionally
to the result of that operation. -}
assumeInCase : (Resource euser v -> Maybe v) -> Resource euser v -> Resource euser v
assumeInCase possibleAssumption res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = assumeInCase possibleAssumption ref.resource } |> Task.succeed))
_ ->
Maybe.map Known (possibleAssumption res)
|> Maybe.withDefault res
{-| If some predicate `satisfies` is satisfied by the resource `res`, then we make the following
optask. -}
dispatchIf : (Resource euser v -> Bool) -> ResourceTask euser v -> Resource euser v -> Resource euser v
dispatchIf satisfies optask res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = dispatchIf satisfies optask ref.resource } |> Task.succeed))
_ ->
dispatchInCase (if satisfies res then always (Just optask) else always Nothing) res
{-| Negation of dispatchIf -}
dispatchIfNot : (Resource euser v -> Bool) -> ResourceTask euser v -> Resource euser v -> Resource euser v
dispatchIfNot satisfies optask res =
dispatchIf (satisfies >> not) optask res
{-| If `possibleOperation` yields some ResourceTask task `optask` when a Resource is applied, then
the resource is replaced by the resource `operationResource optask`, otherwise the resource is
unaffected. If this resource is an operation, then the result of that operation will be used as
the input to the provided function. In this way, operations can be chained arbitrarily deep,
but in a manner that helpfully abstracts away whether we are still waiting or already have the
result in the composition. -}
dispatchInCase : (Resource euser v -> Maybe (ResourceTask euser v)) -> Resource euser v -> Resource euser v
dispatchInCase possibleOperation res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = dispatchInCase possibleOperation ref.resource } |> Task.succeed))
_ ->
Maybe.map operationResource (possibleOperation res)
|> Maybe.withDefault res
{-| If the predicate is satisfied, apply the given transformation function. If this is a pending
operationResource, then apply deriveIf with the same arguments to the result. -}
deriveIf : (Resource euser v' -> Bool) -> (Resource euser v' -> Resource euser v') -> Resource euser v' -> Resource euser v'
deriveIf satisfies f res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = deriveIf satisfies f ref.resource } |> Task.succeed))
_ ->
deriveIfNow satisfies f res
{-| If the predicate is satisfied, apply the given transformation function. -}
deriveIfNow : (Resource euser v' -> Bool) -> (Resource euser v' -> Resource euser v') -> Resource euser v' -> Resource euser v'
deriveIfNow satisfies f res' =
if satisfies res' then f res' else res'
-- NOTE : These primitives force a reduction now even for an optask operation type
-- convenient conversion to a maybe after all mappings are given. This is intended for use when
-- mapping the state of the content to an actual display.
{-| If a resource is known, then give Just it's value, otherwise Nothing. -}
maybeKnownNow : Resource euser v' -> Maybe v'
maybeKnownNow res' =
case res' of
Known x' -> Just x'
_ -> Nothing
{-| If the predicate is satisfied, replace the resource with some known value. -}
assumeIfNow : (Resource euser v' -> Bool) -> v' -> Resource euser v' -> Resource euser v'
assumeIfNow satisfies assumption res' =
if satisfies res' then Known assumption else res'
{-| This is the counterpart to assumeInCase which does _not_ abstract away whether or not this is
some pending optask operation. Concretely, we want this in the case that we are doing model to view
reductions because a pending operation should still have some concrete visible representation, such
as an ajax loader symbol. Of course, one should still correctly call *Integrate so that an operation
is always a `pendingResource` by the time it gets past the `stage` step. -}
assumeInCaseNow : (Resource euser v' -> Maybe v') -> Resource euser v' -> Resource euser v'
assumeInCaseNow possibleAssumption res' =
Maybe.map Known (possibleAssumption res')
|> Maybe.withDefault res'
{-| -}
dispatchInCaseNow : (Resource euser v -> Maybe (ResourceTask euser v)) -> Resource euser v -> Resource euser v
dispatchInCaseNow possibleOperation res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = dispatchInCase possibleOperation ref.resource } |> Task.succeed))
_ ->
Maybe.map operationResource (possibleOperation res)
|> Maybe.withDefault res
{-| In the event that the given resource is not a simple `defResource`, we replace it with a different simple
resource. -}
otherwise : v' -> Resource euser v' -> v'
otherwise assumption res' =
case res' of
Known x' -> x'
_ -> assumption
{-| -}
unknownResource : Resource euser v
unknownResource = Unknown
{-| -}
pendingResource : Resource euser v
pendingResource = Pending
{-| -}
voidResource : Resource euser v
voidResource = Void
{-| -}
undecidedResource : Error.Error euser -> Resource euser v
undecidedResource = Undecided
{-| -}
forbiddenResource : Error.Error euser -> Resource euser v
forbiddenResource = Forbidden
{-| -}
operationResource : ResourceTask euser v -> Resource euser v
operationResource = Operation
{-| -}
defResource : v -> Resource euser v
defResource = Known
{-| -}
groupResource : List (String, Resource euser v) -> Resource euser v
groupResource members =
Group { curr = Dict.empty, chgs = Dict.fromList members }
{-| -}
resultOr : (Error.Error euser -> Resource euser v) -> Result (Error.Error euser) v -> Resource euser v
resultOr errorResource result =
case result of
Result.Ok data -> defResource data
Result.Err err' -> errorResource err'
{-| -}
maybeOr : Resource euser v -> Maybe v -> Resource euser v
maybeOr nothingResource maybeValue =
Maybe.map Known maybeValue
|> Maybe.withDefault nothingResource
{-| Given some configuration and a resource, produce Just an opaque query task or Nothing
when the resource is an operation or the resource is not an operation respectively. -}
dispatch : Resource euser v -> List (ResourceTask euser v)
dispatch res =
dispatch_ [] res
|> Lazy.List.toList -- crunch to a normal list at top level.
dispatch_ : List String -> Resource euser v -> LazyList (ResourceTask euser v)
dispatch_ rpath res =
case res of
Group stct -> groupStructFoldr_ (\key res' ls -> (dispatch_ (key :: rpath) res') +++ ls) Lazy.List.empty stct
Operation optask ->
Lazy.List.singleton
(routeTo (List.reverse rpath) optask
|> catchError undecidedResource)
_ -> Lazy.List.empty
{-| Update the second `Resource` argument by merging the first argument's delta `Resource`. Chooses
the left `Resource` on a conflict, mechanically speaking. -}
update : Resource euser v -> Resource euser v -> Resource euser v
update = update' chooseLeft
{-| Same as `update`, but apply a list of delta resources sequentially. This resolves all conflicts
by `chooseLeft`, which favors the deltas always. -}
updateList : List (Resource euser v) -> Resource euser v -> Resource euser v
updateList = updateList' chooseLeft
{-| Same as `update`, but pass the given conflict resolution choice function to `merge` instead of
`chooseLeft`, which is the default. This allows one to make a selection as to whether or not the
given delta is still relevant. -}
update' : (Resource euser v -> Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v -> Resource euser v
update' mergeChoice = merge mergeChoice
{-| Same as `updateList`, but uses the provided conflict resolution choice function instead of
`chooseLeft` as in `updateList`. This allows one to make a selection as to whether or not the
given delta is still relevant. -}
updateList' : (Resource euser v -> Resource euser v -> Resource euser v) -> List (Resource euser v) -> Resource euser v -> Resource euser v
updateList' mergeChoice deltas res =
mergeMany (flip mergeChoice) (res :: deltas)
{-| Given some configuration and a resource, produce a pendingResource in the case that the
resource is an operation, otherwise give the same resource. -}
integrate : Resource euser v -> Resource euser v
integrate res =
case res of
Group stct -> groupStructMapChange_ integrate stct |> Group
Operation optask -> Pending
_ -> res
{-| `deltaTo` applies the given transformation function to the pending changes to the
`Resource` structure, producing a partial structure representing only what has changed since the
last call to `integrate`. The resulting partial structure is intended for use as a delta, to be
passed to `update` for some other Resource structure. This results in a simple one-way data binding.
To introduce k-way data binding, one need only use the `interpret` function to transform the
`ResourceTask` output of the subordinate views back in to deltas that transform the origin
`Resource` structure. NOTE that this implies when one wishes for the origin structure to reflect
changes to one of it's subordinates, one must dispatch UserTasks that succeed with the intended
changes. This can be very clean as long as there is a bijection between the origin structure
and each of it's subordinates. The complexity of the mapping is of course dependent on your record
design, so one must still take care. -}
deltaTo : (Resource euser v -> Resource euser v') -> Resource euser v -> Resource euser v'
deltaTo f res =
case res of
Group stct ->
Dict.foldl
(\key res' -> deltaTo f res' |> Dict.insert key)
Dict.empty
stct.chgs
|> \chgs' -> { curr = chgs', chgs = Dict.empty }
|> Group
_ -> f res
{-| Like `deltaTo`, but without the transformation. The following equivalency holds -}
deltaOf : Resource euser v -> Resource euser v
deltaOf = deltaTo identity
{-| Convert a resource to program input. I've found that this is a very un-Elm-like way
of doing things that makes the Elm Architecture harder to stick to. If anyone else finds a
counterexample, please let me know! If it does turn out to be useful, I will complete the set.
NOTE : DEPRECIATED, removed from v5.
-}
toProgram : (b -> ProgramInput a b c bad) -> Resource euser b -> Resource euser (ProgramInput a b c bad)
toProgram modelInput model' = therefore modelInput model'
| true | {--
Copyright (c) 2016, PI:NAME:<NAME>END_PI
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--}
module Scaffold.Resource
(Resource,
ResourceTask, UserTask,
ResourceRef,
ResourcePath,
userTask, deltaTask, toProgramTask,
defResource, forbiddenResource, pendingResource, undecidedResource,
unknownResource, voidResource, operationResource, groupResource,
maybeOr, resultOr,
assumeIf, assumeIfNot, assumeIfNow, assumeInCase, assumeInCaseNow,
dispatchIf, dispatchIfNot, dispatchInCase, dispatchInCaseNow,
deriveIf, deriveIfNow, decideBy, maybeKnownNow, otherwise,
therefore, therefore',
comprehend, comprehend',
interpret, interpret',
within,
throughout, throughoutNow,
flatten, flattenDict, collapse,
routeTo, catchError,
isUnknown, isNotUnknown,
isPending, isNotPending,
isUndecided, isNotUndecided,
isForbidden, isNotForbidden,
isVoid, isNotVoid,
isNil, isNotNil,
isKnown, isNotKnown,
isOperation, isNotOperation,
isGroup, isNotGroup,
prefixPath,
atPath,
putPath,
getPath,
deletePath,
writePath,
movePath,
copyPath,
chooseLeft,
chooseRight,
chooseVoid,
chooseNeither,
merge, mergeMany,
update, updateList,
update', updateList',
dispatch, integrate,
deltaTo, deltaOf,
toProgram)
where
{-| Resource system.
# Types
@docs Resource, ResourceTask, ResourceRef, ResourcePath, UserTask
# Define Resources
@docs defResource, forbiddenResource, pendingResource, undecidedResource, unknownResource, voidResource, operationResource, groupResource
# Interpret `Maybe` or `Result` as Resources
@docs maybeOr, resultOr
# Conditional Assumptions
@docs assumeIf, assumeIfNot, assumeIfNow, assumeInCase, assumeInCaseNow
# Conditional Derivations
`deriveIf` and `deriveIfNow` are given as more flexible and readable versions of `assumeInCase`
and `assumeInCaseNow`. Neither muddies the waters with the Maybe type, and the transformation
can be any `Resource euser v -> Resource euser v`, which makes these highly nestable by comparison
to their respective older counterparts.
@docs deriveIf, deriveIfNow
# Resource Output
@docs otherwise, maybeKnownNow
# Bulk Operations
@docs decideBy, flatten, flattenDict, collapse, throughout, throughoutNow, therefore, therefore', within
# Handling `UserTask` and `ResourceTask`
@docs userTask, deltaTask, toProgramTask, comprehend, comprehend', interpret, interpret', routeTo, catchError
# Conditional Operations
@docs dispatchIf, dispatchIfNot, dispatchInCase, dispatchInCaseNow
# Resource Introspection Predicates
@docs isUnknown, isNotUnknown, isPending, isNotPending, isUndecided, isNotUndecided, isForbidden, isNotForbidden, isVoid, isNotVoid, isNil, isNotNil, isKnown, isNotKnown, isOperation, isNotOperation, isGroup, isNotGroup
# Manipulate and Use `ResourcePath`
@docs prefixPath, atPath, putPath, getPath, deletePath, writePath, movePath, copyPath
# Built-in Conflict Operators
For use with `merge` and `mergeMany`.
@docs chooseLeft, chooseRight, chooseVoid, chooseNeither
# Merge Resource Groups
@docs merge, mergeMany
# Update Resources
@docs update, updateList, update', updateList', dispatch, integrate, deltaTo, deltaOf
# Program Resources
@docs toProgram
-}
-- TODO: determine cause of the path reversal strangeness in the example.
import Scaffold.App exposing (..)
import Scaffold.Error as Error
import Signal
import Task exposing (Task, andThen, onError)
import Trampoline exposing (Trampoline)
import Dict exposing (Dict)
import Set exposing (Set)
import Lazy.List exposing (LazyList, (+++))
{-| This is a Task which represents some kind of synchronization with optask data. It can also easily
be used for long running arbitrary computations, too. It produces a Gigan Error or a Resource. -}
type alias ResourceTask euser v = Task (ResourcePath, Error.Error euser) (ResourceRef euser v)
{-| This task simplifies routing out for the user. -}
type alias UserTask euser v = Task (Error.Error euser) (Resource euser v)
{-| A reference to a resource, including it's path. -}
type alias ResourceRef euser v =
{ path : ResourcePath, resource : Resource euser v }
{-| Used as the resource path type. -}
type alias ResourcePath = List String
type alias GroupStruct_ euser v =
{ curr : Dict String (Resource euser v)
, chgs : Dict String (Resource euser v)
}
groupStructMap_ f stct =
{ stct | chgs = groupStructMapped_ f stct }
groupStructKeyMap_ f stct =
{ stct | chgs = groupStructKeyMapped_ f stct }
groupStructMapped_ f stct =
groupStructKeyMapped_ (always f) stct
groupStructKeyMapped_ f stct =
let
curr' = groupStructChanged_ stct |> .curr
in
Dict.map f curr'
groupStructChanged_ stct =
{ curr =
Dict.foldl
(\key value -> case value of
Unknown -> Dict.remove key
Group stct -> Dict.insert key (groupStructChanged_ stct |> Group)
_ -> Dict.insert key value)
stct.curr
stct.chgs
, chgs = Dict.empty
}
groupStructMapChange_ f stct =
groupStructChanged_ { stct | chgs = Dict.map (always f) stct.chgs }
groupStructFoldHelper_ foldf f data stct =
foldf f data (groupStructChanged_ stct |> .curr)
groupStructFoldl_ f data stct =
groupStructFoldHelper_ Dict.foldl f data stct
groupStructFoldr_ f data stct =
groupStructFoldHelper_ Dict.foldr f data stct
groupGet_ key stct =
Maybe.oneOf [Dict.get key stct.chgs, Dict.get key stct.curr]
|> Maybe.withDefault Unknown
groupPut_ key value stct =
{ stct | chgs = Dict.insert key value stct.chgs }
groupUpdate_ key op stct =
groupGet_ key stct
|> \value -> groupPut_ key (op value) stct
groupNew_ =
{ curr = Dict.empty
, chgs = Dict.empty
}
{-| A resource item. -}
type Resource euser v =
Unknown
| Pending
-- No such datum exists.
| Void
-- Gives reason as to why this data are still unknown after a retrieval attempt. If a resource
-- enters in to this state, it's time to intervene, whether automatically or with the aid of user
-- feedback of some kind.
| Undecided (Error.Error euser)
-- This is what is done if the result from the optask operation for the data is an error explaining why
-- access to the data was denied.
| Forbidden (Error.Error euser)
-- If a resource is an Operation, then any primitives not suffixed with Now will result in an operation
| Operation (ResourceTask euser v)
-- known value of type v.
| Known v
-- known to be a collection of string keyed v things.
| Group (GroupStruct_ euser v)
{-| True if the resource is unknownResource. -}
isUnknown : Resource euser v -> Bool
isUnknown res =
case res of
Unknown -> True
_ -> False
{-| False if the resource is unknownResource. -}
isNotUnknown : Resource euser v -> Bool
isNotUnknown = isUnknown >> not
{-| True if the resource is pendingResource. -}
isPending : Resource euser v -> Bool
isPending res =
case res of
Pending -> True
_ -> False
{-| False if the resource is pendingResource. -}
isNotPending : Resource euser v -> Bool
isNotPending = isPending >> not
{-| True if the resource is voidResource. -}
isVoid : Resource euser v -> Bool
isVoid res =
case res of
Void -> True
_ -> False
{-| False if the resource is voidResource. -}
isNotVoid : Resource euser v -> Bool
isNotVoid = isVoid >> not
{-| True if the resource is unknownResource or voidResource. -}
isNil : Resource euser v -> Bool
isNil res =
case res of
Unknown -> True
Void -> True
_ -> False
{-| False if the resource is unknownResource or voidResource. -}
isNotNil : Resource euser v -> Bool
isNotNil = isNil >> not
{-| True if the resource is undecidedResource. -}
isUndecided : Resource euser v -> Bool
isUndecided res =
case res of
Undecided _ -> True
_ -> False
{-| False if the resource is undecidedResource. -}
isNotUndecided : Resource euser v -> Bool
isNotUndecided = isUndecided >> not
{-| True if the resource is forbiddenResource. -}
isForbidden : Resource euser v -> Bool
isForbidden res =
case res of
Forbidden _ -> True
_ -> False
{-| False if the resource is forbiddenResource. -}
isNotForbidden : Resource euser v -> Bool
isNotForbidden = isForbidden >> not
{-| True if the resource is a pending operation. -}
isOperation : Resource euser v -> Bool
isOperation res =
case res of
Operation _ -> True
_ -> False
{-| False if the resource is a pending operation. -}
isNotOperation : Resource euser v -> Bool
isNotOperation = isOperation >> not
{-| True if the resource is known. -}
isKnown : Resource euser v -> Bool
isKnown res =
case res of
Known _ -> True
_ -> False
{-| False if the resource is known. -}
isNotKnown : Resource euser v -> Bool
isNotKnown = isKnown >> not
{-| True if the resource is unknownResource. -}
isGroup : Resource euser v -> Bool
isGroup res =
case res of
Group stct -> True
_ -> False
{-| False if the resource is unknownResource. -}
isNotGroup : Resource euser v -> Bool
isNotGroup = isGroup >> not
{-| Create a task which will route the resulting resource to the given path. -}
userTask : UserTask euser v -> ResourceTask euser v
userTask usertask =
usertask
`andThen` (\res -> Task.succeed { resource = res, path = [ ] })
`onError` (\err' -> Task.fail ([ ], err'))
{-| Transform a `ResourceTask` back in to a `UserTask`, which will produce a nested `Resource`
finger reflecting the final path output of the given `ResourceTask`. This output resource can be
treated just like a delta using the `Resource.merge` and `Resource.mergeMany` functions to inject it
in to the working set. -}
deltaTask : ResourceTask euser v -> UserTask euser v
deltaTask optask =
optask
`andThen` (\{resource, path} -> prefixPath path resource |> Task.succeed)
`onError` (\(path', err') -> undecidedResource err' |> prefixPath path' |> Task.succeed)
{-| Convert a `UserTask euser v` in to an `App.ProgramTask bad a` -}
toProgramTask : (Error.Error euser -> List a) -> (Resource euser v -> List a) -> UserTask euser v -> ProgramTask bad a
toProgramTask errorActions resourceActions =
agent
(resourceActions >> agentSuccess)
(errorActions >> agentSuccess)
{-| The equivalent of therefore for ResourceTasks. This allows you to map fetched data to multiple
models with ease, as long as operations which should effect all of the models are all sunk in to
ResourceTasks producing the base model's type. -}
comprehend : (v -> v') -> ResourceTask euser v -> ResourceTask euser v'
comprehend xdcr optask =
optask `andThen` (\ref -> { ref | resource = therefore xdcr ref.resource } |> Task.succeed)
{-| Like `comprehend`, but accounts for the path of the leaves effected by the transformation
by using `therefore'` on the result of the task. This prepends the reference path of the resource
task, such that global context for the resource's location is available if desired.
Note that you may specify a prefix path to the existing one to provide additional context in large
resource group structures.
-}
comprehend' : (ResourcePath -> v -> v') -> ResourceTask euser v -> ResourceTask euser v'
comprehend' xdcr optask =
optask `andThen` (\ref -> { ref | resource = therefore' xdcr ref.path ref.resource } |> Task.succeed)
-- adapter for therefore implementation
comprehendImpl_r : (ResourcePath -> v -> v') -> ResourcePath -> ResourceTask euser v -> ResourceTask euser v'
comprehendImpl_r rxdcr rpath optask =
optask `andThen` (\ref -> { ref | resource = thereforeImpl_r rxdcr (List.reverse ref.path ++ rpath) ref.resource } |> Task.succeed)
{-| Interpret the given `ResourceTask`'s resource output by a given transform function. NOTE that this
can be literally any function whose signature ends in `ResourceTask euser v -> ResourceTask euser v'`,
which is of course inclusive of `ResourceTask euser v -> ResourceTask euser v'` in the case that
`v` is the same type as `v'`. -}
interpret : (Resource euser v -> Resource euser v') -> ResourceTask euser v -> ResourceTask euser v'
interpret f optask =
optask `andThen` (\ref -> { ref | resource = f ref.resource } |> Task.succeed)
{-| Like `interpret`, but the prefix path of the resource is passed to the given function, and the
user can optionally specify their own prefix path. `interpret'` is to `interpret` what `comprehend'`
is to `comprehend`. -}
interpret' : (ResourcePath -> Resource euser v -> Resource euser v') -> ResourcePath -> ResourceTask euser v -> ResourceTask euser v'
interpret' f prepath optask =
optask `andThen` (\ref -> { ref | resource = f (prepath ++ ref.path) ref.resource } |> Task.succeed)
{-| Route the results of a given `ResourceTask` to a given `ResourcePath`. -}
routeTo : ResourcePath -> ResourceTask euser v -> ResourceTask euser v
routeTo path' optask =
optask `andThen` (\ref -> { ref | path = path' } |> Task.succeed)
{-| Provide a decider that turns an error of type `Error.Error euser` in to a resource of `Resource euser v`. -}
catchError : (Error.Error euser -> Resource euser v) -> ResourceTask euser v -> ResourceTask euser v
catchError decider optask =
optask `onError` (\(path', err') -> Task.succeed { path = path', resource = decider err' })
{-| Collapses a resource tree made of group resources in to a single resource of the same type. -}
collapse : (List (ResourcePath, Resource euser v) -> Resource euser v) -> Resource euser v -> Resource euser v
collapse f res =
collapse_ f [] res
collapse_ : (List (ResourcePath, Resource euser v) -> Resource euser v) -> ResourcePath -> Resource euser v -> Resource euser v
collapse_ frecurse rpath res =
let
cfold key res ls = (List.reverse rpath, collapse_ frecurse (key :: rpath) res) :: ls
in
case res of
Group stct -> groupStructFoldr_ cfold [] stct |> frecurse
_ -> res
{-| Flatten the given resource if it is a group to a resource of the same type. Note that unlike
`collapse`, this function does not recursively collapse the entire tree automatically. This grants
a greater degree of flexibility. -}
flatten : (List (String, Resource euser v) -> Resource euser v) -> Resource euser v -> Resource euser v
flatten fgrp res =
let
cfold key res ls = (key, res) :: ls
in
case res of
Group stct -> groupStructFoldr_ cfold [] stct |> fgrp
_ -> res
{-| Variant of `flatten` whose argument function takes a dictionary instead of a list of pairs. -}
flattenDict : (Dict String (Resource euser v) -> Resource euser v) -> Resource euser v -> Resource euser v
flattenDict fgrp res =
case res of
Group stct ->
stct
|> groupStructChanged_
|> .curr
|> fgrp
_ -> res
{-| Use the given function to transform all leaf resources throughout a group structure. This
applies to the result of any pending resource operations. -}
throughout : (Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v
throughout f res =
case res of
Group stct ->
groupStructMap_ (throughout f) stct
|> Group
Operation optask -> Operation (interpret (throughout f) optask)
_ -> f res
{-| Use the given function to transform all leaf resources throughout a group structure. This version
applies the transformation function now, even if the resource is a pending operation. This should be
used in contexts where we are rendering some resulting view of the resources most of the time. -}
throughoutNow : (Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v
throughoutNow f res =
case res of
Group stct ->
groupStructMap_ (throughout f) stct
|> Group
_ -> f res
{-| Given a resource of value type v, create a resource of value type v' by transforming the
known value or group using some function (v -> v'). NOTE that this will create an entirely new
resouce structure, and thus any pending changes will be integrated immediately. If you wish to
preserve deltas for the purpose of mirroring and efficient data flow, then one should be using
deltaTo in order to transform just the changes. -}
therefore : (v -> v') -> Resource euser v -> Resource euser v'
therefore xdcr =
thereforeImpl_r (always xdcr) [ ]
{-| `therefore`, but which includes the current path as the first argument. -}
therefore' : (ResourcePath -> v -> v') -> ResourcePath -> Resource euser v -> Resource euser v'
therefore' xdcr path =
thereforeImpl_r (List.reverse >> xdcr) (List.reverse path)
-- The implementation deals with reversed paths. This is because during path construction, it is
-- obviously more efficient to push path elements to the head of a list. The given reversed path
-- transducer reverses said path, yielding the path itself, and does so once per concrete leaf in
-- the resource group tree structure. This would only result in poor runtime performance in practice
-- in the unlikely case that we have very large deltas which further consist of very deep trees.
-- Since this scenario is highly unlikely and can easily be avoided by design from an engineering
-- standpoint, that theoretical weakness does not have a substantial concrete cost.
thereforeImpl_r : (ResourcePath -> v -> v') -> ResourcePath -> Resource euser v -> Resource euser v'
thereforeImpl_r rxdcr rpath res =
let
stepIn_ key = thereforeImpl_r rxdcr (key :: rpath)
in
case res of
Unknown -> Unknown
Pending -> Pending
Void -> Void
Undecided err' -> Undecided err'
Forbidden err' -> Forbidden err'
Known x' -> Known (rxdcr rpath x')
Operation optask -> Operation (comprehendImpl_r rxdcr rpath optask)
Group stct -> { curr = Dict.empty, chgs = groupStructKeyMapped_ stepIn_ stct } |> Group
{-| DEPRECIATED version of therefore, not supporting type transformation.
NOTE : removed in version 5.
-}
within : (sub -> sub) -> Resource euser sub -> Resource euser sub
within = therefore
{-| Manipulate an item at the given path, or else do nothing if the path does not exist. -}
atPath : (Resource euser v -> Resource euser v) -> ResourcePath -> Resource euser v -> Resource euser v
atPath operation path res =
case path of
[ ] -> operation res
element :: path' ->
case res of
Group stct ->
groupUpdate_ element (atPath operation path') stct
|> Group
_ -> res
{-| Delete the item at the given path. This equivalency holds:
atPath (always unknownResource) path res == deletePath path res
-}
deletePath : ResourcePath -> Resource euser v -> Resource euser v
deletePath = atPath (always Unknown)
{-| Put a resource in to a group resource at the given path. In the case that something is already
there, use the `choice` function to determine which should be used. See the `choose*` family for some
built-in functions. -}
putPath : (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> Resource euser v -> Resource euser v -> Resource euser v
putPath choice path res' res =
prefixPath path res'
|> \res'' -> merge choice res'' res
{-| Equivalent to `putPath chooseLeft`, this is a simple write which will always blindly overwrite the
current resource at the given path. -}
writePath : ResourcePath -> Resource euser v -> Resource euser v -> Resource euser v
writePath = putPath chooseLeft
{-| Move the resource at a given path `path` in the resource group structure to a target path `path'`. -}
movePath : (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> ResourcePath -> Resource euser v -> Resource euser v
movePath = cpPathImpl_ True
{-| Copy the resource at a given path `path` in the resource group structure to a target path `path'`. -}
copyPath : (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> ResourcePath -> Resource euser v -> Resource euser v
copyPath = cpPathImpl_ False
cpPathImpl_ : Bool -> (Resource euser v -> Resource euser v -> Resource euser v) -> ResourcePath -> ResourcePath -> Resource euser v -> Resource euser v
cpPathImpl_ bDoMove choice path path' res =
if path /= path' then
putPath choice path' (getPath path res) res
|> \res'' -> if bDoMove then putPath chooseLeft path Unknown res'' else res''
else
res
{-| Collision handler for nested Resources that always chooses the left hand side. -}
chooseLeft : Resource euser v -> Resource euser v -> Resource euser v
chooseLeft x _ = x
{-| Collision handler for nested Resources that always chooses the right hand side. -}
chooseRight : Resource euser v -> Resource euser v -> Resource euser v
chooseRight _ x = x
{-| Collision handler for nested Resources that voids collision keys. -}
chooseVoid : Resource euser v -> Resource euser v -> Resource euser v
chooseVoid _ _ = Void
{-| Collision handler that removes collision keys entirely. -}
chooseNeither : Resource euser v -> Resource euser v -> Resource euser v
chooseNeither _ _ = Unknown
{-| Create a path before the given resource. This has the effect of prefixing whatever is there
whether concrete or a group with the given path. Thus, creating a resource path ["foo", "bar"] and
another at ["foo", "baz"] would result in two resources that can be merged without conflicts
guaranteed because their contents are in the `foo -> bar -> ...` and `foo -> baz -> ...` subtries
respectively. -}
prefixPath : ResourcePath -> Resource euser v -> Resource euser v
prefixPath path res =
List.foldr
(\element res' -> Group (groupPut_ element res' groupNew_))
res
path
{-| Merge can be used to assemble path fingers or existing group structures arbitrarily. A common
usage would be to put many different resources at their own prefix paths, then merge them all by
folding on this if your data structure is odd, otherwise use mergeMany if you are already working
with a list. This takes a choice function that determines the outcome of two different resources
existing at the same path, _at least one of which is concrete and not a group_. Groups merge
automatically with eachother. -}
merge : (Resource euser v -> Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v -> Resource euser v
merge choice left' right' =
-- right' is the current group, left' is what's being merged in.
case (left', right') of
(Group lhs, Group rhs) ->
Dict.foldl
(\key res' rhs' ->
groupGet_ key rhs'
|> \res -> groupPut_ key (merge choice res' res) rhs'
)
rhs
(Dict.union lhs.chgs lhs.curr)
|> Group
(Group lhs, old) ->
choice (Group { curr = Dict.empty, chgs = (Dict.union lhs.chgs lhs.curr) }) old
(_, _) -> choice left' right'
{-| Merge many folds from the left over the given list of resources with merge. -}
mergeMany : (Resource euser v -> Resource euser v -> Resource euser v) -> List (Resource euser v) -> Resource euser v
mergeMany choice gs =
case gs of
g :: gs' ->
List.foldl (merge choice) g gs'
[ ] -> Void
{-| Get the item at the given path. Returns unknownResource if the item _might_ exist, but the hierarchy
does not show knowledge at the fringe (i.e., the fringe is unknown at the last known location in
the path), but may also return voidResource to a path which is known not to exist. For example,
if foo is a resource, then foo/bar cannot be a valid path because foo is not a collection. Pending
will be given in the case that an operation is pending. -}
getPath : ResourcePath -> Resource euser v -> Resource euser v
getPath path res =
case path of
[ ] -> res
element :: path' ->
case res of
Group stct ->
groupGet_ element stct
|> getPath path'
Known x' -> Void
Void -> Void
Pending -> Pending
Operation optask -> Pending
_ -> Unknown
{-| Offer a decision on some `undecidedResource res`. Undecided resource is the result of some
problem which may or may not be in control of the client. Such resource may be the result of
anything that can result in an error in your application. If this resource is an operation, then
the assumption will be applied to the result of that operation. -}
decideBy : (Error.Error euser -> Resource euser v) -> Resource euser v -> Resource euser v
decideBy decider res =
case res of
Undecided err' -> decider err'
Operation optask -> Operation (catchError decider optask)
_ -> res
{-| If some predicate `satisfies` is satisfied by the resource `res`, then we make the following
assumption. If this resource is an operation, then the assumption will be applied to
the result of that operation. -}
assumeIf : (Resource euser v -> Bool) -> v -> Resource euser v -> Resource euser v
assumeIf satisfies assume res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = assumeIf satisfies assume ref.resource } |> Task.succeed))
_ ->
if satisfies res then therefore (always assume) res else res
{-| Negation of assumeIf. -}
assumeIfNot : (Resource euser v -> Bool) -> v -> Resource euser v -> Resource euser v
assumeIfNot satisfies assume res =
assumeIf (satisfies >> not) assume res
{-| If `possibleAssumption` yields some value `value'` when a Resource is applied, then that
value is used to overwrite the resource with an assumption `Known value'`, otherwise the Resource
is unaffected. If this resource is an operation, then the assumption will be applied conditionally
to the result of that operation. -}
assumeInCase : (Resource euser v -> Maybe v) -> Resource euser v -> Resource euser v
assumeInCase possibleAssumption res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = assumeInCase possibleAssumption ref.resource } |> Task.succeed))
_ ->
Maybe.map Known (possibleAssumption res)
|> Maybe.withDefault res
{-| If some predicate `satisfies` is satisfied by the resource `res`, then we make the following
optask. -}
dispatchIf : (Resource euser v -> Bool) -> ResourceTask euser v -> Resource euser v -> Resource euser v
dispatchIf satisfies optask res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = dispatchIf satisfies optask ref.resource } |> Task.succeed))
_ ->
dispatchInCase (if satisfies res then always (Just optask) else always Nothing) res
{-| Negation of dispatchIf -}
dispatchIfNot : (Resource euser v -> Bool) -> ResourceTask euser v -> Resource euser v -> Resource euser v
dispatchIfNot satisfies optask res =
dispatchIf (satisfies >> not) optask res
{-| If `possibleOperation` yields some ResourceTask task `optask` when a Resource is applied, then
the resource is replaced by the resource `operationResource optask`, otherwise the resource is
unaffected. If this resource is an operation, then the result of that operation will be used as
the input to the provided function. In this way, operations can be chained arbitrarily deep,
but in a manner that helpfully abstracts away whether we are still waiting or already have the
result in the composition. -}
dispatchInCase : (Resource euser v -> Maybe (ResourceTask euser v)) -> Resource euser v -> Resource euser v
dispatchInCase possibleOperation res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = dispatchInCase possibleOperation ref.resource } |> Task.succeed))
_ ->
Maybe.map operationResource (possibleOperation res)
|> Maybe.withDefault res
{-| If the predicate is satisfied, apply the given transformation function. If this is a pending
operationResource, then apply deriveIf with the same arguments to the result. -}
deriveIf : (Resource euser v' -> Bool) -> (Resource euser v' -> Resource euser v') -> Resource euser v' -> Resource euser v'
deriveIf satisfies f res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = deriveIf satisfies f ref.resource } |> Task.succeed))
_ ->
deriveIfNow satisfies f res
{-| If the predicate is satisfied, apply the given transformation function. -}
deriveIfNow : (Resource euser v' -> Bool) -> (Resource euser v' -> Resource euser v') -> Resource euser v' -> Resource euser v'
deriveIfNow satisfies f res' =
if satisfies res' then f res' else res'
-- NOTE : These primitives force a reduction now even for an optask operation type
-- convenient conversion to a maybe after all mappings are given. This is intended for use when
-- mapping the state of the content to an actual display.
{-| If a resource is known, then give Just it's value, otherwise Nothing. -}
maybeKnownNow : Resource euser v' -> Maybe v'
maybeKnownNow res' =
case res' of
Known x' -> Just x'
_ -> Nothing
{-| If the predicate is satisfied, replace the resource with some known value. -}
assumeIfNow : (Resource euser v' -> Bool) -> v' -> Resource euser v' -> Resource euser v'
assumeIfNow satisfies assumption res' =
if satisfies res' then Known assumption else res'
{-| This is the counterpart to assumeInCase which does _not_ abstract away whether or not this is
some pending optask operation. Concretely, we want this in the case that we are doing model to view
reductions because a pending operation should still have some concrete visible representation, such
as an ajax loader symbol. Of course, one should still correctly call *Integrate so that an operation
is always a `pendingResource` by the time it gets past the `stage` step. -}
assumeInCaseNow : (Resource euser v' -> Maybe v') -> Resource euser v' -> Resource euser v'
assumeInCaseNow possibleAssumption res' =
Maybe.map Known (possibleAssumption res')
|> Maybe.withDefault res'
{-| -}
dispatchInCaseNow : (Resource euser v -> Maybe (ResourceTask euser v)) -> Resource euser v -> Resource euser v
dispatchInCaseNow possibleOperation res =
case res of
Operation optask ->
Operation (optask
`andThen` (\ref -> { ref | resource = dispatchInCase possibleOperation ref.resource } |> Task.succeed))
_ ->
Maybe.map operationResource (possibleOperation res)
|> Maybe.withDefault res
{-| In the event that the given resource is not a simple `defResource`, we replace it with a different simple
resource. -}
otherwise : v' -> Resource euser v' -> v'
otherwise assumption res' =
case res' of
Known x' -> x'
_ -> assumption
{-| -}
unknownResource : Resource euser v
unknownResource = Unknown
{-| -}
pendingResource : Resource euser v
pendingResource = Pending
{-| -}
voidResource : Resource euser v
voidResource = Void
{-| -}
undecidedResource : Error.Error euser -> Resource euser v
undecidedResource = Undecided
{-| -}
forbiddenResource : Error.Error euser -> Resource euser v
forbiddenResource = Forbidden
{-| -}
operationResource : ResourceTask euser v -> Resource euser v
operationResource = Operation
{-| -}
defResource : v -> Resource euser v
defResource = Known
{-| -}
groupResource : List (String, Resource euser v) -> Resource euser v
groupResource members =
Group { curr = Dict.empty, chgs = Dict.fromList members }
{-| -}
resultOr : (Error.Error euser -> Resource euser v) -> Result (Error.Error euser) v -> Resource euser v
resultOr errorResource result =
case result of
Result.Ok data -> defResource data
Result.Err err' -> errorResource err'
{-| -}
maybeOr : Resource euser v -> Maybe v -> Resource euser v
maybeOr nothingResource maybeValue =
Maybe.map Known maybeValue
|> Maybe.withDefault nothingResource
{-| Given some configuration and a resource, produce Just an opaque query task or Nothing
when the resource is an operation or the resource is not an operation respectively. -}
dispatch : Resource euser v -> List (ResourceTask euser v)
dispatch res =
dispatch_ [] res
|> Lazy.List.toList -- crunch to a normal list at top level.
dispatch_ : List String -> Resource euser v -> LazyList (ResourceTask euser v)
dispatch_ rpath res =
case res of
Group stct -> groupStructFoldr_ (\key res' ls -> (dispatch_ (key :: rpath) res') +++ ls) Lazy.List.empty stct
Operation optask ->
Lazy.List.singleton
(routeTo (List.reverse rpath) optask
|> catchError undecidedResource)
_ -> Lazy.List.empty
{-| Update the second `Resource` argument by merging the first argument's delta `Resource`. Chooses
the left `Resource` on a conflict, mechanically speaking. -}
update : Resource euser v -> Resource euser v -> Resource euser v
update = update' chooseLeft
{-| Same as `update`, but apply a list of delta resources sequentially. This resolves all conflicts
by `chooseLeft`, which favors the deltas always. -}
updateList : List (Resource euser v) -> Resource euser v -> Resource euser v
updateList = updateList' chooseLeft
{-| Same as `update`, but pass the given conflict resolution choice function to `merge` instead of
`chooseLeft`, which is the default. This allows one to make a selection as to whether or not the
given delta is still relevant. -}
update' : (Resource euser v -> Resource euser v -> Resource euser v) -> Resource euser v -> Resource euser v -> Resource euser v
update' mergeChoice = merge mergeChoice
{-| Same as `updateList`, but uses the provided conflict resolution choice function instead of
`chooseLeft` as in `updateList`. This allows one to make a selection as to whether or not the
given delta is still relevant. -}
updateList' : (Resource euser v -> Resource euser v -> Resource euser v) -> List (Resource euser v) -> Resource euser v -> Resource euser v
updateList' mergeChoice deltas res =
mergeMany (flip mergeChoice) (res :: deltas)
{-| Given some configuration and a resource, produce a pendingResource in the case that the
resource is an operation, otherwise give the same resource. -}
integrate : Resource euser v -> Resource euser v
integrate res =
case res of
Group stct -> groupStructMapChange_ integrate stct |> Group
Operation optask -> Pending
_ -> res
{-| `deltaTo` applies the given transformation function to the pending changes to the
`Resource` structure, producing a partial structure representing only what has changed since the
last call to `integrate`. The resulting partial structure is intended for use as a delta, to be
passed to `update` for some other Resource structure. This results in a simple one-way data binding.
To introduce k-way data binding, one need only use the `interpret` function to transform the
`ResourceTask` output of the subordinate views back in to deltas that transform the origin
`Resource` structure. NOTE that this implies when one wishes for the origin structure to reflect
changes to one of it's subordinates, one must dispatch UserTasks that succeed with the intended
changes. This can be very clean as long as there is a bijection between the origin structure
and each of it's subordinates. The complexity of the mapping is of course dependent on your record
design, so one must still take care. -}
deltaTo : (Resource euser v -> Resource euser v') -> Resource euser v -> Resource euser v'
deltaTo f res =
case res of
Group stct ->
Dict.foldl
(\key res' -> deltaTo f res' |> Dict.insert key)
Dict.empty
stct.chgs
|> \chgs' -> { curr = chgs', chgs = Dict.empty }
|> Group
_ -> f res
{-| Like `deltaTo`, but without the transformation. The following equivalency holds -}
deltaOf : Resource euser v -> Resource euser v
deltaOf = deltaTo identity
{-| Convert a resource to program input. I've found that this is a very un-Elm-like way
of doing things that makes the Elm Architecture harder to stick to. If anyone else finds a
counterexample, please let me know! If it does turn out to be useful, I will complete the set.
NOTE : DEPRECIATED, removed from v5.
-}
toProgram : (b -> ProgramInput a b c bad) -> Resource euser b -> Resource euser (ProgramInput a b c bad)
toProgram modelInput model' = therefore modelInput model'
| elm |
[
{
"context": "heme.Type exposing (Theme, toCss)\n\n\n\n{-\n Author: Baransu (https://github.com/Baransu)\n Atom One Dark ins",
"end": 256,
"score": 0.9679152369,
"start": 249,
"tag": "NAME",
"value": "Baransu"
},
{
"context": "Css)\n\n\n\n{-\n Author: Baransu (https://github.com/Baransu)\n Atom One Dark inspired theme\n https://githu",
"end": 284,
"score": 0.9996786118,
"start": 277,
"tag": "USERNAME",
"value": "Baransu"
},
{
"context": "tom One Dark inspired theme\n https://github.com/atom/one-dark-syntax\n\n base: #282c34\n mono-1: ",
"end": 344,
"score": 0.7863406539,
"start": 340,
"tag": "USERNAME",
"value": "atom"
}
] | externals/elm-syntax-highlight/src/SyntaxHighlight/Theme/OneDark.elm | calvinmd/lever-components | 71 | module SyntaxHighlight.Theme.OneDark exposing (css, theme)
import SyntaxHighlight.Style exposing (Color(..), RequiredStyles, backgroundColor, italic, noEmphasis, textColor)
import SyntaxHighlight.Theme.Type exposing (Theme, toCss)
{-
Author: Baransu (https://github.com/Baransu)
Atom One Dark inspired theme
https://github.com/atom/one-dark-syntax
base: #282c34
mono-1: #abb2bf
mono-2: #818896
mono-3: #5c6370
hue-1: #56b6c2
hue-2: #61aeee
hue-3: #c678dd
hue-4: #98c379
hue-5: #e06c75
hue-5-2: #be5046
hue-6: #d19a66
hue-6-2: #e6c07b
-}
css : String
css =
toCss theme
theme : Theme
theme =
{ requiredStyles = requiredStyles
, customStyles = []
}
requiredStyles : RequiredStyles
requiredStyles =
{ default = noEmphasis (Hex "#abb2bf") (Hex "#282c34")
, highlight = backgroundColor (Rgba 229 231 235 0.1)
, addition = backgroundColor (Rgba 40 124 82 0.4)
, deletion = backgroundColor (Rgba 136 64 67 0.4)
, comment = textColor (Hex "#5c6370") |> italic
, style1 = textColor (Hex "#d19a66")
, style2 = textColor (Hex "#98c379")
, style3 = textColor (Hex "#c678dd")
, style4 = textColor (Hex "#c678dd")
, style5 = textColor (Hex "#61aeee")
, style6 = textColor (Hex "#d19a66")
, style7 = textColor (Hex "#abb2bf")
}
| 26472 | module SyntaxHighlight.Theme.OneDark exposing (css, theme)
import SyntaxHighlight.Style exposing (Color(..), RequiredStyles, backgroundColor, italic, noEmphasis, textColor)
import SyntaxHighlight.Theme.Type exposing (Theme, toCss)
{-
Author: <NAME> (https://github.com/Baransu)
Atom One Dark inspired theme
https://github.com/atom/one-dark-syntax
base: #282c34
mono-1: #abb2bf
mono-2: #818896
mono-3: #5c6370
hue-1: #56b6c2
hue-2: #61aeee
hue-3: #c678dd
hue-4: #98c379
hue-5: #e06c75
hue-5-2: #be5046
hue-6: #d19a66
hue-6-2: #e6c07b
-}
css : String
css =
toCss theme
theme : Theme
theme =
{ requiredStyles = requiredStyles
, customStyles = []
}
requiredStyles : RequiredStyles
requiredStyles =
{ default = noEmphasis (Hex "#abb2bf") (Hex "#282c34")
, highlight = backgroundColor (Rgba 229 231 235 0.1)
, addition = backgroundColor (Rgba 40 124 82 0.4)
, deletion = backgroundColor (Rgba 136 64 67 0.4)
, comment = textColor (Hex "#5c6370") |> italic
, style1 = textColor (Hex "#d19a66")
, style2 = textColor (Hex "#98c379")
, style3 = textColor (Hex "#c678dd")
, style4 = textColor (Hex "#c678dd")
, style5 = textColor (Hex "#61aeee")
, style6 = textColor (Hex "#d19a66")
, style7 = textColor (Hex "#abb2bf")
}
| true | module SyntaxHighlight.Theme.OneDark exposing (css, theme)
import SyntaxHighlight.Style exposing (Color(..), RequiredStyles, backgroundColor, italic, noEmphasis, textColor)
import SyntaxHighlight.Theme.Type exposing (Theme, toCss)
{-
Author: PI:NAME:<NAME>END_PI (https://github.com/Baransu)
Atom One Dark inspired theme
https://github.com/atom/one-dark-syntax
base: #282c34
mono-1: #abb2bf
mono-2: #818896
mono-3: #5c6370
hue-1: #56b6c2
hue-2: #61aeee
hue-3: #c678dd
hue-4: #98c379
hue-5: #e06c75
hue-5-2: #be5046
hue-6: #d19a66
hue-6-2: #e6c07b
-}
css : String
css =
toCss theme
theme : Theme
theme =
{ requiredStyles = requiredStyles
, customStyles = []
}
requiredStyles : RequiredStyles
requiredStyles =
{ default = noEmphasis (Hex "#abb2bf") (Hex "#282c34")
, highlight = backgroundColor (Rgba 229 231 235 0.1)
, addition = backgroundColor (Rgba 40 124 82 0.4)
, deletion = backgroundColor (Rgba 136 64 67 0.4)
, comment = textColor (Hex "#5c6370") |> italic
, style1 = textColor (Hex "#d19a66")
, style2 = textColor (Hex "#98c379")
, style3 = textColor (Hex "#c678dd")
, style4 = textColor (Hex "#c678dd")
, style5 = textColor (Hex "#61aeee")
, style6 = textColor (Hex "#d19a66")
, style7 = textColor (Hex "#abb2bf")
}
| elm |
[
{
"context": " [ Data.pipeline \"team\" 0 |> Data.withName \"pipeline\" ]\n )\n ",
"end": 9014,
"score": 0.6244531274,
"start": 9006,
"tag": "NAME",
"value": "pipeline"
},
{
"context": " [ Data.pipeline \"team\" 0 |> Data.withName \"pipeline\" ]\n )\n ",
"end": 11104,
"score": 0.5440525413,
"start": 11096,
"tag": "NAME",
"value": "pipeline"
},
{
"context": " |> givenDataUnauthenticated [ { id = 0, name = \"team\" } ]\n |> Tuple.first\n ",
"end": 20175,
"score": 0.8593435287,
"start": 20171,
"tag": "NAME",
"value": "team"
},
{
"context": " |> givenDataUnauthenticated [ { id = 0, name = \"team\" } ]\n |> Tuple.first\n ",
"end": 21100,
"score": 0.7564409971,
"start": 21096,
"tag": "NAME",
"value": "team"
},
{
"context": " |> givenDataUnauthenticated [ { id = 0, name = \"team\" } ]\n |> Tuple.first\n ",
"end": 22086,
"score": 0.5993042588,
"start": 22082,
"tag": "NAME",
"value": "team"
},
{
"context": " |> givenDataUnauthenticated [ { id = 0, name = \"team\" } ]\n |> Tuple.fir",
"end": 33168,
"score": 0.6547669768,
"start": 33164,
"tag": "NAME",
"value": "team"
},
{
"context": " |> givenDataUnauthenticated [ { id = 0, name = \"team\" } ]\n |> Tuple.fir",
"end": 34161,
"score": 0.7620899081,
"start": 34157,
"tag": "NAME",
"value": "team"
},
{
"context": " |> givenDataUnauthenticated [ { id = 0, name = \"team\" } ]\n |> Tuple.fir",
"end": 35218,
"score": 0.974707067,
"start": 35214,
"tag": "NAME",
"value": "team"
},
{
"context": " [ { id = 0, name = \"team\" } ]\n |> Tuple.fir",
"end": 75382,
"score": 0.7669925094,
"start": 75378,
"tag": "NAME",
"value": "team"
}
] | web/elm/tests/PipelineCardTests.elm | CJcrispy/concourse | 0 | module PipelineCardTests exposing (all)
import Application.Application as Application
import Assets
import ColorValues
import Colors
import Common
exposing
( defineHoverBehaviour
, givenDataUnauthenticated
, gotPipelines
, isColorWithStripes
)
import Concourse exposing (JsonValue(..))
import Concourse.BuildStatus exposing (BuildStatus(..))
import Concourse.PipelineStatus exposing (PipelineStatus(..), StatusDetails(..))
import DashboardInstanceGroupTests exposing (pipelineInstanceWithVars)
import DashboardTests
exposing
( afterSeconds
, amber
, apiData
, blue
, brown
, circularJobs
, darkGrey
, fadedGreen
, givenDataAndUser
, green
, iconSelector
, job
, jobWithNameTransitionedAt
, lightGrey
, middleGrey
, orange
, otherJob
, red
, running
, userWithRoles
, whenOnDashboard
, whenOnDashboardViewingAllPipelines
, white
)
import Data
import Dict
import Expect exposing (Expectation)
import Html.Attributes as Attr
import Message.Callback as Callback
import Message.Effects as Effects
import Message.Message as Msgs exposing (DomID(..), PipelinesSection(..))
import Message.Subscription exposing (Delivery(..), Interval(..))
import Message.TopLevelMessage as ApplicationMsgs
import Set
import Test exposing (Test, describe, test)
import Test.Html.Event as Event
import Test.Html.Query as Query
import Test.Html.Selector exposing (attribute, class, containing, id, style, tag, text)
import Time
all : Test
all =
describe "pipeline cards" <|
let
findHeader :
Query.Single ApplicationMsgs.TopLevelMessage
-> Query.Single ApplicationMsgs.TopLevelMessage
findHeader =
Query.find [ class "card-header" ]
findBody :
Query.Single ApplicationMsgs.TopLevelMessage
-> Query.Single ApplicationMsgs.TopLevelMessage
findBody =
Query.find [ class "card-body" ]
findFavoritesSection =
Query.find [ id "dashboard-favorite-pipelines" ]
pipelineWithStatus :
BuildStatus
-> Bool
-> Application.Model
-> Query.Single ApplicationMsgs.TopLevelMessage
pipelineWithStatus status isRunning =
let
jobFunc =
if isRunning then
job >> running
else
job
in
Application.handleCallback
(Callback.AllJobsFetched <| Ok [ jobFunc status ])
>> Tuple.first
>> givenDataUnauthenticated [ { id = 0, name = "team" } ]
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
>> Tuple.first
>> Application.handleDelivery
(ClockTicked OneSecond <| Time.millisToPosix 0)
>> Tuple.first
>> Common.queryView
in
[ describe "when team has no visible pipelines" <|
let
noPipelinesCard : () -> Query.Single ApplicationMsgs.TopLevelMessage
noPipelinesCard _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData
[ ( "some-team", [] )
, ( "other-team", [] )
]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "other-team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "dashboard-team-group"
, attribute <|
Attr.attribute "data-team-name"
"some-team"
]
|> Query.find [ class "card" ]
in
[ describe "card" <|
[ test "card has display flex with direction column" <|
noPipelinesCard
>> Query.has
[ style "display" "flex"
, style "flex-direction" "column"
]
, test "card has width 272px and height 268px" <|
noPipelinesCard
>> Query.has
[ style "width" "272px"
, style "height" "268px"
]
, test "card has a left margin of 25px" <|
noPipelinesCard
>> Query.has
[ style "margin-left" "25px" ]
]
, describe "header" <|
let
header : () -> Query.Single ApplicationMsgs.TopLevelMessage
header =
noPipelinesCard
>> findHeader
in
[ test "says 'no pipeline set' in white font" <|
header
>> Expect.all
[ Query.has [ text "no pipeline set" ]
, Query.has [ style "color" ColorValues.grey20 ]
]
, test "has dark grey background" <|
header
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "text is larger and wider spaced" <|
header
>> Query.has
[ style "font-size" "1.5em"
, style "letter-spacing" "0.1em"
]
, test "text is centered" <|
header
>> Query.has [ style "text-align" "center" ]
]
, describe "body" <|
let
body : () -> Query.Single ApplicationMsgs.TopLevelMessage
body =
noPipelinesCard
>> Query.find [ class "card-body" ]
in
[ test "has 20px 36px padding" <|
body
>> Query.has
[ style "padding" "20px 36px" ]
, test "fills available height" <|
body
>> Query.has [ style "flex-grow" "1" ]
, test "has dark grey background" <|
body
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "has 2px margins above and below" <|
body
>> Query.has [ style "margin" "2px 0" ]
, test "has lighter grey placeholder box that fills" <|
body
>> Expect.all
[ Query.has [ style "display" "flex" ]
, Query.children []
>> Query.first
>> Query.has
[ style "background-color" ColorValues.grey80
, style "flex-grow" "1"
]
]
]
, test "footer is dark grey and 47 pixels tall" <|
noPipelinesCard
>> Query.find [ class "card-footer" ]
>> Query.has
[ style "background-color" ColorValues.grey90
, style "height" "47px"
]
]
, test "is draggable when in all pipelines section and result is not stale" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> Expect.all
[ Query.has [ attribute <| Attr.attribute "draggable" "true" ]
, Query.has [ style "cursor" "move" ]
]
, test "is not draggable when in favorites section" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.handleDelivery
(FavoritedPipelinesReceived <| Ok <| Set.singleton 0)
|> Tuple.first
|> Common.queryView
|> Query.findAll
[ class "card"
, containing [ text "pipeline" ]
]
|> Query.first
|> Expect.all
[ Query.hasNot [ attribute <| Attr.attribute "draggable" "true" ]
, Query.hasNot [ style "cursor" "move" ]
]
, test "is not draggable when rendering based on the cache" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> Expect.all
[ Query.hasNot [ attribute <| Attr.attribute "draggable" "true" ]
, Query.hasNot [ style "cursor" "move" ]
]
, test "fills available space" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> Query.has
[ style "width" "100%"
, style "height" "100%"
, style "display" "flex"
, style "flex-direction" "column"
]
, describe "header" <|
let
header : () -> Query.Single ApplicationMsgs.TopLevelMessage
header _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> findHeader
in
[ test "has dark grey background" <|
header
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "has larger, spaced-out light-grey text" <|
header
>> Query.has
[ style "font-size" "1.5em"
, style "letter-spacing" "0.1em"
, style "color" ColorValues.grey20
]
, test "text does not overflow or wrap" <|
header
>> Query.children []
>> Query.first
>> Query.has
[ style "width" "245px"
, style "white-space" "nowrap"
, style "overflow" "hidden"
, style "text-overflow" "ellipsis"
]
, test "is hoverable" <|
header
>> Query.find [ class "dashboard-pipeline-name" ]
>> Event.simulate Event.mouseEnter
>> Event.expect
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just <|
Msgs.PipelineCardName Msgs.AllPipelinesSection 1
)
, test "has html id" <|
header
>> Query.find [ class "dashboard-pipeline-name" ]
>> Query.has
[ id <|
Effects.toHtmlID <|
Msgs.PipelineCardName Msgs.AllPipelinesSection 1
]
, describe "favorited pipeline instances" <|
let
setup pipelines _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> gotPipelines pipelines
|> Application.handleDelivery
(FavoritedPipelinesReceived <|
Ok (Set.singleton 1)
)
|> Tuple.first
findCardHeader =
Common.queryView
>> findFavoritesSection
>> Query.find
[ class "card"
, containing [ text "group" ]
]
>> Query.find [ class "card-header" ]
in
[ test "header displays instance vars and group name" <|
setup [ pipelineInstanceWithVars 1 [ ( "foo", JsonString "bar" ) ] ]
>> findCardHeader
>> Expect.all
[ Query.has
[ style "height" "80px"
, style "box-sizing" "border-box"
]
, Query.has [ text "group" ]
, Query.has [ containing [ text "foo" ], containing [ text "bar" ] ]
]
, test "an instance with no instance vars displays \"no instance vars\"" <|
setup
[ pipelineInstanceWithVars 1 []
, pipelineInstanceWithVars 2 [ ( "foo", JsonString "bar" ) ]
]
>> findCardHeader
>> Expect.all
[ Query.has
[ style "height" "80px"
, style "box-sizing" "border-box"
]
, Query.has [ text "group" ]
, Query.has [ text "no instance vars" ]
]
, test "all instance vars appear on the same row" <|
setup
[ pipelineInstanceWithVars 1
[ ( "a", JsonString "1" )
, ( "b", JsonString "2" )
]
]
>> findCardHeader
>> Expect.all
[ Query.has
[ style "height" "80px"
, style "box-sizing" "border-box"
]
, Query.has [ text "group" ]
, Query.has
[ containing [ text "a" ]
, containing [ text "1" ]
, containing [ text "b" ]
, containing [ text "2" ]
]
]
]
]
, describe "colored banner" <|
let
findBanner =
Query.find
[ class "card"
, containing [ text "pipeline" ]
]
>> Query.find
[ class "banner" ]
isSolid : String -> Query.Single ApplicationMsgs.TopLevelMessage -> Expectation
isSolid color =
Query.has [ style "background-color" color ]
in
[ describe "non-HD view"
[ test "is 7px tall" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> Query.has [ style "height" "7px" ]
, test "is grey when pipeline is cached" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is dark grey when pipeline is archived" <|
\_ ->
whenOnDashboardViewingAllPipelines { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withArchived True
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid Colors.backgroundDark
, test "is blue when pipeline is paused" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid blue
, test "is green when pipeline is succeeding" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findBanner
|> isSolid green
, test "is green with black stripes when pipeline is succeeding and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
True
|> findBanner
|> isColorWithStripes { thin = green, thick = ColorValues.grey90 }
, test "is grey when pipeline is pending" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is grey with black stripes when pipeline is pending and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusStarted
True
|> findBanner
|> isColorWithStripes { thin = lightGrey, thick = ColorValues.grey90 }
, test "is red when pipeline is failing" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
False
|> findBanner
|> isSolid red
, test "is red with black stripes when pipeline is failing and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
True
|> findBanner
|> isColorWithStripes { thin = red, thick = ColorValues.grey90 }
, test "is amber when pipeline is erroring" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusErrored
False
|> findBanner
|> isSolid amber
, test "is amber with black stripes when pipeline is erroring and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusErrored
True
|> findBanner
|> isColorWithStripes { thin = amber, thick = ColorValues.grey90 }
, test "is brown when pipeline is aborted" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusAborted
False
|> findBanner
|> isSolid brown
, test "is brown with black stripes when pipeline is aborted and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusAborted
True
|> findBanner
|> isColorWithStripes { thin = brown, thick = ColorValues.grey90 }
, describe "status priorities" <|
let
givenTwoJobsWithModifiers :
BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobsWithModifiers firstStatus firstModifier secondStatus secondModifier =
whenOnDashboard { highDensity = False }
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ job firstStatus |> firstModifier
, otherJob secondStatus |> secondModifier
]
)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
givenTwoJobs :
BuildStatus
-> BuildStatus
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobs firstStatus secondStatus =
givenTwoJobsWithModifiers firstStatus identity secondStatus identity
in
[ test "failed is more important than errored" <|
\_ ->
givenTwoJobs
BuildStatusFailed
BuildStatusErrored
|> findBanner
|> isSolid red
, test "errored is more important than aborted" <|
\_ ->
givenTwoJobs
BuildStatusErrored
BuildStatusAborted
|> findBanner
|> isSolid amber
, test "aborted is more important than succeeding" <|
\_ ->
givenTwoJobs
BuildStatusAborted
BuildStatusSucceeded
|> findBanner
|> isSolid brown
, test "succeeding is more important than pending" <|
\_ ->
givenTwoJobs
BuildStatusSucceeded
BuildStatusPending
|> findBanner
|> isSolid green
, test "paused jobs are ignored" <|
\_ ->
givenTwoJobsWithModifiers
BuildStatusSucceeded
identity
BuildStatusFailed
(Data.withPaused True)
|> findBanner
|> isSolid green
]
, test "does not crash with a circular pipeline" <|
\_ ->
whenOnDashboard { highDensity = False }
|> Application.handleCallback (Callback.AllJobsFetched <| Ok circularJobs)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid green
, describe "HD view"
[ test "is 8px wide" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> Query.has [ style "width" "8px" ]
, test "is grey when pipeline is cached" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is dark grey when pipeline is archived" <|
\_ ->
whenOnDashboardViewingAllPipelines { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withArchived True
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid Colors.backgroundDark
, test "is blue when pipeline is paused" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid blue
, test "is green when pipeline is succeeding" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findBanner
|> isSolid green
, test "is green with black stripes when pipeline is succeeding and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusSucceeded
True
|> findBanner
|> isColorWithStripes { thin = green, thick = ColorValues.grey90 }
, test "is grey when pipeline is pending" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is grey with black stripes when pipeline is pending and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusStarted
True
|> findBanner
|> isColorWithStripes { thin = lightGrey, thick = ColorValues.grey90 }
, test "is red when pipeline is failing" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusFailed
False
|> findBanner
|> isSolid red
, test "is red with black stripes when pipeline is failing and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusFailed
True
|> findBanner
|> isColorWithStripes { thin = red, thick = ColorValues.grey90 }
, test "is amber when pipeline is erroring" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusErrored
False
|> findBanner
|> isSolid amber
, test "is amber with black stripes when pipeline is erroring and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusErrored
True
|> findBanner
|> isColorWithStripes { thin = amber, thick = ColorValues.grey90 }
, test "is brown when pipeline is aborted" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusAborted
False
|> findBanner
|> isSolid brown
, test "is brown with black stripes when pipeline is aborted and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusAborted
True
|> findBanner
|> isColorWithStripes { thin = brown, thick = ColorValues.grey90 }
, describe "status priorities" <|
let
givenTwoJobsWithModifiers :
BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobsWithModifiers firstStatus firstModifier secondStatus secondModifier =
whenOnDashboard { highDensity = True }
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ job firstStatus |> firstModifier
, otherJob secondStatus |> secondModifier
]
)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
givenTwoJobs :
BuildStatus
-> BuildStatus
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobs firstStatus secondStatus =
givenTwoJobsWithModifiers firstStatus identity secondStatus identity
in
[ test "failed is more important than errored" <|
\_ ->
givenTwoJobs
BuildStatusFailed
BuildStatusErrored
|> findBanner
|> isSolid red
, test "errored is more important than aborted" <|
\_ ->
givenTwoJobs
BuildStatusErrored
BuildStatusAborted
|> findBanner
|> isSolid amber
, test "aborted is more important than succeeding" <|
\_ ->
givenTwoJobs
BuildStatusAborted
BuildStatusSucceeded
|> findBanner
|> isSolid brown
, test "succeeding is more important than pending" <|
\_ ->
givenTwoJobs
BuildStatusSucceeded
BuildStatusPending
|> findBanner
|> isSolid green
, test "paused jobs are ignored" <|
\_ ->
givenTwoJobsWithModifiers
BuildStatusSucceeded
identity
BuildStatusFailed
(Data.withPaused True)
|> findBanner
|> isSolid green
]
]
]
]
, describe "on HD view" <|
let
setup : () -> Query.Single ApplicationMsgs.TopLevelMessage
setup _ =
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
noPipelines : () -> Query.Single ApplicationMsgs.TopLevelMessage
noPipelines _ =
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData
[ ( "some-team", [] )
, ( "other-team", [] )
]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "other-team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
card : Query.Single ApplicationMsgs.TopLevelMessage -> Query.Single ApplicationMsgs.TopLevelMessage
card =
Query.find
[ class "card"
, containing [ text "pipeline" ]
]
cardText : Query.Single ApplicationMsgs.TopLevelMessage -> Query.Single ApplicationMsgs.TopLevelMessage
cardText =
card
>> Query.children []
>> Query.index 1
noPipelinesCard =
Query.find
[ class "card"
, containing [ text "no pipeline" ]
]
in
[ test "no pipelines card has 14px font and 1px spacing" <|
noPipelines
>> noPipelinesCard
>> Query.has
[ style "font-size" "14px"
, style "letter-spacing" "1px"
]
, test "no pipelines card text is vertically centered" <|
noPipelines
>> noPipelinesCard
>> Query.has
[ style "display" "flex"
, style "align-items" "center"
]
, test "no pipelines card is 60px tall" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "height" "60px" ]
, test "no pipelines card has 60px right margin" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "margin-right" "60px" ]
, test "no pipelines card text has 10px padding" <|
noPipelines
>> noPipelinesCard
>> Query.children []
>> Query.first
>> Query.has [ style "padding" "10px" ]
, test "no pipelines card is 200px wide" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "width" "200px" ]
, test "no pipelines card has dark grey background" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "card name is hoverable" <|
setup
>> card
>> Query.find [ class "dashboardhd-pipeline-name" ]
>> Event.simulate Event.mouseEnter
>> Event.expect
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just <|
Msgs.PipelineCardNameHD 1
)
, test "card name has html id" <|
setup
>> card
>> Query.find [ class "dashboardhd-pipeline-name" ]
>> Query.has
[ id <|
Effects.toHtmlID <|
Msgs.PipelineCardNameHD 1
]
, test "card has larger tighter font" <|
setup
>> card
>> Query.has
[ style "font-size" "19px"
, style "letter-spacing" "1px"
]
, test "card text does not overflow or wrap" <|
setup
>> cardText
>> Query.has
[ style "width" "180px"
, style "white-space" "nowrap"
, style "overflow" "hidden"
, style "text-overflow" "ellipsis"
]
, test "card text is vertically centered" <|
setup
>> cardText
>> Query.has
[ style "align-self" "center" ]
, test "card text has 10px padding" <|
setup
>> cardText
>> Query.has
[ style "padding" "10px" ]
, test "card lays out contents horizontally" <|
setup
>> card
>> Query.has
[ style "display" "flex" ]
, test "card is 60px tall" <|
setup
>> card
>> Query.has [ style "height" "60px" ]
, test "card is 200px wide" <|
setup
>> card
>> Query.has [ style "width" "200px" ]
, test "no triangle when there is no resource error" <|
setup
>> card
>> Query.children []
>> Query.count (Expect.equal 2)
, describe "resource error triangle" <|
let
givenResourceFailingToCheck : () -> Query.Single ApplicationMsgs.TopLevelMessage
givenResourceFailingToCheck _ =
whenOnDashboard { highDensity = True }
|> Application.handleCallback
(Callback.AllResourcesFetched <|
Ok
[ Data.resource Nothing
|> Data.withBuild (Just <| Data.build Concourse.BuildStatus.BuildStatusFailed)
]
)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
resourceErrorTriangle =
Query.children []
>> Query.index -1
in
[ test "exists" <|
givenResourceFailingToCheck
>> card
>> Query.children []
>> Query.count (Expect.equal 3)
, test "is at the top right of card" <|
givenResourceFailingToCheck
>> card
>> Expect.all
[ Query.has [ style "position" "relative" ]
, resourceErrorTriangle
>> Query.has
[ style "position" "absolute"
, style "top" "0"
, style "right" "0"
]
]
, test "is an orange 'top right' triangle" <|
givenResourceFailingToCheck
>> card
>> resourceErrorTriangle
>> Query.has
[ style "width" "0"
, style "height" "0"
, style "border-top" <| "30px solid " ++ orange
, style "border-left" "30px solid transparent"
]
]
, test
("cards are spaced 4px apart vertically and "
++ "60px apart horizontally"
)
<|
setup
>> card
>> Query.has
[ style "margin" "0 60px 4px 0" ]
, test "card is faded green when pipeline is succeeding" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> card
|> Query.has [ style "background-color" fadedGreen ]
, test "card is red when pipeline is failing" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusFailed
False
|> card
|> Query.has [ style "background-color" red ]
, test "card is amber when pipeline is erroring" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusErrored
False
|> card
|> Query.has [ style "background-color" amber ]
, test "card is not affected by jobs from other pipelines" <|
\_ ->
whenOnDashboard { highDensity = True }
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllJobsFetched <|
let
baseJob =
job BuildStatusErrored
in
Ok
[ { baseJob | pipelineName = "other-pipeline" } ]
)
|> Tuple.first
|> Common.queryView
|> card
|> Query.hasNot [ style "background-color" amber ]
]
, describe "body" <|
let
setup : () -> Query.Single ApplicationMsgs.TopLevelMessage
setup _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
in
[ test "has dark grey background" <|
setup
>> findBody
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "has 2px margin above and below" <|
setup
>> findBody
>> Query.has [ style "margin" "2px 0" ]
, test "fills available height" <|
setup
>> findBody
>> Query.has [ style "flex-grow" "1" ]
, test "allows pipeline-grid to fill available height" <|
setup
>> findBody
>> Query.has [ style "display" "flex" ]
, test "pipeline-grid fills available width" <|
setup
>> findBody
>> Query.find [ class "pipeline-grid" ]
>> Query.has
[ style "box-sizing" "border-box"
, style "width" "100%"
]
]
, describe "footer" <|
let
hasStyle : String -> String -> Expectation
hasStyle property value =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.has [ style property value ]
in
[ test "has dark grey background" <|
\_ ->
hasStyle "background-color" ColorValues.grey90
, test "has medium padding" <|
\_ ->
hasStyle "padding" "13.5px"
, test "lays out contents horizontally" <|
\_ ->
hasStyle "display" "flex"
, test "is divided into a left and right section, spread apart" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Expect.all
[ Query.children []
>> Query.count (Expect.equal 2)
, Query.has
[ style "justify-content" "space-between" ]
]
, test "both sections lay out contents horizontally" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.each (Query.has [ style "display" "flex" ])
, describe "left-hand section" <|
let
findStatusIcon =
Query.find [ class "pipeline-status" ]
>> Query.children []
>> Query.first
findStatusText =
Query.find [ class "pipeline-status" ]
>> Query.children []
>> Query.index -1
in
[ describe "when pipeline is paused" <|
let
setup =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
in
[ test "status icon is blue pause" <|
\_ ->
setup
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconPaused
}
++ [ style "background-size" "contain" ]
)
, test "status text is blue" <|
\_ ->
setup
|> findStatusText
|> Query.has [ style "color" blue ]
, test "status text is larger and spaced more widely" <|
\_ ->
setup
|> findStatusText
|> Query.has
[ style "font-size" "18px"
, style "line-height" "20px"
, style "letter-spacing" "0.05em"
]
, test "status text is offset to the right of the icon" <|
\_ ->
setup
|> findStatusText
|> Query.has [ style "margin-left" "8px" ]
, test "status text says 'paused'" <|
\_ ->
setup
|> findStatusText
|> Query.has [ text "paused" ]
]
, describe "when a pipeline is based on cache" <|
let
setup =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
in
[ test "status icon is grey pending" <|
\_ ->
setup
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconStale
}
++ [ style "background-size" "contain" ]
)
, test "status text is grey" <|
\_ ->
setup
|> findStatusText
|> Query.has [ style "color" lightGrey ]
, test "status text says 'loading...'" <|
\_ ->
setup
|> findStatusText
|> Query.has [ text "loading..." ]
, test "pipeline card is faded" <|
\_ ->
setup
|> Query.find [ class "card" ]
|> Query.has [ style "opacity" "0.45" ]
]
, describe "when pipeline has no jobs due to a disabled endpoint" <|
let
setup =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedJobsReceived <| Ok [ Data.job 0 ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllJobsFetched <|
Data.httpNotImplemented
)
domID =
Msgs.PipelineStatusIcon AllPipelinesSection 0
in
[ test "status icon is faded sync" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconJobsDisabled
}
++ [ style "background-size" "contain"
, style "opacity" "0.5"
]
)
, test "status icon is hoverable" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> findStatusIcon
|> Event.simulate Event.mouseEnter
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just domID
)
, test "hovering status icon sends location request" <|
\_ ->
setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just domID
)
|> Tuple.second
|> Common.contains
(Effects.GetViewportOf domID)
, test "hovering status icon shows tooltip" <|
\_ ->
setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just domID
)
|> Tuple.first
|> Application.handleCallback
(Callback.GotViewport domID
(Ok
{ scene =
{ width = 1
, height = 0
}
, viewport =
{ width = 1
, height = 0
, x = 0
, y = 0
}
}
)
)
|> Tuple.first
|> Application.handleCallback
(Callback.GotElement <|
Ok
{ scene =
{ width = 0
, height = 0
}
, viewport =
{ width = 0
, height = 0
, x = 0
, y = 0
}
, element =
{ x = 0
, y = 0
, width = 1
, height = 1
}
}
)
|> Tuple.first
|> Common.queryView
|> Query.has
[ style "position" "fixed"
, containing [ text "automatic job monitoring disabled" ]
]
, test "status text says 'no data'" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> findStatusText
|> Query.has [ text "no data" ]
, test "job preview is empty placeholder" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-body" ]
|> Query.has [ style "background-color" ColorValues.grey90 ]
, test "job data is cleared" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "parallel-grid" ]
|> Query.hasNot [ tag "a" ]
, test "job data is cleared from local cache" <|
\_ ->
setup
|> Tuple.second
|> Common.contains Effects.DeleteCachedJobs
]
, describe "when pipeline is archived" <|
let
setup =
whenOnDashboardViewingAllPipelines { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withArchived True
]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ Data.job 0 ]
)
in
[ test "status section is empty" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "pipeline-status" ]
|> Query.children []
|> Query.count (Expect.equal 0)
, test "job preview is empty placeholder" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-body" ]
|> Query.has [ style "background-color" ColorValues.grey90 ]
, test "there is no pause button" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.hasNot [ class "pause-toggle" ]
]
, describe "when pipeline is pending" <|
[ test "status icon is grey" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconPending
}
++ [ style "background-size" "contain" ]
)
, test "status text is grey" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
False
|> findStatusText
|> Query.has [ style "color" lightGrey ]
, test "status text says 'pending'" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
False
|> findStatusText
|> Query.has
[ text "pending" ]
, test "when running, status text says 'running'" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
True
|> findStatusText
|> Query.has
[ text "running" ]
]
, describe "when pipeline is succeeding"
[ test "status icon is a green check" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconSucceeded
}
++ [ style "background-size" "contain" ]
)
, test "status text is green" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findStatusText
|> Query.has [ style "color" green ]
, test "when running, status text says 'running'" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
True
|> findStatusText
|> Query.has
[ text "running" ]
, test "when not running, status text shows age" <|
\_ ->
whenOnDashboard { highDensity = False }
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ jobWithNameTransitionedAt
"job"
(Just <| Time.millisToPosix 0)
BuildStatusSucceeded
]
)
|> Tuple.first
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> afterSeconds 1
|> Common.queryView
|> findStatusText
|> Query.has
[ text "1s" ]
]
, describe "when pipeline is failing"
[ test "status icon is a red !" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconFailed
}
++ [ style "background-size" "contain" ]
)
, test "status text is red" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
False
|> findStatusText
|> Query.has [ style "color" red ]
]
, test "when pipeline is aborted, status icon is a brown x" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusAborted
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconAborted
}
++ [ style "background-size" "contain" ]
)
, test "when pipeline is errored, status icon is an amber triangle" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusErrored
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconErrored
}
++ [ style "background-size" "contain" ]
)
]
, describe "right-hand section"
[ describe "visibility toggle" <|
let
pipelineId =
Data.pipelineId
visibilityToggle =
Common.queryView
>> Query.findAll [ class "card-footer" ]
>> Query.first
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 2
openEye =
iconSelector
{ size = "20px"
, image = Assets.VisibilityToggleIcon True
}
++ [ style "background-size" "contain" ]
slashedOutEye =
iconSelector
{ size = "20px"
, image = Assets.VisibilityToggleIcon False
}
++ [ style "background-size" "contain" ]
openEyeClickable setup =
[ defineHoverBehaviour
{ name = "open eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "pointer"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "bright 20px square"
, selector =
openEye
++ [ style "opacity" "1"
, style "cursor" "pointer"
]
}
}
, test "has click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
, test "click has HidePipeline effect" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.second
|> Expect.equal
[ Effects.ChangeVisibility
Msgs.Hide
pipelineId
]
, defineHoverBehaviour
{ name = "open eye toggle in favorites section"
, setup =
whenOnDashboard { highDensity = False }
|> Application.handleDelivery
(Message.Subscription.FavoritedPipelinesReceived <| Ok <| Set.singleton 0)
|> Tuple.first
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "pointer"
]
}
, hoverable =
Msgs.VisibilityButton FavoritesSection 0
, hoveredSelector =
{ description = "bright 20px square"
, selector =
openEye
++ [ style "opacity" "1"
, style "cursor" "pointer"
]
}
}
, defineHoverBehaviour
{ name = "visibility spinner"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
}
, test "success resolves spinner to slashed-out eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Hide
pipelineId
(Ok ())
)
|> Tuple.first
|> visibilityToggle
|> Query.has slashedOutEye
, test "error resolves spinner to open eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Hide
pipelineId
Data.httpInternalServerError
)
|> Tuple.first
|> visibilityToggle
|> Query.has openEye
, test "401 redirects to login" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Hide
pipelineId
Data.httpUnauthorized
)
|> Tuple.second
|> Expect.equal
[ Effects.RedirectToLogin ]
]
openEyeUnclickable setup =
[ defineHoverBehaviour
{ name = "open eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
}
, test "has no click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.toResult
|> Expect.err
]
slashedOutEyeClickable setup =
[ defineHoverBehaviour
{ name = "slashed-out eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "0.5"
, style "cursor" "pointer"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "bright 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "1"
, style "cursor" "pointer"
]
}
}
, test "has click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
, test "click has ExposePipeline effect" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.second
|> Expect.equal
[ Effects.ChangeVisibility
Msgs.Expose
pipelineId
]
, defineHoverBehaviour
{ name = "visibility spinner"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
}
, test "success resolves spinner to open eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Expose
pipelineId
(Ok ())
)
|> Tuple.first
|> visibilityToggle
|> Query.has openEye
, test "error resolves spinner to slashed-out eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Expose
pipelineId
Data.httpInternalServerError
)
|> Tuple.first
|> visibilityToggle
|> Query.has slashedOutEye
]
slashedOutEyeUnclickable setup =
[ defineHoverBehaviour
{ name = "slashed-out eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "faded 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
}
, test "has no click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.toResult
|> Expect.err
]
in
[ describe "when authorized" <|
let
whenAuthorizedPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "owner" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
whenAuthorizedNonPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "owner" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPublic False
]
)
in
[ describe "on public pipeline" <|
openEyeClickable whenAuthorizedPublic
, describe "on a non-public pipeline" <|
slashedOutEyeClickable whenAuthorizedNonPublic
]
, describe "when unauthorized" <|
let
whenUnauthorizedPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "viewer" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
whenUnauthorizedNonPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "viewer" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPublic False
]
)
in
[ describe "on public pipeline" <|
openEyeUnclickable whenUnauthorizedPublic
, describe "on a non-public pipeline" <|
slashedOutEyeUnclickable
whenUnauthorizedNonPublic
]
, describe "when unauthenticated" <|
let
whenUnauthenticated =
givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
in
[ describe "on public pipeline" <|
openEyeClickable whenUnauthenticated
]
]
, test "there is medium spacing between the eye and the play/pause button" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.index -1
|> Query.children []
|> Expect.all
[ Query.count (Expect.equal 5)
, Query.index 1 >> Query.has [ style "width" "12px" ]
]
, test "there is medium spacing between the eye and the favorited icon" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.index -1
|> Query.children []
|> Expect.all
[ Query.count (Expect.equal 5)
, Query.index 3 >> Query.has [ style "width" "12px" ]
]
, describe "pause toggle"
[ test "the right section has a 20px square pause button on the left" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.index -1
|> Query.children []
|> Query.index 0
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
)
, test "pause button has pointer cursor when authorized" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.find
(iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
)
|> Query.has [ style "cursor" "pointer" ]
, test "pause button is transparent" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.find
(iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
)
|> Query.has [ style "opacity" "0.5" ]
, defineHoverBehaviour
{ name = "pause button"
, setup =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
, query =
Common.queryView
>> Query.find [ class "card-footer" ]
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 0
, unhoveredSelector =
{ description = "a faded 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "0.5"
]
}
, hoverable = Msgs.PipelineCardPauseToggle AllPipelinesSection 1
, hoveredSelector =
{ description = "a bright 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "1"
]
}
}
, defineHoverBehaviour
{ name = "pause button in favorites section"
, setup =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.handleDelivery
(Message.Subscription.FavoritedPipelinesReceived <| Ok <| Set.singleton 1)
|> Tuple.first
, query =
Common.queryView
>> Query.findAll [ class "card-footer" ]
>> Query.first
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 0
, unhoveredSelector =
{ description = "a faded 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "0.5"
]
}
, hoverable =
Msgs.PipelineCardPauseToggle FavoritesSection 1
, hoveredSelector =
{ description = "a bright 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "1"
]
}
}
, defineHoverBehaviour
{ name = "play button"
, setup =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
, query =
Common.queryView
>> Query.find [ class "card-footer" ]
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 0
, unhoveredSelector =
{ description = "a transparent 20px square play button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PlayIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "0.5"
]
}
, hoverable = Msgs.PipelineCardPauseToggle AllPipelinesSection 1
, hoveredSelector =
{ description = "an opaque 20px square play button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PlayIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "1"
]
}
}
, test "clicking pause button sends TogglePipeline msg" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.find [ class "pause-toggle" ]
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
, test "pause button turns into spinner on click" <|
\_ ->
let
animation =
"container-rotate 1568ms linear infinite"
in
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.has [ style "animation" animation ]
, test "clicking pause button sends toggle api call" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.second
|> Expect.equal [ Effects.SendTogglePipelineRequest Data.pipelineId False ]
, test "all pipelines are refetched after ok toggle call" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.first
|> Application.handleCallback
(Callback.PipelineToggled Data.pipelineId (Ok ()))
|> Tuple.second
|> Expect.equal [ Effects.FetchAllPipelines ]
, test "401 toggle call redirects to login" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.first
|> Application.handleCallback
(Callback.PipelineToggled Data.pipelineId Data.httpUnauthorized)
|> Tuple.second
|> Expect.equal [ Effects.RedirectToLogin ]
]
, describe "favorited icon" <|
let
pipelineId =
0
unfilledFavoritedIcon =
iconSelector
{ size = "20px"
, image = Assets.FavoritedToggleIcon { isFavorited = False, isHovered = False, isSideBar = False }
}
++ [ style "background-size" "contain" ]
unfilledBrightFavoritedIcon =
iconSelector
{ size = "20px"
, image = Assets.FavoritedToggleIcon { isFavorited = False, isHovered = True, isSideBar = False }
}
++ [ style "background-size" "contain" ]
filledFavoritedIcon =
iconSelector
{ size = "20px"
, image = Assets.FavoritedToggleIcon { isFavorited = True, isHovered = False, isSideBar = False }
}
++ [ style "background-size" "contain" ]
favoritedToggle =
Common.queryView
>> Query.findAll [ class "card-footer" ]
>> Query.first
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index -1
favoritedIconClickable setup =
[ defineHoverBehaviour
{ name = "favorited icon toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = favoritedToggle
, unhoveredSelector =
{ description = "faded star icon"
, selector =
unfilledFavoritedIcon
++ [ style "cursor" "pointer" ]
}
, hoverable =
Msgs.PipelineCardFavoritedIcon AllPipelinesSection pipelineId
, hoveredSelector =
{ description = "bright star icon"
, selector =
unfilledBrightFavoritedIcon
++ [ style "cursor" "pointer" ]
}
}
, test "has click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> favoritedToggle
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardFavoritedIcon
AllPipelinesSection
pipelineId
)
, test "click has FavoritedPipeline effect" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardFavoritedIcon
AllPipelinesSection
pipelineId
)
|> Tuple.second
|> Expect.equal
[ Effects.SaveFavoritedPipelines <|
Set.singleton pipelineId
]
, test "favorited pipeline card has a bright filled star icon" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.handleDelivery
(FavoritedPipelinesReceived <|
Ok <|
Set.singleton pipelineId
)
|> Tuple.first
|> favoritedToggle
|> Expect.all
[ Query.has filledFavoritedIcon
]
]
in
favoritedIconClickable
(givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "owner" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
)
]
]
]
| 52109 | module PipelineCardTests exposing (all)
import Application.Application as Application
import Assets
import ColorValues
import Colors
import Common
exposing
( defineHoverBehaviour
, givenDataUnauthenticated
, gotPipelines
, isColorWithStripes
)
import Concourse exposing (JsonValue(..))
import Concourse.BuildStatus exposing (BuildStatus(..))
import Concourse.PipelineStatus exposing (PipelineStatus(..), StatusDetails(..))
import DashboardInstanceGroupTests exposing (pipelineInstanceWithVars)
import DashboardTests
exposing
( afterSeconds
, amber
, apiData
, blue
, brown
, circularJobs
, darkGrey
, fadedGreen
, givenDataAndUser
, green
, iconSelector
, job
, jobWithNameTransitionedAt
, lightGrey
, middleGrey
, orange
, otherJob
, red
, running
, userWithRoles
, whenOnDashboard
, whenOnDashboardViewingAllPipelines
, white
)
import Data
import Dict
import Expect exposing (Expectation)
import Html.Attributes as Attr
import Message.Callback as Callback
import Message.Effects as Effects
import Message.Message as Msgs exposing (DomID(..), PipelinesSection(..))
import Message.Subscription exposing (Delivery(..), Interval(..))
import Message.TopLevelMessage as ApplicationMsgs
import Set
import Test exposing (Test, describe, test)
import Test.Html.Event as Event
import Test.Html.Query as Query
import Test.Html.Selector exposing (attribute, class, containing, id, style, tag, text)
import Time
all : Test
all =
describe "pipeline cards" <|
let
findHeader :
Query.Single ApplicationMsgs.TopLevelMessage
-> Query.Single ApplicationMsgs.TopLevelMessage
findHeader =
Query.find [ class "card-header" ]
findBody :
Query.Single ApplicationMsgs.TopLevelMessage
-> Query.Single ApplicationMsgs.TopLevelMessage
findBody =
Query.find [ class "card-body" ]
findFavoritesSection =
Query.find [ id "dashboard-favorite-pipelines" ]
pipelineWithStatus :
BuildStatus
-> Bool
-> Application.Model
-> Query.Single ApplicationMsgs.TopLevelMessage
pipelineWithStatus status isRunning =
let
jobFunc =
if isRunning then
job >> running
else
job
in
Application.handleCallback
(Callback.AllJobsFetched <| Ok [ jobFunc status ])
>> Tuple.first
>> givenDataUnauthenticated [ { id = 0, name = "team" } ]
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
>> Tuple.first
>> Application.handleDelivery
(ClockTicked OneSecond <| Time.millisToPosix 0)
>> Tuple.first
>> Common.queryView
in
[ describe "when team has no visible pipelines" <|
let
noPipelinesCard : () -> Query.Single ApplicationMsgs.TopLevelMessage
noPipelinesCard _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData
[ ( "some-team", [] )
, ( "other-team", [] )
]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "other-team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "dashboard-team-group"
, attribute <|
Attr.attribute "data-team-name"
"some-team"
]
|> Query.find [ class "card" ]
in
[ describe "card" <|
[ test "card has display flex with direction column" <|
noPipelinesCard
>> Query.has
[ style "display" "flex"
, style "flex-direction" "column"
]
, test "card has width 272px and height 268px" <|
noPipelinesCard
>> Query.has
[ style "width" "272px"
, style "height" "268px"
]
, test "card has a left margin of 25px" <|
noPipelinesCard
>> Query.has
[ style "margin-left" "25px" ]
]
, describe "header" <|
let
header : () -> Query.Single ApplicationMsgs.TopLevelMessage
header =
noPipelinesCard
>> findHeader
in
[ test "says 'no pipeline set' in white font" <|
header
>> Expect.all
[ Query.has [ text "no pipeline set" ]
, Query.has [ style "color" ColorValues.grey20 ]
]
, test "has dark grey background" <|
header
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "text is larger and wider spaced" <|
header
>> Query.has
[ style "font-size" "1.5em"
, style "letter-spacing" "0.1em"
]
, test "text is centered" <|
header
>> Query.has [ style "text-align" "center" ]
]
, describe "body" <|
let
body : () -> Query.Single ApplicationMsgs.TopLevelMessage
body =
noPipelinesCard
>> Query.find [ class "card-body" ]
in
[ test "has 20px 36px padding" <|
body
>> Query.has
[ style "padding" "20px 36px" ]
, test "fills available height" <|
body
>> Query.has [ style "flex-grow" "1" ]
, test "has dark grey background" <|
body
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "has 2px margins above and below" <|
body
>> Query.has [ style "margin" "2px 0" ]
, test "has lighter grey placeholder box that fills" <|
body
>> Expect.all
[ Query.has [ style "display" "flex" ]
, Query.children []
>> Query.first
>> Query.has
[ style "background-color" ColorValues.grey80
, style "flex-grow" "1"
]
]
]
, test "footer is dark grey and 47 pixels tall" <|
noPipelinesCard
>> Query.find [ class "card-footer" ]
>> Query.has
[ style "background-color" ColorValues.grey90
, style "height" "47px"
]
]
, test "is draggable when in all pipelines section and result is not stale" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "<NAME>" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> Expect.all
[ Query.has [ attribute <| Attr.attribute "draggable" "true" ]
, Query.has [ style "cursor" "move" ]
]
, test "is not draggable when in favorites section" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.handleDelivery
(FavoritedPipelinesReceived <| Ok <| Set.singleton 0)
|> Tuple.first
|> Common.queryView
|> Query.findAll
[ class "card"
, containing [ text "pipeline" ]
]
|> Query.first
|> Expect.all
[ Query.hasNot [ attribute <| Attr.attribute "draggable" "true" ]
, Query.hasNot [ style "cursor" "move" ]
]
, test "is not draggable when rendering based on the cache" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "<NAME>" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> Expect.all
[ Query.hasNot [ attribute <| Attr.attribute "draggable" "true" ]
, Query.hasNot [ style "cursor" "move" ]
]
, test "fills available space" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> Query.has
[ style "width" "100%"
, style "height" "100%"
, style "display" "flex"
, style "flex-direction" "column"
]
, describe "header" <|
let
header : () -> Query.Single ApplicationMsgs.TopLevelMessage
header _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> findHeader
in
[ test "has dark grey background" <|
header
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "has larger, spaced-out light-grey text" <|
header
>> Query.has
[ style "font-size" "1.5em"
, style "letter-spacing" "0.1em"
, style "color" ColorValues.grey20
]
, test "text does not overflow or wrap" <|
header
>> Query.children []
>> Query.first
>> Query.has
[ style "width" "245px"
, style "white-space" "nowrap"
, style "overflow" "hidden"
, style "text-overflow" "ellipsis"
]
, test "is hoverable" <|
header
>> Query.find [ class "dashboard-pipeline-name" ]
>> Event.simulate Event.mouseEnter
>> Event.expect
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just <|
Msgs.PipelineCardName Msgs.AllPipelinesSection 1
)
, test "has html id" <|
header
>> Query.find [ class "dashboard-pipeline-name" ]
>> Query.has
[ id <|
Effects.toHtmlID <|
Msgs.PipelineCardName Msgs.AllPipelinesSection 1
]
, describe "favorited pipeline instances" <|
let
setup pipelines _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> gotPipelines pipelines
|> Application.handleDelivery
(FavoritedPipelinesReceived <|
Ok (Set.singleton 1)
)
|> Tuple.first
findCardHeader =
Common.queryView
>> findFavoritesSection
>> Query.find
[ class "card"
, containing [ text "group" ]
]
>> Query.find [ class "card-header" ]
in
[ test "header displays instance vars and group name" <|
setup [ pipelineInstanceWithVars 1 [ ( "foo", JsonString "bar" ) ] ]
>> findCardHeader
>> Expect.all
[ Query.has
[ style "height" "80px"
, style "box-sizing" "border-box"
]
, Query.has [ text "group" ]
, Query.has [ containing [ text "foo" ], containing [ text "bar" ] ]
]
, test "an instance with no instance vars displays \"no instance vars\"" <|
setup
[ pipelineInstanceWithVars 1 []
, pipelineInstanceWithVars 2 [ ( "foo", JsonString "bar" ) ]
]
>> findCardHeader
>> Expect.all
[ Query.has
[ style "height" "80px"
, style "box-sizing" "border-box"
]
, Query.has [ text "group" ]
, Query.has [ text "no instance vars" ]
]
, test "all instance vars appear on the same row" <|
setup
[ pipelineInstanceWithVars 1
[ ( "a", JsonString "1" )
, ( "b", JsonString "2" )
]
]
>> findCardHeader
>> Expect.all
[ Query.has
[ style "height" "80px"
, style "box-sizing" "border-box"
]
, Query.has [ text "group" ]
, Query.has
[ containing [ text "a" ]
, containing [ text "1" ]
, containing [ text "b" ]
, containing [ text "2" ]
]
]
]
]
, describe "colored banner" <|
let
findBanner =
Query.find
[ class "card"
, containing [ text "pipeline" ]
]
>> Query.find
[ class "banner" ]
isSolid : String -> Query.Single ApplicationMsgs.TopLevelMessage -> Expectation
isSolid color =
Query.has [ style "background-color" color ]
in
[ describe "non-HD view"
[ test "is 7px tall" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> Query.has [ style "height" "7px" ]
, test "is grey when pipeline is cached" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "<NAME>" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is dark grey when pipeline is archived" <|
\_ ->
whenOnDashboardViewingAllPipelines { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "<NAME>" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withArchived True
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid Colors.backgroundDark
, test "is blue when pipeline is paused" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "<NAME>" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid blue
, test "is green when pipeline is succeeding" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findBanner
|> isSolid green
, test "is green with black stripes when pipeline is succeeding and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
True
|> findBanner
|> isColorWithStripes { thin = green, thick = ColorValues.grey90 }
, test "is grey when pipeline is pending" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is grey with black stripes when pipeline is pending and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusStarted
True
|> findBanner
|> isColorWithStripes { thin = lightGrey, thick = ColorValues.grey90 }
, test "is red when pipeline is failing" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
False
|> findBanner
|> isSolid red
, test "is red with black stripes when pipeline is failing and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
True
|> findBanner
|> isColorWithStripes { thin = red, thick = ColorValues.grey90 }
, test "is amber when pipeline is erroring" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusErrored
False
|> findBanner
|> isSolid amber
, test "is amber with black stripes when pipeline is erroring and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusErrored
True
|> findBanner
|> isColorWithStripes { thin = amber, thick = ColorValues.grey90 }
, test "is brown when pipeline is aborted" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusAborted
False
|> findBanner
|> isSolid brown
, test "is brown with black stripes when pipeline is aborted and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusAborted
True
|> findBanner
|> isColorWithStripes { thin = brown, thick = ColorValues.grey90 }
, describe "status priorities" <|
let
givenTwoJobsWithModifiers :
BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobsWithModifiers firstStatus firstModifier secondStatus secondModifier =
whenOnDashboard { highDensity = False }
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ job firstStatus |> firstModifier
, otherJob secondStatus |> secondModifier
]
)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
givenTwoJobs :
BuildStatus
-> BuildStatus
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobs firstStatus secondStatus =
givenTwoJobsWithModifiers firstStatus identity secondStatus identity
in
[ test "failed is more important than errored" <|
\_ ->
givenTwoJobs
BuildStatusFailed
BuildStatusErrored
|> findBanner
|> isSolid red
, test "errored is more important than aborted" <|
\_ ->
givenTwoJobs
BuildStatusErrored
BuildStatusAborted
|> findBanner
|> isSolid amber
, test "aborted is more important than succeeding" <|
\_ ->
givenTwoJobs
BuildStatusAborted
BuildStatusSucceeded
|> findBanner
|> isSolid brown
, test "succeeding is more important than pending" <|
\_ ->
givenTwoJobs
BuildStatusSucceeded
BuildStatusPending
|> findBanner
|> isSolid green
, test "paused jobs are ignored" <|
\_ ->
givenTwoJobsWithModifiers
BuildStatusSucceeded
identity
BuildStatusFailed
(Data.withPaused True)
|> findBanner
|> isSolid green
]
, test "does not crash with a circular pipeline" <|
\_ ->
whenOnDashboard { highDensity = False }
|> Application.handleCallback (Callback.AllJobsFetched <| Ok circularJobs)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid green
, describe "HD view"
[ test "is 8px wide" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> Query.has [ style "width" "8px" ]
, test "is grey when pipeline is cached" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated [ { id = 0, name = "<NAME>" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is dark grey when pipeline is archived" <|
\_ ->
whenOnDashboardViewingAllPipelines { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "<NAME>" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withArchived True
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid Colors.backgroundDark
, test "is blue when pipeline is paused" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated [ { id = 0, name = "<NAME>" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid blue
, test "is green when pipeline is succeeding" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findBanner
|> isSolid green
, test "is green with black stripes when pipeline is succeeding and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusSucceeded
True
|> findBanner
|> isColorWithStripes { thin = green, thick = ColorValues.grey90 }
, test "is grey when pipeline is pending" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is grey with black stripes when pipeline is pending and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusStarted
True
|> findBanner
|> isColorWithStripes { thin = lightGrey, thick = ColorValues.grey90 }
, test "is red when pipeline is failing" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusFailed
False
|> findBanner
|> isSolid red
, test "is red with black stripes when pipeline is failing and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusFailed
True
|> findBanner
|> isColorWithStripes { thin = red, thick = ColorValues.grey90 }
, test "is amber when pipeline is erroring" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusErrored
False
|> findBanner
|> isSolid amber
, test "is amber with black stripes when pipeline is erroring and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusErrored
True
|> findBanner
|> isColorWithStripes { thin = amber, thick = ColorValues.grey90 }
, test "is brown when pipeline is aborted" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusAborted
False
|> findBanner
|> isSolid brown
, test "is brown with black stripes when pipeline is aborted and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusAborted
True
|> findBanner
|> isColorWithStripes { thin = brown, thick = ColorValues.grey90 }
, describe "status priorities" <|
let
givenTwoJobsWithModifiers :
BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobsWithModifiers firstStatus firstModifier secondStatus secondModifier =
whenOnDashboard { highDensity = True }
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ job firstStatus |> firstModifier
, otherJob secondStatus |> secondModifier
]
)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
givenTwoJobs :
BuildStatus
-> BuildStatus
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobs firstStatus secondStatus =
givenTwoJobsWithModifiers firstStatus identity secondStatus identity
in
[ test "failed is more important than errored" <|
\_ ->
givenTwoJobs
BuildStatusFailed
BuildStatusErrored
|> findBanner
|> isSolid red
, test "errored is more important than aborted" <|
\_ ->
givenTwoJobs
BuildStatusErrored
BuildStatusAborted
|> findBanner
|> isSolid amber
, test "aborted is more important than succeeding" <|
\_ ->
givenTwoJobs
BuildStatusAborted
BuildStatusSucceeded
|> findBanner
|> isSolid brown
, test "succeeding is more important than pending" <|
\_ ->
givenTwoJobs
BuildStatusSucceeded
BuildStatusPending
|> findBanner
|> isSolid green
, test "paused jobs are ignored" <|
\_ ->
givenTwoJobsWithModifiers
BuildStatusSucceeded
identity
BuildStatusFailed
(Data.withPaused True)
|> findBanner
|> isSolid green
]
]
]
]
, describe "on HD view" <|
let
setup : () -> Query.Single ApplicationMsgs.TopLevelMessage
setup _ =
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
noPipelines : () -> Query.Single ApplicationMsgs.TopLevelMessage
noPipelines _ =
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData
[ ( "some-team", [] )
, ( "other-team", [] )
]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "other-team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
card : Query.Single ApplicationMsgs.TopLevelMessage -> Query.Single ApplicationMsgs.TopLevelMessage
card =
Query.find
[ class "card"
, containing [ text "pipeline" ]
]
cardText : Query.Single ApplicationMsgs.TopLevelMessage -> Query.Single ApplicationMsgs.TopLevelMessage
cardText =
card
>> Query.children []
>> Query.index 1
noPipelinesCard =
Query.find
[ class "card"
, containing [ text "no pipeline" ]
]
in
[ test "no pipelines card has 14px font and 1px spacing" <|
noPipelines
>> noPipelinesCard
>> Query.has
[ style "font-size" "14px"
, style "letter-spacing" "1px"
]
, test "no pipelines card text is vertically centered" <|
noPipelines
>> noPipelinesCard
>> Query.has
[ style "display" "flex"
, style "align-items" "center"
]
, test "no pipelines card is 60px tall" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "height" "60px" ]
, test "no pipelines card has 60px right margin" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "margin-right" "60px" ]
, test "no pipelines card text has 10px padding" <|
noPipelines
>> noPipelinesCard
>> Query.children []
>> Query.first
>> Query.has [ style "padding" "10px" ]
, test "no pipelines card is 200px wide" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "width" "200px" ]
, test "no pipelines card has dark grey background" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "card name is hoverable" <|
setup
>> card
>> Query.find [ class "dashboardhd-pipeline-name" ]
>> Event.simulate Event.mouseEnter
>> Event.expect
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just <|
Msgs.PipelineCardNameHD 1
)
, test "card name has html id" <|
setup
>> card
>> Query.find [ class "dashboardhd-pipeline-name" ]
>> Query.has
[ id <|
Effects.toHtmlID <|
Msgs.PipelineCardNameHD 1
]
, test "card has larger tighter font" <|
setup
>> card
>> Query.has
[ style "font-size" "19px"
, style "letter-spacing" "1px"
]
, test "card text does not overflow or wrap" <|
setup
>> cardText
>> Query.has
[ style "width" "180px"
, style "white-space" "nowrap"
, style "overflow" "hidden"
, style "text-overflow" "ellipsis"
]
, test "card text is vertically centered" <|
setup
>> cardText
>> Query.has
[ style "align-self" "center" ]
, test "card text has 10px padding" <|
setup
>> cardText
>> Query.has
[ style "padding" "10px" ]
, test "card lays out contents horizontally" <|
setup
>> card
>> Query.has
[ style "display" "flex" ]
, test "card is 60px tall" <|
setup
>> card
>> Query.has [ style "height" "60px" ]
, test "card is 200px wide" <|
setup
>> card
>> Query.has [ style "width" "200px" ]
, test "no triangle when there is no resource error" <|
setup
>> card
>> Query.children []
>> Query.count (Expect.equal 2)
, describe "resource error triangle" <|
let
givenResourceFailingToCheck : () -> Query.Single ApplicationMsgs.TopLevelMessage
givenResourceFailingToCheck _ =
whenOnDashboard { highDensity = True }
|> Application.handleCallback
(Callback.AllResourcesFetched <|
Ok
[ Data.resource Nothing
|> Data.withBuild (Just <| Data.build Concourse.BuildStatus.BuildStatusFailed)
]
)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
resourceErrorTriangle =
Query.children []
>> Query.index -1
in
[ test "exists" <|
givenResourceFailingToCheck
>> card
>> Query.children []
>> Query.count (Expect.equal 3)
, test "is at the top right of card" <|
givenResourceFailingToCheck
>> card
>> Expect.all
[ Query.has [ style "position" "relative" ]
, resourceErrorTriangle
>> Query.has
[ style "position" "absolute"
, style "top" "0"
, style "right" "0"
]
]
, test "is an orange 'top right' triangle" <|
givenResourceFailingToCheck
>> card
>> resourceErrorTriangle
>> Query.has
[ style "width" "0"
, style "height" "0"
, style "border-top" <| "30px solid " ++ orange
, style "border-left" "30px solid transparent"
]
]
, test
("cards are spaced 4px apart vertically and "
++ "60px apart horizontally"
)
<|
setup
>> card
>> Query.has
[ style "margin" "0 60px 4px 0" ]
, test "card is faded green when pipeline is succeeding" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> card
|> Query.has [ style "background-color" fadedGreen ]
, test "card is red when pipeline is failing" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusFailed
False
|> card
|> Query.has [ style "background-color" red ]
, test "card is amber when pipeline is erroring" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusErrored
False
|> card
|> Query.has [ style "background-color" amber ]
, test "card is not affected by jobs from other pipelines" <|
\_ ->
whenOnDashboard { highDensity = True }
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllJobsFetched <|
let
baseJob =
job BuildStatusErrored
in
Ok
[ { baseJob | pipelineName = "other-pipeline" } ]
)
|> Tuple.first
|> Common.queryView
|> card
|> Query.hasNot [ style "background-color" amber ]
]
, describe "body" <|
let
setup : () -> Query.Single ApplicationMsgs.TopLevelMessage
setup _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
in
[ test "has dark grey background" <|
setup
>> findBody
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "has 2px margin above and below" <|
setup
>> findBody
>> Query.has [ style "margin" "2px 0" ]
, test "fills available height" <|
setup
>> findBody
>> Query.has [ style "flex-grow" "1" ]
, test "allows pipeline-grid to fill available height" <|
setup
>> findBody
>> Query.has [ style "display" "flex" ]
, test "pipeline-grid fills available width" <|
setup
>> findBody
>> Query.find [ class "pipeline-grid" ]
>> Query.has
[ style "box-sizing" "border-box"
, style "width" "100%"
]
]
, describe "footer" <|
let
hasStyle : String -> String -> Expectation
hasStyle property value =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.has [ style property value ]
in
[ test "has dark grey background" <|
\_ ->
hasStyle "background-color" ColorValues.grey90
, test "has medium padding" <|
\_ ->
hasStyle "padding" "13.5px"
, test "lays out contents horizontally" <|
\_ ->
hasStyle "display" "flex"
, test "is divided into a left and right section, spread apart" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Expect.all
[ Query.children []
>> Query.count (Expect.equal 2)
, Query.has
[ style "justify-content" "space-between" ]
]
, test "both sections lay out contents horizontally" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.each (Query.has [ style "display" "flex" ])
, describe "left-hand section" <|
let
findStatusIcon =
Query.find [ class "pipeline-status" ]
>> Query.children []
>> Query.first
findStatusText =
Query.find [ class "pipeline-status" ]
>> Query.children []
>> Query.index -1
in
[ describe "when pipeline is paused" <|
let
setup =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
in
[ test "status icon is blue pause" <|
\_ ->
setup
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconPaused
}
++ [ style "background-size" "contain" ]
)
, test "status text is blue" <|
\_ ->
setup
|> findStatusText
|> Query.has [ style "color" blue ]
, test "status text is larger and spaced more widely" <|
\_ ->
setup
|> findStatusText
|> Query.has
[ style "font-size" "18px"
, style "line-height" "20px"
, style "letter-spacing" "0.05em"
]
, test "status text is offset to the right of the icon" <|
\_ ->
setup
|> findStatusText
|> Query.has [ style "margin-left" "8px" ]
, test "status text says 'paused'" <|
\_ ->
setup
|> findStatusText
|> Query.has [ text "paused" ]
]
, describe "when a pipeline is based on cache" <|
let
setup =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
in
[ test "status icon is grey pending" <|
\_ ->
setup
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconStale
}
++ [ style "background-size" "contain" ]
)
, test "status text is grey" <|
\_ ->
setup
|> findStatusText
|> Query.has [ style "color" lightGrey ]
, test "status text says 'loading...'" <|
\_ ->
setup
|> findStatusText
|> Query.has [ text "loading..." ]
, test "pipeline card is faded" <|
\_ ->
setup
|> Query.find [ class "card" ]
|> Query.has [ style "opacity" "0.45" ]
]
, describe "when pipeline has no jobs due to a disabled endpoint" <|
let
setup =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedJobsReceived <| Ok [ Data.job 0 ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllJobsFetched <|
Data.httpNotImplemented
)
domID =
Msgs.PipelineStatusIcon AllPipelinesSection 0
in
[ test "status icon is faded sync" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconJobsDisabled
}
++ [ style "background-size" "contain"
, style "opacity" "0.5"
]
)
, test "status icon is hoverable" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> findStatusIcon
|> Event.simulate Event.mouseEnter
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just domID
)
, test "hovering status icon sends location request" <|
\_ ->
setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just domID
)
|> Tuple.second
|> Common.contains
(Effects.GetViewportOf domID)
, test "hovering status icon shows tooltip" <|
\_ ->
setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just domID
)
|> Tuple.first
|> Application.handleCallback
(Callback.GotViewport domID
(Ok
{ scene =
{ width = 1
, height = 0
}
, viewport =
{ width = 1
, height = 0
, x = 0
, y = 0
}
}
)
)
|> Tuple.first
|> Application.handleCallback
(Callback.GotElement <|
Ok
{ scene =
{ width = 0
, height = 0
}
, viewport =
{ width = 0
, height = 0
, x = 0
, y = 0
}
, element =
{ x = 0
, y = 0
, width = 1
, height = 1
}
}
)
|> Tuple.first
|> Common.queryView
|> Query.has
[ style "position" "fixed"
, containing [ text "automatic job monitoring disabled" ]
]
, test "status text says 'no data'" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> findStatusText
|> Query.has [ text "no data" ]
, test "job preview is empty placeholder" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-body" ]
|> Query.has [ style "background-color" ColorValues.grey90 ]
, test "job data is cleared" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "parallel-grid" ]
|> Query.hasNot [ tag "a" ]
, test "job data is cleared from local cache" <|
\_ ->
setup
|> Tuple.second
|> Common.contains Effects.DeleteCachedJobs
]
, describe "when pipeline is archived" <|
let
setup =
whenOnDashboardViewingAllPipelines { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "<NAME>" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withArchived True
]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ Data.job 0 ]
)
in
[ test "status section is empty" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "pipeline-status" ]
|> Query.children []
|> Query.count (Expect.equal 0)
, test "job preview is empty placeholder" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-body" ]
|> Query.has [ style "background-color" ColorValues.grey90 ]
, test "there is no pause button" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.hasNot [ class "pause-toggle" ]
]
, describe "when pipeline is pending" <|
[ test "status icon is grey" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconPending
}
++ [ style "background-size" "contain" ]
)
, test "status text is grey" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
False
|> findStatusText
|> Query.has [ style "color" lightGrey ]
, test "status text says 'pending'" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
False
|> findStatusText
|> Query.has
[ text "pending" ]
, test "when running, status text says 'running'" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
True
|> findStatusText
|> Query.has
[ text "running" ]
]
, describe "when pipeline is succeeding"
[ test "status icon is a green check" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconSucceeded
}
++ [ style "background-size" "contain" ]
)
, test "status text is green" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findStatusText
|> Query.has [ style "color" green ]
, test "when running, status text says 'running'" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
True
|> findStatusText
|> Query.has
[ text "running" ]
, test "when not running, status text shows age" <|
\_ ->
whenOnDashboard { highDensity = False }
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ jobWithNameTransitionedAt
"job"
(Just <| Time.millisToPosix 0)
BuildStatusSucceeded
]
)
|> Tuple.first
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> afterSeconds 1
|> Common.queryView
|> findStatusText
|> Query.has
[ text "1s" ]
]
, describe "when pipeline is failing"
[ test "status icon is a red !" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconFailed
}
++ [ style "background-size" "contain" ]
)
, test "status text is red" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
False
|> findStatusText
|> Query.has [ style "color" red ]
]
, test "when pipeline is aborted, status icon is a brown x" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusAborted
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconAborted
}
++ [ style "background-size" "contain" ]
)
, test "when pipeline is errored, status icon is an amber triangle" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusErrored
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconErrored
}
++ [ style "background-size" "contain" ]
)
]
, describe "right-hand section"
[ describe "visibility toggle" <|
let
pipelineId =
Data.pipelineId
visibilityToggle =
Common.queryView
>> Query.findAll [ class "card-footer" ]
>> Query.first
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 2
openEye =
iconSelector
{ size = "20px"
, image = Assets.VisibilityToggleIcon True
}
++ [ style "background-size" "contain" ]
slashedOutEye =
iconSelector
{ size = "20px"
, image = Assets.VisibilityToggleIcon False
}
++ [ style "background-size" "contain" ]
openEyeClickable setup =
[ defineHoverBehaviour
{ name = "open eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "pointer"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "bright 20px square"
, selector =
openEye
++ [ style "opacity" "1"
, style "cursor" "pointer"
]
}
}
, test "has click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
, test "click has HidePipeline effect" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.second
|> Expect.equal
[ Effects.ChangeVisibility
Msgs.Hide
pipelineId
]
, defineHoverBehaviour
{ name = "open eye toggle in favorites section"
, setup =
whenOnDashboard { highDensity = False }
|> Application.handleDelivery
(Message.Subscription.FavoritedPipelinesReceived <| Ok <| Set.singleton 0)
|> Tuple.first
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "pointer"
]
}
, hoverable =
Msgs.VisibilityButton FavoritesSection 0
, hoveredSelector =
{ description = "bright 20px square"
, selector =
openEye
++ [ style "opacity" "1"
, style "cursor" "pointer"
]
}
}
, defineHoverBehaviour
{ name = "visibility spinner"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
}
, test "success resolves spinner to slashed-out eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Hide
pipelineId
(Ok ())
)
|> Tuple.first
|> visibilityToggle
|> Query.has slashedOutEye
, test "error resolves spinner to open eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Hide
pipelineId
Data.httpInternalServerError
)
|> Tuple.first
|> visibilityToggle
|> Query.has openEye
, test "401 redirects to login" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Hide
pipelineId
Data.httpUnauthorized
)
|> Tuple.second
|> Expect.equal
[ Effects.RedirectToLogin ]
]
openEyeUnclickable setup =
[ defineHoverBehaviour
{ name = "open eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
}
, test "has no click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.toResult
|> Expect.err
]
slashedOutEyeClickable setup =
[ defineHoverBehaviour
{ name = "slashed-out eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "0.5"
, style "cursor" "pointer"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "bright 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "1"
, style "cursor" "pointer"
]
}
}
, test "has click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
, test "click has ExposePipeline effect" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.second
|> Expect.equal
[ Effects.ChangeVisibility
Msgs.Expose
pipelineId
]
, defineHoverBehaviour
{ name = "visibility spinner"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
}
, test "success resolves spinner to open eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Expose
pipelineId
(Ok ())
)
|> Tuple.first
|> visibilityToggle
|> Query.has openEye
, test "error resolves spinner to slashed-out eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Expose
pipelineId
Data.httpInternalServerError
)
|> Tuple.first
|> visibilityToggle
|> Query.has slashedOutEye
]
slashedOutEyeUnclickable setup =
[ defineHoverBehaviour
{ name = "slashed-out eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "faded 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
}
, test "has no click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.toResult
|> Expect.err
]
in
[ describe "when authorized" <|
let
whenAuthorizedPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "owner" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
whenAuthorizedNonPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "owner" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPublic False
]
)
in
[ describe "on public pipeline" <|
openEyeClickable whenAuthorizedPublic
, describe "on a non-public pipeline" <|
slashedOutEyeClickable whenAuthorizedNonPublic
]
, describe "when unauthorized" <|
let
whenUnauthorizedPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "viewer" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
whenUnauthorizedNonPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "viewer" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPublic False
]
)
in
[ describe "on public pipeline" <|
openEyeUnclickable whenUnauthorizedPublic
, describe "on a non-public pipeline" <|
slashedOutEyeUnclickable
whenUnauthorizedNonPublic
]
, describe "when unauthenticated" <|
let
whenUnauthenticated =
givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
in
[ describe "on public pipeline" <|
openEyeClickable whenUnauthenticated
]
]
, test "there is medium spacing between the eye and the play/pause button" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.index -1
|> Query.children []
|> Expect.all
[ Query.count (Expect.equal 5)
, Query.index 1 >> Query.has [ style "width" "12px" ]
]
, test "there is medium spacing between the eye and the favorited icon" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.index -1
|> Query.children []
|> Expect.all
[ Query.count (Expect.equal 5)
, Query.index 3 >> Query.has [ style "width" "12px" ]
]
, describe "pause toggle"
[ test "the right section has a 20px square pause button on the left" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.index -1
|> Query.children []
|> Query.index 0
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
)
, test "pause button has pointer cursor when authorized" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.find
(iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
)
|> Query.has [ style "cursor" "pointer" ]
, test "pause button is transparent" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.find
(iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
)
|> Query.has [ style "opacity" "0.5" ]
, defineHoverBehaviour
{ name = "pause button"
, setup =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
, query =
Common.queryView
>> Query.find [ class "card-footer" ]
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 0
, unhoveredSelector =
{ description = "a faded 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "0.5"
]
}
, hoverable = Msgs.PipelineCardPauseToggle AllPipelinesSection 1
, hoveredSelector =
{ description = "a bright 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "1"
]
}
}
, defineHoverBehaviour
{ name = "pause button in favorites section"
, setup =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.handleDelivery
(Message.Subscription.FavoritedPipelinesReceived <| Ok <| Set.singleton 1)
|> Tuple.first
, query =
Common.queryView
>> Query.findAll [ class "card-footer" ]
>> Query.first
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 0
, unhoveredSelector =
{ description = "a faded 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "0.5"
]
}
, hoverable =
Msgs.PipelineCardPauseToggle FavoritesSection 1
, hoveredSelector =
{ description = "a bright 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "1"
]
}
}
, defineHoverBehaviour
{ name = "play button"
, setup =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
, query =
Common.queryView
>> Query.find [ class "card-footer" ]
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 0
, unhoveredSelector =
{ description = "a transparent 20px square play button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PlayIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "0.5"
]
}
, hoverable = Msgs.PipelineCardPauseToggle AllPipelinesSection 1
, hoveredSelector =
{ description = "an opaque 20px square play button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PlayIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "1"
]
}
}
, test "clicking pause button sends TogglePipeline msg" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.find [ class "pause-toggle" ]
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
, test "pause button turns into spinner on click" <|
\_ ->
let
animation =
"container-rotate 1568ms linear infinite"
in
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.has [ style "animation" animation ]
, test "clicking pause button sends toggle api call" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.second
|> Expect.equal [ Effects.SendTogglePipelineRequest Data.pipelineId False ]
, test "all pipelines are refetched after ok toggle call" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.first
|> Application.handleCallback
(Callback.PipelineToggled Data.pipelineId (Ok ()))
|> Tuple.second
|> Expect.equal [ Effects.FetchAllPipelines ]
, test "401 toggle call redirects to login" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.first
|> Application.handleCallback
(Callback.PipelineToggled Data.pipelineId Data.httpUnauthorized)
|> Tuple.second
|> Expect.equal [ Effects.RedirectToLogin ]
]
, describe "favorited icon" <|
let
pipelineId =
0
unfilledFavoritedIcon =
iconSelector
{ size = "20px"
, image = Assets.FavoritedToggleIcon { isFavorited = False, isHovered = False, isSideBar = False }
}
++ [ style "background-size" "contain" ]
unfilledBrightFavoritedIcon =
iconSelector
{ size = "20px"
, image = Assets.FavoritedToggleIcon { isFavorited = False, isHovered = True, isSideBar = False }
}
++ [ style "background-size" "contain" ]
filledFavoritedIcon =
iconSelector
{ size = "20px"
, image = Assets.FavoritedToggleIcon { isFavorited = True, isHovered = False, isSideBar = False }
}
++ [ style "background-size" "contain" ]
favoritedToggle =
Common.queryView
>> Query.findAll [ class "card-footer" ]
>> Query.first
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index -1
favoritedIconClickable setup =
[ defineHoverBehaviour
{ name = "favorited icon toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = favoritedToggle
, unhoveredSelector =
{ description = "faded star icon"
, selector =
unfilledFavoritedIcon
++ [ style "cursor" "pointer" ]
}
, hoverable =
Msgs.PipelineCardFavoritedIcon AllPipelinesSection pipelineId
, hoveredSelector =
{ description = "bright star icon"
, selector =
unfilledBrightFavoritedIcon
++ [ style "cursor" "pointer" ]
}
}
, test "has click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> favoritedToggle
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardFavoritedIcon
AllPipelinesSection
pipelineId
)
, test "click has FavoritedPipeline effect" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardFavoritedIcon
AllPipelinesSection
pipelineId
)
|> Tuple.second
|> Expect.equal
[ Effects.SaveFavoritedPipelines <|
Set.singleton pipelineId
]
, test "favorited pipeline card has a bright filled star icon" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.handleDelivery
(FavoritedPipelinesReceived <|
Ok <|
Set.singleton pipelineId
)
|> Tuple.first
|> favoritedToggle
|> Expect.all
[ Query.has filledFavoritedIcon
]
]
in
favoritedIconClickable
(givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "owner" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
)
]
]
]
| true | module PipelineCardTests exposing (all)
import Application.Application as Application
import Assets
import ColorValues
import Colors
import Common
exposing
( defineHoverBehaviour
, givenDataUnauthenticated
, gotPipelines
, isColorWithStripes
)
import Concourse exposing (JsonValue(..))
import Concourse.BuildStatus exposing (BuildStatus(..))
import Concourse.PipelineStatus exposing (PipelineStatus(..), StatusDetails(..))
import DashboardInstanceGroupTests exposing (pipelineInstanceWithVars)
import DashboardTests
exposing
( afterSeconds
, amber
, apiData
, blue
, brown
, circularJobs
, darkGrey
, fadedGreen
, givenDataAndUser
, green
, iconSelector
, job
, jobWithNameTransitionedAt
, lightGrey
, middleGrey
, orange
, otherJob
, red
, running
, userWithRoles
, whenOnDashboard
, whenOnDashboardViewingAllPipelines
, white
)
import Data
import Dict
import Expect exposing (Expectation)
import Html.Attributes as Attr
import Message.Callback as Callback
import Message.Effects as Effects
import Message.Message as Msgs exposing (DomID(..), PipelinesSection(..))
import Message.Subscription exposing (Delivery(..), Interval(..))
import Message.TopLevelMessage as ApplicationMsgs
import Set
import Test exposing (Test, describe, test)
import Test.Html.Event as Event
import Test.Html.Query as Query
import Test.Html.Selector exposing (attribute, class, containing, id, style, tag, text)
import Time
all : Test
all =
describe "pipeline cards" <|
let
findHeader :
Query.Single ApplicationMsgs.TopLevelMessage
-> Query.Single ApplicationMsgs.TopLevelMessage
findHeader =
Query.find [ class "card-header" ]
findBody :
Query.Single ApplicationMsgs.TopLevelMessage
-> Query.Single ApplicationMsgs.TopLevelMessage
findBody =
Query.find [ class "card-body" ]
findFavoritesSection =
Query.find [ id "dashboard-favorite-pipelines" ]
pipelineWithStatus :
BuildStatus
-> Bool
-> Application.Model
-> Query.Single ApplicationMsgs.TopLevelMessage
pipelineWithStatus status isRunning =
let
jobFunc =
if isRunning then
job >> running
else
job
in
Application.handleCallback
(Callback.AllJobsFetched <| Ok [ jobFunc status ])
>> Tuple.first
>> givenDataUnauthenticated [ { id = 0, name = "team" } ]
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
>> Tuple.first
>> Application.handleDelivery
(ClockTicked OneSecond <| Time.millisToPosix 0)
>> Tuple.first
>> Common.queryView
in
[ describe "when team has no visible pipelines" <|
let
noPipelinesCard : () -> Query.Single ApplicationMsgs.TopLevelMessage
noPipelinesCard _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData
[ ( "some-team", [] )
, ( "other-team", [] )
]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "other-team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "dashboard-team-group"
, attribute <|
Attr.attribute "data-team-name"
"some-team"
]
|> Query.find [ class "card" ]
in
[ describe "card" <|
[ test "card has display flex with direction column" <|
noPipelinesCard
>> Query.has
[ style "display" "flex"
, style "flex-direction" "column"
]
, test "card has width 272px and height 268px" <|
noPipelinesCard
>> Query.has
[ style "width" "272px"
, style "height" "268px"
]
, test "card has a left margin of 25px" <|
noPipelinesCard
>> Query.has
[ style "margin-left" "25px" ]
]
, describe "header" <|
let
header : () -> Query.Single ApplicationMsgs.TopLevelMessage
header =
noPipelinesCard
>> findHeader
in
[ test "says 'no pipeline set' in white font" <|
header
>> Expect.all
[ Query.has [ text "no pipeline set" ]
, Query.has [ style "color" ColorValues.grey20 ]
]
, test "has dark grey background" <|
header
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "text is larger and wider spaced" <|
header
>> Query.has
[ style "font-size" "1.5em"
, style "letter-spacing" "0.1em"
]
, test "text is centered" <|
header
>> Query.has [ style "text-align" "center" ]
]
, describe "body" <|
let
body : () -> Query.Single ApplicationMsgs.TopLevelMessage
body =
noPipelinesCard
>> Query.find [ class "card-body" ]
in
[ test "has 20px 36px padding" <|
body
>> Query.has
[ style "padding" "20px 36px" ]
, test "fills available height" <|
body
>> Query.has [ style "flex-grow" "1" ]
, test "has dark grey background" <|
body
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "has 2px margins above and below" <|
body
>> Query.has [ style "margin" "2px 0" ]
, test "has lighter grey placeholder box that fills" <|
body
>> Expect.all
[ Query.has [ style "display" "flex" ]
, Query.children []
>> Query.first
>> Query.has
[ style "background-color" ColorValues.grey80
, style "flex-grow" "1"
]
]
]
, test "footer is dark grey and 47 pixels tall" <|
noPipelinesCard
>> Query.find [ class "card-footer" ]
>> Query.has
[ style "background-color" ColorValues.grey90
, style "height" "47px"
]
]
, test "is draggable when in all pipelines section and result is not stale" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "PI:NAME:<NAME>END_PI" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> Expect.all
[ Query.has [ attribute <| Attr.attribute "draggable" "true" ]
, Query.has [ style "cursor" "move" ]
]
, test "is not draggable when in favorites section" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.handleDelivery
(FavoritedPipelinesReceived <| Ok <| Set.singleton 0)
|> Tuple.first
|> Common.queryView
|> Query.findAll
[ class "card"
, containing [ text "pipeline" ]
]
|> Query.first
|> Expect.all
[ Query.hasNot [ attribute <| Attr.attribute "draggable" "true" ]
, Query.hasNot [ style "cursor" "move" ]
]
, test "is not draggable when rendering based on the cache" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "PI:NAME:<NAME>END_PI" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> Expect.all
[ Query.hasNot [ attribute <| Attr.attribute "draggable" "true" ]
, Query.hasNot [ style "cursor" "move" ]
]
, test "fills available space" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated (apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> Query.has
[ style "width" "100%"
, style "height" "100%"
, style "display" "flex"
, style "flex-direction" "column"
]
, describe "header" <|
let
header : () -> Query.Single ApplicationMsgs.TopLevelMessage
header _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
|> findHeader
in
[ test "has dark grey background" <|
header
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "has larger, spaced-out light-grey text" <|
header
>> Query.has
[ style "font-size" "1.5em"
, style "letter-spacing" "0.1em"
, style "color" ColorValues.grey20
]
, test "text does not overflow or wrap" <|
header
>> Query.children []
>> Query.first
>> Query.has
[ style "width" "245px"
, style "white-space" "nowrap"
, style "overflow" "hidden"
, style "text-overflow" "ellipsis"
]
, test "is hoverable" <|
header
>> Query.find [ class "dashboard-pipeline-name" ]
>> Event.simulate Event.mouseEnter
>> Event.expect
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just <|
Msgs.PipelineCardName Msgs.AllPipelinesSection 1
)
, test "has html id" <|
header
>> Query.find [ class "dashboard-pipeline-name" ]
>> Query.has
[ id <|
Effects.toHtmlID <|
Msgs.PipelineCardName Msgs.AllPipelinesSection 1
]
, describe "favorited pipeline instances" <|
let
setup pipelines _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> gotPipelines pipelines
|> Application.handleDelivery
(FavoritedPipelinesReceived <|
Ok (Set.singleton 1)
)
|> Tuple.first
findCardHeader =
Common.queryView
>> findFavoritesSection
>> Query.find
[ class "card"
, containing [ text "group" ]
]
>> Query.find [ class "card-header" ]
in
[ test "header displays instance vars and group name" <|
setup [ pipelineInstanceWithVars 1 [ ( "foo", JsonString "bar" ) ] ]
>> findCardHeader
>> Expect.all
[ Query.has
[ style "height" "80px"
, style "box-sizing" "border-box"
]
, Query.has [ text "group" ]
, Query.has [ containing [ text "foo" ], containing [ text "bar" ] ]
]
, test "an instance with no instance vars displays \"no instance vars\"" <|
setup
[ pipelineInstanceWithVars 1 []
, pipelineInstanceWithVars 2 [ ( "foo", JsonString "bar" ) ]
]
>> findCardHeader
>> Expect.all
[ Query.has
[ style "height" "80px"
, style "box-sizing" "border-box"
]
, Query.has [ text "group" ]
, Query.has [ text "no instance vars" ]
]
, test "all instance vars appear on the same row" <|
setup
[ pipelineInstanceWithVars 1
[ ( "a", JsonString "1" )
, ( "b", JsonString "2" )
]
]
>> findCardHeader
>> Expect.all
[ Query.has
[ style "height" "80px"
, style "box-sizing" "border-box"
]
, Query.has [ text "group" ]
, Query.has
[ containing [ text "a" ]
, containing [ text "1" ]
, containing [ text "b" ]
, containing [ text "2" ]
]
]
]
]
, describe "colored banner" <|
let
findBanner =
Query.find
[ class "card"
, containing [ text "pipeline" ]
]
>> Query.find
[ class "banner" ]
isSolid : String -> Query.Single ApplicationMsgs.TopLevelMessage -> Expectation
isSolid color =
Query.has [ style "background-color" color ]
in
[ describe "non-HD view"
[ test "is 7px tall" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> Query.has [ style "height" "7px" ]
, test "is grey when pipeline is cached" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "PI:NAME:<NAME>END_PI" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is dark grey when pipeline is archived" <|
\_ ->
whenOnDashboardViewingAllPipelines { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "PI:NAME:<NAME>END_PI" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withArchived True
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid Colors.backgroundDark
, test "is blue when pipeline is paused" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "PI:NAME:<NAME>END_PI" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid blue
, test "is green when pipeline is succeeding" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findBanner
|> isSolid green
, test "is green with black stripes when pipeline is succeeding and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
True
|> findBanner
|> isColorWithStripes { thin = green, thick = ColorValues.grey90 }
, test "is grey when pipeline is pending" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is grey with black stripes when pipeline is pending and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusStarted
True
|> findBanner
|> isColorWithStripes { thin = lightGrey, thick = ColorValues.grey90 }
, test "is red when pipeline is failing" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
False
|> findBanner
|> isSolid red
, test "is red with black stripes when pipeline is failing and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
True
|> findBanner
|> isColorWithStripes { thin = red, thick = ColorValues.grey90 }
, test "is amber when pipeline is erroring" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusErrored
False
|> findBanner
|> isSolid amber
, test "is amber with black stripes when pipeline is erroring and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusErrored
True
|> findBanner
|> isColorWithStripes { thin = amber, thick = ColorValues.grey90 }
, test "is brown when pipeline is aborted" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusAborted
False
|> findBanner
|> isSolid brown
, test "is brown with black stripes when pipeline is aborted and running" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusAborted
True
|> findBanner
|> isColorWithStripes { thin = brown, thick = ColorValues.grey90 }
, describe "status priorities" <|
let
givenTwoJobsWithModifiers :
BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobsWithModifiers firstStatus firstModifier secondStatus secondModifier =
whenOnDashboard { highDensity = False }
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ job firstStatus |> firstModifier
, otherJob secondStatus |> secondModifier
]
)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
givenTwoJobs :
BuildStatus
-> BuildStatus
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobs firstStatus secondStatus =
givenTwoJobsWithModifiers firstStatus identity secondStatus identity
in
[ test "failed is more important than errored" <|
\_ ->
givenTwoJobs
BuildStatusFailed
BuildStatusErrored
|> findBanner
|> isSolid red
, test "errored is more important than aborted" <|
\_ ->
givenTwoJobs
BuildStatusErrored
BuildStatusAborted
|> findBanner
|> isSolid amber
, test "aborted is more important than succeeding" <|
\_ ->
givenTwoJobs
BuildStatusAborted
BuildStatusSucceeded
|> findBanner
|> isSolid brown
, test "succeeding is more important than pending" <|
\_ ->
givenTwoJobs
BuildStatusSucceeded
BuildStatusPending
|> findBanner
|> isSolid green
, test "paused jobs are ignored" <|
\_ ->
givenTwoJobsWithModifiers
BuildStatusSucceeded
identity
BuildStatusFailed
(Data.withPaused True)
|> findBanner
|> isSolid green
]
, test "does not crash with a circular pipeline" <|
\_ ->
whenOnDashboard { highDensity = False }
|> Application.handleCallback (Callback.AllJobsFetched <| Ok circularJobs)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid green
, describe "HD view"
[ test "is 8px wide" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> Query.has [ style "width" "8px" ]
, test "is grey when pipeline is cached" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated [ { id = 0, name = "PI:NAME:<NAME>END_PI" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is dark grey when pipeline is archived" <|
\_ ->
whenOnDashboardViewingAllPipelines { highDensity = False }
|> givenDataUnauthenticated [ { id = 0, name = "PI:NAME:<NAME>END_PI" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withArchived True
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid Colors.backgroundDark
, test "is blue when pipeline is paused" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated [ { id = 0, name = "PI:NAME:<NAME>END_PI" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid blue
, test "is green when pipeline is succeeding" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findBanner
|> isSolid green
, test "is green with black stripes when pipeline is succeeding and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusSucceeded
True
|> findBanner
|> isColorWithStripes { thin = green, thick = ColorValues.grey90 }
, test "is grey when pipeline is pending" <|
\_ ->
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> findBanner
|> isSolid lightGrey
, test "is grey with black stripes when pipeline is pending and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusStarted
True
|> findBanner
|> isColorWithStripes { thin = lightGrey, thick = ColorValues.grey90 }
, test "is red when pipeline is failing" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusFailed
False
|> findBanner
|> isSolid red
, test "is red with black stripes when pipeline is failing and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusFailed
True
|> findBanner
|> isColorWithStripes { thin = red, thick = ColorValues.grey90 }
, test "is amber when pipeline is erroring" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusErrored
False
|> findBanner
|> isSolid amber
, test "is amber with black stripes when pipeline is erroring and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusErrored
True
|> findBanner
|> isColorWithStripes { thin = amber, thick = ColorValues.grey90 }
, test "is brown when pipeline is aborted" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusAborted
False
|> findBanner
|> isSolid brown
, test "is brown with black stripes when pipeline is aborted and running" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusAborted
True
|> findBanner
|> isColorWithStripes { thin = brown, thick = ColorValues.grey90 }
, describe "status priorities" <|
let
givenTwoJobsWithModifiers :
BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> BuildStatus
-> (Concourse.Job -> Concourse.Job)
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobsWithModifiers firstStatus firstModifier secondStatus secondModifier =
whenOnDashboard { highDensity = True }
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ job firstStatus |> firstModifier
, otherJob secondStatus |> secondModifier
]
)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
givenTwoJobs :
BuildStatus
-> BuildStatus
-> Query.Single ApplicationMsgs.TopLevelMessage
givenTwoJobs firstStatus secondStatus =
givenTwoJobsWithModifiers firstStatus identity secondStatus identity
in
[ test "failed is more important than errored" <|
\_ ->
givenTwoJobs
BuildStatusFailed
BuildStatusErrored
|> findBanner
|> isSolid red
, test "errored is more important than aborted" <|
\_ ->
givenTwoJobs
BuildStatusErrored
BuildStatusAborted
|> findBanner
|> isSolid amber
, test "aborted is more important than succeeding" <|
\_ ->
givenTwoJobs
BuildStatusAborted
BuildStatusSucceeded
|> findBanner
|> isSolid brown
, test "succeeding is more important than pending" <|
\_ ->
givenTwoJobs
BuildStatusSucceeded
BuildStatusPending
|> findBanner
|> isSolid green
, test "paused jobs are ignored" <|
\_ ->
givenTwoJobsWithModifiers
BuildStatusSucceeded
identity
BuildStatusFailed
(Data.withPaused True)
|> findBanner
|> isSolid green
]
]
]
]
, describe "on HD view" <|
let
setup : () -> Query.Single ApplicationMsgs.TopLevelMessage
setup _ =
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
noPipelines : () -> Query.Single ApplicationMsgs.TopLevelMessage
noPipelines _ =
whenOnDashboard { highDensity = True }
|> givenDataUnauthenticated
(apiData
[ ( "some-team", [] )
, ( "other-team", [] )
]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "other-team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
card : Query.Single ApplicationMsgs.TopLevelMessage -> Query.Single ApplicationMsgs.TopLevelMessage
card =
Query.find
[ class "card"
, containing [ text "pipeline" ]
]
cardText : Query.Single ApplicationMsgs.TopLevelMessage -> Query.Single ApplicationMsgs.TopLevelMessage
cardText =
card
>> Query.children []
>> Query.index 1
noPipelinesCard =
Query.find
[ class "card"
, containing [ text "no pipeline" ]
]
in
[ test "no pipelines card has 14px font and 1px spacing" <|
noPipelines
>> noPipelinesCard
>> Query.has
[ style "font-size" "14px"
, style "letter-spacing" "1px"
]
, test "no pipelines card text is vertically centered" <|
noPipelines
>> noPipelinesCard
>> Query.has
[ style "display" "flex"
, style "align-items" "center"
]
, test "no pipelines card is 60px tall" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "height" "60px" ]
, test "no pipelines card has 60px right margin" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "margin-right" "60px" ]
, test "no pipelines card text has 10px padding" <|
noPipelines
>> noPipelinesCard
>> Query.children []
>> Query.first
>> Query.has [ style "padding" "10px" ]
, test "no pipelines card is 200px wide" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "width" "200px" ]
, test "no pipelines card has dark grey background" <|
noPipelines
>> noPipelinesCard
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "card name is hoverable" <|
setup
>> card
>> Query.find [ class "dashboardhd-pipeline-name" ]
>> Event.simulate Event.mouseEnter
>> Event.expect
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just <|
Msgs.PipelineCardNameHD 1
)
, test "card name has html id" <|
setup
>> card
>> Query.find [ class "dashboardhd-pipeline-name" ]
>> Query.has
[ id <|
Effects.toHtmlID <|
Msgs.PipelineCardNameHD 1
]
, test "card has larger tighter font" <|
setup
>> card
>> Query.has
[ style "font-size" "19px"
, style "letter-spacing" "1px"
]
, test "card text does not overflow or wrap" <|
setup
>> cardText
>> Query.has
[ style "width" "180px"
, style "white-space" "nowrap"
, style "overflow" "hidden"
, style "text-overflow" "ellipsis"
]
, test "card text is vertically centered" <|
setup
>> cardText
>> Query.has
[ style "align-self" "center" ]
, test "card text has 10px padding" <|
setup
>> cardText
>> Query.has
[ style "padding" "10px" ]
, test "card lays out contents horizontally" <|
setup
>> card
>> Query.has
[ style "display" "flex" ]
, test "card is 60px tall" <|
setup
>> card
>> Query.has [ style "height" "60px" ]
, test "card is 200px wide" <|
setup
>> card
>> Query.has [ style "width" "200px" ]
, test "no triangle when there is no resource error" <|
setup
>> card
>> Query.children []
>> Query.count (Expect.equal 2)
, describe "resource error triangle" <|
let
givenResourceFailingToCheck : () -> Query.Single ApplicationMsgs.TopLevelMessage
givenResourceFailingToCheck _ =
whenOnDashboard { highDensity = True }
|> Application.handleCallback
(Callback.AllResourcesFetched <|
Ok
[ Data.resource Nothing
|> Data.withBuild (Just <| Data.build Concourse.BuildStatus.BuildStatusFailed)
]
)
|> Tuple.first
|> givenDataUnauthenticated [ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
resourceErrorTriangle =
Query.children []
>> Query.index -1
in
[ test "exists" <|
givenResourceFailingToCheck
>> card
>> Query.children []
>> Query.count (Expect.equal 3)
, test "is at the top right of card" <|
givenResourceFailingToCheck
>> card
>> Expect.all
[ Query.has [ style "position" "relative" ]
, resourceErrorTriangle
>> Query.has
[ style "position" "absolute"
, style "top" "0"
, style "right" "0"
]
]
, test "is an orange 'top right' triangle" <|
givenResourceFailingToCheck
>> card
>> resourceErrorTriangle
>> Query.has
[ style "width" "0"
, style "height" "0"
, style "border-top" <| "30px solid " ++ orange
, style "border-left" "30px solid transparent"
]
]
, test
("cards are spaced 4px apart vertically and "
++ "60px apart horizontally"
)
<|
setup
>> card
>> Query.has
[ style "margin" "0 60px 4px 0" ]
, test "card is faded green when pipeline is succeeding" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> card
|> Query.has [ style "background-color" fadedGreen ]
, test "card is red when pipeline is failing" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusFailed
False
|> card
|> Query.has [ style "background-color" red ]
, test "card is amber when pipeline is erroring" <|
\_ ->
whenOnDashboard { highDensity = True }
|> pipelineWithStatus
BuildStatusErrored
False
|> card
|> Query.has [ style "background-color" amber ]
, test "card is not affected by jobs from other pipelines" <|
\_ ->
whenOnDashboard { highDensity = True }
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllJobsFetched <|
let
baseJob =
job BuildStatusErrored
in
Ok
[ { baseJob | pipelineName = "other-pipeline" } ]
)
|> Tuple.first
|> Common.queryView
|> card
|> Query.hasNot [ style "background-color" amber ]
]
, describe "body" <|
let
setup : () -> Query.Single ApplicationMsgs.TopLevelMessage
setup _ =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find
[ class "card"
, containing [ text "pipeline" ]
]
in
[ test "has dark grey background" <|
setup
>> findBody
>> Query.has [ style "background-color" ColorValues.grey90 ]
, test "has 2px margin above and below" <|
setup
>> findBody
>> Query.has [ style "margin" "2px 0" ]
, test "fills available height" <|
setup
>> findBody
>> Query.has [ style "flex-grow" "1" ]
, test "allows pipeline-grid to fill available height" <|
setup
>> findBody
>> Query.has [ style "display" "flex" ]
, test "pipeline-grid fills available width" <|
setup
>> findBody
>> Query.find [ class "pipeline-grid" ]
>> Query.has
[ style "box-sizing" "border-box"
, style "width" "100%"
]
]
, describe "footer" <|
let
hasStyle : String -> String -> Expectation
hasStyle property value =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.has [ style property value ]
in
[ test "has dark grey background" <|
\_ ->
hasStyle "background-color" ColorValues.grey90
, test "has medium padding" <|
\_ ->
hasStyle "padding" "13.5px"
, test "lays out contents horizontally" <|
\_ ->
hasStyle "display" "flex"
, test "is divided into a left and right section, spread apart" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Expect.all
[ Query.children []
>> Query.count (Expect.equal 2)
, Query.has
[ style "justify-content" "space-between" ]
]
, test "both sections lay out contents horizontally" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.each (Query.has [ style "display" "flex" ])
, describe "left-hand section" <|
let
findStatusIcon =
Query.find [ class "pipeline-status" ]
>> Query.children []
>> Query.first
findStatusText =
Query.find [ class "pipeline-status" ]
>> Query.children []
>> Query.index -1
in
[ describe "when pipeline is paused" <|
let
setup =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
in
[ test "status icon is blue pause" <|
\_ ->
setup
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconPaused
}
++ [ style "background-size" "contain" ]
)
, test "status text is blue" <|
\_ ->
setup
|> findStatusText
|> Query.has [ style "color" blue ]
, test "status text is larger and spaced more widely" <|
\_ ->
setup
|> findStatusText
|> Query.has
[ style "font-size" "18px"
, style "line-height" "20px"
, style "letter-spacing" "0.05em"
]
, test "status text is offset to the right of the icon" <|
\_ ->
setup
|> findStatusText
|> Query.has [ style "margin-left" "8px" ]
, test "status text says 'paused'" <|
\_ ->
setup
|> findStatusText
|> Query.has [ text "paused" ]
]
, describe "when a pipeline is based on cache" <|
let
setup =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
|> Common.queryView
in
[ test "status icon is grey pending" <|
\_ ->
setup
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconStale
}
++ [ style "background-size" "contain" ]
)
, test "status text is grey" <|
\_ ->
setup
|> findStatusText
|> Query.has [ style "color" lightGrey ]
, test "status text says 'loading...'" <|
\_ ->
setup
|> findStatusText
|> Query.has [ text "loading..." ]
, test "pipeline card is faded" <|
\_ ->
setup
|> Query.find [ class "card" ]
|> Query.has [ style "opacity" "0.45" ]
]
, describe "when pipeline has no jobs due to a disabled endpoint" <|
let
setup =
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleDelivery
(CachedJobsReceived <| Ok [ Data.job 0 ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllJobsFetched <|
Data.httpNotImplemented
)
domID =
Msgs.PipelineStatusIcon AllPipelinesSection 0
in
[ test "status icon is faded sync" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconJobsDisabled
}
++ [ style "background-size" "contain"
, style "opacity" "0.5"
]
)
, test "status icon is hoverable" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> findStatusIcon
|> Event.simulate Event.mouseEnter
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just domID
)
, test "hovering status icon sends location request" <|
\_ ->
setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just domID
)
|> Tuple.second
|> Common.contains
(Effects.GetViewportOf domID)
, test "hovering status icon shows tooltip" <|
\_ ->
setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Hover <|
Just domID
)
|> Tuple.first
|> Application.handleCallback
(Callback.GotViewport domID
(Ok
{ scene =
{ width = 1
, height = 0
}
, viewport =
{ width = 1
, height = 0
, x = 0
, y = 0
}
}
)
)
|> Tuple.first
|> Application.handleCallback
(Callback.GotElement <|
Ok
{ scene =
{ width = 0
, height = 0
}
, viewport =
{ width = 0
, height = 0
, x = 0
, y = 0
}
, element =
{ x = 0
, y = 0
, width = 1
, height = 1
}
}
)
|> Tuple.first
|> Common.queryView
|> Query.has
[ style "position" "fixed"
, containing [ text "automatic job monitoring disabled" ]
]
, test "status text says 'no data'" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> findStatusText
|> Query.has [ text "no data" ]
, test "job preview is empty placeholder" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-body" ]
|> Query.has [ style "background-color" ColorValues.grey90 ]
, test "job data is cleared" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "parallel-grid" ]
|> Query.hasNot [ tag "a" ]
, test "job data is cleared from local cache" <|
\_ ->
setup
|> Tuple.second
|> Common.contains Effects.DeleteCachedJobs
]
, describe "when pipeline is archived" <|
let
setup =
whenOnDashboardViewingAllPipelines { highDensity = False }
|> givenDataUnauthenticated
[ { id = 0, name = "PI:NAME:<NAME>END_PI" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withArchived True
]
)
|> Tuple.first
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ Data.job 0 ]
)
in
[ test "status section is empty" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "pipeline-status" ]
|> Query.children []
|> Query.count (Expect.equal 0)
, test "job preview is empty placeholder" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-body" ]
|> Query.has [ style "background-color" ColorValues.grey90 ]
, test "there is no pause button" <|
\_ ->
setup
|> Tuple.first
|> Common.queryView
|> Query.hasNot [ class "pause-toggle" ]
]
, describe "when pipeline is pending" <|
[ test "status icon is grey" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconPending
}
++ [ style "background-size" "contain" ]
)
, test "status text is grey" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
False
|> findStatusText
|> Query.has [ style "color" lightGrey ]
, test "status text says 'pending'" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
False
|> findStatusText
|> Query.has
[ text "pending" ]
, test "when running, status text says 'running'" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusPending
True
|> findStatusText
|> Query.has
[ text "running" ]
]
, describe "when pipeline is succeeding"
[ test "status icon is a green check" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconSucceeded
}
++ [ style "background-size" "contain" ]
)
, test "status text is green" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
False
|> findStatusText
|> Query.has [ style "color" green ]
, test "when running, status text says 'running'" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusSucceeded
True
|> findStatusText
|> Query.has
[ text "running" ]
, test "when not running, status text shows age" <|
\_ ->
whenOnDashboard { highDensity = False }
|> Application.handleCallback
(Callback.AllJobsFetched <|
Ok
[ jobWithNameTransitionedAt
"job"
(Just <| Time.millisToPosix 0)
BuildStatusSucceeded
]
)
|> Tuple.first
|> givenDataUnauthenticated
[ { id = 0, name = "team" } ]
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> afterSeconds 1
|> Common.queryView
|> findStatusText
|> Query.has
[ text "1s" ]
]
, describe "when pipeline is failing"
[ test "status icon is a red !" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconFailed
}
++ [ style "background-size" "contain" ]
)
, test "status text is red" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusFailed
False
|> findStatusText
|> Query.has [ style "color" red ]
]
, test "when pipeline is aborted, status icon is a brown x" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusAborted
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconAborted
}
++ [ style "background-size" "contain" ]
)
, test "when pipeline is errored, status icon is an amber triangle" <|
\_ ->
whenOnDashboard { highDensity = False }
|> pipelineWithStatus
BuildStatusErrored
False
|> findStatusIcon
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PipelineStatusIconErrored
}
++ [ style "background-size" "contain" ]
)
]
, describe "right-hand section"
[ describe "visibility toggle" <|
let
pipelineId =
Data.pipelineId
visibilityToggle =
Common.queryView
>> Query.findAll [ class "card-footer" ]
>> Query.first
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 2
openEye =
iconSelector
{ size = "20px"
, image = Assets.VisibilityToggleIcon True
}
++ [ style "background-size" "contain" ]
slashedOutEye =
iconSelector
{ size = "20px"
, image = Assets.VisibilityToggleIcon False
}
++ [ style "background-size" "contain" ]
openEyeClickable setup =
[ defineHoverBehaviour
{ name = "open eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "pointer"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "bright 20px square"
, selector =
openEye
++ [ style "opacity" "1"
, style "cursor" "pointer"
]
}
}
, test "has click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
, test "click has HidePipeline effect" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.second
|> Expect.equal
[ Effects.ChangeVisibility
Msgs.Hide
pipelineId
]
, defineHoverBehaviour
{ name = "open eye toggle in favorites section"
, setup =
whenOnDashboard { highDensity = False }
|> Application.handleDelivery
(Message.Subscription.FavoritedPipelinesReceived <| Ok <| Set.singleton 0)
|> Tuple.first
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "pointer"
]
}
, hoverable =
Msgs.VisibilityButton FavoritesSection 0
, hoveredSelector =
{ description = "bright 20px square"
, selector =
openEye
++ [ style "opacity" "1"
, style "cursor" "pointer"
]
}
}
, defineHoverBehaviour
{ name = "visibility spinner"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
}
, test "success resolves spinner to slashed-out eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Hide
pipelineId
(Ok ())
)
|> Tuple.first
|> visibilityToggle
|> Query.has slashedOutEye
, test "error resolves spinner to open eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Hide
pipelineId
Data.httpInternalServerError
)
|> Tuple.first
|> visibilityToggle
|> Query.has openEye
, test "401 redirects to login" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Hide
pipelineId
Data.httpUnauthorized
)
|> Tuple.second
|> Expect.equal
[ Effects.RedirectToLogin ]
]
openEyeUnclickable setup =
[ defineHoverBehaviour
{ name = "open eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "faded 20px square"
, selector =
openEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
}
, test "has no click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.toResult
|> Expect.err
]
slashedOutEyeClickable setup =
[ defineHoverBehaviour
{ name = "slashed-out eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "0.5"
, style "cursor" "pointer"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "bright 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "1"
, style "cursor" "pointer"
]
}
}
, test "has click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
, test "click has ExposePipeline effect" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.second
|> Expect.equal
[ Effects.ChangeVisibility
Msgs.Expose
pipelineId
]
, defineHoverBehaviour
{ name = "visibility spinner"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "20px spinner"
, selector =
[ style "animation"
"container-rotate 1568ms linear infinite"
, style "height" "20px"
, style "width" "20px"
]
}
}
, test "success resolves spinner to open eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Expose
pipelineId
(Ok ())
)
|> Tuple.first
|> visibilityToggle
|> Query.has openEye
, test "error resolves spinner to slashed-out eye" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.VisibilityButton AllPipelinesSection 0
)
|> Tuple.first
|> Application.handleCallback
(Callback.VisibilityChanged
Msgs.Expose
pipelineId
Data.httpInternalServerError
)
|> Tuple.first
|> visibilityToggle
|> Query.has slashedOutEye
]
slashedOutEyeUnclickable setup =
[ defineHoverBehaviour
{ name = "slashed-out eye toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = visibilityToggle
, unhoveredSelector =
{ description = "faded 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
, hoverable =
Msgs.VisibilityButton AllPipelinesSection 0
, hoveredSelector =
{ description = "faded 20px square"
, selector =
slashedOutEye
++ [ style "opacity" "0.5"
, style "cursor" "default"
]
}
}
, test "has no click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> visibilityToggle
|> Event.simulate Event.click
|> Event.toResult
|> Expect.err
]
in
[ describe "when authorized" <|
let
whenAuthorizedPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "owner" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
whenAuthorizedNonPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "owner" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPublic False
]
)
in
[ describe "on public pipeline" <|
openEyeClickable whenAuthorizedPublic
, describe "on a non-public pipeline" <|
slashedOutEyeClickable whenAuthorizedNonPublic
]
, describe "when unauthorized" <|
let
whenUnauthorizedPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "viewer" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
whenUnauthorizedNonPublic =
givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "viewer" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0
|> Data.withName "pipeline"
|> Data.withPublic False
]
)
in
[ describe "on public pipeline" <|
openEyeUnclickable whenUnauthorizedPublic
, describe "on a non-public pipeline" <|
slashedOutEyeUnclickable
whenUnauthorizedNonPublic
]
, describe "when unauthenticated" <|
let
whenUnauthenticated =
givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
in
[ describe "on public pipeline" <|
openEyeClickable whenUnauthenticated
]
]
, test "there is medium spacing between the eye and the play/pause button" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.index -1
|> Query.children []
|> Expect.all
[ Query.count (Expect.equal 5)
, Query.index 1 >> Query.has [ style "width" "12px" ]
]
, test "there is medium spacing between the eye and the favorited icon" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.index -1
|> Query.children []
|> Expect.all
[ Query.count (Expect.equal 5)
, Query.index 3 >> Query.has [ style "width" "12px" ]
]
, describe "pause toggle"
[ test "the right section has a 20px square pause button on the left" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.children []
|> Query.index -1
|> Query.children []
|> Query.index 0
|> Query.has
(iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
)
, test "pause button has pointer cursor when authorized" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.find
(iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
)
|> Query.has [ style "cursor" "pointer" ]
, test "pause button is transparent" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.find
(iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
)
|> Query.has [ style "opacity" "0.5" ]
, defineHoverBehaviour
{ name = "pause button"
, setup =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
, query =
Common.queryView
>> Query.find [ class "card-footer" ]
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 0
, unhoveredSelector =
{ description = "a faded 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "0.5"
]
}
, hoverable = Msgs.PipelineCardPauseToggle AllPipelinesSection 1
, hoveredSelector =
{ description = "a bright 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "1"
]
}
}
, defineHoverBehaviour
{ name = "pause button in favorites section"
, setup =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.handleDelivery
(Message.Subscription.FavoritedPipelinesReceived <| Ok <| Set.singleton 1)
|> Tuple.first
, query =
Common.queryView
>> Query.findAll [ class "card-footer" ]
>> Query.first
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 0
, unhoveredSelector =
{ description = "a faded 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "0.5"
]
}
, hoverable =
Msgs.PipelineCardPauseToggle FavoritesSection 1
, hoveredSelector =
{ description = "a bright 20px square pause button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PauseIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "1"
]
}
}
, defineHoverBehaviour
{ name = "play button"
, setup =
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1
|> Data.withName "pipeline"
|> Data.withPaused True
]
)
|> Tuple.first
, query =
Common.queryView
>> Query.find [ class "card-footer" ]
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index 0
, unhoveredSelector =
{ description = "a transparent 20px square play button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PlayIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "0.5"
]
}
, hoverable = Msgs.PipelineCardPauseToggle AllPipelinesSection 1
, hoveredSelector =
{ description = "an opaque 20px square play button with pointer cursor"
, selector =
iconSelector
{ size = "20px"
, image = Assets.PlayIcon
}
++ [ style "cursor" "pointer"
, style "opacity" "1"
]
}
}
, test "clicking pause button sends TogglePipeline msg" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.find [ class "pause-toggle" ]
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
, test "pause button turns into spinner on click" <|
\_ ->
let
animation =
"container-rotate 1568ms linear infinite"
in
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "card-footer" ]
|> Query.has [ style "animation" animation ]
, test "clicking pause button sends toggle api call" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.second
|> Expect.equal [ Effects.SendTogglePipelineRequest Data.pipelineId False ]
, test "all pipelines are refetched after ok toggle call" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles [ ( "team", [ "owner" ] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.first
|> Application.handleCallback
(Callback.PipelineToggled Data.pipelineId (Ok ()))
|> Tuple.second
|> Expect.equal [ Effects.FetchAllPipelines ]
, test "401 toggle call redirects to login" <|
\_ ->
whenOnDashboard { highDensity = False }
|> givenDataUnauthenticated
(apiData [ ( "team", [] ) ])
|> Tuple.first
|> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 1 |> Data.withName "pipeline" ]
)
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardPauseToggle AllPipelinesSection 1
)
|> Tuple.first
|> Application.handleCallback
(Callback.PipelineToggled Data.pipelineId Data.httpUnauthorized)
|> Tuple.second
|> Expect.equal [ Effects.RedirectToLogin ]
]
, describe "favorited icon" <|
let
pipelineId =
0
unfilledFavoritedIcon =
iconSelector
{ size = "20px"
, image = Assets.FavoritedToggleIcon { isFavorited = False, isHovered = False, isSideBar = False }
}
++ [ style "background-size" "contain" ]
unfilledBrightFavoritedIcon =
iconSelector
{ size = "20px"
, image = Assets.FavoritedToggleIcon { isFavorited = False, isHovered = True, isSideBar = False }
}
++ [ style "background-size" "contain" ]
filledFavoritedIcon =
iconSelector
{ size = "20px"
, image = Assets.FavoritedToggleIcon { isFavorited = True, isHovered = False, isSideBar = False }
}
++ [ style "background-size" "contain" ]
favoritedToggle =
Common.queryView
>> Query.findAll [ class "card-footer" ]
>> Query.first
>> Query.children []
>> Query.index -1
>> Query.children []
>> Query.index -1
favoritedIconClickable setup =
[ defineHoverBehaviour
{ name = "favorited icon toggle"
, setup =
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
, query = favoritedToggle
, unhoveredSelector =
{ description = "faded star icon"
, selector =
unfilledFavoritedIcon
++ [ style "cursor" "pointer" ]
}
, hoverable =
Msgs.PipelineCardFavoritedIcon AllPipelinesSection pipelineId
, hoveredSelector =
{ description = "bright star icon"
, selector =
unfilledBrightFavoritedIcon
++ [ style "cursor" "pointer" ]
}
}
, test "has click handler" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> favoritedToggle
|> Event.simulate Event.click
|> Event.expect
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardFavoritedIcon
AllPipelinesSection
pipelineId
)
, test "click has FavoritedPipeline effect" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.update
(ApplicationMsgs.Update <|
Msgs.Click <|
Msgs.PipelineCardFavoritedIcon
AllPipelinesSection
pipelineId
)
|> Tuple.second
|> Expect.equal
[ Effects.SaveFavoritedPipelines <|
Set.singleton pipelineId
]
, test "favorited pipeline card has a bright filled star icon" <|
\_ ->
whenOnDashboard { highDensity = False }
|> setup
|> Tuple.first
|> Application.handleDelivery
(FavoritedPipelinesReceived <|
Ok <|
Set.singleton pipelineId
)
|> Tuple.first
|> favoritedToggle
|> Expect.all
[ Query.has filledFavoritedIcon
]
]
in
favoritedIconClickable
(givenDataAndUser
(apiData [ ( "team", [] ) ])
(userWithRoles
[ ( "team", [ "owner" ] ) ]
)
>> Tuple.first
>> Application.handleCallback
(Callback.AllPipelinesFetched <|
Ok
[ Data.pipeline "team" 0 |> Data.withName "pipeline" ]
)
)
]
]
]
| elm |
[
{
"context": " noteType : String\n }\n\nbassNoteKeys = [ 192, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 189, 187 ]\nchromaticChordKeys = [ 81, 87, 69, 82,",
"end": 162,
"score": 0.8982279301,
"start": 118,
"tag": "KEY",
"value": "192, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48,"
},
{
"context": " [ 192, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 189, 187 ]\nchromaticChordKeys = [ 81, 87, 69, 82, 84,",
"end": 166,
"score": 0.7629141212,
"start": 165,
"tag": "KEY",
"value": "9"
},
{
"context": "2, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 189, 187 ]\nchromaticChordKeys = [ 81, 87, 69, 82, 84, 89, ",
"end": 171,
"score": 0.5602450371,
"start": 170,
"tag": "KEY",
"value": "7"
},
{
"context": " 55, 56, 57, 48, 189, 187 ]\nchromaticChordKeys = [ 81, 87, 69, 82, 84, 89, 85, 73, 79, 80, 219, 221, ",
"end": 196,
"score": 0.8322554231,
"start": 196,
"tag": "KEY",
"value": ""
},
{
"context": "55, 56, 57, 48, 189, 187 ]\nchromaticChordKeys = [ 81, 87, 69, 82, 84, 89, 85, 73, 79, 80, 219, 221, 220 ]\n\n-- NOTE B3 and C4 bass notes don'",
"end": 236,
"score": 0.9287096858,
"start": 197,
"tag": "KEY",
"value": "81, 87, 69, 82, 84, 89, 85, 73, 79, 80,"
},
{
"context": "eys = [ 81, 87, 69, 82, 84, 89, 85, 73, 79, 80, 219, 221, 220 ]\n\n-- NOTE B3 and C4 bass notes don't l",
"end": 240,
"score": 0.9079460502,
"start": 239,
"tag": "KEY",
"value": "9"
},
{
"context": " [ 81, 87, 69, 82, 84, 89, 85, 73, 79, 80, 219, 221, 220 ]\n\n-- NOTE B3 and C4 bass notes don't light ",
"end": 245,
"score": 0.6769035459,
"start": 244,
"tag": "KEY",
"value": "1"
}
] | Constants.elm | billgathen/cyber-transcriber | 0 | module Constants where
type alias KeyMap =
{
label : String,
noteType : String
}
bassNoteKeys = [ 192, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 189, 187 ]
chromaticChordKeys = [ 81, 87, 69, 82, 84, 89, 85, 73, 79, 80, 219, 221, 220 ]
-- NOTE B3 and C4 bass notes don't light on Firefox b/c the bassNoteKeys array uses the Chrome charCode
-- The note plays, though, because Music is based on key inputs
keyMapping : Int -> KeyMap
keyMapping key =
case key of
192 -> KeyMap "C" "bass"
49 -> KeyMap "C#" "bass"
50 -> KeyMap "D" "bass"
51 -> KeyMap "D#" "bass"
52 -> KeyMap "E" "bass"
53 -> KeyMap "F" "bass"
54 -> KeyMap "F#" "bass"
55 -> KeyMap "G" "bass"
56 -> KeyMap "G#" "bass"
57 -> KeyMap "A" "bass"
48 -> KeyMap "A#" "bass"
189 -> KeyMap "B" "bass"
187 -> KeyMap "C" "bass"
173 -> KeyMap "B" "bass"
61 -> KeyMap "C" "bass"
81 -> KeyMap "C" "chord"
87 -> KeyMap "C#" "chord"
69 -> KeyMap "D" "chord"
82 -> KeyMap "D#" "chord"
84 -> KeyMap "E" "chord"
89 -> KeyMap "F" "chord"
85 -> KeyMap "F#" "chord"
73 -> KeyMap "G" "chord"
79 -> KeyMap "G#" "chord"
80 -> KeyMap "A" "chord"
219 -> KeyMap "A#" "chord"
221 -> KeyMap "B" "chord"
220 -> KeyMap "C" "chord"
_ -> KeyMap "" ""
| 29340 | module Constants where
type alias KeyMap =
{
label : String,
noteType : String
}
bassNoteKeys = [ <KEY> 18<KEY>, 18<KEY> ]
chromaticChordKeys = [<KEY> <KEY> 21<KEY>, 22<KEY>, 220 ]
-- NOTE B3 and C4 bass notes don't light on Firefox b/c the bassNoteKeys array uses the Chrome charCode
-- The note plays, though, because Music is based on key inputs
keyMapping : Int -> KeyMap
keyMapping key =
case key of
192 -> KeyMap "C" "bass"
49 -> KeyMap "C#" "bass"
50 -> KeyMap "D" "bass"
51 -> KeyMap "D#" "bass"
52 -> KeyMap "E" "bass"
53 -> KeyMap "F" "bass"
54 -> KeyMap "F#" "bass"
55 -> KeyMap "G" "bass"
56 -> KeyMap "G#" "bass"
57 -> KeyMap "A" "bass"
48 -> KeyMap "A#" "bass"
189 -> KeyMap "B" "bass"
187 -> KeyMap "C" "bass"
173 -> KeyMap "B" "bass"
61 -> KeyMap "C" "bass"
81 -> KeyMap "C" "chord"
87 -> KeyMap "C#" "chord"
69 -> KeyMap "D" "chord"
82 -> KeyMap "D#" "chord"
84 -> KeyMap "E" "chord"
89 -> KeyMap "F" "chord"
85 -> KeyMap "F#" "chord"
73 -> KeyMap "G" "chord"
79 -> KeyMap "G#" "chord"
80 -> KeyMap "A" "chord"
219 -> KeyMap "A#" "chord"
221 -> KeyMap "B" "chord"
220 -> KeyMap "C" "chord"
_ -> KeyMap "" ""
| true | module Constants where
type alias KeyMap =
{
label : String,
noteType : String
}
bassNoteKeys = [ PI:KEY:<KEY>END_PI 18PI:KEY:<KEY>END_PI, 18PI:KEY:<KEY>END_PI ]
chromaticChordKeys = [PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI 21PI:KEY:<KEY>END_PI, 22PI:KEY:<KEY>END_PI, 220 ]
-- NOTE B3 and C4 bass notes don't light on Firefox b/c the bassNoteKeys array uses the Chrome charCode
-- The note plays, though, because Music is based on key inputs
keyMapping : Int -> KeyMap
keyMapping key =
case key of
192 -> KeyMap "C" "bass"
49 -> KeyMap "C#" "bass"
50 -> KeyMap "D" "bass"
51 -> KeyMap "D#" "bass"
52 -> KeyMap "E" "bass"
53 -> KeyMap "F" "bass"
54 -> KeyMap "F#" "bass"
55 -> KeyMap "G" "bass"
56 -> KeyMap "G#" "bass"
57 -> KeyMap "A" "bass"
48 -> KeyMap "A#" "bass"
189 -> KeyMap "B" "bass"
187 -> KeyMap "C" "bass"
173 -> KeyMap "B" "bass"
61 -> KeyMap "C" "bass"
81 -> KeyMap "C" "chord"
87 -> KeyMap "C#" "chord"
69 -> KeyMap "D" "chord"
82 -> KeyMap "D#" "chord"
84 -> KeyMap "E" "chord"
89 -> KeyMap "F" "chord"
85 -> KeyMap "F#" "chord"
73 -> KeyMap "G" "chord"
79 -> KeyMap "G#" "chord"
80 -> KeyMap "A" "chord"
219 -> KeyMap "A#" "chord"
221 -> KeyMap "B" "chord"
220 -> KeyMap "C" "chord"
_ -> KeyMap "" ""
| elm |
[
{
"context": "-- Copyright (c) 2017 Daan Wendelen\n-- All rights reserved.\n-- \n-- Redistribution and",
"end": 35,
"score": 0.999814868,
"start": 22,
"tag": "NAME",
"value": "Daan Wendelen"
}
] | day12/day12a.elm | dwendelen/adventofcode_2017 | 0 | -- Copyright (c) 2017 Daan Wendelen
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- * Neither the name of the copyright holder nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Html exposing (..)
import Dict exposing (..)
import Array exposing (..)
import Debug exposing (..)
main = text <| toString <| solve input
--solve: String -> Int
solve input =
let
initialDict = parse input
initialSize = Dict.size initialDict
dictAfterRemoval = removeGroup 0 initialDict
in
initialSize - (Dict.size dictAfterRemoval)
removeGroup id dict =
if Dict.member id dict then
let
deps = Dict.get id dict |> Maybe.withDefault []
newDict = Dict.remove id dict
in
deps
|> List.foldl removeGroup newDict
else
dict
parse: String -> Dict Int (List Int)
parse string =
String.split "\n" input
|> List.map parseLine
|> Dict.fromList
parseLine line =
case (String.split " <-> " line) of
id::deps::[] ->
let
iid = toIntOrZero id
ideps =
String.split ", " deps
|> List.map toIntOrZero
in
(iid, ideps)
_ -> (-1, [])
input2 = """0 <-> 2
1 <-> 1
2 <-> 0, 3, 4
3 <-> 2, 4
4 <-> 2, 3, 6
5 <-> 6
6 <-> 4, 5"""
input = """0 <-> 889, 1229, 1736
1 <-> 1, 480, 793, 1361
2 <-> 607
3 <-> 273, 422
4 <-> 965, 1052, 1130, 1591
5 <-> 1998
6 <-> 483, 1628
7 <-> 1012, 1242, 1244, 1491
8 <-> 524
9 <-> 13, 281, 1498
10 <-> 10
11 <-> 1956
12 <-> 598, 621, 1210
13 <-> 9
14 <-> 1728
15 <-> 912, 1461
16 <-> 1489, 1680, 1994
17 <-> 854
18 <-> 1157, 1299
19 <-> 759
20 <-> 1352, 1831
21 <-> 1425
22 <-> 470, 685, 857, 1526
23 <-> 405
24 <-> 43, 536, 1849
25 <-> 1674
26 <-> 26, 1738
27 <-> 558
28 <-> 1863
29 <-> 154, 649, 1818
30 <-> 721, 1366
31 <-> 725
32 <-> 413, 880, 903
33 <-> 414, 442, 1403
34 <-> 489, 1308
35 <-> 385, 1254, 1464
36 <-> 167, 1013, 1860
37 <-> 535
38 <-> 605, 1297
39 <-> 680, 1408, 1982
40 <-> 169, 615, 952, 1547
41 <-> 644, 991, 1319, 1509
42 <-> 453, 1315
43 <-> 24, 200, 805
44 <-> 919, 1083
45 <-> 500
46 <-> 1532, 1550
47 <-> 910, 1837
48 <-> 1849
49 <-> 542, 1945
50 <-> 57, 660
51 <-> 354, 934
52 <-> 1212
53 <-> 569
54 <-> 706
55 <-> 55, 114, 1077
56 <-> 1453
57 <-> 50, 1438
58 <-> 616, 738
59 <-> 1242
60 <-> 312, 523, 648
61 <-> 748, 1780, 1965
62 <-> 1533, 1909
63 <-> 562, 661, 1016
64 <-> 280, 300, 677
65 <-> 661, 698, 1881
66 <-> 283, 440
67 <-> 382, 421
68 <-> 986, 1592, 1824
69 <-> 541, 1363
70 <-> 266, 1855
71 <-> 371, 433, 1055, 1682
72 <-> 793
73 <-> 73
74 <-> 1139
75 <-> 770, 1190, 1409, 1433, 1886
76 <-> 1135
77 <-> 492, 1771
78 <-> 575, 1107, 1596, 1670
79 <-> 1374
80 <-> 1168, 1519
81 <-> 1258
82 <-> 919, 1519, 1768
83 <-> 1463
84 <-> 684
85 <-> 517, 1655
86 <-> 1226
87 <-> 1700
88 <-> 523, 1292, 1939
89 <-> 177, 1695, 1706
90 <-> 400, 1683
91 <-> 194
92 <-> 106, 1546
93 <-> 104
94 <-> 501, 1686
95 <-> 285, 1985
96 <-> 402, 770
97 <-> 196
98 <-> 318, 1827
99 <-> 220, 1272, 1766, 1802
100 <-> 1105
101 <-> 380, 957
102 <-> 1305, 1483
103 <-> 262, 481, 621
104 <-> 93, 708, 1731
105 <-> 282
106 <-> 92, 901
107 <-> 553, 742, 1833
108 <-> 480, 1140
109 <-> 1247
110 <-> 1549
111 <-> 1283
112 <-> 1503, 1963
113 <-> 819, 1601
114 <-> 55, 593, 1020
115 <-> 324
116 <-> 378
117 <-> 1534
118 <-> 1740, 1836
119 <-> 1223, 1283
120 <-> 435, 1063
121 <-> 404, 939
122 <-> 294, 360, 1809
123 <-> 1166
124 <-> 1988
125 <-> 163
126 <-> 126
127 <-> 255, 754
128 <-> 634, 969
129 <-> 563, 1732, 1926
130 <-> 1196
131 <-> 1019, 1429
132 <-> 1287, 1417
133 <-> 1453
134 <-> 184, 786
135 <-> 647
136 <-> 260, 306
137 <-> 1342
138 <-> 292
139 <-> 1265
140 <-> 613
141 <-> 1001, 1217
142 <-> 142, 1901
143 <-> 758, 822, 1533
144 <-> 866, 930, 1197, 1443, 1665
145 <-> 1672
146 <-> 1937
147 <-> 1409, 1697
148 <-> 608, 954, 1624
149 <-> 527, 652, 1938
150 <-> 709
151 <-> 447, 1305, 1314
152 <-> 1741
153 <-> 901, 1997
154 <-> 29, 929
155 <-> 1178, 1976
156 <-> 560
157 <-> 522
158 <-> 541
159 <-> 1212, 1878
160 <-> 1078
161 <-> 1128, 1913
162 <-> 588, 734
163 <-> 125, 1073, 1952
164 <-> 1156
165 <-> 1781
166 <-> 1692
167 <-> 36, 1637
168 <-> 1043, 1085
169 <-> 40, 334, 1257, 1313
170 <-> 170
171 <-> 171
172 <-> 1391
173 <-> 925
174 <-> 1733
175 <-> 175, 1466
176 <-> 726, 1182
177 <-> 89, 1100
178 <-> 611, 1141
179 <-> 1036, 1307
180 <-> 1556
181 <-> 1930
182 <-> 775, 1284
183 <-> 1907
184 <-> 134, 1981
185 <-> 255, 1278
186 <-> 1891
187 <-> 531, 1318
188 <-> 790, 1623
189 <-> 379, 1749, 1865
190 <-> 1103, 1676
191 <-> 534
192 <-> 477
193 <-> 193, 860
194 <-> 91, 710, 1780
195 <-> 290, 1383, 1510
196 <-> 97, 1664
197 <-> 1416
198 <-> 287, 1760
199 <-> 366
200 <-> 43
201 <-> 813, 1882
202 <-> 246, 1175
203 <-> 203, 1007
204 <-> 204, 923
205 <-> 924
206 <-> 1162, 1818
207 <-> 365, 487, 923
208 <-> 1281, 1290
209 <-> 1280
210 <-> 210, 288, 1333
211 <-> 211, 417, 754
212 <-> 1698
213 <-> 1626
214 <-> 1256
215 <-> 215, 1385, 1671
216 <-> 811, 1025
217 <-> 554, 1715
218 <-> 1483
219 <-> 1741
220 <-> 99, 530, 1081, 1319, 1801
221 <-> 804, 1144
222 <-> 1288, 1702
223 <-> 223, 1231
224 <-> 649, 1179
225 <-> 1271, 1776
226 <-> 226, 1991
227 <-> 496, 857, 1004, 1821
228 <-> 371, 500
229 <-> 1162
230 <-> 693, 1081
231 <-> 506, 973
232 <-> 859, 969, 1922
233 <-> 233
234 <-> 875, 1006
235 <-> 1035, 1998
236 <-> 236
237 <-> 289, 569, 1440
238 <-> 1249, 1923
239 <-> 1564, 1775, 1944
240 <-> 1888
241 <-> 951, 1874
242 <-> 825
243 <-> 384, 983, 1838
244 <-> 715, 1501
245 <-> 592, 671
246 <-> 202, 391, 632, 656
247 <-> 663
248 <-> 253, 752
249 <-> 1073, 1558
250 <-> 290
251 <-> 792, 1389
252 <-> 797
253 <-> 248, 771
254 <-> 254, 1047
255 <-> 127, 185, 369
256 <-> 623
257 <-> 1636, 1740
258 <-> 317
259 <-> 1775
260 <-> 136, 561, 1290
261 <-> 359, 1657
262 <-> 103, 697, 1074
263 <-> 1205
264 <-> 1779, 1782
265 <-> 1407
266 <-> 70, 1215, 1306
267 <-> 333, 790
268 <-> 603
269 <-> 269, 1497
270 <-> 270, 1613
271 <-> 1416, 1562, 1923
272 <-> 579, 894
273 <-> 3, 993
274 <-> 333
275 <-> 1188
276 <-> 535, 645, 1166, 1269
277 <-> 1369
278 <-> 744, 1717
279 <-> 349, 695, 985, 1096
280 <-> 64, 1516
281 <-> 9, 427, 768, 1468
282 <-> 105, 867
283 <-> 66, 1235, 1525, 1748
284 <-> 530
285 <-> 95, 800, 1191
286 <-> 339, 611, 1581
287 <-> 198, 1285, 1501
288 <-> 210, 1059
289 <-> 237, 1928
290 <-> 195, 250, 1934
291 <-> 337, 1902
292 <-> 138, 1805, 1849
293 <-> 906
294 <-> 122, 1582
295 <-> 602
296 <-> 778
297 <-> 471, 483
298 <-> 298
299 <-> 402, 729
300 <-> 64, 1002
301 <-> 856
302 <-> 1084, 1538, 1739
303 <-> 892, 1774
304 <-> 1029, 1350
305 <-> 521, 1628, 1902
306 <-> 136, 469, 653, 835
307 <-> 981
308 <-> 1997
309 <-> 1612
310 <-> 1338, 1571
311 <-> 1388
312 <-> 60
313 <-> 1557
314 <-> 886, 1704
315 <-> 672, 779
316 <-> 1062, 1906
317 <-> 258, 1290
318 <-> 98, 318
319 <-> 1974
320 <-> 839
321 <-> 395, 615, 909, 1046
322 <-> 1077, 1390, 1989
323 <-> 323, 773, 1571
324 <-> 115, 493, 511, 650
325 <-> 325
326 <-> 1944, 1972
327 <-> 1489
328 <-> 412, 468
329 <-> 1637
330 <-> 556, 1176
331 <-> 656
332 <-> 564, 1688
333 <-> 267, 274, 421, 1205, 1743
334 <-> 169, 1896
335 <-> 1176
336 <-> 638, 1408, 1633
337 <-> 291, 844, 1549
338 <-> 515
339 <-> 286
340 <-> 340, 1959
341 <-> 943
342 <-> 417, 638, 1116, 1536
343 <-> 1030
344 <-> 584, 1751
345 <-> 345, 1810
346 <-> 346
347 <-> 587
348 <-> 515, 1187
349 <-> 279, 349
350 <-> 1749
351 <-> 1030, 1097
352 <-> 352
353 <-> 353, 683
354 <-> 51, 354, 735
355 <-> 1362
356 <-> 1593
357 <-> 357
358 <-> 441, 501, 899, 1672
359 <-> 261
360 <-> 122, 360, 1234, 1927
361 <-> 736
362 <-> 1169
363 <-> 780
364 <-> 444, 905, 1049, 1911
365 <-> 207
366 <-> 199, 1469
367 <-> 1612
368 <-> 675, 1800
369 <-> 255
370 <-> 370, 873, 962, 1238
371 <-> 71, 228, 456
372 <-> 1912
373 <-> 1318
374 <-> 1018, 1246
375 <-> 898, 1303
376 <-> 376, 573
377 <-> 1080
378 <-> 116, 1140
379 <-> 189, 1984
380 <-> 101
381 <-> 472, 827, 1097
382 <-> 67
383 <-> 383, 582
384 <-> 243, 432, 444, 569, 634
385 <-> 35
386 <-> 1496
387 <-> 637, 737, 756, 1293
388 <-> 1562
389 <-> 633
390 <-> 488
391 <-> 246, 853, 1422
392 <-> 1253, 1331
393 <-> 921, 1567, 1777, 1970
394 <-> 809
395 <-> 321, 798, 1040
396 <-> 746, 1332
397 <-> 400, 953
398 <-> 1958
399 <-> 399
400 <-> 90, 397, 808, 1485
401 <-> 1395
402 <-> 96, 299, 1388
403 <-> 716
404 <-> 121
405 <-> 23, 934, 1221
406 <-> 1007
407 <-> 1391
408 <-> 497, 1090, 1644
409 <-> 1479
410 <-> 793, 1977
411 <-> 1026
412 <-> 328, 581, 806
413 <-> 32, 1354
414 <-> 33, 1920
415 <-> 799, 1207, 1880
416 <-> 1862
417 <-> 211, 342, 589, 1858
418 <-> 556, 1437, 1490
419 <-> 1393
420 <-> 420
421 <-> 67, 333, 1813
422 <-> 3, 706, 1598, 1721
423 <-> 1834
424 <-> 854, 1442
425 <-> 855, 1080
426 <-> 1408, 1469
427 <-> 281
428 <-> 832, 1998
429 <-> 553, 657, 834
430 <-> 1466
431 <-> 1357
432 <-> 384
433 <-> 71
434 <-> 434, 489, 1137
435 <-> 120
436 <-> 972, 1461
437 <-> 550
438 <-> 486, 844
439 <-> 978
440 <-> 66, 705, 1850
441 <-> 358, 589, 783, 804, 1129
442 <-> 33, 497
443 <-> 1806
444 <-> 364, 384, 1698
445 <-> 1208, 1294, 1452
446 <-> 1143, 1452
447 <-> 151, 1072
448 <-> 448
449 <-> 997, 1829
450 <-> 1277
451 <-> 1531, 1866
452 <-> 1175, 1622, 1975
453 <-> 42, 1486
454 <-> 689
455 <-> 1497
456 <-> 371, 1577
457 <-> 702
458 <-> 461, 921, 1279
459 <-> 1004
460 <-> 485, 505, 1211, 1451
461 <-> 458, 541, 916, 1844
462 <-> 1281
463 <-> 856, 1481
464 <-> 602, 1476, 1553
465 <-> 543, 1566
466 <-> 847, 1593
467 <-> 1270
468 <-> 328, 829
469 <-> 306, 667, 720, 1931
470 <-> 22
471 <-> 297
472 <-> 381
473 <-> 473
474 <-> 599, 1146
475 <-> 1570, 1894
476 <-> 1145
477 <-> 192, 1193, 1690
478 <-> 1469, 1840
479 <-> 1684
480 <-> 1, 108
481 <-> 103, 963
482 <-> 1778
483 <-> 6, 297, 1662
484 <-> 1435
485 <-> 460
486 <-> 438
487 <-> 207, 998, 1185
488 <-> 390, 1231, 1668
489 <-> 34, 434, 1341
490 <-> 990, 1203
491 <-> 936
492 <-> 77
493 <-> 324
494 <-> 1984
495 <-> 495, 1954
496 <-> 227
497 <-> 408, 442, 1551
498 <-> 1704, 1788
499 <-> 836
500 <-> 45, 228, 1358, 1798
501 <-> 94, 358, 1559
502 <-> 951
503 <-> 1036
504 <-> 1303
505 <-> 460
506 <-> 231, 606, 1473
507 <-> 1109
508 <-> 1724
509 <-> 1644
510 <-> 848
511 <-> 324, 1036
512 <-> 523
513 <-> 809, 1294
514 <-> 785
515 <-> 338, 348, 1027, 1193, 1226
516 <-> 1988
517 <-> 85, 1482
518 <-> 518
519 <-> 1625
520 <-> 520
521 <-> 305, 1033
522 <-> 157, 1355, 1476, 1588
523 <-> 60, 88, 512
524 <-> 8, 1998
525 <-> 990, 1275
526 <-> 1310, 1552
527 <-> 149, 979, 1805
528 <-> 698
529 <-> 631, 970
530 <-> 220, 284, 1533, 1944
531 <-> 187, 551, 1168, 1574
532 <-> 1484
533 <-> 892
534 <-> 191, 879
535 <-> 37, 276, 1527
536 <-> 24, 1094
537 <-> 747, 952
538 <-> 1620, 1735
539 <-> 858, 1467
540 <-> 1263, 1572
541 <-> 69, 158, 461
542 <-> 49, 1384
543 <-> 465, 639, 873
544 <-> 1338
545 <-> 1967
546 <-> 806, 1239
547 <-> 792, 1039, 1078
548 <-> 548, 1891, 1941
549 <-> 861
550 <-> 437, 1209, 1967
551 <-> 531, 888, 896
552 <-> 798
553 <-> 107, 429, 1330, 1951
554 <-> 217
555 <-> 744, 947, 1246
556 <-> 330, 418, 1070, 1925
557 <-> 1826, 1854
558 <-> 27, 1629
559 <-> 1042, 1150
560 <-> 156, 1472, 1834
561 <-> 260
562 <-> 63
563 <-> 129, 1309
564 <-> 332
565 <-> 1770, 1842
566 <-> 621
567 <-> 1160, 1178, 1642
568 <-> 895
569 <-> 53, 237, 384
570 <-> 641
571 <-> 571, 1261, 1924
572 <-> 882
573 <-> 376
574 <-> 982
575 <-> 78, 1255
576 <-> 887, 1539
577 <-> 603, 1122, 1679
578 <-> 742
579 <-> 272, 1444, 1747
580 <-> 797, 1554, 1718
581 <-> 412, 1926
582 <-> 383
583 <-> 1611
584 <-> 344, 1620
585 <-> 1692
586 <-> 1383
587 <-> 347, 1351
588 <-> 162, 1220
589 <-> 417, 441
590 <-> 1919
591 <-> 884, 992
592 <-> 245, 814
593 <-> 114
594 <-> 1843
595 <-> 1809
596 <-> 837
597 <-> 1563, 1575
598 <-> 12, 605, 984
599 <-> 474, 1218
600 <-> 732, 1237, 1714
601 <-> 1913
602 <-> 295, 464, 1061
603 <-> 268, 577, 720
604 <-> 604
605 <-> 38, 598
606 <-> 506, 686, 1813
607 <-> 2, 1948
608 <-> 148
609 <-> 1571
610 <-> 772, 901
611 <-> 178, 286, 880
612 <-> 1814
613 <-> 140, 883, 1198, 1764, 1942
614 <-> 1352
615 <-> 40, 321
616 <-> 58, 1413
617 <-> 624, 1008, 1591, 1791
618 <-> 1625
619 <-> 871, 1567
620 <-> 1954
621 <-> 12, 103, 566
622 <-> 1895
623 <-> 256, 1767
624 <-> 617
625 <-> 663
626 <-> 626
627 <-> 1650
628 <-> 884
629 <-> 1104, 1421
630 <-> 630, 864
631 <-> 529, 646
632 <-> 246
633 <-> 389, 1847
634 <-> 128, 384
635 <-> 1553, 1817
636 <-> 636
637 <-> 387
638 <-> 336, 342, 646, 1453
639 <-> 543, 815, 1087
640 <-> 1422, 1597
641 <-> 570, 805, 993, 1961
642 <-> 1371
643 <-> 959, 1044, 1444
644 <-> 41
645 <-> 276, 1022, 1184
646 <-> 631, 638, 1790
647 <-> 135, 1286
648 <-> 60
649 <-> 29, 224, 1636
650 <-> 324
651 <-> 863, 1321
652 <-> 149, 687, 1128, 1346
653 <-> 306
654 <-> 1409
655 <-> 1142, 1733
656 <-> 246, 331, 768, 1815
657 <-> 429
658 <-> 1511, 1569
659 <-> 1744
660 <-> 50, 796, 1524
661 <-> 63, 65, 810
662 <-> 995, 1661
663 <-> 247, 625, 1001
664 <-> 664
665 <-> 1305
666 <-> 666, 1817
667 <-> 469, 1003, 1550
668 <-> 1540, 1958
669 <-> 831, 883, 1349, 1719
670 <-> 1531
671 <-> 245, 671, 1693
672 <-> 315, 1088
673 <-> 942, 1381, 1660
674 <-> 880
675 <-> 368
676 <-> 1269, 1699
677 <-> 64, 1654
678 <-> 784
679 <-> 1760
680 <-> 39
681 <-> 681
682 <-> 728, 749, 1995
683 <-> 353
684 <-> 84, 1150
685 <-> 22
686 <-> 606
687 <-> 652, 1687
688 <-> 1878
689 <-> 454, 689
690 <-> 924, 1183
691 <-> 1410, 1413
692 <-> 1702
693 <-> 230, 1658
694 <-> 820, 1282, 1873
695 <-> 279
696 <-> 1168
697 <-> 262, 766, 776
698 <-> 65, 528, 698, 940
699 <-> 1778
700 <-> 743, 1459, 1825
701 <-> 1475
702 <-> 457, 792, 861, 1467
703 <-> 1581
704 <-> 1969
705 <-> 440, 1145
706 <-> 54, 422
707 <-> 1015, 1780
708 <-> 104, 1266
709 <-> 150, 1778
710 <-> 194
711 <-> 751
712 <-> 963
713 <-> 1525, 1762
714 <-> 1713
715 <-> 244, 1293, 1421
716 <-> 403, 1572
717 <-> 1142
718 <-> 1204
719 <-> 1672
720 <-> 469, 603
721 <-> 30, 1268, 1400
722 <-> 1183
723 <-> 1012
724 <-> 1029, 1289, 1368
725 <-> 31, 1039
726 <-> 176, 726
727 <-> 856
728 <-> 682, 1000
729 <-> 299, 1216, 1967
730 <-> 850, 900
731 <-> 1540, 1884
732 <-> 600, 784
733 <-> 1655
734 <-> 162
735 <-> 354, 1955
736 <-> 361, 1084, 1822
737 <-> 387
738 <-> 58, 1573
739 <-> 1119, 1216, 1822
740 <-> 829, 1219
741 <-> 1164
742 <-> 107, 578
743 <-> 700, 1744
744 <-> 278, 555
745 <-> 835, 1903
746 <-> 396
747 <-> 537, 1843
748 <-> 61
749 <-> 682, 1217, 1731
750 <-> 874, 1110, 1724
751 <-> 711, 1767
752 <-> 248, 1011
753 <-> 1327, 1885
754 <-> 127, 211, 1117
755 <-> 755
756 <-> 387
757 <-> 1098, 1169
758 <-> 143, 1689
759 <-> 19, 1517
760 <-> 831, 1915
761 <-> 761, 1195
762 <-> 1634
763 <-> 763
764 <-> 848, 1375
765 <-> 765, 1136
766 <-> 697, 1295, 1887
767 <-> 1906
768 <-> 281, 656, 1031
769 <-> 1457, 1863
770 <-> 75, 96
771 <-> 253, 846, 1375
772 <-> 610
773 <-> 323
774 <-> 1067
775 <-> 182, 1494
776 <-> 697
777 <-> 1136
778 <-> 296, 1057
779 <-> 315, 1631, 1796
780 <-> 363, 780, 1814
781 <-> 928, 1423
782 <-> 1850
783 <-> 441
784 <-> 678, 732, 999, 1988
785 <-> 514, 1248
786 <-> 134, 786, 1009
787 <-> 1348, 1863
788 <-> 891, 1183, 1455
789 <-> 1310, 1420, 1510
790 <-> 188, 267
791 <-> 1276
792 <-> 251, 547, 702
793 <-> 1, 72, 410, 1092
794 <-> 880
795 <-> 1799, 1807
796 <-> 660, 1548
797 <-> 252, 580, 797
798 <-> 395, 552
799 <-> 415, 799
800 <-> 285, 1889
801 <-> 801
802 <-> 802
803 <-> 1188, 1326, 1935
804 <-> 221, 441
805 <-> 43, 641, 1772
806 <-> 412, 546, 918, 1617
807 <-> 876, 1887
808 <-> 400, 1435, 1716
809 <-> 394, 513
810 <-> 661
811 <-> 216, 1259
812 <-> 1883
813 <-> 201, 1692
814 <-> 592
815 <-> 639
816 <-> 1041, 1734
817 <-> 1134, 1432
818 <-> 1575
819 <-> 113, 1063
820 <-> 694
821 <-> 1242
822 <-> 143, 892
823 <-> 1393, 1492
824 <-> 946
825 <-> 242, 999
826 <-> 1594
827 <-> 381, 1079, 1580
828 <-> 1941
829 <-> 468, 740, 1905
830 <-> 977, 1260, 1861
831 <-> 669, 760, 946, 1332
832 <-> 428, 832, 944, 1172
833 <-> 837, 1008, 1470
834 <-> 429, 915
835 <-> 306, 745, 976
836 <-> 499, 967
837 <-> 596, 833, 974
838 <-> 1335
839 <-> 320, 839, 1703
840 <-> 1053, 1398, 1760
841 <-> 1193
842 <-> 842, 1066, 1108
843 <-> 1414, 1697, 1894
844 <-> 337, 438
845 <-> 1506
846 <-> 771
847 <-> 466, 907, 1432
848 <-> 510, 764
849 <-> 1063, 1195, 1701
850 <-> 730, 1551
851 <-> 1112, 1331, 1479
852 <-> 1652
853 <-> 391
854 <-> 17, 424, 906, 1665
855 <-> 425, 1082
856 <-> 301, 463, 727, 1744
857 <-> 22, 227
858 <-> 539, 1252, 1472
859 <-> 232, 1843
860 <-> 193
861 <-> 549, 702, 1709, 1884
862 <-> 1149
863 <-> 651, 955
864 <-> 630
865 <-> 1138
866 <-> 144, 1111, 1114
867 <-> 282, 1487, 1835
868 <-> 1699
869 <-> 869
870 <-> 1487
871 <-> 619
872 <-> 872
873 <-> 370, 543, 1968
874 <-> 750, 874
875 <-> 234, 1202, 1473
876 <-> 807, 933, 1741
877 <-> 1205, 1874
878 <-> 1831
879 <-> 534, 1860
880 <-> 32, 611, 674, 794
881 <-> 1361, 1750
882 <-> 572, 1495
883 <-> 613, 669
884 <-> 591, 628, 1815
885 <-> 996, 1237
886 <-> 314, 1709
887 <-> 576
888 <-> 551
889 <-> 0, 1494
890 <-> 1100, 1966
891 <-> 788, 1312
892 <-> 303, 533, 822, 1334, 1812, 1935
893 <-> 1723
894 <-> 272, 1992
895 <-> 568, 1038
896 <-> 551, 1425
897 <-> 1783
898 <-> 375
899 <-> 358
900 <-> 730
901 <-> 106, 153, 610
902 <-> 1203
903 <-> 32, 1935
904 <-> 1109
905 <-> 364
906 <-> 293, 854, 1565
907 <-> 847, 1139, 1180, 1431, 1563, 1878
908 <-> 1908
909 <-> 321, 943
910 <-> 47, 1067
911 <-> 1468, 1495
912 <-> 15
913 <-> 1692
914 <-> 922, 1445
915 <-> 834, 1002
916 <-> 461
917 <-> 1177, 1924
918 <-> 806, 962, 1058, 1419
919 <-> 44, 82, 1933
920 <-> 1147, 1539
921 <-> 393, 458, 1055, 1951
922 <-> 914, 1271
923 <-> 204, 207, 1201
924 <-> 205, 690
925 <-> 173, 1816
926 <-> 1279
927 <-> 927
928 <-> 781
929 <-> 154
930 <-> 144
931 <-> 972, 1237
932 <-> 1317
933 <-> 876, 1756
934 <-> 51, 405, 1105, 1960
935 <-> 935, 1674
936 <-> 491, 1201, 1247
937 <-> 956, 1576, 1788
938 <-> 1377, 1733
939 <-> 121, 1638
940 <-> 698, 1808
941 <-> 1665, 1957
942 <-> 673
943 <-> 341, 909
944 <-> 832
945 <-> 1087, 1340
946 <-> 824, 831
947 <-> 555
948 <-> 959
949 <-> 1068
950 <-> 1664
951 <-> 241, 502, 1151
952 <-> 40, 537, 1376
953 <-> 397
954 <-> 148, 1075, 1364
955 <-> 863, 1235, 1618, 1724
956 <-> 937
957 <-> 101, 1323
958 <-> 1794, 1972
959 <-> 643, 948, 1023
960 <-> 960, 1417
961 <-> 1278
962 <-> 370, 918
963 <-> 481, 712
964 <-> 1198
965 <-> 4
966 <-> 966
967 <-> 836, 967, 1821
968 <-> 1513
969 <-> 128, 232
970 <-> 529
971 <-> 1471
972 <-> 436, 931
973 <-> 231
974 <-> 837
975 <-> 1390
976 <-> 835
977 <-> 830
978 <-> 439, 1687
979 <-> 527
980 <-> 980, 1609, 1940
981 <-> 307, 1671
982 <-> 574, 1318, 1643
983 <-> 243
984 <-> 598
985 <-> 279
986 <-> 68
987 <-> 1060
988 <-> 1942
989 <-> 1478
990 <-> 490, 525, 1838
991 <-> 41, 1263, 1302
992 <-> 591
993 <-> 273, 641
994 <-> 1026, 1240, 1618
995 <-> 662, 1545
996 <-> 885, 1528
997 <-> 449, 1058
998 <-> 487
999 <-> 784, 825
1000 <-> 728
1001 <-> 141, 663, 1626, 1681
1002 <-> 300, 915
1003 <-> 667
1004 <-> 227, 459
1005 <-> 1780
1006 <-> 234, 1578
1007 <-> 203, 406
1008 <-> 617, 833
1009 <-> 786, 1064
1010 <-> 1010, 1031, 1919
1011 <-> 752, 1754
1012 <-> 7, 723, 1068, 1181
1013 <-> 36
1014 <-> 1594
1015 <-> 707
1016 <-> 63
1017 <-> 1511
1018 <-> 374, 1034
1019 <-> 131, 1155
1020 <-> 114
1021 <-> 1288
1022 <-> 645
1023 <-> 959, 1375
1024 <-> 1024
1025 <-> 216
1026 <-> 411, 994
1027 <-> 515
1028 <-> 1417
1029 <-> 304, 724
1030 <-> 343, 351
1031 <-> 768, 1010
1032 <-> 1032
1033 <-> 521
1034 <-> 1018
1035 <-> 235, 1578
1036 <-> 179, 503, 511, 1036
1037 <-> 1037, 1044
1038 <-> 895, 1125
1039 <-> 547, 725, 1599
1040 <-> 395
1041 <-> 816
1042 <-> 559, 1042
1043 <-> 168, 1873
1044 <-> 643, 1037, 1312
1045 <-> 1232
1046 <-> 321
1047 <-> 254
1048 <-> 1747
1049 <-> 364
1050 <-> 1050, 1947, 1963
1051 <-> 1156
1052 <-> 4, 1201
1053 <-> 840
1054 <-> 1133, 1342, 1537, 1708, 1778
1055 <-> 71, 921, 1786
1056 <-> 1672
1057 <-> 778, 1423, 1787
1058 <-> 918, 997
1059 <-> 288, 1337, 1401
1060 <-> 987, 1781
1061 <-> 602, 1660
1062 <-> 316, 1863
1063 <-> 120, 819, 849
1064 <-> 1009
1065 <-> 1065
1066 <-> 842
1067 <-> 774, 910, 1089
1068 <-> 949, 1012
1069 <-> 1900
1070 <-> 556
1071 <-> 1884
1072 <-> 447, 1122
1073 <-> 163, 249, 1073, 1237
1074 <-> 262
1075 <-> 954, 1075, 1789
1076 <-> 1076, 1680
1077 <-> 55, 322
1078 <-> 160, 547
1079 <-> 827, 1079
1080 <-> 377, 425, 1739
1081 <-> 220, 230
1082 <-> 855, 1638
1083 <-> 44
1084 <-> 302, 736
1085 <-> 168, 1431
1086 <-> 1973
1087 <-> 639, 945
1088 <-> 672
1089 <-> 1067, 1190
1090 <-> 408, 1492
1091 <-> 1674
1092 <-> 793
1093 <-> 1802
1094 <-> 536
1095 <-> 1095, 1204
1096 <-> 279
1097 <-> 351, 381
1098 <-> 757, 1519
1099 <-> 1099, 1752
1100 <-> 177, 890
1101 <-> 1145
1102 <-> 1280
1103 <-> 190, 1200
1104 <-> 629
1105 <-> 100, 934
1106 <-> 1426
1107 <-> 78, 1497
1108 <-> 842
1109 <-> 507, 904, 1109
1110 <-> 750
1111 <-> 866
1112 <-> 851
1113 <-> 1113
1114 <-> 866, 1131, 1861
1115 <-> 1187, 1629
1116 <-> 342
1117 <-> 754
1118 <-> 1637
1119 <-> 739
1120 <-> 1837
1121 <-> 1133, 1758
1122 <-> 577, 1072, 1349
1123 <-> 1359
1124 <-> 1174
1125 <-> 1038, 1789
1126 <-> 1260
1127 <-> 1213
1128 <-> 161, 652
1129 <-> 441
1130 <-> 4
1131 <-> 1114
1132 <-> 1132, 1979
1133 <-> 1054, 1121, 1253
1134 <-> 817
1135 <-> 76, 1606
1136 <-> 765, 777, 1860
1137 <-> 434
1138 <-> 865, 1280, 1471, 1736
1139 <-> 74, 907
1140 <-> 108, 378
1141 <-> 178
1142 <-> 655, 717
1143 <-> 446
1144 <-> 221
1145 <-> 476, 705, 1101, 1271, 1956
1146 <-> 474, 1179, 1936
1147 <-> 920, 1147
1148 <-> 1148, 1795
1149 <-> 862, 1799
1150 <-> 559, 684, 1797
1151 <-> 951
1152 <-> 1229
1153 <-> 1515, 1530
1154 <-> 1154
1155 <-> 1019, 1300
1156 <-> 164, 1051, 1156
1157 <-> 18, 1157
1158 <-> 1208
1159 <-> 1651
1160 <-> 567, 1510, 1710
1161 <-> 1161, 1427, 1590
1162 <-> 206, 229, 1561
1163 <-> 1388
1164 <-> 741, 1494
1165 <-> 1217
1166 <-> 123, 276
1167 <-> 1262, 1547
1168 <-> 80, 531, 696
1169 <-> 362, 757, 1504
1170 <-> 1854
1171 <-> 1171, 1898
1172 <-> 832
1173 <-> 1173, 1315
1174 <-> 1124, 1174, 1831
1175 <-> 202, 452
1176 <-> 330, 335, 1761
1177 <-> 917
1178 <-> 155, 567
1179 <-> 224, 1146
1180 <-> 907, 1661
1181 <-> 1012
1182 <-> 176
1183 <-> 690, 722, 788
1184 <-> 645
1185 <-> 487
1186 <-> 1659
1187 <-> 348, 1115, 1670
1188 <-> 275, 803
1189 <-> 1689
1190 <-> 75, 1089
1191 <-> 285
1192 <-> 1744
1193 <-> 477, 515, 841
1194 <-> 1308
1195 <-> 761, 849
1196 <-> 130, 1993
1197 <-> 144
1198 <-> 613, 964, 1329
1199 <-> 1389
1200 <-> 1103
1201 <-> 923, 936, 1052
1202 <-> 875
1203 <-> 490, 902, 1692
1204 <-> 718, 1095, 1245
1205 <-> 263, 333, 877
1206 <-> 1311
1207 <-> 415, 1883
1208 <-> 445, 1158
1209 <-> 550, 1640
1210 <-> 12, 1210, 1428
1211 <-> 460, 1529
1212 <-> 52, 159, 1493, 1819
1213 <-> 1127, 1213
1214 <-> 1214, 1436
1215 <-> 266, 1758
1216 <-> 729, 739
1217 <-> 141, 749, 1165, 1315
1218 <-> 599, 1595
1219 <-> 740, 1549
1220 <-> 588, 1374
1221 <-> 405
1222 <-> 1966
1223 <-> 119
1224 <-> 1528
1225 <-> 1314
1226 <-> 86, 515
1227 <-> 1681
1228 <-> 1228
1229 <-> 0, 1152, 1374
1230 <-> 1453
1231 <-> 223, 488
1232 <-> 1045, 1261
1233 <-> 1759
1234 <-> 360
1235 <-> 283, 955, 1241, 1783
1236 <-> 1356
1237 <-> 600, 885, 931, 1073
1238 <-> 370, 1602
1239 <-> 546, 1373
1240 <-> 994
1241 <-> 1235, 1392
1242 <-> 7, 59, 821, 1945
1243 <-> 1296
1244 <-> 7, 1300, 1434
1245 <-> 1204, 1347
1246 <-> 374, 555, 1508
1247 <-> 109, 936
1248 <-> 785, 1715
1249 <-> 238
1250 <-> 1600, 1623
1251 <-> 1251
1252 <-> 858
1253 <-> 392, 1133
1254 <-> 35, 1394
1255 <-> 575
1256 <-> 214, 1607, 1685
1257 <-> 169
1258 <-> 81, 1264, 1320
1259 <-> 811, 1425
1260 <-> 830, 1126
1261 <-> 571, 1232
1262 <-> 1167, 1862
1263 <-> 540, 991
1264 <-> 1258, 1651
1265 <-> 139, 1569
1266 <-> 708
1267 <-> 1267
1268 <-> 721
1269 <-> 276, 676, 1759
1270 <-> 467, 1270, 1916
1271 <-> 225, 922, 1145, 1700
1272 <-> 99
1273 <-> 1302
1274 <-> 1966
1275 <-> 525
1276 <-> 791, 1834
1277 <-> 450, 1474, 1645
1278 <-> 185, 961
1279 <-> 458, 926
1280 <-> 209, 1102, 1138
1281 <-> 208, 462, 1943
1282 <-> 694, 1522
1283 <-> 111, 119, 1407
1284 <-> 182, 1996
1285 <-> 287
1286 <-> 647, 1286, 1715
1287 <-> 132
1288 <-> 222, 1021, 1398
1289 <-> 724
1290 <-> 208, 260, 317
1291 <-> 1498
1292 <-> 88
1293 <-> 387, 715, 1322, 1519, 1645
1294 <-> 445, 513, 1504
1295 <-> 766
1296 <-> 1243, 1379, 1964
1297 <-> 38, 1669
1298 <-> 1906
1299 <-> 18, 1804
1300 <-> 1155, 1244
1301 <-> 1371, 1453
1302 <-> 991, 1273
1303 <-> 375, 504, 1948
1304 <-> 1667, 1933
1305 <-> 102, 151, 665
1306 <-> 266
1307 <-> 179
1308 <-> 34, 1194
1309 <-> 563
1310 <-> 526, 789
1311 <-> 1206, 1311, 1769
1312 <-> 891, 1044
1313 <-> 169
1314 <-> 151, 1225
1315 <-> 42, 1173, 1217
1316 <-> 1316
1317 <-> 932, 1805
1318 <-> 187, 373, 982
1319 <-> 41, 220, 1948
1320 <-> 1258, 1859
1321 <-> 651
1322 <-> 1293
1323 <-> 957, 1472
1324 <-> 1324
1325 <-> 1325
1326 <-> 803, 1846
1327 <-> 753
1328 <-> 1879
1329 <-> 1198
1330 <-> 553, 1330
1331 <-> 392, 851
1332 <-> 396, 831
1333 <-> 210
1334 <-> 892
1335 <-> 838, 1552, 1568
1336 <-> 1336
1337 <-> 1059
1338 <-> 310, 544
1339 <-> 1897
1340 <-> 945
1341 <-> 489
1342 <-> 137, 1054
1343 <-> 1343
1344 <-> 1946
1345 <-> 1345
1346 <-> 652
1347 <-> 1245, 1914, 1930
1348 <-> 787, 1591
1349 <-> 669, 1122
1350 <-> 304, 1790
1351 <-> 587, 1997
1352 <-> 20, 614
1353 <-> 1738
1354 <-> 413, 1608
1355 <-> 522, 1816, 1917
1356 <-> 1236, 1450
1357 <-> 431, 1575
1358 <-> 500
1359 <-> 1123, 1599
1360 <-> 1370, 1385
1361 <-> 1, 881
1362 <-> 355, 1611, 1952
1363 <-> 69
1364 <-> 954
1365 <-> 1948
1366 <-> 30, 1470
1367 <-> 1527
1368 <-> 724
1369 <-> 277, 1482
1370 <-> 1360
1371 <-> 642, 1301, 1478, 1485
1372 <-> 1372, 1594
1373 <-> 1239
1374 <-> 79, 1220, 1229
1375 <-> 764, 771, 1023
1376 <-> 952
1377 <-> 938, 1520, 1730
1378 <-> 1378, 1411, 1823
1379 <-> 1296, 1832
1380 <-> 1380
1381 <-> 673
1382 <-> 1382
1383 <-> 195, 586
1384 <-> 542
1385 <-> 215, 1360
1386 <-> 1386
1387 <-> 1536
1388 <-> 311, 402, 1163
1389 <-> 251, 1199
1390 <-> 322, 975
1391 <-> 172, 407, 1453
1392 <-> 1241, 1587
1393 <-> 419, 823, 1636
1394 <-> 1254, 1588, 1699
1395 <-> 401, 1621
1396 <-> 1396, 1870
1397 <-> 1629
1398 <-> 840, 1288
1399 <-> 1399, 1932
1400 <-> 721
1401 <-> 1059
1402 <-> 1402
1403 <-> 33
1404 <-> 1449, 1632, 1832
1405 <-> 1634
1406 <-> 1726
1407 <-> 265, 1283, 1999
1408 <-> 39, 336, 426
1409 <-> 75, 147, 654
1410 <-> 691, 1780
1411 <-> 1378
1412 <-> 1447, 1759
1413 <-> 616, 691
1414 <-> 843
1415 <-> 1415
1416 <-> 197, 271
1417 <-> 132, 960, 1028
1418 <-> 1418, 1426
1419 <-> 918, 1560
1420 <-> 789
1421 <-> 629, 715
1422 <-> 391, 640
1423 <-> 781, 1057
1424 <-> 1614
1425 <-> 21, 896, 1259
1426 <-> 1106, 1418
1427 <-> 1161
1428 <-> 1210, 1677
1429 <-> 131
1430 <-> 1822
1431 <-> 907, 1085, 1846
1432 <-> 817, 847
1433 <-> 75
1434 <-> 1244
1435 <-> 484, 808
1436 <-> 1214
1437 <-> 418
1438 <-> 57
1439 <-> 1469, 1824
1440 <-> 237
1441 <-> 1722
1442 <-> 424, 1678
1443 <-> 144
1444 <-> 579, 643, 1869
1445 <-> 914
1446 <-> 1524, 1728
1447 <-> 1412, 1962
1448 <-> 1485
1449 <-> 1404
1450 <-> 1356, 1647
1451 <-> 460, 1907, 1967
1452 <-> 445, 446
1453 <-> 56, 133, 638, 1230, 1301, 1391
1454 <-> 1994
1455 <-> 788
1456 <-> 1914
1457 <-> 769
1458 <-> 1458
1459 <-> 700, 1796
1460 <-> 1799
1461 <-> 15, 436
1462 <-> 1678
1463 <-> 83, 1553, 1684
1464 <-> 35
1465 <-> 1471
1466 <-> 175, 430
1467 <-> 539, 702
1468 <-> 281, 911, 1475
1469 <-> 366, 426, 478, 1439, 1524
1470 <-> 833, 1366
1471 <-> 971, 1138, 1465
1472 <-> 560, 858, 1323, 1937
1473 <-> 506, 875
1474 <-> 1277, 1937
1475 <-> 701, 1468
1476 <-> 464, 522
1477 <-> 1785
1478 <-> 989, 1371
1479 <-> 409, 851
1480 <-> 1677
1481 <-> 463
1482 <-> 517, 1369, 1482
1483 <-> 102, 218
1484 <-> 532, 1531, 1735
1485 <-> 400, 1371, 1448
1486 <-> 453
1487 <-> 867, 870, 1577, 1584
1488 <-> 1488
1489 <-> 16, 327
1490 <-> 418
1491 <-> 7, 1589
1492 <-> 823, 1090
1493 <-> 1212, 1519, 1675
1494 <-> 775, 889, 1164
1495 <-> 882, 911
1496 <-> 386, 1496
1497 <-> 269, 455, 1107
1498 <-> 9, 1291, 1758
1499 <-> 1685, 1893
1500 <-> 1657
1501 <-> 244, 287
1502 <-> 1951
1503 <-> 112
1504 <-> 1169, 1294
1505 <-> 1987
1506 <-> 845, 1905
1507 <-> 1507
1508 <-> 1246
1509 <-> 41
1510 <-> 195, 789, 1160, 1980
1511 <-> 658, 1017
1512 <-> 1990
1513 <-> 968, 1513, 1612
1514 <-> 1514
1515 <-> 1153, 1632
1516 <-> 280
1517 <-> 759
1518 <-> 1837
1519 <-> 80, 82, 1098, 1293, 1493
1520 <-> 1377, 1978
1521 <-> 1521
1522 <-> 1282
1523 <-> 1749, 1876
1524 <-> 660, 1446, 1469, 1535, 1729
1525 <-> 283, 713
1526 <-> 22, 1767
1527 <-> 535, 1367, 1889
1528 <-> 996, 1224
1529 <-> 1211, 1736
1530 <-> 1153
1531 <-> 451, 670, 1484
1532 <-> 46
1533 <-> 62, 143, 530
1534 <-> 117, 1992
1535 <-> 1524
1536 <-> 342, 1387
1537 <-> 1054
1538 <-> 302, 1589
1539 <-> 576, 920
1540 <-> 668, 731
1541 <-> 1639
1542 <-> 1542
1543 <-> 1702
1544 <-> 1927
1545 <-> 995
1546 <-> 92, 1890
1547 <-> 40, 1167
1548 <-> 796
1549 <-> 110, 337, 1219
1550 <-> 46, 667
1551 <-> 497, 850
1552 <-> 526, 1335
1553 <-> 464, 635, 1463
1554 <-> 580, 1696
1555 <-> 1556, 1648, 1867
1556 <-> 180, 1555, 1676
1557 <-> 313, 1831
1558 <-> 249
1559 <-> 501
1560 <-> 1419
1561 <-> 1162
1562 <-> 271, 388
1563 <-> 597, 907
1564 <-> 239
1565 <-> 906, 1854
1566 <-> 465
1567 <-> 393, 619
1568 <-> 1335, 1745
1569 <-> 658, 1265, 1651
1570 <-> 475
1571 <-> 310, 323, 609
1572 <-> 540, 716
1573 <-> 738
1574 <-> 531
1575 <-> 597, 818, 1357
1576 <-> 937
1577 <-> 456, 1487, 1630
1578 <-> 1006, 1035
1579 <-> 1704
1580 <-> 827
1581 <-> 286, 703, 1888
1582 <-> 294
1583 <-> 1907
1584 <-> 1487
1585 <-> 1955
1586 <-> 1586, 1641
1587 <-> 1392
1588 <-> 522, 1394
1589 <-> 1491, 1538, 1589
1590 <-> 1161, 1642, 1946
1591 <-> 4, 617, 1348
1592 <-> 68
1593 <-> 356, 466
1594 <-> 826, 1014, 1372
1595 <-> 1218
1596 <-> 78
1597 <-> 640
1598 <-> 422
1599 <-> 1039, 1359
1600 <-> 1250
1601 <-> 113, 1631
1602 <-> 1238
1603 <-> 1603
1604 <-> 1604
1605 <-> 1980
1606 <-> 1135, 1828
1607 <-> 1256, 1607
1608 <-> 1354
1609 <-> 980, 1864
1610 <-> 1610
1611 <-> 583, 1362
1612 <-> 309, 367, 1513
1613 <-> 270, 1620
1614 <-> 1424, 1688
1615 <-> 1615
1616 <-> 1884
1617 <-> 806, 1763
1618 <-> 955, 994, 1897
1619 <-> 1622
1620 <-> 538, 584, 1613
1621 <-> 1395, 1621
1622 <-> 452, 1619
1623 <-> 188, 1250
1624 <-> 148
1625 <-> 519, 618, 1625, 1765
1626 <-> 213, 1001
1627 <-> 1929
1628 <-> 6, 305
1629 <-> 558, 1115, 1397
1630 <-> 1577
1631 <-> 779, 1601
1632 <-> 1404, 1515
1633 <-> 336
1634 <-> 762, 1405, 1734
1635 <-> 1635
1636 <-> 257, 649, 1393
1637 <-> 167, 329, 1118
1638 <-> 939, 1082
1639 <-> 1541, 1639
1640 <-> 1209
1641 <-> 1586
1642 <-> 567, 1590
1643 <-> 982
1644 <-> 408, 509
1645 <-> 1277, 1293
1646 <-> 1836, 1875
1647 <-> 1450, 1772
1648 <-> 1555, 1946
1649 <-> 1743
1650 <-> 627, 1720
1651 <-> 1159, 1264, 1569
1652 <-> 852, 1930
1653 <-> 1653
1654 <-> 677
1655 <-> 85, 733
1656 <-> 1875
1657 <-> 261, 1500, 1703
1658 <-> 693, 1679
1659 <-> 1186, 1659
1660 <-> 673, 1061
1661 <-> 662, 1180
1662 <-> 483
1663 <-> 1663, 1904
1664 <-> 196, 950, 1664
1665 <-> 144, 854, 941
1666 <-> 1666
1667 <-> 1304, 1890
1668 <-> 488
1669 <-> 1297
1670 <-> 78, 1187
1671 <-> 215, 981
1672 <-> 145, 358, 719, 1056
1673 <-> 1673
1674 <-> 25, 935, 1091
1675 <-> 1493
1676 <-> 190, 1556
1677 <-> 1428, 1480
1678 <-> 1442, 1462, 1987
1679 <-> 577, 1658
1680 <-> 16, 1076
1681 <-> 1001, 1227
1682 <-> 71
1683 <-> 90
1684 <-> 479, 1463, 1852
1685 <-> 1256, 1499
1686 <-> 94
1687 <-> 687, 978, 1787
1688 <-> 332, 1614, 1688
1689 <-> 758, 1189, 1779
1690 <-> 477
1691 <-> 1691, 1986
1692 <-> 166, 585, 813, 913, 1203, 1913
1693 <-> 671
1694 <-> 1711
1695 <-> 89, 1795
1696 <-> 1554
1697 <-> 147, 843, 1900
1698 <-> 212, 444, 1793
1699 <-> 676, 868, 1394, 1705
1700 <-> 87, 1271
1701 <-> 849
1702 <-> 222, 692, 1543
1703 <-> 839, 1657
1704 <-> 314, 498, 1579
1705 <-> 1699
1706 <-> 89, 1993
1707 <-> 1990, 1994
1708 <-> 1054, 1892
1709 <-> 861, 886
1710 <-> 1160
1711 <-> 1694, 1737
1712 <-> 1712
1713 <-> 714, 1935
1714 <-> 600
1715 <-> 217, 1248, 1286
1716 <-> 808
1717 <-> 278, 1914
1718 <-> 580
1719 <-> 669
1720 <-> 1650, 1762, 1856
1721 <-> 422, 1918
1722 <-> 1441, 1722
1723 <-> 893, 1915
1724 <-> 508, 750, 955
1725 <-> 1725
1726 <-> 1406, 1959
1727 <-> 1797
1728 <-> 14, 1446
1729 <-> 1524
1730 <-> 1377, 1737
1731 <-> 104, 749
1732 <-> 129, 1908
1733 <-> 174, 655, 938
1734 <-> 816, 1634, 1734
1735 <-> 538, 1484
1736 <-> 0, 1138, 1529
1737 <-> 1711, 1730
1738 <-> 26, 1353, 1757
1739 <-> 302, 1080
1740 <-> 118, 257
1741 <-> 152, 219, 876
1742 <-> 1841, 1945
1743 <-> 333, 1649
1744 <-> 659, 743, 856, 1192
1745 <-> 1568
1746 <-> 1746
1747 <-> 579, 1048
1748 <-> 283
1749 <-> 189, 350, 1523, 1848, 1894
1750 <-> 881
1751 <-> 344
1752 <-> 1099
1753 <-> 1753
1754 <-> 1011
1755 <-> 1755, 1939
1756 <-> 933
1757 <-> 1738
1758 <-> 1121, 1215, 1498
1759 <-> 1233, 1269, 1412
1760 <-> 198, 679, 840
1761 <-> 1176
1762 <-> 713, 1720
1763 <-> 1617
1764 <-> 613
1765 <-> 1625
1766 <-> 99
1767 <-> 623, 751, 1526
1768 <-> 82
1769 <-> 1311, 1921
1770 <-> 565, 1995
1771 <-> 77, 1771
1772 <-> 805, 1647, 1772
1773 <-> 1773, 1826
1774 <-> 303
1775 <-> 239, 259
1776 <-> 225
1777 <-> 393
1778 <-> 482, 699, 709, 1054
1779 <-> 264, 1689
1780 <-> 61, 194, 707, 1005, 1410, 1999
1781 <-> 165, 1060, 1978
1782 <-> 264
1783 <-> 897, 1235, 1845
1784 <-> 1784
1785 <-> 1477, 1915
1786 <-> 1055
1787 <-> 1057, 1687, 1899
1788 <-> 498, 937, 1859
1789 <-> 1075, 1125
1790 <-> 646, 1350
1791 <-> 617
1792 <-> 1855
1793 <-> 1698
1794 <-> 958
1795 <-> 1148, 1695
1796 <-> 779, 1459, 1857
1797 <-> 1150, 1727
1798 <-> 500
1799 <-> 795, 1149, 1460
1800 <-> 368, 1800
1801 <-> 220
1802 <-> 99, 1093
1803 <-> 1810
1804 <-> 1299
1805 <-> 292, 527, 1317
1806 <-> 443, 1865
1807 <-> 795, 1911
1808 <-> 940
1809 <-> 122, 595
1810 <-> 345, 1803
1811 <-> 1980
1812 <-> 892
1813 <-> 421, 606
1814 <-> 612, 780
1815 <-> 656, 884
1816 <-> 925, 1355
1817 <-> 635, 666
1818 <-> 29, 206
1819 <-> 1212
1820 <-> 1874
1821 <-> 227, 967
1822 <-> 736, 739, 1430
1823 <-> 1378
1824 <-> 68, 1439
1825 <-> 700
1826 <-> 557, 1773
1827 <-> 98, 1971
1828 <-> 1606, 1865
1829 <-> 449
1830 <-> 1830
1831 <-> 20, 878, 1174, 1557
1832 <-> 1379, 1404, 1832
1833 <-> 107
1834 <-> 423, 560, 1276
1835 <-> 867
1836 <-> 118, 1646
1837 <-> 47, 1120, 1518
1838 <-> 243, 990
1839 <-> 1839
1840 <-> 478
1841 <-> 1742
1842 <-> 565
1843 <-> 594, 747, 859
1844 <-> 461
1845 <-> 1783
1846 <-> 1326, 1431
1847 <-> 633, 1888
1848 <-> 1749
1849 <-> 24, 48, 292, 1851
1850 <-> 440, 782
1851 <-> 1849
1852 <-> 1684
1853 <-> 1853
1854 <-> 557, 1170, 1565
1855 <-> 70, 1792
1856 <-> 1720
1857 <-> 1796
1858 <-> 417
1859 <-> 1320, 1788
1860 <-> 36, 879, 1136
1861 <-> 830, 1114
1862 <-> 416, 1262
1863 <-> 28, 769, 787, 1062
1864 <-> 1609, 1920, 1953
1865 <-> 189, 1806, 1828, 1969
1866 <-> 451
1867 <-> 1555
1868 <-> 1868
1869 <-> 1444
1870 <-> 1396
1871 <-> 1939
1872 <-> 1914
1873 <-> 694, 1043
1874 <-> 241, 877, 1820
1875 <-> 1646, 1656
1876 <-> 1523
1877 <-> 1877
1878 <-> 159, 688, 907
1879 <-> 1328, 1879
1880 <-> 415
1881 <-> 65
1882 <-> 201
1883 <-> 812, 1207
1884 <-> 731, 861, 1071, 1616
1885 <-> 753, 1885
1886 <-> 75
1887 <-> 766, 807
1888 <-> 240, 1581, 1847
1889 <-> 800, 1527
1890 <-> 1546, 1667
1891 <-> 186, 548
1892 <-> 1708
1893 <-> 1499
1894 <-> 475, 843, 1749
1895 <-> 622, 1895, 1978
1896 <-> 334
1897 <-> 1339, 1618, 1949
1898 <-> 1171
1899 <-> 1787
1900 <-> 1069, 1697
1901 <-> 142
1902 <-> 291, 305
1903 <-> 745
1904 <-> 1663
1905 <-> 829, 1506
1906 <-> 316, 767, 1298, 1999
1907 <-> 183, 1451, 1583
1908 <-> 908, 1732
1909 <-> 62
1910 <-> 1999
1911 <-> 364, 1807
1912 <-> 372, 1912
1913 <-> 161, 601, 1692
1914 <-> 1347, 1456, 1717, 1872
1915 <-> 760, 1723, 1785
1916 <-> 1270
1917 <-> 1355
1918 <-> 1721
1919 <-> 590, 1010
1920 <-> 414, 1864
1921 <-> 1769
1922 <-> 232
1923 <-> 238, 271, 1923
1924 <-> 571, 917
1925 <-> 556, 1925
1926 <-> 129, 581
1927 <-> 360, 1544
1928 <-> 289
1929 <-> 1627, 1929
1930 <-> 181, 1347, 1652
1931 <-> 469, 1931
1932 <-> 1399
1933 <-> 919, 1304
1934 <-> 290
1935 <-> 803, 892, 903, 1713
1936 <-> 1146
1937 <-> 146, 1472, 1474
1938 <-> 149
1939 <-> 88, 1755, 1871
1940 <-> 980
1941 <-> 548, 828
1942 <-> 613, 988
1943 <-> 1281
1944 <-> 239, 326, 530
1945 <-> 49, 1242, 1742
1946 <-> 1344, 1590, 1648
1947 <-> 1050
1948 <-> 607, 1303, 1319, 1365
1949 <-> 1897
1950 <-> 1950
1951 <-> 553, 921, 1502
1952 <-> 163, 1362
1953 <-> 1864
1954 <-> 495, 620
1955 <-> 735, 1585
1956 <-> 11, 1145
1957 <-> 941
1958 <-> 398, 668
1959 <-> 340, 1726
1960 <-> 934
1961 <-> 641
1962 <-> 1447
1963 <-> 112, 1050
1964 <-> 1296
1965 <-> 61
1966 <-> 890, 1222, 1274
1967 <-> 545, 550, 729, 1451
1968 <-> 873
1969 <-> 704, 1865
1970 <-> 393
1971 <-> 1827
1972 <-> 326, 958
1973 <-> 1086, 1973
1974 <-> 319, 1974
1975 <-> 452
1976 <-> 155
1977 <-> 410
1978 <-> 1520, 1781, 1895
1979 <-> 1132
1980 <-> 1510, 1605, 1811
1981 <-> 184
1982 <-> 39
1983 <-> 1983
1984 <-> 379, 494
1985 <-> 95
1986 <-> 1691
1987 <-> 1505, 1678
1988 <-> 124, 516, 784
1989 <-> 322
1990 <-> 1512, 1707
1991 <-> 226
1992 <-> 894, 1534
1993 <-> 1196, 1706
1994 <-> 16, 1454, 1707
1995 <-> 682, 1770
1996 <-> 1284
1997 <-> 153, 308, 1351
1998 <-> 5, 235, 428, 524
1999 <-> 1407, 1780, 1906, 1910"""
zip: List a -> List b -> List (a, b)
zip list1 list2 =
zip2 list1 list2 []
zip2: List a -> List b -> List(a, b) -> List(a, b)
zip2 list1 list2 acc =
case list1 of
[] -> acc
head1::tail1 ->
case list2 of
[] -> acc
head2::tail2 ->
zip2 tail1 tail2 (List.append acc [(head1, head2)])
toIntOrZero: String -> Int
toIntOrZero char =
case (String.toInt char) of
Ok a ->
a
Err _ ->
0
outerProduct: List a -> List (a, a)
outerProduct list =
List.concatMap (\e ->
List.map (\i -> (e, i)) list
) list
histogram: List comparable -> Dict comparable Int
histogram list =
List.foldl histo_inc Dict.empty list
histo_inc: comparable -> Dict comparable Int -> Dict comparable Int
histo_inc dir dict =
if Dict.member dir dict then
Dict.update dir (Maybe.map ((+) 1)) dict
else
Dict.insert dir 1 dict
| 13893 | -- Copyright (c) 2017 <NAME>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- * Neither the name of the copyright holder nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Html exposing (..)
import Dict exposing (..)
import Array exposing (..)
import Debug exposing (..)
main = text <| toString <| solve input
--solve: String -> Int
solve input =
let
initialDict = parse input
initialSize = Dict.size initialDict
dictAfterRemoval = removeGroup 0 initialDict
in
initialSize - (Dict.size dictAfterRemoval)
removeGroup id dict =
if Dict.member id dict then
let
deps = Dict.get id dict |> Maybe.withDefault []
newDict = Dict.remove id dict
in
deps
|> List.foldl removeGroup newDict
else
dict
parse: String -> Dict Int (List Int)
parse string =
String.split "\n" input
|> List.map parseLine
|> Dict.fromList
parseLine line =
case (String.split " <-> " line) of
id::deps::[] ->
let
iid = toIntOrZero id
ideps =
String.split ", " deps
|> List.map toIntOrZero
in
(iid, ideps)
_ -> (-1, [])
input2 = """0 <-> 2
1 <-> 1
2 <-> 0, 3, 4
3 <-> 2, 4
4 <-> 2, 3, 6
5 <-> 6
6 <-> 4, 5"""
input = """0 <-> 889, 1229, 1736
1 <-> 1, 480, 793, 1361
2 <-> 607
3 <-> 273, 422
4 <-> 965, 1052, 1130, 1591
5 <-> 1998
6 <-> 483, 1628
7 <-> 1012, 1242, 1244, 1491
8 <-> 524
9 <-> 13, 281, 1498
10 <-> 10
11 <-> 1956
12 <-> 598, 621, 1210
13 <-> 9
14 <-> 1728
15 <-> 912, 1461
16 <-> 1489, 1680, 1994
17 <-> 854
18 <-> 1157, 1299
19 <-> 759
20 <-> 1352, 1831
21 <-> 1425
22 <-> 470, 685, 857, 1526
23 <-> 405
24 <-> 43, 536, 1849
25 <-> 1674
26 <-> 26, 1738
27 <-> 558
28 <-> 1863
29 <-> 154, 649, 1818
30 <-> 721, 1366
31 <-> 725
32 <-> 413, 880, 903
33 <-> 414, 442, 1403
34 <-> 489, 1308
35 <-> 385, 1254, 1464
36 <-> 167, 1013, 1860
37 <-> 535
38 <-> 605, 1297
39 <-> 680, 1408, 1982
40 <-> 169, 615, 952, 1547
41 <-> 644, 991, 1319, 1509
42 <-> 453, 1315
43 <-> 24, 200, 805
44 <-> 919, 1083
45 <-> 500
46 <-> 1532, 1550
47 <-> 910, 1837
48 <-> 1849
49 <-> 542, 1945
50 <-> 57, 660
51 <-> 354, 934
52 <-> 1212
53 <-> 569
54 <-> 706
55 <-> 55, 114, 1077
56 <-> 1453
57 <-> 50, 1438
58 <-> 616, 738
59 <-> 1242
60 <-> 312, 523, 648
61 <-> 748, 1780, 1965
62 <-> 1533, 1909
63 <-> 562, 661, 1016
64 <-> 280, 300, 677
65 <-> 661, 698, 1881
66 <-> 283, 440
67 <-> 382, 421
68 <-> 986, 1592, 1824
69 <-> 541, 1363
70 <-> 266, 1855
71 <-> 371, 433, 1055, 1682
72 <-> 793
73 <-> 73
74 <-> 1139
75 <-> 770, 1190, 1409, 1433, 1886
76 <-> 1135
77 <-> 492, 1771
78 <-> 575, 1107, 1596, 1670
79 <-> 1374
80 <-> 1168, 1519
81 <-> 1258
82 <-> 919, 1519, 1768
83 <-> 1463
84 <-> 684
85 <-> 517, 1655
86 <-> 1226
87 <-> 1700
88 <-> 523, 1292, 1939
89 <-> 177, 1695, 1706
90 <-> 400, 1683
91 <-> 194
92 <-> 106, 1546
93 <-> 104
94 <-> 501, 1686
95 <-> 285, 1985
96 <-> 402, 770
97 <-> 196
98 <-> 318, 1827
99 <-> 220, 1272, 1766, 1802
100 <-> 1105
101 <-> 380, 957
102 <-> 1305, 1483
103 <-> 262, 481, 621
104 <-> 93, 708, 1731
105 <-> 282
106 <-> 92, 901
107 <-> 553, 742, 1833
108 <-> 480, 1140
109 <-> 1247
110 <-> 1549
111 <-> 1283
112 <-> 1503, 1963
113 <-> 819, 1601
114 <-> 55, 593, 1020
115 <-> 324
116 <-> 378
117 <-> 1534
118 <-> 1740, 1836
119 <-> 1223, 1283
120 <-> 435, 1063
121 <-> 404, 939
122 <-> 294, 360, 1809
123 <-> 1166
124 <-> 1988
125 <-> 163
126 <-> 126
127 <-> 255, 754
128 <-> 634, 969
129 <-> 563, 1732, 1926
130 <-> 1196
131 <-> 1019, 1429
132 <-> 1287, 1417
133 <-> 1453
134 <-> 184, 786
135 <-> 647
136 <-> 260, 306
137 <-> 1342
138 <-> 292
139 <-> 1265
140 <-> 613
141 <-> 1001, 1217
142 <-> 142, 1901
143 <-> 758, 822, 1533
144 <-> 866, 930, 1197, 1443, 1665
145 <-> 1672
146 <-> 1937
147 <-> 1409, 1697
148 <-> 608, 954, 1624
149 <-> 527, 652, 1938
150 <-> 709
151 <-> 447, 1305, 1314
152 <-> 1741
153 <-> 901, 1997
154 <-> 29, 929
155 <-> 1178, 1976
156 <-> 560
157 <-> 522
158 <-> 541
159 <-> 1212, 1878
160 <-> 1078
161 <-> 1128, 1913
162 <-> 588, 734
163 <-> 125, 1073, 1952
164 <-> 1156
165 <-> 1781
166 <-> 1692
167 <-> 36, 1637
168 <-> 1043, 1085
169 <-> 40, 334, 1257, 1313
170 <-> 170
171 <-> 171
172 <-> 1391
173 <-> 925
174 <-> 1733
175 <-> 175, 1466
176 <-> 726, 1182
177 <-> 89, 1100
178 <-> 611, 1141
179 <-> 1036, 1307
180 <-> 1556
181 <-> 1930
182 <-> 775, 1284
183 <-> 1907
184 <-> 134, 1981
185 <-> 255, 1278
186 <-> 1891
187 <-> 531, 1318
188 <-> 790, 1623
189 <-> 379, 1749, 1865
190 <-> 1103, 1676
191 <-> 534
192 <-> 477
193 <-> 193, 860
194 <-> 91, 710, 1780
195 <-> 290, 1383, 1510
196 <-> 97, 1664
197 <-> 1416
198 <-> 287, 1760
199 <-> 366
200 <-> 43
201 <-> 813, 1882
202 <-> 246, 1175
203 <-> 203, 1007
204 <-> 204, 923
205 <-> 924
206 <-> 1162, 1818
207 <-> 365, 487, 923
208 <-> 1281, 1290
209 <-> 1280
210 <-> 210, 288, 1333
211 <-> 211, 417, 754
212 <-> 1698
213 <-> 1626
214 <-> 1256
215 <-> 215, 1385, 1671
216 <-> 811, 1025
217 <-> 554, 1715
218 <-> 1483
219 <-> 1741
220 <-> 99, 530, 1081, 1319, 1801
221 <-> 804, 1144
222 <-> 1288, 1702
223 <-> 223, 1231
224 <-> 649, 1179
225 <-> 1271, 1776
226 <-> 226, 1991
227 <-> 496, 857, 1004, 1821
228 <-> 371, 500
229 <-> 1162
230 <-> 693, 1081
231 <-> 506, 973
232 <-> 859, 969, 1922
233 <-> 233
234 <-> 875, 1006
235 <-> 1035, 1998
236 <-> 236
237 <-> 289, 569, 1440
238 <-> 1249, 1923
239 <-> 1564, 1775, 1944
240 <-> 1888
241 <-> 951, 1874
242 <-> 825
243 <-> 384, 983, 1838
244 <-> 715, 1501
245 <-> 592, 671
246 <-> 202, 391, 632, 656
247 <-> 663
248 <-> 253, 752
249 <-> 1073, 1558
250 <-> 290
251 <-> 792, 1389
252 <-> 797
253 <-> 248, 771
254 <-> 254, 1047
255 <-> 127, 185, 369
256 <-> 623
257 <-> 1636, 1740
258 <-> 317
259 <-> 1775
260 <-> 136, 561, 1290
261 <-> 359, 1657
262 <-> 103, 697, 1074
263 <-> 1205
264 <-> 1779, 1782
265 <-> 1407
266 <-> 70, 1215, 1306
267 <-> 333, 790
268 <-> 603
269 <-> 269, 1497
270 <-> 270, 1613
271 <-> 1416, 1562, 1923
272 <-> 579, 894
273 <-> 3, 993
274 <-> 333
275 <-> 1188
276 <-> 535, 645, 1166, 1269
277 <-> 1369
278 <-> 744, 1717
279 <-> 349, 695, 985, 1096
280 <-> 64, 1516
281 <-> 9, 427, 768, 1468
282 <-> 105, 867
283 <-> 66, 1235, 1525, 1748
284 <-> 530
285 <-> 95, 800, 1191
286 <-> 339, 611, 1581
287 <-> 198, 1285, 1501
288 <-> 210, 1059
289 <-> 237, 1928
290 <-> 195, 250, 1934
291 <-> 337, 1902
292 <-> 138, 1805, 1849
293 <-> 906
294 <-> 122, 1582
295 <-> 602
296 <-> 778
297 <-> 471, 483
298 <-> 298
299 <-> 402, 729
300 <-> 64, 1002
301 <-> 856
302 <-> 1084, 1538, 1739
303 <-> 892, 1774
304 <-> 1029, 1350
305 <-> 521, 1628, 1902
306 <-> 136, 469, 653, 835
307 <-> 981
308 <-> 1997
309 <-> 1612
310 <-> 1338, 1571
311 <-> 1388
312 <-> 60
313 <-> 1557
314 <-> 886, 1704
315 <-> 672, 779
316 <-> 1062, 1906
317 <-> 258, 1290
318 <-> 98, 318
319 <-> 1974
320 <-> 839
321 <-> 395, 615, 909, 1046
322 <-> 1077, 1390, 1989
323 <-> 323, 773, 1571
324 <-> 115, 493, 511, 650
325 <-> 325
326 <-> 1944, 1972
327 <-> 1489
328 <-> 412, 468
329 <-> 1637
330 <-> 556, 1176
331 <-> 656
332 <-> 564, 1688
333 <-> 267, 274, 421, 1205, 1743
334 <-> 169, 1896
335 <-> 1176
336 <-> 638, 1408, 1633
337 <-> 291, 844, 1549
338 <-> 515
339 <-> 286
340 <-> 340, 1959
341 <-> 943
342 <-> 417, 638, 1116, 1536
343 <-> 1030
344 <-> 584, 1751
345 <-> 345, 1810
346 <-> 346
347 <-> 587
348 <-> 515, 1187
349 <-> 279, 349
350 <-> 1749
351 <-> 1030, 1097
352 <-> 352
353 <-> 353, 683
354 <-> 51, 354, 735
355 <-> 1362
356 <-> 1593
357 <-> 357
358 <-> 441, 501, 899, 1672
359 <-> 261
360 <-> 122, 360, 1234, 1927
361 <-> 736
362 <-> 1169
363 <-> 780
364 <-> 444, 905, 1049, 1911
365 <-> 207
366 <-> 199, 1469
367 <-> 1612
368 <-> 675, 1800
369 <-> 255
370 <-> 370, 873, 962, 1238
371 <-> 71, 228, 456
372 <-> 1912
373 <-> 1318
374 <-> 1018, 1246
375 <-> 898, 1303
376 <-> 376, 573
377 <-> 1080
378 <-> 116, 1140
379 <-> 189, 1984
380 <-> 101
381 <-> 472, 827, 1097
382 <-> 67
383 <-> 383, 582
384 <-> 243, 432, 444, 569, 634
385 <-> 35
386 <-> 1496
387 <-> 637, 737, 756, 1293
388 <-> 1562
389 <-> 633
390 <-> 488
391 <-> 246, 853, 1422
392 <-> 1253, 1331
393 <-> 921, 1567, 1777, 1970
394 <-> 809
395 <-> 321, 798, 1040
396 <-> 746, 1332
397 <-> 400, 953
398 <-> 1958
399 <-> 399
400 <-> 90, 397, 808, 1485
401 <-> 1395
402 <-> 96, 299, 1388
403 <-> 716
404 <-> 121
405 <-> 23, 934, 1221
406 <-> 1007
407 <-> 1391
408 <-> 497, 1090, 1644
409 <-> 1479
410 <-> 793, 1977
411 <-> 1026
412 <-> 328, 581, 806
413 <-> 32, 1354
414 <-> 33, 1920
415 <-> 799, 1207, 1880
416 <-> 1862
417 <-> 211, 342, 589, 1858
418 <-> 556, 1437, 1490
419 <-> 1393
420 <-> 420
421 <-> 67, 333, 1813
422 <-> 3, 706, 1598, 1721
423 <-> 1834
424 <-> 854, 1442
425 <-> 855, 1080
426 <-> 1408, 1469
427 <-> 281
428 <-> 832, 1998
429 <-> 553, 657, 834
430 <-> 1466
431 <-> 1357
432 <-> 384
433 <-> 71
434 <-> 434, 489, 1137
435 <-> 120
436 <-> 972, 1461
437 <-> 550
438 <-> 486, 844
439 <-> 978
440 <-> 66, 705, 1850
441 <-> 358, 589, 783, 804, 1129
442 <-> 33, 497
443 <-> 1806
444 <-> 364, 384, 1698
445 <-> 1208, 1294, 1452
446 <-> 1143, 1452
447 <-> 151, 1072
448 <-> 448
449 <-> 997, 1829
450 <-> 1277
451 <-> 1531, 1866
452 <-> 1175, 1622, 1975
453 <-> 42, 1486
454 <-> 689
455 <-> 1497
456 <-> 371, 1577
457 <-> 702
458 <-> 461, 921, 1279
459 <-> 1004
460 <-> 485, 505, 1211, 1451
461 <-> 458, 541, 916, 1844
462 <-> 1281
463 <-> 856, 1481
464 <-> 602, 1476, 1553
465 <-> 543, 1566
466 <-> 847, 1593
467 <-> 1270
468 <-> 328, 829
469 <-> 306, 667, 720, 1931
470 <-> 22
471 <-> 297
472 <-> 381
473 <-> 473
474 <-> 599, 1146
475 <-> 1570, 1894
476 <-> 1145
477 <-> 192, 1193, 1690
478 <-> 1469, 1840
479 <-> 1684
480 <-> 1, 108
481 <-> 103, 963
482 <-> 1778
483 <-> 6, 297, 1662
484 <-> 1435
485 <-> 460
486 <-> 438
487 <-> 207, 998, 1185
488 <-> 390, 1231, 1668
489 <-> 34, 434, 1341
490 <-> 990, 1203
491 <-> 936
492 <-> 77
493 <-> 324
494 <-> 1984
495 <-> 495, 1954
496 <-> 227
497 <-> 408, 442, 1551
498 <-> 1704, 1788
499 <-> 836
500 <-> 45, 228, 1358, 1798
501 <-> 94, 358, 1559
502 <-> 951
503 <-> 1036
504 <-> 1303
505 <-> 460
506 <-> 231, 606, 1473
507 <-> 1109
508 <-> 1724
509 <-> 1644
510 <-> 848
511 <-> 324, 1036
512 <-> 523
513 <-> 809, 1294
514 <-> 785
515 <-> 338, 348, 1027, 1193, 1226
516 <-> 1988
517 <-> 85, 1482
518 <-> 518
519 <-> 1625
520 <-> 520
521 <-> 305, 1033
522 <-> 157, 1355, 1476, 1588
523 <-> 60, 88, 512
524 <-> 8, 1998
525 <-> 990, 1275
526 <-> 1310, 1552
527 <-> 149, 979, 1805
528 <-> 698
529 <-> 631, 970
530 <-> 220, 284, 1533, 1944
531 <-> 187, 551, 1168, 1574
532 <-> 1484
533 <-> 892
534 <-> 191, 879
535 <-> 37, 276, 1527
536 <-> 24, 1094
537 <-> 747, 952
538 <-> 1620, 1735
539 <-> 858, 1467
540 <-> 1263, 1572
541 <-> 69, 158, 461
542 <-> 49, 1384
543 <-> 465, 639, 873
544 <-> 1338
545 <-> 1967
546 <-> 806, 1239
547 <-> 792, 1039, 1078
548 <-> 548, 1891, 1941
549 <-> 861
550 <-> 437, 1209, 1967
551 <-> 531, 888, 896
552 <-> 798
553 <-> 107, 429, 1330, 1951
554 <-> 217
555 <-> 744, 947, 1246
556 <-> 330, 418, 1070, 1925
557 <-> 1826, 1854
558 <-> 27, 1629
559 <-> 1042, 1150
560 <-> 156, 1472, 1834
561 <-> 260
562 <-> 63
563 <-> 129, 1309
564 <-> 332
565 <-> 1770, 1842
566 <-> 621
567 <-> 1160, 1178, 1642
568 <-> 895
569 <-> 53, 237, 384
570 <-> 641
571 <-> 571, 1261, 1924
572 <-> 882
573 <-> 376
574 <-> 982
575 <-> 78, 1255
576 <-> 887, 1539
577 <-> 603, 1122, 1679
578 <-> 742
579 <-> 272, 1444, 1747
580 <-> 797, 1554, 1718
581 <-> 412, 1926
582 <-> 383
583 <-> 1611
584 <-> 344, 1620
585 <-> 1692
586 <-> 1383
587 <-> 347, 1351
588 <-> 162, 1220
589 <-> 417, 441
590 <-> 1919
591 <-> 884, 992
592 <-> 245, 814
593 <-> 114
594 <-> 1843
595 <-> 1809
596 <-> 837
597 <-> 1563, 1575
598 <-> 12, 605, 984
599 <-> 474, 1218
600 <-> 732, 1237, 1714
601 <-> 1913
602 <-> 295, 464, 1061
603 <-> 268, 577, 720
604 <-> 604
605 <-> 38, 598
606 <-> 506, 686, 1813
607 <-> 2, 1948
608 <-> 148
609 <-> 1571
610 <-> 772, 901
611 <-> 178, 286, 880
612 <-> 1814
613 <-> 140, 883, 1198, 1764, 1942
614 <-> 1352
615 <-> 40, 321
616 <-> 58, 1413
617 <-> 624, 1008, 1591, 1791
618 <-> 1625
619 <-> 871, 1567
620 <-> 1954
621 <-> 12, 103, 566
622 <-> 1895
623 <-> 256, 1767
624 <-> 617
625 <-> 663
626 <-> 626
627 <-> 1650
628 <-> 884
629 <-> 1104, 1421
630 <-> 630, 864
631 <-> 529, 646
632 <-> 246
633 <-> 389, 1847
634 <-> 128, 384
635 <-> 1553, 1817
636 <-> 636
637 <-> 387
638 <-> 336, 342, 646, 1453
639 <-> 543, 815, 1087
640 <-> 1422, 1597
641 <-> 570, 805, 993, 1961
642 <-> 1371
643 <-> 959, 1044, 1444
644 <-> 41
645 <-> 276, 1022, 1184
646 <-> 631, 638, 1790
647 <-> 135, 1286
648 <-> 60
649 <-> 29, 224, 1636
650 <-> 324
651 <-> 863, 1321
652 <-> 149, 687, 1128, 1346
653 <-> 306
654 <-> 1409
655 <-> 1142, 1733
656 <-> 246, 331, 768, 1815
657 <-> 429
658 <-> 1511, 1569
659 <-> 1744
660 <-> 50, 796, 1524
661 <-> 63, 65, 810
662 <-> 995, 1661
663 <-> 247, 625, 1001
664 <-> 664
665 <-> 1305
666 <-> 666, 1817
667 <-> 469, 1003, 1550
668 <-> 1540, 1958
669 <-> 831, 883, 1349, 1719
670 <-> 1531
671 <-> 245, 671, 1693
672 <-> 315, 1088
673 <-> 942, 1381, 1660
674 <-> 880
675 <-> 368
676 <-> 1269, 1699
677 <-> 64, 1654
678 <-> 784
679 <-> 1760
680 <-> 39
681 <-> 681
682 <-> 728, 749, 1995
683 <-> 353
684 <-> 84, 1150
685 <-> 22
686 <-> 606
687 <-> 652, 1687
688 <-> 1878
689 <-> 454, 689
690 <-> 924, 1183
691 <-> 1410, 1413
692 <-> 1702
693 <-> 230, 1658
694 <-> 820, 1282, 1873
695 <-> 279
696 <-> 1168
697 <-> 262, 766, 776
698 <-> 65, 528, 698, 940
699 <-> 1778
700 <-> 743, 1459, 1825
701 <-> 1475
702 <-> 457, 792, 861, 1467
703 <-> 1581
704 <-> 1969
705 <-> 440, 1145
706 <-> 54, 422
707 <-> 1015, 1780
708 <-> 104, 1266
709 <-> 150, 1778
710 <-> 194
711 <-> 751
712 <-> 963
713 <-> 1525, 1762
714 <-> 1713
715 <-> 244, 1293, 1421
716 <-> 403, 1572
717 <-> 1142
718 <-> 1204
719 <-> 1672
720 <-> 469, 603
721 <-> 30, 1268, 1400
722 <-> 1183
723 <-> 1012
724 <-> 1029, 1289, 1368
725 <-> 31, 1039
726 <-> 176, 726
727 <-> 856
728 <-> 682, 1000
729 <-> 299, 1216, 1967
730 <-> 850, 900
731 <-> 1540, 1884
732 <-> 600, 784
733 <-> 1655
734 <-> 162
735 <-> 354, 1955
736 <-> 361, 1084, 1822
737 <-> 387
738 <-> 58, 1573
739 <-> 1119, 1216, 1822
740 <-> 829, 1219
741 <-> 1164
742 <-> 107, 578
743 <-> 700, 1744
744 <-> 278, 555
745 <-> 835, 1903
746 <-> 396
747 <-> 537, 1843
748 <-> 61
749 <-> 682, 1217, 1731
750 <-> 874, 1110, 1724
751 <-> 711, 1767
752 <-> 248, 1011
753 <-> 1327, 1885
754 <-> 127, 211, 1117
755 <-> 755
756 <-> 387
757 <-> 1098, 1169
758 <-> 143, 1689
759 <-> 19, 1517
760 <-> 831, 1915
761 <-> 761, 1195
762 <-> 1634
763 <-> 763
764 <-> 848, 1375
765 <-> 765, 1136
766 <-> 697, 1295, 1887
767 <-> 1906
768 <-> 281, 656, 1031
769 <-> 1457, 1863
770 <-> 75, 96
771 <-> 253, 846, 1375
772 <-> 610
773 <-> 323
774 <-> 1067
775 <-> 182, 1494
776 <-> 697
777 <-> 1136
778 <-> 296, 1057
779 <-> 315, 1631, 1796
780 <-> 363, 780, 1814
781 <-> 928, 1423
782 <-> 1850
783 <-> 441
784 <-> 678, 732, 999, 1988
785 <-> 514, 1248
786 <-> 134, 786, 1009
787 <-> 1348, 1863
788 <-> 891, 1183, 1455
789 <-> 1310, 1420, 1510
790 <-> 188, 267
791 <-> 1276
792 <-> 251, 547, 702
793 <-> 1, 72, 410, 1092
794 <-> 880
795 <-> 1799, 1807
796 <-> 660, 1548
797 <-> 252, 580, 797
798 <-> 395, 552
799 <-> 415, 799
800 <-> 285, 1889
801 <-> 801
802 <-> 802
803 <-> 1188, 1326, 1935
804 <-> 221, 441
805 <-> 43, 641, 1772
806 <-> 412, 546, 918, 1617
807 <-> 876, 1887
808 <-> 400, 1435, 1716
809 <-> 394, 513
810 <-> 661
811 <-> 216, 1259
812 <-> 1883
813 <-> 201, 1692
814 <-> 592
815 <-> 639
816 <-> 1041, 1734
817 <-> 1134, 1432
818 <-> 1575
819 <-> 113, 1063
820 <-> 694
821 <-> 1242
822 <-> 143, 892
823 <-> 1393, 1492
824 <-> 946
825 <-> 242, 999
826 <-> 1594
827 <-> 381, 1079, 1580
828 <-> 1941
829 <-> 468, 740, 1905
830 <-> 977, 1260, 1861
831 <-> 669, 760, 946, 1332
832 <-> 428, 832, 944, 1172
833 <-> 837, 1008, 1470
834 <-> 429, 915
835 <-> 306, 745, 976
836 <-> 499, 967
837 <-> 596, 833, 974
838 <-> 1335
839 <-> 320, 839, 1703
840 <-> 1053, 1398, 1760
841 <-> 1193
842 <-> 842, 1066, 1108
843 <-> 1414, 1697, 1894
844 <-> 337, 438
845 <-> 1506
846 <-> 771
847 <-> 466, 907, 1432
848 <-> 510, 764
849 <-> 1063, 1195, 1701
850 <-> 730, 1551
851 <-> 1112, 1331, 1479
852 <-> 1652
853 <-> 391
854 <-> 17, 424, 906, 1665
855 <-> 425, 1082
856 <-> 301, 463, 727, 1744
857 <-> 22, 227
858 <-> 539, 1252, 1472
859 <-> 232, 1843
860 <-> 193
861 <-> 549, 702, 1709, 1884
862 <-> 1149
863 <-> 651, 955
864 <-> 630
865 <-> 1138
866 <-> 144, 1111, 1114
867 <-> 282, 1487, 1835
868 <-> 1699
869 <-> 869
870 <-> 1487
871 <-> 619
872 <-> 872
873 <-> 370, 543, 1968
874 <-> 750, 874
875 <-> 234, 1202, 1473
876 <-> 807, 933, 1741
877 <-> 1205, 1874
878 <-> 1831
879 <-> 534, 1860
880 <-> 32, 611, 674, 794
881 <-> 1361, 1750
882 <-> 572, 1495
883 <-> 613, 669
884 <-> 591, 628, 1815
885 <-> 996, 1237
886 <-> 314, 1709
887 <-> 576
888 <-> 551
889 <-> 0, 1494
890 <-> 1100, 1966
891 <-> 788, 1312
892 <-> 303, 533, 822, 1334, 1812, 1935
893 <-> 1723
894 <-> 272, 1992
895 <-> 568, 1038
896 <-> 551, 1425
897 <-> 1783
898 <-> 375
899 <-> 358
900 <-> 730
901 <-> 106, 153, 610
902 <-> 1203
903 <-> 32, 1935
904 <-> 1109
905 <-> 364
906 <-> 293, 854, 1565
907 <-> 847, 1139, 1180, 1431, 1563, 1878
908 <-> 1908
909 <-> 321, 943
910 <-> 47, 1067
911 <-> 1468, 1495
912 <-> 15
913 <-> 1692
914 <-> 922, 1445
915 <-> 834, 1002
916 <-> 461
917 <-> 1177, 1924
918 <-> 806, 962, 1058, 1419
919 <-> 44, 82, 1933
920 <-> 1147, 1539
921 <-> 393, 458, 1055, 1951
922 <-> 914, 1271
923 <-> 204, 207, 1201
924 <-> 205, 690
925 <-> 173, 1816
926 <-> 1279
927 <-> 927
928 <-> 781
929 <-> 154
930 <-> 144
931 <-> 972, 1237
932 <-> 1317
933 <-> 876, 1756
934 <-> 51, 405, 1105, 1960
935 <-> 935, 1674
936 <-> 491, 1201, 1247
937 <-> 956, 1576, 1788
938 <-> 1377, 1733
939 <-> 121, 1638
940 <-> 698, 1808
941 <-> 1665, 1957
942 <-> 673
943 <-> 341, 909
944 <-> 832
945 <-> 1087, 1340
946 <-> 824, 831
947 <-> 555
948 <-> 959
949 <-> 1068
950 <-> 1664
951 <-> 241, 502, 1151
952 <-> 40, 537, 1376
953 <-> 397
954 <-> 148, 1075, 1364
955 <-> 863, 1235, 1618, 1724
956 <-> 937
957 <-> 101, 1323
958 <-> 1794, 1972
959 <-> 643, 948, 1023
960 <-> 960, 1417
961 <-> 1278
962 <-> 370, 918
963 <-> 481, 712
964 <-> 1198
965 <-> 4
966 <-> 966
967 <-> 836, 967, 1821
968 <-> 1513
969 <-> 128, 232
970 <-> 529
971 <-> 1471
972 <-> 436, 931
973 <-> 231
974 <-> 837
975 <-> 1390
976 <-> 835
977 <-> 830
978 <-> 439, 1687
979 <-> 527
980 <-> 980, 1609, 1940
981 <-> 307, 1671
982 <-> 574, 1318, 1643
983 <-> 243
984 <-> 598
985 <-> 279
986 <-> 68
987 <-> 1060
988 <-> 1942
989 <-> 1478
990 <-> 490, 525, 1838
991 <-> 41, 1263, 1302
992 <-> 591
993 <-> 273, 641
994 <-> 1026, 1240, 1618
995 <-> 662, 1545
996 <-> 885, 1528
997 <-> 449, 1058
998 <-> 487
999 <-> 784, 825
1000 <-> 728
1001 <-> 141, 663, 1626, 1681
1002 <-> 300, 915
1003 <-> 667
1004 <-> 227, 459
1005 <-> 1780
1006 <-> 234, 1578
1007 <-> 203, 406
1008 <-> 617, 833
1009 <-> 786, 1064
1010 <-> 1010, 1031, 1919
1011 <-> 752, 1754
1012 <-> 7, 723, 1068, 1181
1013 <-> 36
1014 <-> 1594
1015 <-> 707
1016 <-> 63
1017 <-> 1511
1018 <-> 374, 1034
1019 <-> 131, 1155
1020 <-> 114
1021 <-> 1288
1022 <-> 645
1023 <-> 959, 1375
1024 <-> 1024
1025 <-> 216
1026 <-> 411, 994
1027 <-> 515
1028 <-> 1417
1029 <-> 304, 724
1030 <-> 343, 351
1031 <-> 768, 1010
1032 <-> 1032
1033 <-> 521
1034 <-> 1018
1035 <-> 235, 1578
1036 <-> 179, 503, 511, 1036
1037 <-> 1037, 1044
1038 <-> 895, 1125
1039 <-> 547, 725, 1599
1040 <-> 395
1041 <-> 816
1042 <-> 559, 1042
1043 <-> 168, 1873
1044 <-> 643, 1037, 1312
1045 <-> 1232
1046 <-> 321
1047 <-> 254
1048 <-> 1747
1049 <-> 364
1050 <-> 1050, 1947, 1963
1051 <-> 1156
1052 <-> 4, 1201
1053 <-> 840
1054 <-> 1133, 1342, 1537, 1708, 1778
1055 <-> 71, 921, 1786
1056 <-> 1672
1057 <-> 778, 1423, 1787
1058 <-> 918, 997
1059 <-> 288, 1337, 1401
1060 <-> 987, 1781
1061 <-> 602, 1660
1062 <-> 316, 1863
1063 <-> 120, 819, 849
1064 <-> 1009
1065 <-> 1065
1066 <-> 842
1067 <-> 774, 910, 1089
1068 <-> 949, 1012
1069 <-> 1900
1070 <-> 556
1071 <-> 1884
1072 <-> 447, 1122
1073 <-> 163, 249, 1073, 1237
1074 <-> 262
1075 <-> 954, 1075, 1789
1076 <-> 1076, 1680
1077 <-> 55, 322
1078 <-> 160, 547
1079 <-> 827, 1079
1080 <-> 377, 425, 1739
1081 <-> 220, 230
1082 <-> 855, 1638
1083 <-> 44
1084 <-> 302, 736
1085 <-> 168, 1431
1086 <-> 1973
1087 <-> 639, 945
1088 <-> 672
1089 <-> 1067, 1190
1090 <-> 408, 1492
1091 <-> 1674
1092 <-> 793
1093 <-> 1802
1094 <-> 536
1095 <-> 1095, 1204
1096 <-> 279
1097 <-> 351, 381
1098 <-> 757, 1519
1099 <-> 1099, 1752
1100 <-> 177, 890
1101 <-> 1145
1102 <-> 1280
1103 <-> 190, 1200
1104 <-> 629
1105 <-> 100, 934
1106 <-> 1426
1107 <-> 78, 1497
1108 <-> 842
1109 <-> 507, 904, 1109
1110 <-> 750
1111 <-> 866
1112 <-> 851
1113 <-> 1113
1114 <-> 866, 1131, 1861
1115 <-> 1187, 1629
1116 <-> 342
1117 <-> 754
1118 <-> 1637
1119 <-> 739
1120 <-> 1837
1121 <-> 1133, 1758
1122 <-> 577, 1072, 1349
1123 <-> 1359
1124 <-> 1174
1125 <-> 1038, 1789
1126 <-> 1260
1127 <-> 1213
1128 <-> 161, 652
1129 <-> 441
1130 <-> 4
1131 <-> 1114
1132 <-> 1132, 1979
1133 <-> 1054, 1121, 1253
1134 <-> 817
1135 <-> 76, 1606
1136 <-> 765, 777, 1860
1137 <-> 434
1138 <-> 865, 1280, 1471, 1736
1139 <-> 74, 907
1140 <-> 108, 378
1141 <-> 178
1142 <-> 655, 717
1143 <-> 446
1144 <-> 221
1145 <-> 476, 705, 1101, 1271, 1956
1146 <-> 474, 1179, 1936
1147 <-> 920, 1147
1148 <-> 1148, 1795
1149 <-> 862, 1799
1150 <-> 559, 684, 1797
1151 <-> 951
1152 <-> 1229
1153 <-> 1515, 1530
1154 <-> 1154
1155 <-> 1019, 1300
1156 <-> 164, 1051, 1156
1157 <-> 18, 1157
1158 <-> 1208
1159 <-> 1651
1160 <-> 567, 1510, 1710
1161 <-> 1161, 1427, 1590
1162 <-> 206, 229, 1561
1163 <-> 1388
1164 <-> 741, 1494
1165 <-> 1217
1166 <-> 123, 276
1167 <-> 1262, 1547
1168 <-> 80, 531, 696
1169 <-> 362, 757, 1504
1170 <-> 1854
1171 <-> 1171, 1898
1172 <-> 832
1173 <-> 1173, 1315
1174 <-> 1124, 1174, 1831
1175 <-> 202, 452
1176 <-> 330, 335, 1761
1177 <-> 917
1178 <-> 155, 567
1179 <-> 224, 1146
1180 <-> 907, 1661
1181 <-> 1012
1182 <-> 176
1183 <-> 690, 722, 788
1184 <-> 645
1185 <-> 487
1186 <-> 1659
1187 <-> 348, 1115, 1670
1188 <-> 275, 803
1189 <-> 1689
1190 <-> 75, 1089
1191 <-> 285
1192 <-> 1744
1193 <-> 477, 515, 841
1194 <-> 1308
1195 <-> 761, 849
1196 <-> 130, 1993
1197 <-> 144
1198 <-> 613, 964, 1329
1199 <-> 1389
1200 <-> 1103
1201 <-> 923, 936, 1052
1202 <-> 875
1203 <-> 490, 902, 1692
1204 <-> 718, 1095, 1245
1205 <-> 263, 333, 877
1206 <-> 1311
1207 <-> 415, 1883
1208 <-> 445, 1158
1209 <-> 550, 1640
1210 <-> 12, 1210, 1428
1211 <-> 460, 1529
1212 <-> 52, 159, 1493, 1819
1213 <-> 1127, 1213
1214 <-> 1214, 1436
1215 <-> 266, 1758
1216 <-> 729, 739
1217 <-> 141, 749, 1165, 1315
1218 <-> 599, 1595
1219 <-> 740, 1549
1220 <-> 588, 1374
1221 <-> 405
1222 <-> 1966
1223 <-> 119
1224 <-> 1528
1225 <-> 1314
1226 <-> 86, 515
1227 <-> 1681
1228 <-> 1228
1229 <-> 0, 1152, 1374
1230 <-> 1453
1231 <-> 223, 488
1232 <-> 1045, 1261
1233 <-> 1759
1234 <-> 360
1235 <-> 283, 955, 1241, 1783
1236 <-> 1356
1237 <-> 600, 885, 931, 1073
1238 <-> 370, 1602
1239 <-> 546, 1373
1240 <-> 994
1241 <-> 1235, 1392
1242 <-> 7, 59, 821, 1945
1243 <-> 1296
1244 <-> 7, 1300, 1434
1245 <-> 1204, 1347
1246 <-> 374, 555, 1508
1247 <-> 109, 936
1248 <-> 785, 1715
1249 <-> 238
1250 <-> 1600, 1623
1251 <-> 1251
1252 <-> 858
1253 <-> 392, 1133
1254 <-> 35, 1394
1255 <-> 575
1256 <-> 214, 1607, 1685
1257 <-> 169
1258 <-> 81, 1264, 1320
1259 <-> 811, 1425
1260 <-> 830, 1126
1261 <-> 571, 1232
1262 <-> 1167, 1862
1263 <-> 540, 991
1264 <-> 1258, 1651
1265 <-> 139, 1569
1266 <-> 708
1267 <-> 1267
1268 <-> 721
1269 <-> 276, 676, 1759
1270 <-> 467, 1270, 1916
1271 <-> 225, 922, 1145, 1700
1272 <-> 99
1273 <-> 1302
1274 <-> 1966
1275 <-> 525
1276 <-> 791, 1834
1277 <-> 450, 1474, 1645
1278 <-> 185, 961
1279 <-> 458, 926
1280 <-> 209, 1102, 1138
1281 <-> 208, 462, 1943
1282 <-> 694, 1522
1283 <-> 111, 119, 1407
1284 <-> 182, 1996
1285 <-> 287
1286 <-> 647, 1286, 1715
1287 <-> 132
1288 <-> 222, 1021, 1398
1289 <-> 724
1290 <-> 208, 260, 317
1291 <-> 1498
1292 <-> 88
1293 <-> 387, 715, 1322, 1519, 1645
1294 <-> 445, 513, 1504
1295 <-> 766
1296 <-> 1243, 1379, 1964
1297 <-> 38, 1669
1298 <-> 1906
1299 <-> 18, 1804
1300 <-> 1155, 1244
1301 <-> 1371, 1453
1302 <-> 991, 1273
1303 <-> 375, 504, 1948
1304 <-> 1667, 1933
1305 <-> 102, 151, 665
1306 <-> 266
1307 <-> 179
1308 <-> 34, 1194
1309 <-> 563
1310 <-> 526, 789
1311 <-> 1206, 1311, 1769
1312 <-> 891, 1044
1313 <-> 169
1314 <-> 151, 1225
1315 <-> 42, 1173, 1217
1316 <-> 1316
1317 <-> 932, 1805
1318 <-> 187, 373, 982
1319 <-> 41, 220, 1948
1320 <-> 1258, 1859
1321 <-> 651
1322 <-> 1293
1323 <-> 957, 1472
1324 <-> 1324
1325 <-> 1325
1326 <-> 803, 1846
1327 <-> 753
1328 <-> 1879
1329 <-> 1198
1330 <-> 553, 1330
1331 <-> 392, 851
1332 <-> 396, 831
1333 <-> 210
1334 <-> 892
1335 <-> 838, 1552, 1568
1336 <-> 1336
1337 <-> 1059
1338 <-> 310, 544
1339 <-> 1897
1340 <-> 945
1341 <-> 489
1342 <-> 137, 1054
1343 <-> 1343
1344 <-> 1946
1345 <-> 1345
1346 <-> 652
1347 <-> 1245, 1914, 1930
1348 <-> 787, 1591
1349 <-> 669, 1122
1350 <-> 304, 1790
1351 <-> 587, 1997
1352 <-> 20, 614
1353 <-> 1738
1354 <-> 413, 1608
1355 <-> 522, 1816, 1917
1356 <-> 1236, 1450
1357 <-> 431, 1575
1358 <-> 500
1359 <-> 1123, 1599
1360 <-> 1370, 1385
1361 <-> 1, 881
1362 <-> 355, 1611, 1952
1363 <-> 69
1364 <-> 954
1365 <-> 1948
1366 <-> 30, 1470
1367 <-> 1527
1368 <-> 724
1369 <-> 277, 1482
1370 <-> 1360
1371 <-> 642, 1301, 1478, 1485
1372 <-> 1372, 1594
1373 <-> 1239
1374 <-> 79, 1220, 1229
1375 <-> 764, 771, 1023
1376 <-> 952
1377 <-> 938, 1520, 1730
1378 <-> 1378, 1411, 1823
1379 <-> 1296, 1832
1380 <-> 1380
1381 <-> 673
1382 <-> 1382
1383 <-> 195, 586
1384 <-> 542
1385 <-> 215, 1360
1386 <-> 1386
1387 <-> 1536
1388 <-> 311, 402, 1163
1389 <-> 251, 1199
1390 <-> 322, 975
1391 <-> 172, 407, 1453
1392 <-> 1241, 1587
1393 <-> 419, 823, 1636
1394 <-> 1254, 1588, 1699
1395 <-> 401, 1621
1396 <-> 1396, 1870
1397 <-> 1629
1398 <-> 840, 1288
1399 <-> 1399, 1932
1400 <-> 721
1401 <-> 1059
1402 <-> 1402
1403 <-> 33
1404 <-> 1449, 1632, 1832
1405 <-> 1634
1406 <-> 1726
1407 <-> 265, 1283, 1999
1408 <-> 39, 336, 426
1409 <-> 75, 147, 654
1410 <-> 691, 1780
1411 <-> 1378
1412 <-> 1447, 1759
1413 <-> 616, 691
1414 <-> 843
1415 <-> 1415
1416 <-> 197, 271
1417 <-> 132, 960, 1028
1418 <-> 1418, 1426
1419 <-> 918, 1560
1420 <-> 789
1421 <-> 629, 715
1422 <-> 391, 640
1423 <-> 781, 1057
1424 <-> 1614
1425 <-> 21, 896, 1259
1426 <-> 1106, 1418
1427 <-> 1161
1428 <-> 1210, 1677
1429 <-> 131
1430 <-> 1822
1431 <-> 907, 1085, 1846
1432 <-> 817, 847
1433 <-> 75
1434 <-> 1244
1435 <-> 484, 808
1436 <-> 1214
1437 <-> 418
1438 <-> 57
1439 <-> 1469, 1824
1440 <-> 237
1441 <-> 1722
1442 <-> 424, 1678
1443 <-> 144
1444 <-> 579, 643, 1869
1445 <-> 914
1446 <-> 1524, 1728
1447 <-> 1412, 1962
1448 <-> 1485
1449 <-> 1404
1450 <-> 1356, 1647
1451 <-> 460, 1907, 1967
1452 <-> 445, 446
1453 <-> 56, 133, 638, 1230, 1301, 1391
1454 <-> 1994
1455 <-> 788
1456 <-> 1914
1457 <-> 769
1458 <-> 1458
1459 <-> 700, 1796
1460 <-> 1799
1461 <-> 15, 436
1462 <-> 1678
1463 <-> 83, 1553, 1684
1464 <-> 35
1465 <-> 1471
1466 <-> 175, 430
1467 <-> 539, 702
1468 <-> 281, 911, 1475
1469 <-> 366, 426, 478, 1439, 1524
1470 <-> 833, 1366
1471 <-> 971, 1138, 1465
1472 <-> 560, 858, 1323, 1937
1473 <-> 506, 875
1474 <-> 1277, 1937
1475 <-> 701, 1468
1476 <-> 464, 522
1477 <-> 1785
1478 <-> 989, 1371
1479 <-> 409, 851
1480 <-> 1677
1481 <-> 463
1482 <-> 517, 1369, 1482
1483 <-> 102, 218
1484 <-> 532, 1531, 1735
1485 <-> 400, 1371, 1448
1486 <-> 453
1487 <-> 867, 870, 1577, 1584
1488 <-> 1488
1489 <-> 16, 327
1490 <-> 418
1491 <-> 7, 1589
1492 <-> 823, 1090
1493 <-> 1212, 1519, 1675
1494 <-> 775, 889, 1164
1495 <-> 882, 911
1496 <-> 386, 1496
1497 <-> 269, 455, 1107
1498 <-> 9, 1291, 1758
1499 <-> 1685, 1893
1500 <-> 1657
1501 <-> 244, 287
1502 <-> 1951
1503 <-> 112
1504 <-> 1169, 1294
1505 <-> 1987
1506 <-> 845, 1905
1507 <-> 1507
1508 <-> 1246
1509 <-> 41
1510 <-> 195, 789, 1160, 1980
1511 <-> 658, 1017
1512 <-> 1990
1513 <-> 968, 1513, 1612
1514 <-> 1514
1515 <-> 1153, 1632
1516 <-> 280
1517 <-> 759
1518 <-> 1837
1519 <-> 80, 82, 1098, 1293, 1493
1520 <-> 1377, 1978
1521 <-> 1521
1522 <-> 1282
1523 <-> 1749, 1876
1524 <-> 660, 1446, 1469, 1535, 1729
1525 <-> 283, 713
1526 <-> 22, 1767
1527 <-> 535, 1367, 1889
1528 <-> 996, 1224
1529 <-> 1211, 1736
1530 <-> 1153
1531 <-> 451, 670, 1484
1532 <-> 46
1533 <-> 62, 143, 530
1534 <-> 117, 1992
1535 <-> 1524
1536 <-> 342, 1387
1537 <-> 1054
1538 <-> 302, 1589
1539 <-> 576, 920
1540 <-> 668, 731
1541 <-> 1639
1542 <-> 1542
1543 <-> 1702
1544 <-> 1927
1545 <-> 995
1546 <-> 92, 1890
1547 <-> 40, 1167
1548 <-> 796
1549 <-> 110, 337, 1219
1550 <-> 46, 667
1551 <-> 497, 850
1552 <-> 526, 1335
1553 <-> 464, 635, 1463
1554 <-> 580, 1696
1555 <-> 1556, 1648, 1867
1556 <-> 180, 1555, 1676
1557 <-> 313, 1831
1558 <-> 249
1559 <-> 501
1560 <-> 1419
1561 <-> 1162
1562 <-> 271, 388
1563 <-> 597, 907
1564 <-> 239
1565 <-> 906, 1854
1566 <-> 465
1567 <-> 393, 619
1568 <-> 1335, 1745
1569 <-> 658, 1265, 1651
1570 <-> 475
1571 <-> 310, 323, 609
1572 <-> 540, 716
1573 <-> 738
1574 <-> 531
1575 <-> 597, 818, 1357
1576 <-> 937
1577 <-> 456, 1487, 1630
1578 <-> 1006, 1035
1579 <-> 1704
1580 <-> 827
1581 <-> 286, 703, 1888
1582 <-> 294
1583 <-> 1907
1584 <-> 1487
1585 <-> 1955
1586 <-> 1586, 1641
1587 <-> 1392
1588 <-> 522, 1394
1589 <-> 1491, 1538, 1589
1590 <-> 1161, 1642, 1946
1591 <-> 4, 617, 1348
1592 <-> 68
1593 <-> 356, 466
1594 <-> 826, 1014, 1372
1595 <-> 1218
1596 <-> 78
1597 <-> 640
1598 <-> 422
1599 <-> 1039, 1359
1600 <-> 1250
1601 <-> 113, 1631
1602 <-> 1238
1603 <-> 1603
1604 <-> 1604
1605 <-> 1980
1606 <-> 1135, 1828
1607 <-> 1256, 1607
1608 <-> 1354
1609 <-> 980, 1864
1610 <-> 1610
1611 <-> 583, 1362
1612 <-> 309, 367, 1513
1613 <-> 270, 1620
1614 <-> 1424, 1688
1615 <-> 1615
1616 <-> 1884
1617 <-> 806, 1763
1618 <-> 955, 994, 1897
1619 <-> 1622
1620 <-> 538, 584, 1613
1621 <-> 1395, 1621
1622 <-> 452, 1619
1623 <-> 188, 1250
1624 <-> 148
1625 <-> 519, 618, 1625, 1765
1626 <-> 213, 1001
1627 <-> 1929
1628 <-> 6, 305
1629 <-> 558, 1115, 1397
1630 <-> 1577
1631 <-> 779, 1601
1632 <-> 1404, 1515
1633 <-> 336
1634 <-> 762, 1405, 1734
1635 <-> 1635
1636 <-> 257, 649, 1393
1637 <-> 167, 329, 1118
1638 <-> 939, 1082
1639 <-> 1541, 1639
1640 <-> 1209
1641 <-> 1586
1642 <-> 567, 1590
1643 <-> 982
1644 <-> 408, 509
1645 <-> 1277, 1293
1646 <-> 1836, 1875
1647 <-> 1450, 1772
1648 <-> 1555, 1946
1649 <-> 1743
1650 <-> 627, 1720
1651 <-> 1159, 1264, 1569
1652 <-> 852, 1930
1653 <-> 1653
1654 <-> 677
1655 <-> 85, 733
1656 <-> 1875
1657 <-> 261, 1500, 1703
1658 <-> 693, 1679
1659 <-> 1186, 1659
1660 <-> 673, 1061
1661 <-> 662, 1180
1662 <-> 483
1663 <-> 1663, 1904
1664 <-> 196, 950, 1664
1665 <-> 144, 854, 941
1666 <-> 1666
1667 <-> 1304, 1890
1668 <-> 488
1669 <-> 1297
1670 <-> 78, 1187
1671 <-> 215, 981
1672 <-> 145, 358, 719, 1056
1673 <-> 1673
1674 <-> 25, 935, 1091
1675 <-> 1493
1676 <-> 190, 1556
1677 <-> 1428, 1480
1678 <-> 1442, 1462, 1987
1679 <-> 577, 1658
1680 <-> 16, 1076
1681 <-> 1001, 1227
1682 <-> 71
1683 <-> 90
1684 <-> 479, 1463, 1852
1685 <-> 1256, 1499
1686 <-> 94
1687 <-> 687, 978, 1787
1688 <-> 332, 1614, 1688
1689 <-> 758, 1189, 1779
1690 <-> 477
1691 <-> 1691, 1986
1692 <-> 166, 585, 813, 913, 1203, 1913
1693 <-> 671
1694 <-> 1711
1695 <-> 89, 1795
1696 <-> 1554
1697 <-> 147, 843, 1900
1698 <-> 212, 444, 1793
1699 <-> 676, 868, 1394, 1705
1700 <-> 87, 1271
1701 <-> 849
1702 <-> 222, 692, 1543
1703 <-> 839, 1657
1704 <-> 314, 498, 1579
1705 <-> 1699
1706 <-> 89, 1993
1707 <-> 1990, 1994
1708 <-> 1054, 1892
1709 <-> 861, 886
1710 <-> 1160
1711 <-> 1694, 1737
1712 <-> 1712
1713 <-> 714, 1935
1714 <-> 600
1715 <-> 217, 1248, 1286
1716 <-> 808
1717 <-> 278, 1914
1718 <-> 580
1719 <-> 669
1720 <-> 1650, 1762, 1856
1721 <-> 422, 1918
1722 <-> 1441, 1722
1723 <-> 893, 1915
1724 <-> 508, 750, 955
1725 <-> 1725
1726 <-> 1406, 1959
1727 <-> 1797
1728 <-> 14, 1446
1729 <-> 1524
1730 <-> 1377, 1737
1731 <-> 104, 749
1732 <-> 129, 1908
1733 <-> 174, 655, 938
1734 <-> 816, 1634, 1734
1735 <-> 538, 1484
1736 <-> 0, 1138, 1529
1737 <-> 1711, 1730
1738 <-> 26, 1353, 1757
1739 <-> 302, 1080
1740 <-> 118, 257
1741 <-> 152, 219, 876
1742 <-> 1841, 1945
1743 <-> 333, 1649
1744 <-> 659, 743, 856, 1192
1745 <-> 1568
1746 <-> 1746
1747 <-> 579, 1048
1748 <-> 283
1749 <-> 189, 350, 1523, 1848, 1894
1750 <-> 881
1751 <-> 344
1752 <-> 1099
1753 <-> 1753
1754 <-> 1011
1755 <-> 1755, 1939
1756 <-> 933
1757 <-> 1738
1758 <-> 1121, 1215, 1498
1759 <-> 1233, 1269, 1412
1760 <-> 198, 679, 840
1761 <-> 1176
1762 <-> 713, 1720
1763 <-> 1617
1764 <-> 613
1765 <-> 1625
1766 <-> 99
1767 <-> 623, 751, 1526
1768 <-> 82
1769 <-> 1311, 1921
1770 <-> 565, 1995
1771 <-> 77, 1771
1772 <-> 805, 1647, 1772
1773 <-> 1773, 1826
1774 <-> 303
1775 <-> 239, 259
1776 <-> 225
1777 <-> 393
1778 <-> 482, 699, 709, 1054
1779 <-> 264, 1689
1780 <-> 61, 194, 707, 1005, 1410, 1999
1781 <-> 165, 1060, 1978
1782 <-> 264
1783 <-> 897, 1235, 1845
1784 <-> 1784
1785 <-> 1477, 1915
1786 <-> 1055
1787 <-> 1057, 1687, 1899
1788 <-> 498, 937, 1859
1789 <-> 1075, 1125
1790 <-> 646, 1350
1791 <-> 617
1792 <-> 1855
1793 <-> 1698
1794 <-> 958
1795 <-> 1148, 1695
1796 <-> 779, 1459, 1857
1797 <-> 1150, 1727
1798 <-> 500
1799 <-> 795, 1149, 1460
1800 <-> 368, 1800
1801 <-> 220
1802 <-> 99, 1093
1803 <-> 1810
1804 <-> 1299
1805 <-> 292, 527, 1317
1806 <-> 443, 1865
1807 <-> 795, 1911
1808 <-> 940
1809 <-> 122, 595
1810 <-> 345, 1803
1811 <-> 1980
1812 <-> 892
1813 <-> 421, 606
1814 <-> 612, 780
1815 <-> 656, 884
1816 <-> 925, 1355
1817 <-> 635, 666
1818 <-> 29, 206
1819 <-> 1212
1820 <-> 1874
1821 <-> 227, 967
1822 <-> 736, 739, 1430
1823 <-> 1378
1824 <-> 68, 1439
1825 <-> 700
1826 <-> 557, 1773
1827 <-> 98, 1971
1828 <-> 1606, 1865
1829 <-> 449
1830 <-> 1830
1831 <-> 20, 878, 1174, 1557
1832 <-> 1379, 1404, 1832
1833 <-> 107
1834 <-> 423, 560, 1276
1835 <-> 867
1836 <-> 118, 1646
1837 <-> 47, 1120, 1518
1838 <-> 243, 990
1839 <-> 1839
1840 <-> 478
1841 <-> 1742
1842 <-> 565
1843 <-> 594, 747, 859
1844 <-> 461
1845 <-> 1783
1846 <-> 1326, 1431
1847 <-> 633, 1888
1848 <-> 1749
1849 <-> 24, 48, 292, 1851
1850 <-> 440, 782
1851 <-> 1849
1852 <-> 1684
1853 <-> 1853
1854 <-> 557, 1170, 1565
1855 <-> 70, 1792
1856 <-> 1720
1857 <-> 1796
1858 <-> 417
1859 <-> 1320, 1788
1860 <-> 36, 879, 1136
1861 <-> 830, 1114
1862 <-> 416, 1262
1863 <-> 28, 769, 787, 1062
1864 <-> 1609, 1920, 1953
1865 <-> 189, 1806, 1828, 1969
1866 <-> 451
1867 <-> 1555
1868 <-> 1868
1869 <-> 1444
1870 <-> 1396
1871 <-> 1939
1872 <-> 1914
1873 <-> 694, 1043
1874 <-> 241, 877, 1820
1875 <-> 1646, 1656
1876 <-> 1523
1877 <-> 1877
1878 <-> 159, 688, 907
1879 <-> 1328, 1879
1880 <-> 415
1881 <-> 65
1882 <-> 201
1883 <-> 812, 1207
1884 <-> 731, 861, 1071, 1616
1885 <-> 753, 1885
1886 <-> 75
1887 <-> 766, 807
1888 <-> 240, 1581, 1847
1889 <-> 800, 1527
1890 <-> 1546, 1667
1891 <-> 186, 548
1892 <-> 1708
1893 <-> 1499
1894 <-> 475, 843, 1749
1895 <-> 622, 1895, 1978
1896 <-> 334
1897 <-> 1339, 1618, 1949
1898 <-> 1171
1899 <-> 1787
1900 <-> 1069, 1697
1901 <-> 142
1902 <-> 291, 305
1903 <-> 745
1904 <-> 1663
1905 <-> 829, 1506
1906 <-> 316, 767, 1298, 1999
1907 <-> 183, 1451, 1583
1908 <-> 908, 1732
1909 <-> 62
1910 <-> 1999
1911 <-> 364, 1807
1912 <-> 372, 1912
1913 <-> 161, 601, 1692
1914 <-> 1347, 1456, 1717, 1872
1915 <-> 760, 1723, 1785
1916 <-> 1270
1917 <-> 1355
1918 <-> 1721
1919 <-> 590, 1010
1920 <-> 414, 1864
1921 <-> 1769
1922 <-> 232
1923 <-> 238, 271, 1923
1924 <-> 571, 917
1925 <-> 556, 1925
1926 <-> 129, 581
1927 <-> 360, 1544
1928 <-> 289
1929 <-> 1627, 1929
1930 <-> 181, 1347, 1652
1931 <-> 469, 1931
1932 <-> 1399
1933 <-> 919, 1304
1934 <-> 290
1935 <-> 803, 892, 903, 1713
1936 <-> 1146
1937 <-> 146, 1472, 1474
1938 <-> 149
1939 <-> 88, 1755, 1871
1940 <-> 980
1941 <-> 548, 828
1942 <-> 613, 988
1943 <-> 1281
1944 <-> 239, 326, 530
1945 <-> 49, 1242, 1742
1946 <-> 1344, 1590, 1648
1947 <-> 1050
1948 <-> 607, 1303, 1319, 1365
1949 <-> 1897
1950 <-> 1950
1951 <-> 553, 921, 1502
1952 <-> 163, 1362
1953 <-> 1864
1954 <-> 495, 620
1955 <-> 735, 1585
1956 <-> 11, 1145
1957 <-> 941
1958 <-> 398, 668
1959 <-> 340, 1726
1960 <-> 934
1961 <-> 641
1962 <-> 1447
1963 <-> 112, 1050
1964 <-> 1296
1965 <-> 61
1966 <-> 890, 1222, 1274
1967 <-> 545, 550, 729, 1451
1968 <-> 873
1969 <-> 704, 1865
1970 <-> 393
1971 <-> 1827
1972 <-> 326, 958
1973 <-> 1086, 1973
1974 <-> 319, 1974
1975 <-> 452
1976 <-> 155
1977 <-> 410
1978 <-> 1520, 1781, 1895
1979 <-> 1132
1980 <-> 1510, 1605, 1811
1981 <-> 184
1982 <-> 39
1983 <-> 1983
1984 <-> 379, 494
1985 <-> 95
1986 <-> 1691
1987 <-> 1505, 1678
1988 <-> 124, 516, 784
1989 <-> 322
1990 <-> 1512, 1707
1991 <-> 226
1992 <-> 894, 1534
1993 <-> 1196, 1706
1994 <-> 16, 1454, 1707
1995 <-> 682, 1770
1996 <-> 1284
1997 <-> 153, 308, 1351
1998 <-> 5, 235, 428, 524
1999 <-> 1407, 1780, 1906, 1910"""
zip: List a -> List b -> List (a, b)
zip list1 list2 =
zip2 list1 list2 []
zip2: List a -> List b -> List(a, b) -> List(a, b)
zip2 list1 list2 acc =
case list1 of
[] -> acc
head1::tail1 ->
case list2 of
[] -> acc
head2::tail2 ->
zip2 tail1 tail2 (List.append acc [(head1, head2)])
toIntOrZero: String -> Int
toIntOrZero char =
case (String.toInt char) of
Ok a ->
a
Err _ ->
0
outerProduct: List a -> List (a, a)
outerProduct list =
List.concatMap (\e ->
List.map (\i -> (e, i)) list
) list
histogram: List comparable -> Dict comparable Int
histogram list =
List.foldl histo_inc Dict.empty list
histo_inc: comparable -> Dict comparable Int -> Dict comparable Int
histo_inc dir dict =
if Dict.member dir dict then
Dict.update dir (Maybe.map ((+) 1)) dict
else
Dict.insert dir 1 dict
| true | -- Copyright (c) 2017 PI:NAME:<NAME>END_PI
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- * Neither the name of the copyright holder nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Html exposing (..)
import Dict exposing (..)
import Array exposing (..)
import Debug exposing (..)
main = text <| toString <| solve input
--solve: String -> Int
solve input =
let
initialDict = parse input
initialSize = Dict.size initialDict
dictAfterRemoval = removeGroup 0 initialDict
in
initialSize - (Dict.size dictAfterRemoval)
removeGroup id dict =
if Dict.member id dict then
let
deps = Dict.get id dict |> Maybe.withDefault []
newDict = Dict.remove id dict
in
deps
|> List.foldl removeGroup newDict
else
dict
parse: String -> Dict Int (List Int)
parse string =
String.split "\n" input
|> List.map parseLine
|> Dict.fromList
parseLine line =
case (String.split " <-> " line) of
id::deps::[] ->
let
iid = toIntOrZero id
ideps =
String.split ", " deps
|> List.map toIntOrZero
in
(iid, ideps)
_ -> (-1, [])
input2 = """0 <-> 2
1 <-> 1
2 <-> 0, 3, 4
3 <-> 2, 4
4 <-> 2, 3, 6
5 <-> 6
6 <-> 4, 5"""
input = """0 <-> 889, 1229, 1736
1 <-> 1, 480, 793, 1361
2 <-> 607
3 <-> 273, 422
4 <-> 965, 1052, 1130, 1591
5 <-> 1998
6 <-> 483, 1628
7 <-> 1012, 1242, 1244, 1491
8 <-> 524
9 <-> 13, 281, 1498
10 <-> 10
11 <-> 1956
12 <-> 598, 621, 1210
13 <-> 9
14 <-> 1728
15 <-> 912, 1461
16 <-> 1489, 1680, 1994
17 <-> 854
18 <-> 1157, 1299
19 <-> 759
20 <-> 1352, 1831
21 <-> 1425
22 <-> 470, 685, 857, 1526
23 <-> 405
24 <-> 43, 536, 1849
25 <-> 1674
26 <-> 26, 1738
27 <-> 558
28 <-> 1863
29 <-> 154, 649, 1818
30 <-> 721, 1366
31 <-> 725
32 <-> 413, 880, 903
33 <-> 414, 442, 1403
34 <-> 489, 1308
35 <-> 385, 1254, 1464
36 <-> 167, 1013, 1860
37 <-> 535
38 <-> 605, 1297
39 <-> 680, 1408, 1982
40 <-> 169, 615, 952, 1547
41 <-> 644, 991, 1319, 1509
42 <-> 453, 1315
43 <-> 24, 200, 805
44 <-> 919, 1083
45 <-> 500
46 <-> 1532, 1550
47 <-> 910, 1837
48 <-> 1849
49 <-> 542, 1945
50 <-> 57, 660
51 <-> 354, 934
52 <-> 1212
53 <-> 569
54 <-> 706
55 <-> 55, 114, 1077
56 <-> 1453
57 <-> 50, 1438
58 <-> 616, 738
59 <-> 1242
60 <-> 312, 523, 648
61 <-> 748, 1780, 1965
62 <-> 1533, 1909
63 <-> 562, 661, 1016
64 <-> 280, 300, 677
65 <-> 661, 698, 1881
66 <-> 283, 440
67 <-> 382, 421
68 <-> 986, 1592, 1824
69 <-> 541, 1363
70 <-> 266, 1855
71 <-> 371, 433, 1055, 1682
72 <-> 793
73 <-> 73
74 <-> 1139
75 <-> 770, 1190, 1409, 1433, 1886
76 <-> 1135
77 <-> 492, 1771
78 <-> 575, 1107, 1596, 1670
79 <-> 1374
80 <-> 1168, 1519
81 <-> 1258
82 <-> 919, 1519, 1768
83 <-> 1463
84 <-> 684
85 <-> 517, 1655
86 <-> 1226
87 <-> 1700
88 <-> 523, 1292, 1939
89 <-> 177, 1695, 1706
90 <-> 400, 1683
91 <-> 194
92 <-> 106, 1546
93 <-> 104
94 <-> 501, 1686
95 <-> 285, 1985
96 <-> 402, 770
97 <-> 196
98 <-> 318, 1827
99 <-> 220, 1272, 1766, 1802
100 <-> 1105
101 <-> 380, 957
102 <-> 1305, 1483
103 <-> 262, 481, 621
104 <-> 93, 708, 1731
105 <-> 282
106 <-> 92, 901
107 <-> 553, 742, 1833
108 <-> 480, 1140
109 <-> 1247
110 <-> 1549
111 <-> 1283
112 <-> 1503, 1963
113 <-> 819, 1601
114 <-> 55, 593, 1020
115 <-> 324
116 <-> 378
117 <-> 1534
118 <-> 1740, 1836
119 <-> 1223, 1283
120 <-> 435, 1063
121 <-> 404, 939
122 <-> 294, 360, 1809
123 <-> 1166
124 <-> 1988
125 <-> 163
126 <-> 126
127 <-> 255, 754
128 <-> 634, 969
129 <-> 563, 1732, 1926
130 <-> 1196
131 <-> 1019, 1429
132 <-> 1287, 1417
133 <-> 1453
134 <-> 184, 786
135 <-> 647
136 <-> 260, 306
137 <-> 1342
138 <-> 292
139 <-> 1265
140 <-> 613
141 <-> 1001, 1217
142 <-> 142, 1901
143 <-> 758, 822, 1533
144 <-> 866, 930, 1197, 1443, 1665
145 <-> 1672
146 <-> 1937
147 <-> 1409, 1697
148 <-> 608, 954, 1624
149 <-> 527, 652, 1938
150 <-> 709
151 <-> 447, 1305, 1314
152 <-> 1741
153 <-> 901, 1997
154 <-> 29, 929
155 <-> 1178, 1976
156 <-> 560
157 <-> 522
158 <-> 541
159 <-> 1212, 1878
160 <-> 1078
161 <-> 1128, 1913
162 <-> 588, 734
163 <-> 125, 1073, 1952
164 <-> 1156
165 <-> 1781
166 <-> 1692
167 <-> 36, 1637
168 <-> 1043, 1085
169 <-> 40, 334, 1257, 1313
170 <-> 170
171 <-> 171
172 <-> 1391
173 <-> 925
174 <-> 1733
175 <-> 175, 1466
176 <-> 726, 1182
177 <-> 89, 1100
178 <-> 611, 1141
179 <-> 1036, 1307
180 <-> 1556
181 <-> 1930
182 <-> 775, 1284
183 <-> 1907
184 <-> 134, 1981
185 <-> 255, 1278
186 <-> 1891
187 <-> 531, 1318
188 <-> 790, 1623
189 <-> 379, 1749, 1865
190 <-> 1103, 1676
191 <-> 534
192 <-> 477
193 <-> 193, 860
194 <-> 91, 710, 1780
195 <-> 290, 1383, 1510
196 <-> 97, 1664
197 <-> 1416
198 <-> 287, 1760
199 <-> 366
200 <-> 43
201 <-> 813, 1882
202 <-> 246, 1175
203 <-> 203, 1007
204 <-> 204, 923
205 <-> 924
206 <-> 1162, 1818
207 <-> 365, 487, 923
208 <-> 1281, 1290
209 <-> 1280
210 <-> 210, 288, 1333
211 <-> 211, 417, 754
212 <-> 1698
213 <-> 1626
214 <-> 1256
215 <-> 215, 1385, 1671
216 <-> 811, 1025
217 <-> 554, 1715
218 <-> 1483
219 <-> 1741
220 <-> 99, 530, 1081, 1319, 1801
221 <-> 804, 1144
222 <-> 1288, 1702
223 <-> 223, 1231
224 <-> 649, 1179
225 <-> 1271, 1776
226 <-> 226, 1991
227 <-> 496, 857, 1004, 1821
228 <-> 371, 500
229 <-> 1162
230 <-> 693, 1081
231 <-> 506, 973
232 <-> 859, 969, 1922
233 <-> 233
234 <-> 875, 1006
235 <-> 1035, 1998
236 <-> 236
237 <-> 289, 569, 1440
238 <-> 1249, 1923
239 <-> 1564, 1775, 1944
240 <-> 1888
241 <-> 951, 1874
242 <-> 825
243 <-> 384, 983, 1838
244 <-> 715, 1501
245 <-> 592, 671
246 <-> 202, 391, 632, 656
247 <-> 663
248 <-> 253, 752
249 <-> 1073, 1558
250 <-> 290
251 <-> 792, 1389
252 <-> 797
253 <-> 248, 771
254 <-> 254, 1047
255 <-> 127, 185, 369
256 <-> 623
257 <-> 1636, 1740
258 <-> 317
259 <-> 1775
260 <-> 136, 561, 1290
261 <-> 359, 1657
262 <-> 103, 697, 1074
263 <-> 1205
264 <-> 1779, 1782
265 <-> 1407
266 <-> 70, 1215, 1306
267 <-> 333, 790
268 <-> 603
269 <-> 269, 1497
270 <-> 270, 1613
271 <-> 1416, 1562, 1923
272 <-> 579, 894
273 <-> 3, 993
274 <-> 333
275 <-> 1188
276 <-> 535, 645, 1166, 1269
277 <-> 1369
278 <-> 744, 1717
279 <-> 349, 695, 985, 1096
280 <-> 64, 1516
281 <-> 9, 427, 768, 1468
282 <-> 105, 867
283 <-> 66, 1235, 1525, 1748
284 <-> 530
285 <-> 95, 800, 1191
286 <-> 339, 611, 1581
287 <-> 198, 1285, 1501
288 <-> 210, 1059
289 <-> 237, 1928
290 <-> 195, 250, 1934
291 <-> 337, 1902
292 <-> 138, 1805, 1849
293 <-> 906
294 <-> 122, 1582
295 <-> 602
296 <-> 778
297 <-> 471, 483
298 <-> 298
299 <-> 402, 729
300 <-> 64, 1002
301 <-> 856
302 <-> 1084, 1538, 1739
303 <-> 892, 1774
304 <-> 1029, 1350
305 <-> 521, 1628, 1902
306 <-> 136, 469, 653, 835
307 <-> 981
308 <-> 1997
309 <-> 1612
310 <-> 1338, 1571
311 <-> 1388
312 <-> 60
313 <-> 1557
314 <-> 886, 1704
315 <-> 672, 779
316 <-> 1062, 1906
317 <-> 258, 1290
318 <-> 98, 318
319 <-> 1974
320 <-> 839
321 <-> 395, 615, 909, 1046
322 <-> 1077, 1390, 1989
323 <-> 323, 773, 1571
324 <-> 115, 493, 511, 650
325 <-> 325
326 <-> 1944, 1972
327 <-> 1489
328 <-> 412, 468
329 <-> 1637
330 <-> 556, 1176
331 <-> 656
332 <-> 564, 1688
333 <-> 267, 274, 421, 1205, 1743
334 <-> 169, 1896
335 <-> 1176
336 <-> 638, 1408, 1633
337 <-> 291, 844, 1549
338 <-> 515
339 <-> 286
340 <-> 340, 1959
341 <-> 943
342 <-> 417, 638, 1116, 1536
343 <-> 1030
344 <-> 584, 1751
345 <-> 345, 1810
346 <-> 346
347 <-> 587
348 <-> 515, 1187
349 <-> 279, 349
350 <-> 1749
351 <-> 1030, 1097
352 <-> 352
353 <-> 353, 683
354 <-> 51, 354, 735
355 <-> 1362
356 <-> 1593
357 <-> 357
358 <-> 441, 501, 899, 1672
359 <-> 261
360 <-> 122, 360, 1234, 1927
361 <-> 736
362 <-> 1169
363 <-> 780
364 <-> 444, 905, 1049, 1911
365 <-> 207
366 <-> 199, 1469
367 <-> 1612
368 <-> 675, 1800
369 <-> 255
370 <-> 370, 873, 962, 1238
371 <-> 71, 228, 456
372 <-> 1912
373 <-> 1318
374 <-> 1018, 1246
375 <-> 898, 1303
376 <-> 376, 573
377 <-> 1080
378 <-> 116, 1140
379 <-> 189, 1984
380 <-> 101
381 <-> 472, 827, 1097
382 <-> 67
383 <-> 383, 582
384 <-> 243, 432, 444, 569, 634
385 <-> 35
386 <-> 1496
387 <-> 637, 737, 756, 1293
388 <-> 1562
389 <-> 633
390 <-> 488
391 <-> 246, 853, 1422
392 <-> 1253, 1331
393 <-> 921, 1567, 1777, 1970
394 <-> 809
395 <-> 321, 798, 1040
396 <-> 746, 1332
397 <-> 400, 953
398 <-> 1958
399 <-> 399
400 <-> 90, 397, 808, 1485
401 <-> 1395
402 <-> 96, 299, 1388
403 <-> 716
404 <-> 121
405 <-> 23, 934, 1221
406 <-> 1007
407 <-> 1391
408 <-> 497, 1090, 1644
409 <-> 1479
410 <-> 793, 1977
411 <-> 1026
412 <-> 328, 581, 806
413 <-> 32, 1354
414 <-> 33, 1920
415 <-> 799, 1207, 1880
416 <-> 1862
417 <-> 211, 342, 589, 1858
418 <-> 556, 1437, 1490
419 <-> 1393
420 <-> 420
421 <-> 67, 333, 1813
422 <-> 3, 706, 1598, 1721
423 <-> 1834
424 <-> 854, 1442
425 <-> 855, 1080
426 <-> 1408, 1469
427 <-> 281
428 <-> 832, 1998
429 <-> 553, 657, 834
430 <-> 1466
431 <-> 1357
432 <-> 384
433 <-> 71
434 <-> 434, 489, 1137
435 <-> 120
436 <-> 972, 1461
437 <-> 550
438 <-> 486, 844
439 <-> 978
440 <-> 66, 705, 1850
441 <-> 358, 589, 783, 804, 1129
442 <-> 33, 497
443 <-> 1806
444 <-> 364, 384, 1698
445 <-> 1208, 1294, 1452
446 <-> 1143, 1452
447 <-> 151, 1072
448 <-> 448
449 <-> 997, 1829
450 <-> 1277
451 <-> 1531, 1866
452 <-> 1175, 1622, 1975
453 <-> 42, 1486
454 <-> 689
455 <-> 1497
456 <-> 371, 1577
457 <-> 702
458 <-> 461, 921, 1279
459 <-> 1004
460 <-> 485, 505, 1211, 1451
461 <-> 458, 541, 916, 1844
462 <-> 1281
463 <-> 856, 1481
464 <-> 602, 1476, 1553
465 <-> 543, 1566
466 <-> 847, 1593
467 <-> 1270
468 <-> 328, 829
469 <-> 306, 667, 720, 1931
470 <-> 22
471 <-> 297
472 <-> 381
473 <-> 473
474 <-> 599, 1146
475 <-> 1570, 1894
476 <-> 1145
477 <-> 192, 1193, 1690
478 <-> 1469, 1840
479 <-> 1684
480 <-> 1, 108
481 <-> 103, 963
482 <-> 1778
483 <-> 6, 297, 1662
484 <-> 1435
485 <-> 460
486 <-> 438
487 <-> 207, 998, 1185
488 <-> 390, 1231, 1668
489 <-> 34, 434, 1341
490 <-> 990, 1203
491 <-> 936
492 <-> 77
493 <-> 324
494 <-> 1984
495 <-> 495, 1954
496 <-> 227
497 <-> 408, 442, 1551
498 <-> 1704, 1788
499 <-> 836
500 <-> 45, 228, 1358, 1798
501 <-> 94, 358, 1559
502 <-> 951
503 <-> 1036
504 <-> 1303
505 <-> 460
506 <-> 231, 606, 1473
507 <-> 1109
508 <-> 1724
509 <-> 1644
510 <-> 848
511 <-> 324, 1036
512 <-> 523
513 <-> 809, 1294
514 <-> 785
515 <-> 338, 348, 1027, 1193, 1226
516 <-> 1988
517 <-> 85, 1482
518 <-> 518
519 <-> 1625
520 <-> 520
521 <-> 305, 1033
522 <-> 157, 1355, 1476, 1588
523 <-> 60, 88, 512
524 <-> 8, 1998
525 <-> 990, 1275
526 <-> 1310, 1552
527 <-> 149, 979, 1805
528 <-> 698
529 <-> 631, 970
530 <-> 220, 284, 1533, 1944
531 <-> 187, 551, 1168, 1574
532 <-> 1484
533 <-> 892
534 <-> 191, 879
535 <-> 37, 276, 1527
536 <-> 24, 1094
537 <-> 747, 952
538 <-> 1620, 1735
539 <-> 858, 1467
540 <-> 1263, 1572
541 <-> 69, 158, 461
542 <-> 49, 1384
543 <-> 465, 639, 873
544 <-> 1338
545 <-> 1967
546 <-> 806, 1239
547 <-> 792, 1039, 1078
548 <-> 548, 1891, 1941
549 <-> 861
550 <-> 437, 1209, 1967
551 <-> 531, 888, 896
552 <-> 798
553 <-> 107, 429, 1330, 1951
554 <-> 217
555 <-> 744, 947, 1246
556 <-> 330, 418, 1070, 1925
557 <-> 1826, 1854
558 <-> 27, 1629
559 <-> 1042, 1150
560 <-> 156, 1472, 1834
561 <-> 260
562 <-> 63
563 <-> 129, 1309
564 <-> 332
565 <-> 1770, 1842
566 <-> 621
567 <-> 1160, 1178, 1642
568 <-> 895
569 <-> 53, 237, 384
570 <-> 641
571 <-> 571, 1261, 1924
572 <-> 882
573 <-> 376
574 <-> 982
575 <-> 78, 1255
576 <-> 887, 1539
577 <-> 603, 1122, 1679
578 <-> 742
579 <-> 272, 1444, 1747
580 <-> 797, 1554, 1718
581 <-> 412, 1926
582 <-> 383
583 <-> 1611
584 <-> 344, 1620
585 <-> 1692
586 <-> 1383
587 <-> 347, 1351
588 <-> 162, 1220
589 <-> 417, 441
590 <-> 1919
591 <-> 884, 992
592 <-> 245, 814
593 <-> 114
594 <-> 1843
595 <-> 1809
596 <-> 837
597 <-> 1563, 1575
598 <-> 12, 605, 984
599 <-> 474, 1218
600 <-> 732, 1237, 1714
601 <-> 1913
602 <-> 295, 464, 1061
603 <-> 268, 577, 720
604 <-> 604
605 <-> 38, 598
606 <-> 506, 686, 1813
607 <-> 2, 1948
608 <-> 148
609 <-> 1571
610 <-> 772, 901
611 <-> 178, 286, 880
612 <-> 1814
613 <-> 140, 883, 1198, 1764, 1942
614 <-> 1352
615 <-> 40, 321
616 <-> 58, 1413
617 <-> 624, 1008, 1591, 1791
618 <-> 1625
619 <-> 871, 1567
620 <-> 1954
621 <-> 12, 103, 566
622 <-> 1895
623 <-> 256, 1767
624 <-> 617
625 <-> 663
626 <-> 626
627 <-> 1650
628 <-> 884
629 <-> 1104, 1421
630 <-> 630, 864
631 <-> 529, 646
632 <-> 246
633 <-> 389, 1847
634 <-> 128, 384
635 <-> 1553, 1817
636 <-> 636
637 <-> 387
638 <-> 336, 342, 646, 1453
639 <-> 543, 815, 1087
640 <-> 1422, 1597
641 <-> 570, 805, 993, 1961
642 <-> 1371
643 <-> 959, 1044, 1444
644 <-> 41
645 <-> 276, 1022, 1184
646 <-> 631, 638, 1790
647 <-> 135, 1286
648 <-> 60
649 <-> 29, 224, 1636
650 <-> 324
651 <-> 863, 1321
652 <-> 149, 687, 1128, 1346
653 <-> 306
654 <-> 1409
655 <-> 1142, 1733
656 <-> 246, 331, 768, 1815
657 <-> 429
658 <-> 1511, 1569
659 <-> 1744
660 <-> 50, 796, 1524
661 <-> 63, 65, 810
662 <-> 995, 1661
663 <-> 247, 625, 1001
664 <-> 664
665 <-> 1305
666 <-> 666, 1817
667 <-> 469, 1003, 1550
668 <-> 1540, 1958
669 <-> 831, 883, 1349, 1719
670 <-> 1531
671 <-> 245, 671, 1693
672 <-> 315, 1088
673 <-> 942, 1381, 1660
674 <-> 880
675 <-> 368
676 <-> 1269, 1699
677 <-> 64, 1654
678 <-> 784
679 <-> 1760
680 <-> 39
681 <-> 681
682 <-> 728, 749, 1995
683 <-> 353
684 <-> 84, 1150
685 <-> 22
686 <-> 606
687 <-> 652, 1687
688 <-> 1878
689 <-> 454, 689
690 <-> 924, 1183
691 <-> 1410, 1413
692 <-> 1702
693 <-> 230, 1658
694 <-> 820, 1282, 1873
695 <-> 279
696 <-> 1168
697 <-> 262, 766, 776
698 <-> 65, 528, 698, 940
699 <-> 1778
700 <-> 743, 1459, 1825
701 <-> 1475
702 <-> 457, 792, 861, 1467
703 <-> 1581
704 <-> 1969
705 <-> 440, 1145
706 <-> 54, 422
707 <-> 1015, 1780
708 <-> 104, 1266
709 <-> 150, 1778
710 <-> 194
711 <-> 751
712 <-> 963
713 <-> 1525, 1762
714 <-> 1713
715 <-> 244, 1293, 1421
716 <-> 403, 1572
717 <-> 1142
718 <-> 1204
719 <-> 1672
720 <-> 469, 603
721 <-> 30, 1268, 1400
722 <-> 1183
723 <-> 1012
724 <-> 1029, 1289, 1368
725 <-> 31, 1039
726 <-> 176, 726
727 <-> 856
728 <-> 682, 1000
729 <-> 299, 1216, 1967
730 <-> 850, 900
731 <-> 1540, 1884
732 <-> 600, 784
733 <-> 1655
734 <-> 162
735 <-> 354, 1955
736 <-> 361, 1084, 1822
737 <-> 387
738 <-> 58, 1573
739 <-> 1119, 1216, 1822
740 <-> 829, 1219
741 <-> 1164
742 <-> 107, 578
743 <-> 700, 1744
744 <-> 278, 555
745 <-> 835, 1903
746 <-> 396
747 <-> 537, 1843
748 <-> 61
749 <-> 682, 1217, 1731
750 <-> 874, 1110, 1724
751 <-> 711, 1767
752 <-> 248, 1011
753 <-> 1327, 1885
754 <-> 127, 211, 1117
755 <-> 755
756 <-> 387
757 <-> 1098, 1169
758 <-> 143, 1689
759 <-> 19, 1517
760 <-> 831, 1915
761 <-> 761, 1195
762 <-> 1634
763 <-> 763
764 <-> 848, 1375
765 <-> 765, 1136
766 <-> 697, 1295, 1887
767 <-> 1906
768 <-> 281, 656, 1031
769 <-> 1457, 1863
770 <-> 75, 96
771 <-> 253, 846, 1375
772 <-> 610
773 <-> 323
774 <-> 1067
775 <-> 182, 1494
776 <-> 697
777 <-> 1136
778 <-> 296, 1057
779 <-> 315, 1631, 1796
780 <-> 363, 780, 1814
781 <-> 928, 1423
782 <-> 1850
783 <-> 441
784 <-> 678, 732, 999, 1988
785 <-> 514, 1248
786 <-> 134, 786, 1009
787 <-> 1348, 1863
788 <-> 891, 1183, 1455
789 <-> 1310, 1420, 1510
790 <-> 188, 267
791 <-> 1276
792 <-> 251, 547, 702
793 <-> 1, 72, 410, 1092
794 <-> 880
795 <-> 1799, 1807
796 <-> 660, 1548
797 <-> 252, 580, 797
798 <-> 395, 552
799 <-> 415, 799
800 <-> 285, 1889
801 <-> 801
802 <-> 802
803 <-> 1188, 1326, 1935
804 <-> 221, 441
805 <-> 43, 641, 1772
806 <-> 412, 546, 918, 1617
807 <-> 876, 1887
808 <-> 400, 1435, 1716
809 <-> 394, 513
810 <-> 661
811 <-> 216, 1259
812 <-> 1883
813 <-> 201, 1692
814 <-> 592
815 <-> 639
816 <-> 1041, 1734
817 <-> 1134, 1432
818 <-> 1575
819 <-> 113, 1063
820 <-> 694
821 <-> 1242
822 <-> 143, 892
823 <-> 1393, 1492
824 <-> 946
825 <-> 242, 999
826 <-> 1594
827 <-> 381, 1079, 1580
828 <-> 1941
829 <-> 468, 740, 1905
830 <-> 977, 1260, 1861
831 <-> 669, 760, 946, 1332
832 <-> 428, 832, 944, 1172
833 <-> 837, 1008, 1470
834 <-> 429, 915
835 <-> 306, 745, 976
836 <-> 499, 967
837 <-> 596, 833, 974
838 <-> 1335
839 <-> 320, 839, 1703
840 <-> 1053, 1398, 1760
841 <-> 1193
842 <-> 842, 1066, 1108
843 <-> 1414, 1697, 1894
844 <-> 337, 438
845 <-> 1506
846 <-> 771
847 <-> 466, 907, 1432
848 <-> 510, 764
849 <-> 1063, 1195, 1701
850 <-> 730, 1551
851 <-> 1112, 1331, 1479
852 <-> 1652
853 <-> 391
854 <-> 17, 424, 906, 1665
855 <-> 425, 1082
856 <-> 301, 463, 727, 1744
857 <-> 22, 227
858 <-> 539, 1252, 1472
859 <-> 232, 1843
860 <-> 193
861 <-> 549, 702, 1709, 1884
862 <-> 1149
863 <-> 651, 955
864 <-> 630
865 <-> 1138
866 <-> 144, 1111, 1114
867 <-> 282, 1487, 1835
868 <-> 1699
869 <-> 869
870 <-> 1487
871 <-> 619
872 <-> 872
873 <-> 370, 543, 1968
874 <-> 750, 874
875 <-> 234, 1202, 1473
876 <-> 807, 933, 1741
877 <-> 1205, 1874
878 <-> 1831
879 <-> 534, 1860
880 <-> 32, 611, 674, 794
881 <-> 1361, 1750
882 <-> 572, 1495
883 <-> 613, 669
884 <-> 591, 628, 1815
885 <-> 996, 1237
886 <-> 314, 1709
887 <-> 576
888 <-> 551
889 <-> 0, 1494
890 <-> 1100, 1966
891 <-> 788, 1312
892 <-> 303, 533, 822, 1334, 1812, 1935
893 <-> 1723
894 <-> 272, 1992
895 <-> 568, 1038
896 <-> 551, 1425
897 <-> 1783
898 <-> 375
899 <-> 358
900 <-> 730
901 <-> 106, 153, 610
902 <-> 1203
903 <-> 32, 1935
904 <-> 1109
905 <-> 364
906 <-> 293, 854, 1565
907 <-> 847, 1139, 1180, 1431, 1563, 1878
908 <-> 1908
909 <-> 321, 943
910 <-> 47, 1067
911 <-> 1468, 1495
912 <-> 15
913 <-> 1692
914 <-> 922, 1445
915 <-> 834, 1002
916 <-> 461
917 <-> 1177, 1924
918 <-> 806, 962, 1058, 1419
919 <-> 44, 82, 1933
920 <-> 1147, 1539
921 <-> 393, 458, 1055, 1951
922 <-> 914, 1271
923 <-> 204, 207, 1201
924 <-> 205, 690
925 <-> 173, 1816
926 <-> 1279
927 <-> 927
928 <-> 781
929 <-> 154
930 <-> 144
931 <-> 972, 1237
932 <-> 1317
933 <-> 876, 1756
934 <-> 51, 405, 1105, 1960
935 <-> 935, 1674
936 <-> 491, 1201, 1247
937 <-> 956, 1576, 1788
938 <-> 1377, 1733
939 <-> 121, 1638
940 <-> 698, 1808
941 <-> 1665, 1957
942 <-> 673
943 <-> 341, 909
944 <-> 832
945 <-> 1087, 1340
946 <-> 824, 831
947 <-> 555
948 <-> 959
949 <-> 1068
950 <-> 1664
951 <-> 241, 502, 1151
952 <-> 40, 537, 1376
953 <-> 397
954 <-> 148, 1075, 1364
955 <-> 863, 1235, 1618, 1724
956 <-> 937
957 <-> 101, 1323
958 <-> 1794, 1972
959 <-> 643, 948, 1023
960 <-> 960, 1417
961 <-> 1278
962 <-> 370, 918
963 <-> 481, 712
964 <-> 1198
965 <-> 4
966 <-> 966
967 <-> 836, 967, 1821
968 <-> 1513
969 <-> 128, 232
970 <-> 529
971 <-> 1471
972 <-> 436, 931
973 <-> 231
974 <-> 837
975 <-> 1390
976 <-> 835
977 <-> 830
978 <-> 439, 1687
979 <-> 527
980 <-> 980, 1609, 1940
981 <-> 307, 1671
982 <-> 574, 1318, 1643
983 <-> 243
984 <-> 598
985 <-> 279
986 <-> 68
987 <-> 1060
988 <-> 1942
989 <-> 1478
990 <-> 490, 525, 1838
991 <-> 41, 1263, 1302
992 <-> 591
993 <-> 273, 641
994 <-> 1026, 1240, 1618
995 <-> 662, 1545
996 <-> 885, 1528
997 <-> 449, 1058
998 <-> 487
999 <-> 784, 825
1000 <-> 728
1001 <-> 141, 663, 1626, 1681
1002 <-> 300, 915
1003 <-> 667
1004 <-> 227, 459
1005 <-> 1780
1006 <-> 234, 1578
1007 <-> 203, 406
1008 <-> 617, 833
1009 <-> 786, 1064
1010 <-> 1010, 1031, 1919
1011 <-> 752, 1754
1012 <-> 7, 723, 1068, 1181
1013 <-> 36
1014 <-> 1594
1015 <-> 707
1016 <-> 63
1017 <-> 1511
1018 <-> 374, 1034
1019 <-> 131, 1155
1020 <-> 114
1021 <-> 1288
1022 <-> 645
1023 <-> 959, 1375
1024 <-> 1024
1025 <-> 216
1026 <-> 411, 994
1027 <-> 515
1028 <-> 1417
1029 <-> 304, 724
1030 <-> 343, 351
1031 <-> 768, 1010
1032 <-> 1032
1033 <-> 521
1034 <-> 1018
1035 <-> 235, 1578
1036 <-> 179, 503, 511, 1036
1037 <-> 1037, 1044
1038 <-> 895, 1125
1039 <-> 547, 725, 1599
1040 <-> 395
1041 <-> 816
1042 <-> 559, 1042
1043 <-> 168, 1873
1044 <-> 643, 1037, 1312
1045 <-> 1232
1046 <-> 321
1047 <-> 254
1048 <-> 1747
1049 <-> 364
1050 <-> 1050, 1947, 1963
1051 <-> 1156
1052 <-> 4, 1201
1053 <-> 840
1054 <-> 1133, 1342, 1537, 1708, 1778
1055 <-> 71, 921, 1786
1056 <-> 1672
1057 <-> 778, 1423, 1787
1058 <-> 918, 997
1059 <-> 288, 1337, 1401
1060 <-> 987, 1781
1061 <-> 602, 1660
1062 <-> 316, 1863
1063 <-> 120, 819, 849
1064 <-> 1009
1065 <-> 1065
1066 <-> 842
1067 <-> 774, 910, 1089
1068 <-> 949, 1012
1069 <-> 1900
1070 <-> 556
1071 <-> 1884
1072 <-> 447, 1122
1073 <-> 163, 249, 1073, 1237
1074 <-> 262
1075 <-> 954, 1075, 1789
1076 <-> 1076, 1680
1077 <-> 55, 322
1078 <-> 160, 547
1079 <-> 827, 1079
1080 <-> 377, 425, 1739
1081 <-> 220, 230
1082 <-> 855, 1638
1083 <-> 44
1084 <-> 302, 736
1085 <-> 168, 1431
1086 <-> 1973
1087 <-> 639, 945
1088 <-> 672
1089 <-> 1067, 1190
1090 <-> 408, 1492
1091 <-> 1674
1092 <-> 793
1093 <-> 1802
1094 <-> 536
1095 <-> 1095, 1204
1096 <-> 279
1097 <-> 351, 381
1098 <-> 757, 1519
1099 <-> 1099, 1752
1100 <-> 177, 890
1101 <-> 1145
1102 <-> 1280
1103 <-> 190, 1200
1104 <-> 629
1105 <-> 100, 934
1106 <-> 1426
1107 <-> 78, 1497
1108 <-> 842
1109 <-> 507, 904, 1109
1110 <-> 750
1111 <-> 866
1112 <-> 851
1113 <-> 1113
1114 <-> 866, 1131, 1861
1115 <-> 1187, 1629
1116 <-> 342
1117 <-> 754
1118 <-> 1637
1119 <-> 739
1120 <-> 1837
1121 <-> 1133, 1758
1122 <-> 577, 1072, 1349
1123 <-> 1359
1124 <-> 1174
1125 <-> 1038, 1789
1126 <-> 1260
1127 <-> 1213
1128 <-> 161, 652
1129 <-> 441
1130 <-> 4
1131 <-> 1114
1132 <-> 1132, 1979
1133 <-> 1054, 1121, 1253
1134 <-> 817
1135 <-> 76, 1606
1136 <-> 765, 777, 1860
1137 <-> 434
1138 <-> 865, 1280, 1471, 1736
1139 <-> 74, 907
1140 <-> 108, 378
1141 <-> 178
1142 <-> 655, 717
1143 <-> 446
1144 <-> 221
1145 <-> 476, 705, 1101, 1271, 1956
1146 <-> 474, 1179, 1936
1147 <-> 920, 1147
1148 <-> 1148, 1795
1149 <-> 862, 1799
1150 <-> 559, 684, 1797
1151 <-> 951
1152 <-> 1229
1153 <-> 1515, 1530
1154 <-> 1154
1155 <-> 1019, 1300
1156 <-> 164, 1051, 1156
1157 <-> 18, 1157
1158 <-> 1208
1159 <-> 1651
1160 <-> 567, 1510, 1710
1161 <-> 1161, 1427, 1590
1162 <-> 206, 229, 1561
1163 <-> 1388
1164 <-> 741, 1494
1165 <-> 1217
1166 <-> 123, 276
1167 <-> 1262, 1547
1168 <-> 80, 531, 696
1169 <-> 362, 757, 1504
1170 <-> 1854
1171 <-> 1171, 1898
1172 <-> 832
1173 <-> 1173, 1315
1174 <-> 1124, 1174, 1831
1175 <-> 202, 452
1176 <-> 330, 335, 1761
1177 <-> 917
1178 <-> 155, 567
1179 <-> 224, 1146
1180 <-> 907, 1661
1181 <-> 1012
1182 <-> 176
1183 <-> 690, 722, 788
1184 <-> 645
1185 <-> 487
1186 <-> 1659
1187 <-> 348, 1115, 1670
1188 <-> 275, 803
1189 <-> 1689
1190 <-> 75, 1089
1191 <-> 285
1192 <-> 1744
1193 <-> 477, 515, 841
1194 <-> 1308
1195 <-> 761, 849
1196 <-> 130, 1993
1197 <-> 144
1198 <-> 613, 964, 1329
1199 <-> 1389
1200 <-> 1103
1201 <-> 923, 936, 1052
1202 <-> 875
1203 <-> 490, 902, 1692
1204 <-> 718, 1095, 1245
1205 <-> 263, 333, 877
1206 <-> 1311
1207 <-> 415, 1883
1208 <-> 445, 1158
1209 <-> 550, 1640
1210 <-> 12, 1210, 1428
1211 <-> 460, 1529
1212 <-> 52, 159, 1493, 1819
1213 <-> 1127, 1213
1214 <-> 1214, 1436
1215 <-> 266, 1758
1216 <-> 729, 739
1217 <-> 141, 749, 1165, 1315
1218 <-> 599, 1595
1219 <-> 740, 1549
1220 <-> 588, 1374
1221 <-> 405
1222 <-> 1966
1223 <-> 119
1224 <-> 1528
1225 <-> 1314
1226 <-> 86, 515
1227 <-> 1681
1228 <-> 1228
1229 <-> 0, 1152, 1374
1230 <-> 1453
1231 <-> 223, 488
1232 <-> 1045, 1261
1233 <-> 1759
1234 <-> 360
1235 <-> 283, 955, 1241, 1783
1236 <-> 1356
1237 <-> 600, 885, 931, 1073
1238 <-> 370, 1602
1239 <-> 546, 1373
1240 <-> 994
1241 <-> 1235, 1392
1242 <-> 7, 59, 821, 1945
1243 <-> 1296
1244 <-> 7, 1300, 1434
1245 <-> 1204, 1347
1246 <-> 374, 555, 1508
1247 <-> 109, 936
1248 <-> 785, 1715
1249 <-> 238
1250 <-> 1600, 1623
1251 <-> 1251
1252 <-> 858
1253 <-> 392, 1133
1254 <-> 35, 1394
1255 <-> 575
1256 <-> 214, 1607, 1685
1257 <-> 169
1258 <-> 81, 1264, 1320
1259 <-> 811, 1425
1260 <-> 830, 1126
1261 <-> 571, 1232
1262 <-> 1167, 1862
1263 <-> 540, 991
1264 <-> 1258, 1651
1265 <-> 139, 1569
1266 <-> 708
1267 <-> 1267
1268 <-> 721
1269 <-> 276, 676, 1759
1270 <-> 467, 1270, 1916
1271 <-> 225, 922, 1145, 1700
1272 <-> 99
1273 <-> 1302
1274 <-> 1966
1275 <-> 525
1276 <-> 791, 1834
1277 <-> 450, 1474, 1645
1278 <-> 185, 961
1279 <-> 458, 926
1280 <-> 209, 1102, 1138
1281 <-> 208, 462, 1943
1282 <-> 694, 1522
1283 <-> 111, 119, 1407
1284 <-> 182, 1996
1285 <-> 287
1286 <-> 647, 1286, 1715
1287 <-> 132
1288 <-> 222, 1021, 1398
1289 <-> 724
1290 <-> 208, 260, 317
1291 <-> 1498
1292 <-> 88
1293 <-> 387, 715, 1322, 1519, 1645
1294 <-> 445, 513, 1504
1295 <-> 766
1296 <-> 1243, 1379, 1964
1297 <-> 38, 1669
1298 <-> 1906
1299 <-> 18, 1804
1300 <-> 1155, 1244
1301 <-> 1371, 1453
1302 <-> 991, 1273
1303 <-> 375, 504, 1948
1304 <-> 1667, 1933
1305 <-> 102, 151, 665
1306 <-> 266
1307 <-> 179
1308 <-> 34, 1194
1309 <-> 563
1310 <-> 526, 789
1311 <-> 1206, 1311, 1769
1312 <-> 891, 1044
1313 <-> 169
1314 <-> 151, 1225
1315 <-> 42, 1173, 1217
1316 <-> 1316
1317 <-> 932, 1805
1318 <-> 187, 373, 982
1319 <-> 41, 220, 1948
1320 <-> 1258, 1859
1321 <-> 651
1322 <-> 1293
1323 <-> 957, 1472
1324 <-> 1324
1325 <-> 1325
1326 <-> 803, 1846
1327 <-> 753
1328 <-> 1879
1329 <-> 1198
1330 <-> 553, 1330
1331 <-> 392, 851
1332 <-> 396, 831
1333 <-> 210
1334 <-> 892
1335 <-> 838, 1552, 1568
1336 <-> 1336
1337 <-> 1059
1338 <-> 310, 544
1339 <-> 1897
1340 <-> 945
1341 <-> 489
1342 <-> 137, 1054
1343 <-> 1343
1344 <-> 1946
1345 <-> 1345
1346 <-> 652
1347 <-> 1245, 1914, 1930
1348 <-> 787, 1591
1349 <-> 669, 1122
1350 <-> 304, 1790
1351 <-> 587, 1997
1352 <-> 20, 614
1353 <-> 1738
1354 <-> 413, 1608
1355 <-> 522, 1816, 1917
1356 <-> 1236, 1450
1357 <-> 431, 1575
1358 <-> 500
1359 <-> 1123, 1599
1360 <-> 1370, 1385
1361 <-> 1, 881
1362 <-> 355, 1611, 1952
1363 <-> 69
1364 <-> 954
1365 <-> 1948
1366 <-> 30, 1470
1367 <-> 1527
1368 <-> 724
1369 <-> 277, 1482
1370 <-> 1360
1371 <-> 642, 1301, 1478, 1485
1372 <-> 1372, 1594
1373 <-> 1239
1374 <-> 79, 1220, 1229
1375 <-> 764, 771, 1023
1376 <-> 952
1377 <-> 938, 1520, 1730
1378 <-> 1378, 1411, 1823
1379 <-> 1296, 1832
1380 <-> 1380
1381 <-> 673
1382 <-> 1382
1383 <-> 195, 586
1384 <-> 542
1385 <-> 215, 1360
1386 <-> 1386
1387 <-> 1536
1388 <-> 311, 402, 1163
1389 <-> 251, 1199
1390 <-> 322, 975
1391 <-> 172, 407, 1453
1392 <-> 1241, 1587
1393 <-> 419, 823, 1636
1394 <-> 1254, 1588, 1699
1395 <-> 401, 1621
1396 <-> 1396, 1870
1397 <-> 1629
1398 <-> 840, 1288
1399 <-> 1399, 1932
1400 <-> 721
1401 <-> 1059
1402 <-> 1402
1403 <-> 33
1404 <-> 1449, 1632, 1832
1405 <-> 1634
1406 <-> 1726
1407 <-> 265, 1283, 1999
1408 <-> 39, 336, 426
1409 <-> 75, 147, 654
1410 <-> 691, 1780
1411 <-> 1378
1412 <-> 1447, 1759
1413 <-> 616, 691
1414 <-> 843
1415 <-> 1415
1416 <-> 197, 271
1417 <-> 132, 960, 1028
1418 <-> 1418, 1426
1419 <-> 918, 1560
1420 <-> 789
1421 <-> 629, 715
1422 <-> 391, 640
1423 <-> 781, 1057
1424 <-> 1614
1425 <-> 21, 896, 1259
1426 <-> 1106, 1418
1427 <-> 1161
1428 <-> 1210, 1677
1429 <-> 131
1430 <-> 1822
1431 <-> 907, 1085, 1846
1432 <-> 817, 847
1433 <-> 75
1434 <-> 1244
1435 <-> 484, 808
1436 <-> 1214
1437 <-> 418
1438 <-> 57
1439 <-> 1469, 1824
1440 <-> 237
1441 <-> 1722
1442 <-> 424, 1678
1443 <-> 144
1444 <-> 579, 643, 1869
1445 <-> 914
1446 <-> 1524, 1728
1447 <-> 1412, 1962
1448 <-> 1485
1449 <-> 1404
1450 <-> 1356, 1647
1451 <-> 460, 1907, 1967
1452 <-> 445, 446
1453 <-> 56, 133, 638, 1230, 1301, 1391
1454 <-> 1994
1455 <-> 788
1456 <-> 1914
1457 <-> 769
1458 <-> 1458
1459 <-> 700, 1796
1460 <-> 1799
1461 <-> 15, 436
1462 <-> 1678
1463 <-> 83, 1553, 1684
1464 <-> 35
1465 <-> 1471
1466 <-> 175, 430
1467 <-> 539, 702
1468 <-> 281, 911, 1475
1469 <-> 366, 426, 478, 1439, 1524
1470 <-> 833, 1366
1471 <-> 971, 1138, 1465
1472 <-> 560, 858, 1323, 1937
1473 <-> 506, 875
1474 <-> 1277, 1937
1475 <-> 701, 1468
1476 <-> 464, 522
1477 <-> 1785
1478 <-> 989, 1371
1479 <-> 409, 851
1480 <-> 1677
1481 <-> 463
1482 <-> 517, 1369, 1482
1483 <-> 102, 218
1484 <-> 532, 1531, 1735
1485 <-> 400, 1371, 1448
1486 <-> 453
1487 <-> 867, 870, 1577, 1584
1488 <-> 1488
1489 <-> 16, 327
1490 <-> 418
1491 <-> 7, 1589
1492 <-> 823, 1090
1493 <-> 1212, 1519, 1675
1494 <-> 775, 889, 1164
1495 <-> 882, 911
1496 <-> 386, 1496
1497 <-> 269, 455, 1107
1498 <-> 9, 1291, 1758
1499 <-> 1685, 1893
1500 <-> 1657
1501 <-> 244, 287
1502 <-> 1951
1503 <-> 112
1504 <-> 1169, 1294
1505 <-> 1987
1506 <-> 845, 1905
1507 <-> 1507
1508 <-> 1246
1509 <-> 41
1510 <-> 195, 789, 1160, 1980
1511 <-> 658, 1017
1512 <-> 1990
1513 <-> 968, 1513, 1612
1514 <-> 1514
1515 <-> 1153, 1632
1516 <-> 280
1517 <-> 759
1518 <-> 1837
1519 <-> 80, 82, 1098, 1293, 1493
1520 <-> 1377, 1978
1521 <-> 1521
1522 <-> 1282
1523 <-> 1749, 1876
1524 <-> 660, 1446, 1469, 1535, 1729
1525 <-> 283, 713
1526 <-> 22, 1767
1527 <-> 535, 1367, 1889
1528 <-> 996, 1224
1529 <-> 1211, 1736
1530 <-> 1153
1531 <-> 451, 670, 1484
1532 <-> 46
1533 <-> 62, 143, 530
1534 <-> 117, 1992
1535 <-> 1524
1536 <-> 342, 1387
1537 <-> 1054
1538 <-> 302, 1589
1539 <-> 576, 920
1540 <-> 668, 731
1541 <-> 1639
1542 <-> 1542
1543 <-> 1702
1544 <-> 1927
1545 <-> 995
1546 <-> 92, 1890
1547 <-> 40, 1167
1548 <-> 796
1549 <-> 110, 337, 1219
1550 <-> 46, 667
1551 <-> 497, 850
1552 <-> 526, 1335
1553 <-> 464, 635, 1463
1554 <-> 580, 1696
1555 <-> 1556, 1648, 1867
1556 <-> 180, 1555, 1676
1557 <-> 313, 1831
1558 <-> 249
1559 <-> 501
1560 <-> 1419
1561 <-> 1162
1562 <-> 271, 388
1563 <-> 597, 907
1564 <-> 239
1565 <-> 906, 1854
1566 <-> 465
1567 <-> 393, 619
1568 <-> 1335, 1745
1569 <-> 658, 1265, 1651
1570 <-> 475
1571 <-> 310, 323, 609
1572 <-> 540, 716
1573 <-> 738
1574 <-> 531
1575 <-> 597, 818, 1357
1576 <-> 937
1577 <-> 456, 1487, 1630
1578 <-> 1006, 1035
1579 <-> 1704
1580 <-> 827
1581 <-> 286, 703, 1888
1582 <-> 294
1583 <-> 1907
1584 <-> 1487
1585 <-> 1955
1586 <-> 1586, 1641
1587 <-> 1392
1588 <-> 522, 1394
1589 <-> 1491, 1538, 1589
1590 <-> 1161, 1642, 1946
1591 <-> 4, 617, 1348
1592 <-> 68
1593 <-> 356, 466
1594 <-> 826, 1014, 1372
1595 <-> 1218
1596 <-> 78
1597 <-> 640
1598 <-> 422
1599 <-> 1039, 1359
1600 <-> 1250
1601 <-> 113, 1631
1602 <-> 1238
1603 <-> 1603
1604 <-> 1604
1605 <-> 1980
1606 <-> 1135, 1828
1607 <-> 1256, 1607
1608 <-> 1354
1609 <-> 980, 1864
1610 <-> 1610
1611 <-> 583, 1362
1612 <-> 309, 367, 1513
1613 <-> 270, 1620
1614 <-> 1424, 1688
1615 <-> 1615
1616 <-> 1884
1617 <-> 806, 1763
1618 <-> 955, 994, 1897
1619 <-> 1622
1620 <-> 538, 584, 1613
1621 <-> 1395, 1621
1622 <-> 452, 1619
1623 <-> 188, 1250
1624 <-> 148
1625 <-> 519, 618, 1625, 1765
1626 <-> 213, 1001
1627 <-> 1929
1628 <-> 6, 305
1629 <-> 558, 1115, 1397
1630 <-> 1577
1631 <-> 779, 1601
1632 <-> 1404, 1515
1633 <-> 336
1634 <-> 762, 1405, 1734
1635 <-> 1635
1636 <-> 257, 649, 1393
1637 <-> 167, 329, 1118
1638 <-> 939, 1082
1639 <-> 1541, 1639
1640 <-> 1209
1641 <-> 1586
1642 <-> 567, 1590
1643 <-> 982
1644 <-> 408, 509
1645 <-> 1277, 1293
1646 <-> 1836, 1875
1647 <-> 1450, 1772
1648 <-> 1555, 1946
1649 <-> 1743
1650 <-> 627, 1720
1651 <-> 1159, 1264, 1569
1652 <-> 852, 1930
1653 <-> 1653
1654 <-> 677
1655 <-> 85, 733
1656 <-> 1875
1657 <-> 261, 1500, 1703
1658 <-> 693, 1679
1659 <-> 1186, 1659
1660 <-> 673, 1061
1661 <-> 662, 1180
1662 <-> 483
1663 <-> 1663, 1904
1664 <-> 196, 950, 1664
1665 <-> 144, 854, 941
1666 <-> 1666
1667 <-> 1304, 1890
1668 <-> 488
1669 <-> 1297
1670 <-> 78, 1187
1671 <-> 215, 981
1672 <-> 145, 358, 719, 1056
1673 <-> 1673
1674 <-> 25, 935, 1091
1675 <-> 1493
1676 <-> 190, 1556
1677 <-> 1428, 1480
1678 <-> 1442, 1462, 1987
1679 <-> 577, 1658
1680 <-> 16, 1076
1681 <-> 1001, 1227
1682 <-> 71
1683 <-> 90
1684 <-> 479, 1463, 1852
1685 <-> 1256, 1499
1686 <-> 94
1687 <-> 687, 978, 1787
1688 <-> 332, 1614, 1688
1689 <-> 758, 1189, 1779
1690 <-> 477
1691 <-> 1691, 1986
1692 <-> 166, 585, 813, 913, 1203, 1913
1693 <-> 671
1694 <-> 1711
1695 <-> 89, 1795
1696 <-> 1554
1697 <-> 147, 843, 1900
1698 <-> 212, 444, 1793
1699 <-> 676, 868, 1394, 1705
1700 <-> 87, 1271
1701 <-> 849
1702 <-> 222, 692, 1543
1703 <-> 839, 1657
1704 <-> 314, 498, 1579
1705 <-> 1699
1706 <-> 89, 1993
1707 <-> 1990, 1994
1708 <-> 1054, 1892
1709 <-> 861, 886
1710 <-> 1160
1711 <-> 1694, 1737
1712 <-> 1712
1713 <-> 714, 1935
1714 <-> 600
1715 <-> 217, 1248, 1286
1716 <-> 808
1717 <-> 278, 1914
1718 <-> 580
1719 <-> 669
1720 <-> 1650, 1762, 1856
1721 <-> 422, 1918
1722 <-> 1441, 1722
1723 <-> 893, 1915
1724 <-> 508, 750, 955
1725 <-> 1725
1726 <-> 1406, 1959
1727 <-> 1797
1728 <-> 14, 1446
1729 <-> 1524
1730 <-> 1377, 1737
1731 <-> 104, 749
1732 <-> 129, 1908
1733 <-> 174, 655, 938
1734 <-> 816, 1634, 1734
1735 <-> 538, 1484
1736 <-> 0, 1138, 1529
1737 <-> 1711, 1730
1738 <-> 26, 1353, 1757
1739 <-> 302, 1080
1740 <-> 118, 257
1741 <-> 152, 219, 876
1742 <-> 1841, 1945
1743 <-> 333, 1649
1744 <-> 659, 743, 856, 1192
1745 <-> 1568
1746 <-> 1746
1747 <-> 579, 1048
1748 <-> 283
1749 <-> 189, 350, 1523, 1848, 1894
1750 <-> 881
1751 <-> 344
1752 <-> 1099
1753 <-> 1753
1754 <-> 1011
1755 <-> 1755, 1939
1756 <-> 933
1757 <-> 1738
1758 <-> 1121, 1215, 1498
1759 <-> 1233, 1269, 1412
1760 <-> 198, 679, 840
1761 <-> 1176
1762 <-> 713, 1720
1763 <-> 1617
1764 <-> 613
1765 <-> 1625
1766 <-> 99
1767 <-> 623, 751, 1526
1768 <-> 82
1769 <-> 1311, 1921
1770 <-> 565, 1995
1771 <-> 77, 1771
1772 <-> 805, 1647, 1772
1773 <-> 1773, 1826
1774 <-> 303
1775 <-> 239, 259
1776 <-> 225
1777 <-> 393
1778 <-> 482, 699, 709, 1054
1779 <-> 264, 1689
1780 <-> 61, 194, 707, 1005, 1410, 1999
1781 <-> 165, 1060, 1978
1782 <-> 264
1783 <-> 897, 1235, 1845
1784 <-> 1784
1785 <-> 1477, 1915
1786 <-> 1055
1787 <-> 1057, 1687, 1899
1788 <-> 498, 937, 1859
1789 <-> 1075, 1125
1790 <-> 646, 1350
1791 <-> 617
1792 <-> 1855
1793 <-> 1698
1794 <-> 958
1795 <-> 1148, 1695
1796 <-> 779, 1459, 1857
1797 <-> 1150, 1727
1798 <-> 500
1799 <-> 795, 1149, 1460
1800 <-> 368, 1800
1801 <-> 220
1802 <-> 99, 1093
1803 <-> 1810
1804 <-> 1299
1805 <-> 292, 527, 1317
1806 <-> 443, 1865
1807 <-> 795, 1911
1808 <-> 940
1809 <-> 122, 595
1810 <-> 345, 1803
1811 <-> 1980
1812 <-> 892
1813 <-> 421, 606
1814 <-> 612, 780
1815 <-> 656, 884
1816 <-> 925, 1355
1817 <-> 635, 666
1818 <-> 29, 206
1819 <-> 1212
1820 <-> 1874
1821 <-> 227, 967
1822 <-> 736, 739, 1430
1823 <-> 1378
1824 <-> 68, 1439
1825 <-> 700
1826 <-> 557, 1773
1827 <-> 98, 1971
1828 <-> 1606, 1865
1829 <-> 449
1830 <-> 1830
1831 <-> 20, 878, 1174, 1557
1832 <-> 1379, 1404, 1832
1833 <-> 107
1834 <-> 423, 560, 1276
1835 <-> 867
1836 <-> 118, 1646
1837 <-> 47, 1120, 1518
1838 <-> 243, 990
1839 <-> 1839
1840 <-> 478
1841 <-> 1742
1842 <-> 565
1843 <-> 594, 747, 859
1844 <-> 461
1845 <-> 1783
1846 <-> 1326, 1431
1847 <-> 633, 1888
1848 <-> 1749
1849 <-> 24, 48, 292, 1851
1850 <-> 440, 782
1851 <-> 1849
1852 <-> 1684
1853 <-> 1853
1854 <-> 557, 1170, 1565
1855 <-> 70, 1792
1856 <-> 1720
1857 <-> 1796
1858 <-> 417
1859 <-> 1320, 1788
1860 <-> 36, 879, 1136
1861 <-> 830, 1114
1862 <-> 416, 1262
1863 <-> 28, 769, 787, 1062
1864 <-> 1609, 1920, 1953
1865 <-> 189, 1806, 1828, 1969
1866 <-> 451
1867 <-> 1555
1868 <-> 1868
1869 <-> 1444
1870 <-> 1396
1871 <-> 1939
1872 <-> 1914
1873 <-> 694, 1043
1874 <-> 241, 877, 1820
1875 <-> 1646, 1656
1876 <-> 1523
1877 <-> 1877
1878 <-> 159, 688, 907
1879 <-> 1328, 1879
1880 <-> 415
1881 <-> 65
1882 <-> 201
1883 <-> 812, 1207
1884 <-> 731, 861, 1071, 1616
1885 <-> 753, 1885
1886 <-> 75
1887 <-> 766, 807
1888 <-> 240, 1581, 1847
1889 <-> 800, 1527
1890 <-> 1546, 1667
1891 <-> 186, 548
1892 <-> 1708
1893 <-> 1499
1894 <-> 475, 843, 1749
1895 <-> 622, 1895, 1978
1896 <-> 334
1897 <-> 1339, 1618, 1949
1898 <-> 1171
1899 <-> 1787
1900 <-> 1069, 1697
1901 <-> 142
1902 <-> 291, 305
1903 <-> 745
1904 <-> 1663
1905 <-> 829, 1506
1906 <-> 316, 767, 1298, 1999
1907 <-> 183, 1451, 1583
1908 <-> 908, 1732
1909 <-> 62
1910 <-> 1999
1911 <-> 364, 1807
1912 <-> 372, 1912
1913 <-> 161, 601, 1692
1914 <-> 1347, 1456, 1717, 1872
1915 <-> 760, 1723, 1785
1916 <-> 1270
1917 <-> 1355
1918 <-> 1721
1919 <-> 590, 1010
1920 <-> 414, 1864
1921 <-> 1769
1922 <-> 232
1923 <-> 238, 271, 1923
1924 <-> 571, 917
1925 <-> 556, 1925
1926 <-> 129, 581
1927 <-> 360, 1544
1928 <-> 289
1929 <-> 1627, 1929
1930 <-> 181, 1347, 1652
1931 <-> 469, 1931
1932 <-> 1399
1933 <-> 919, 1304
1934 <-> 290
1935 <-> 803, 892, 903, 1713
1936 <-> 1146
1937 <-> 146, 1472, 1474
1938 <-> 149
1939 <-> 88, 1755, 1871
1940 <-> 980
1941 <-> 548, 828
1942 <-> 613, 988
1943 <-> 1281
1944 <-> 239, 326, 530
1945 <-> 49, 1242, 1742
1946 <-> 1344, 1590, 1648
1947 <-> 1050
1948 <-> 607, 1303, 1319, 1365
1949 <-> 1897
1950 <-> 1950
1951 <-> 553, 921, 1502
1952 <-> 163, 1362
1953 <-> 1864
1954 <-> 495, 620
1955 <-> 735, 1585
1956 <-> 11, 1145
1957 <-> 941
1958 <-> 398, 668
1959 <-> 340, 1726
1960 <-> 934
1961 <-> 641
1962 <-> 1447
1963 <-> 112, 1050
1964 <-> 1296
1965 <-> 61
1966 <-> 890, 1222, 1274
1967 <-> 545, 550, 729, 1451
1968 <-> 873
1969 <-> 704, 1865
1970 <-> 393
1971 <-> 1827
1972 <-> 326, 958
1973 <-> 1086, 1973
1974 <-> 319, 1974
1975 <-> 452
1976 <-> 155
1977 <-> 410
1978 <-> 1520, 1781, 1895
1979 <-> 1132
1980 <-> 1510, 1605, 1811
1981 <-> 184
1982 <-> 39
1983 <-> 1983
1984 <-> 379, 494
1985 <-> 95
1986 <-> 1691
1987 <-> 1505, 1678
1988 <-> 124, 516, 784
1989 <-> 322
1990 <-> 1512, 1707
1991 <-> 226
1992 <-> 894, 1534
1993 <-> 1196, 1706
1994 <-> 16, 1454, 1707
1995 <-> 682, 1770
1996 <-> 1284
1997 <-> 153, 308, 1351
1998 <-> 5, 235, 428, 524
1999 <-> 1407, 1780, 1906, 1910"""
zip: List a -> List b -> List (a, b)
zip list1 list2 =
zip2 list1 list2 []
zip2: List a -> List b -> List(a, b) -> List(a, b)
zip2 list1 list2 acc =
case list1 of
[] -> acc
head1::tail1 ->
case list2 of
[] -> acc
head2::tail2 ->
zip2 tail1 tail2 (List.append acc [(head1, head2)])
toIntOrZero: String -> Int
toIntOrZero char =
case (String.toInt char) of
Ok a ->
a
Err _ ->
0
outerProduct: List a -> List (a, a)
outerProduct list =
List.concatMap (\e ->
List.map (\i -> (e, i)) list
) list
histogram: List comparable -> Dict comparable Int
histogram list =
List.foldl histo_inc Dict.empty list
histo_inc: comparable -> Dict comparable Int -> Dict comparable Int
histo_inc dir dict =
if Dict.member dir dict then
Dict.update dir (Maybe.map ((+) 1)) dict
else
Dict.insert dir 1 dict
| elm |
[
{
"context": "ars [] [ C.bar .income [] ]\n [ { name = \"Anna\", income = 60 }\n , { name = \"Karenina\", ",
"end": 50203,
"score": 0.9993464947,
"start": 50199,
"tag": "NAME",
"value": "Anna"
},
{
"context": "ame = \"Anna\", income = 60 }\n , { name = \"Karenina\", income = 70 }\n , { name = \"Jane\", inco",
"end": 50250,
"score": 0.999674499,
"start": 50242,
"tag": "NAME",
"value": "Karenina"
},
{
"context": "= \"Karenina\", income = 70 }\n , { name = \"Jane\", income = 80 }\n ]\n\n , C.binLabels ",
"end": 50293,
"score": 0.9993025064,
"start": 50289,
"tag": "NAME",
"value": "Jane"
},
{
"context": " [ C.bar .income [] ]\n [ { name = \"Anna\", income = 60 }\n , { name = \"Karenina\", ",
"end": 51939,
"score": 0.9994192123,
"start": 51935,
"tag": "NAME",
"value": "Anna"
},
{
"context": "ame = \"Anna\", income = 60 }\n , { name = \"Karenina\", income = 70 }\n , { name = \"Jane\", inco",
"end": 51986,
"score": 0.9996663928,
"start": 51978,
"tag": "NAME",
"value": "Karenina"
},
{
"context": "= \"Karenina\", income = 70 }\n , { name = \"Jane\", income = 80 }\n ]\n\n , C.barLabels ",
"end": 52029,
"score": 0.9993766546,
"start": 52025,
"tag": "NAME",
"value": "Jane"
},
{
"context": " [ C.bar .income [] ]\n [ { name = \"Anna\", income = 60 }\n , { name = \"Karenina\", ",
"end": 53631,
"score": 0.9994722605,
"start": 53627,
"tag": "NAME",
"value": "Anna"
},
{
"context": "ame = \"Anna\", income = 60 }\n , { name = \"Karenina\", income = 70 }\n , { name = \"Jane\", inco",
"end": 53678,
"score": 0.9996522069,
"start": 53670,
"tag": "NAME",
"value": "Karenina"
},
{
"context": "= \"Karenina\", income = 70 }\n , { name = \"Jane\", income = 80 }\n ]\n\n , C.each model",
"end": 53721,
"score": 0.9995393753,
"start": 53717,
"tag": "NAME",
"value": "Jane"
},
{
"context": "of data.\n\n\n C.binned 10 .score\n [ Result \"Anna\" 43\n , Result \"Maya\" 65\n , Result \"Joan",
"end": 79480,
"score": 0.9981453419,
"start": 79476,
"tag": "NAME",
"value": "Anna"
},
{
"context": "0 .score\n [ Result \"Anna\" 43\n , Result \"Maya\" 65\n , Result \"Joan\" 69\n , Result \"Tina",
"end": 79505,
"score": 0.9991308451,
"start": 79501,
"tag": "NAME",
"value": "Maya"
},
{
"context": "Anna\" 43\n , Result \"Maya\" 65\n , Result \"Joan\" 69\n , Result \"Tina\" 98\n ]\n == [ {",
"end": 79530,
"score": 0.9990990758,
"start": 79526,
"tag": "NAME",
"value": "Joan"
},
{
"context": "Maya\" 65\n , Result \"Joan\" 69\n , Result \"Tina\" 98\n ]\n == [ { bin = 40, data = [ Resul",
"end": 79555,
"score": 0.9683049917,
"start": 79551,
"tag": "NAME",
"value": "Tina"
},
{
"context": "8\n ]\n == [ { bin = 40, data = [ Result \"Anna\" 43 ] }\n , { bin = 60, data = [ Result \"M",
"end": 79612,
"score": 0.9981689453,
"start": 79608,
"tag": "NAME",
"value": "Anna"
},
{
"context": "a\" 43 ] }\n , { bin = 60, data = [ Result \"Maya\" 65, Result \"Joan\" 69 ] }\n , { bin = 90, ",
"end": 79665,
"score": 0.9982996583,
"start": 79661,
"tag": "NAME",
"value": "Maya"
},
{
"context": " , { bin = 60, data = [ Result \"Maya\" 65, Result \"Joan\" 69 ] }\n , { bin = 90, data = [ Result \"T",
"end": 79683,
"score": 0.9985064864,
"start": 79679,
"tag": "NAME",
"value": "Joan"
},
{
"context": "n\" 69 ] }\n , { bin = 90, data = [ Result \"Tina\" 98 ] }\n ]\n\n type alias Result = { nam",
"end": 79736,
"score": 0.9947328568,
"start": 79732,
"tag": "NAME",
"value": "Tina"
}
] | src/Chart.elm | RalfNorthman/charts | 0 | module Chart exposing
( chart
, Element, bars, series, seriesMap, barsMap
, Property, bar, scatter, interpolated
, barMaybe, scatterMaybe, interpolatedMaybe
, stacked, named, variation, amongst
, xAxis, yAxis, xTicks, yTicks, xLabels, yLabels, grid
, binLabels, barLabels, dotLabels, productLabel
, xLabel, yLabel, xTick, yTick
, generate, floats, ints, times
, label, labelAt, legendsAt
, tooltip, line, rect, none
, svg, svgAt, html, htmlAt
, each, eachBin, eachStack, eachBar, eachDot, eachProduct, eachCustom
, withPlane, withBins, withStacks, withBars, withDots, withProducts
, binned
)
{-| Alpha version!
**See also the visual catalog of
examples at [elm-charts.org](https://www.elm-charts.org/documentation).**
The configuration of this charting library mirrors the pattern of HTML elements
and attributes. It looks something like this:
import Html exposing (Html)
import Chart as C
import Chart.Attributes as CA
view : Html msg
view =
C.chart
[ CA.width 300
, CA.height 300
]
[ C.grid []
, C.xLabels []
, C.yLabels []
, C.bars []
[ C.bar .income [ CA.color "red" ]
, C.bar .spending [ CA.opacity 0.8 ]
]
data
]
All the elements, like `chart`, `grid`, `xLabels`, `yLabels`, `bars` and `bar` in the example
above, are defined in this module. All the attributes, like `width`, `height`, `color`, and `opacity`,
are defined in `Chart.Attributes`. Attributes and other functions related to events are located in
the `Chart.Events` module. Lastly, `Chart.Svg` holds charting primitives in case you have very special
needs.
NOTE: Some of the more advanced elements utilize helper functions in `Chart.Events`
too. If that is the case, I will make a note in the comment of the element.
In the following examples, I will assume the imports:
import Html as H exposing (Html)
import Html.Attributes as HA
import Html.Events as HE
import Svg as S
import Svg.Attributes as SA
import Svg.Events as SE
import Chart as C
import Chart.Attributes as CA
import Chart.Events as CE
# The frame
@docs chart
@docs Element
# Chart elements
## Bar charts
@docs bars, barsMap, bar, barMaybe
## Scatter and line charts
@docs series, seriesMap, scatter, scatterMaybe, interpolated, interpolatedMaybe
## Stacking, naming, and variation
@docs Property, stacked, named, variation, amongst
# Navigation elements
## Axis lines
@docs xAxis, yAxis
## Axis ticks
@docs xTicks, yTicks
## Axis labels
@docs xLabels, yLabels
## Grid
@docs grid
## Custom Axis labels and ticks
@docs xLabel, yLabel, xTick, yTick
@docs generate, floats, ints, times
## Data labels
@docs binLabels, barLabels, dotLabels, productLabel
## General labels
@docs label, labelAt
## Legends
@docs legendsAt
## Other navigation helpers
@docs tooltip, line, rect
# Arbitrary elements
@docs svgAt, htmlAt, svg, html, none
# Advanced elements
## For each item, do..
@docs eachBin, eachStack, eachBar, eachDot, eachProduct, each, eachCustom
## With all item, do..
@docs withBins, withStacks, withBars, withDots, withProducts
## Using the plane, do..
@docs withPlane
# Data helper
@docs binned
-}
import Internal.Coordinates as C
import Svg as S
import Svg.Attributes as SA
import Svg.Events as SE
import Html as H
import Html.Attributes as HA
import Intervals as I
import Internal.Property as P
import Time
import Dict exposing (Dict)
import Internal.Item as Item
import Internal.Produce as Produce
import Internal.Legend as Legend
import Internal.Group as Group
import Internal.Helpers as Helpers
import Internal.Svg as IS
import Internal.Events as IE
import Chart.Svg as CS
import Chart.Attributes as CA exposing (Attribute)
import Chart.Events as CE
{-| -}
type alias Container data msg =
{ width : Float
, height : Float
, margin : { top : Float, bottom : Float, left : Float, right : Float }
, padding : { top : Float, bottom : Float, left : Float, right : Float }
, responsive : Bool
, range : List (Attribute C.Axis)
, domain : List (Attribute C.Axis)
, events : List (CE.Event data msg)
, htmlAttrs : List (H.Attribute msg)
, attrs : List (S.Attribute msg)
}
{-| This is the root element of your chart. All your chart elements must be contained in
a `chart` element. The below example illustrates what configurations are available for
the `chart` element.
view : Html msg
view =
C.chart
[ CA.width 300 -- Sets width of chart
, CA.height 500 -- Sets height of chart
, CA.static -- Don't scale with parent container
, CA.margin { top = 10, bottom = 20, left = 20, right = 20 }
-- Add space around your chart.
-- Useful if you have labels which extend
-- outside the main chart area.
, CA.padding { top = 10, bottom = 10, left = 10, right = 10 }
-- Expand your domain / range by a set
-- amount of SVG units.
-- Useful if you have e.g. scatter dots
-- which extend beyond your main chart area,
-- and you'd like them to be within.
-- Control the range and domain of your chart.
-- Your range and domain is by default set to the limits of
-- your data, but you can change them like this:
, CA.range
[ CA.lowest -5 CA.orLower
-- Makes sure that your x-axis begins at -5 or lower, no matter
-- what your data is like.
, CA.highest 10 CA.orHigher
-- Makes sure that your x-axis ends at 10 or higher, no matter
-- what your data is like.
]
, CA.domain
[ CA.lowest 0 CA.exactly ]
-- Makes sure that your y-axis begins at exactly 0, no matter
-- what your data is like.
-- Add event triggers to your chart. Learn more about these in
-- the `Chart.Events` module.
, CE.onMouseMove OnHovering (CE.getNearest C.bar)
, CE.onMouseLeave (OnHovering [])
-- Add arbitrary HTML and SVG attributes to your chart.
, CA.htmlAttrs [ HA.style "background" "beige" ]
, CA.attrs [ SA.id "my-chart" ]
]
[ C.grid []
, C.xLabels []
, C.yLabels []
, ..
]
-}
chart : List (Attribute (Container data msg)) -> List (Element data msg) -> H.Html msg
chart edits unindexedElements =
let config =
Helpers.apply edits
{ width = 300
, height = 300
, margin = { top = 0, bottom = 0, left = 0, right = 0 }
, padding = { top = 0, bottom = 0, left = 0, right = 0 }
, responsive = True
, range = []
, domain = []
, events = []
, attrs = [ SA.style "overflow: visible;" ]
, htmlAttrs = []
}
elements =
let toIndexedEl el ( acc, index ) =
case el of
Indexed toElAndIndex ->
let ( newEl, newIndex ) = toElAndIndex index in
( acc ++ [ newEl ], newIndex )
_ ->
( acc ++ [ el ], index )
in
List.foldl toIndexedEl ( [], 0 ) unindexedElements
|> Tuple.first
plane =
definePlane config elements
items =
getItems plane elements
legends_ =
getLegends elements
tickValues =
getTickValues plane items elements
( beforeEls, chartEls, afterEls ) =
viewElements config plane tickValues items legends_ elements
toEvent (IE.Event event_) =
let (IE.Decoder decoder) = event_.decoder in
IS.Event event_.name (decoder items)
in
IS.container plane
{ attrs = config.attrs
, htmlAttrs = config.htmlAttrs
, responsive = config.responsive
, events = List.map toEvent config.events
}
beforeEls
chartEls
afterEls
-- ELEMENTS
{-| The representation of a chart element.
-}
type Element data msg
= Indexed (Int -> ( Element data msg, Int ))
| SeriesElement
(List C.Position)
(List (Item.Product CE.Any (Maybe Float) data))
(List Legend.Legend)
(C.Plane -> S.Svg msg)
| BarsElement
(List C.Position)
(List (Item.Product CE.Any (Maybe Float) data))
(List Legend.Legend)
(C.Plane -> TickValues -> TickValues)
(C.Plane -> S.Svg msg)
| AxisElement
(C.Plane -> TickValues -> TickValues)
(C.Plane -> S.Svg msg)
| TicksElement
(C.Plane -> TickValues -> TickValues)
(C.Plane -> S.Svg msg)
| TickElement
(C.Plane -> Tick)
(C.Plane -> Tick -> TickValues -> TickValues)
(C.Plane -> Tick -> S.Svg msg)
| LabelsElement
(C.Plane -> Labels)
(C.Plane -> Labels -> TickValues -> TickValues)
(C.Plane -> Labels -> S.Svg msg)
| LabelElement
(C.Plane -> Label)
(C.Plane -> Label -> TickValues -> TickValues)
(C.Plane -> Label -> S.Svg msg)
| GridElement
(C.Plane -> TickValues -> S.Svg msg)
| SubElements
(C.Plane -> List (Item.Product CE.Any (Maybe Float) data) -> List (Element data msg))
| ListOfElements
(List (Element data msg))
| SvgElement
(C.Plane -> S.Svg msg)
| HtmlElement
(C.Plane -> List Legend.Legend -> H.Html msg)
definePlane : Container data msg -> List (Element data msg) -> C.Plane
definePlane config elements =
let collectLimits el acc =
case el of
Indexed _ -> acc
SeriesElement lims _ _ _ -> acc ++ lims
BarsElement lims _ _ _ _ -> acc ++ lims
AxisElement _ _ -> acc
TicksElement _ _ -> acc
TickElement _ _ _ -> acc
LabelsElement _ _ _ -> acc
LabelElement _ _ _ -> acc
GridElement _ -> acc
SubElements _ -> acc
ListOfElements subs -> List.foldl collectLimits acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
limits_ =
List.foldl collectLimits [] elements
|> C.foldPosition identity
|> \pos -> { x = toLimit pos.x1 pos.x2, y = toLimit pos.y1 pos.y2 }
|> \{ x, y } -> { x = fixSingles x, y = fixSingles y }
toLimit min max =
{ min = min, max = max, dataMin = min, dataMax = max }
fixSingles bs =
if bs.min == bs.max then { bs | max = bs.min + 10 } else bs
calcRange =
case config.range of
[] -> limits_.x
some -> List.foldl (\f b -> f b) limits_.x some
calcDomain =
case config.domain of
[] -> CA.lowest 0 CA.orLower limits_.y
some -> List.foldl (\f b -> f b) limits_.y some
unpadded =
{ width = max 1 (config.width - config.padding.left - config.padding.right)
, height = max 1 (config.height - config.padding.bottom - config.padding.top)
, margin = config.margin
, x = calcRange
, y = calcDomain
}
scalePadX =
C.scaleCartesianX unpadded
scalePadY =
C.scaleCartesianY unpadded
xMin = calcRange.min - scalePadX config.padding.left
xMax = calcRange.max + scalePadX config.padding.right
yMin = calcDomain.min - scalePadY config.padding.bottom
yMax = calcDomain.max + scalePadY config.padding.top
in
{ width = config.width
, height = config.height
, margin = config.margin
, x =
{ calcRange
| min = min xMin xMax
, max = max xMin xMax
}
, y =
{ calcDomain
| min = min yMin yMax
, max = max yMin yMax
}
}
getItems : C.Plane -> List (Element data msg) -> List (Item.Product CE.Any (Maybe Float) data)
getItems plane elements =
let toItems el acc =
case el of
Indexed _ -> acc
SeriesElement _ items _ _ -> acc ++ items
BarsElement _ items _ _ _ -> acc ++ items
AxisElement func _ -> acc
TicksElement _ _ -> acc
TickElement _ _ _ -> acc
LabelsElement _ _ _ -> acc
LabelElement _ _ _ -> acc
GridElement _ -> acc
SubElements _ -> acc -- TODO add phantom type to only allow decorative els in this
ListOfElements subs -> List.foldl toItems acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
in
List.foldl toItems [] elements
getLegends : List (Element data msg) -> List Legend.Legend
getLegends elements =
let toLegends el acc =
case el of
Indexed _ -> acc
SeriesElement _ _ legends_ _ -> acc ++ legends_
BarsElement _ _ legends_ _ _ -> acc ++ legends_
AxisElement _ _ -> acc
TicksElement _ _ -> acc
TickElement _ _ _ -> acc
LabelsElement _ _ _ -> acc
LabelElement _ _ _ -> acc
GridElement _ -> acc
SubElements _ -> acc
ListOfElements subs -> List.foldl toLegends acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
in
List.foldl toLegends [] elements
{-| -}
type alias TickValues =
{ xAxis : List Float
, yAxis : List Float
, xs : List Float
, ys : List Float
}
getTickValues : C.Plane -> List (Item.Product CE.Any (Maybe Float) data) -> List (Element data msg) -> TickValues
getTickValues plane items elements =
let toValues el acc =
case el of
Indexed _ -> acc
SeriesElement _ _ _ _ -> acc
BarsElement _ _ _ func _ -> func plane acc
AxisElement func _ -> func plane acc
TicksElement func _ -> func plane acc
TickElement toC func _ -> func plane (toC plane) acc
LabelsElement toC func _ -> func plane (toC plane) acc
LabelElement toC func _ -> func plane (toC plane) acc
SubElements func -> List.foldl toValues acc (func plane items)
GridElement _ -> acc
ListOfElements subs -> List.foldl toValues acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
in
List.foldl toValues (TickValues [] [] [] []) elements
viewElements : Container data msg -> C.Plane -> TickValues -> List (Item.Product CE.Any (Maybe Float) data) -> List Legend.Legend -> List (Element data msg) -> ( List (H.Html msg), List (S.Svg msg), List (H.Html msg) )
viewElements config plane tickValues allItems allLegends elements =
let viewOne el ( before, chart_, after ) =
case el of
Indexed _ -> ( before,chart_, after )
SeriesElement _ _ _ view -> ( before, view plane :: chart_, after )
BarsElement _ _ _ _ view -> ( before, view plane :: chart_, after )
AxisElement _ view -> ( before, view plane :: chart_, after )
TicksElement _ view -> ( before, view plane :: chart_, after )
TickElement toC _ view -> ( before, view plane (toC plane) :: chart_, after )
LabelsElement toC _ view -> ( before, view plane (toC plane) :: chart_, after )
LabelElement toC _ view -> ( before, view plane (toC plane) :: chart_, after )
GridElement view -> ( before, view plane tickValues :: chart_, after )
SubElements func -> List.foldr viewOne ( before, chart_, after ) (func plane allItems)
ListOfElements els -> List.foldr viewOne ( before, chart_, after ) els
SvgElement view -> ( before, view plane :: chart_, after )
HtmlElement view ->
( if List.length chart_ > 0 then view plane allLegends :: before else before
, chart_
, if List.length chart_ > 0 then after else view plane allLegends :: after
)
in
List.foldr viewOne ([], [], []) elements
-- TOOLTIP
type alias Tooltip =
{ direction : Maybe IS.Direction
, focal : Maybe (C.Position -> C.Position)
, height : Float
, width : Float
, offset : Float
, arrow : Bool
, border : String
, background : String
}
{-| Add a tooltip for a specific item.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.product) ]
[ C.series .year
[ C.scatter .income [] ]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 56000 }
, { year = 2020, income = 62000 }
]
, C.each model.hovering <| \plane product ->
[ C.tooltip product [] [] [] ]
]
Customizations:
C.tooltip item
[ -- Change direction
CA.onTop -- Always place tooltip on top of the item
, CA.onBottom -- Always place tooltip below of the item
, CA.onRight -- Always place tooltip on the right of the item
, CA.onLeft -- Always place tooltip on the left of the item
, CA.onLeftOrRight -- Place tooltip on the left or right of the item,
-- depending on which side has more space available
, CA.onTopOrBottom -- Place tooltip on the top or bottom of the item,
-- depending on which side has more space available
-- Change focal point (where on the item the tooltip is achored)
, CA.top
, CA.bottom
, CA.left
, CA.right
, CA.center
, CA.topLeft
, CA.topRight
, CA.topCenter
, CA.bottomLeft
, CA.bottomRight
, CA.bottomCenter
, CA.leftCenter
, CA.rightCenter
, CA.offset 20 -- Change offset between focal point and tooltip
, CA.noArrow -- Remove little box arrow
, CA.border "blue" -- Change border color
, CA.background -- Change background color
]
[] -- Add any HTML attributes
[] -- Add any HTML children (Will be filled with default tooltip if left empty)
-}
tooltip : Item.Item a -> List (Attribute Tooltip) -> List (H.Attribute Never) -> List (H.Html Never) -> Element data msg
tooltip i edits attrs_ content =
html <| \p ->
let pos = Item.getLimits i
content_ = if content == [] then Item.toHtml i else content
in
if IS.isWithinPlane p pos.x1 pos.y2 -- TODO
then CS.tooltip p (Item.getPosition p i) edits attrs_ content_
else H.text ""
-- AXIS
{-| -}
type alias Axis =
{ limits : List (Attribute C.Axis)
, pinned : C.Axis -> Float
, arrow : Bool
, color : String
, width : Float
}
{-| Add an x-axis line to your chart. The example below illustrates
the styling options:
C.chart []
[ C.xAxis
[ CA.color "red" -- Change color of line
, CA.width 2 -- Change width of line
, CA.noArrow -- Remove arrow from line
, CA.pinned .max -- Change what y position the axis is set at
-- .max is at the very top
-- .min is at the very bottom
-- CA.zero is the closest you can go to zero
-- (always 3) is at y = 3.
, CA.limits
[ CA.lowest 2 CA.exactly
, CA.highest 8 CA.exactly
]
-- Change from where to where you line goes.
-- The example will make a line where x1 = 2 to x2 = 8
]
]
-}
xAxis : List (Attribute Axis) -> Element item msg
xAxis edits =
let config =
Helpers.apply edits
{ limits = []
, pinned = CA.zero
, color = ""
, arrow = True
, width = 1
}
addTickValues p ts =
{ ts | yAxis = config.pinned p.y :: ts.yAxis }
in
AxisElement addTickValues <| \p ->
let xLimit = List.foldl (\f x -> f x) p.x config.limits in
S.g
[ SA.class "elm-charts__x-axis" ]
[ CS.line p
[ CA.color config.color
, CA.width config.width
, CA.y1 (config.pinned p.y)
, CA.x1 (max p.x.min xLimit.min)
, CA.x2 (min p.x.max xLimit.max)
]
, if config.arrow then
CS.arrow p
[ CA.color config.color ]
{ x = xLimit.max
, y = config.pinned p.y
}
else
S.text ""
]
{-| Add an y-axis line to your chart. The styling options are the same
as for `xAxis`.
-}
yAxis : List (Attribute Axis) -> Element item msg
yAxis edits =
let config =
Helpers.apply edits
{ limits = []
, pinned = CA.zero
, color = ""
, arrow = True
, width = 1
}
addTickValues p ts =
{ ts | xAxis = config.pinned p.x :: ts.xAxis }
in
AxisElement addTickValues <| \p ->
let yLimit = List.foldl (\f y -> f y) p.y config.limits in
S.g
[ SA.class "elm-charts__y-axis" ]
[ CS.line p
[ CA.color config.color
, CA.width config.width
, CA.x1 (config.pinned p.x)
, CA.y1 (max p.y.min yLimit.min)
, CA.y2 (min p.y.max yLimit.max)
]
, if config.arrow then
CS.arrow p [ CA.color config.color, CA.rotate -90 ]
{ x = config.pinned p.x
, y = yLimit.max
}
else
S.text ""
]
type alias Ticks =
{ color : String
, height : Float
, width : Float
, pinned : C.Axis -> Float
, limits : List (Attribute C.Axis)
, amount : Int
, flip : Bool
, grid : Bool
, generate : IS.TickType
}
{-| Produce a set of ticks at "nice" numbers on the x-axis of your chart.
The example below illustrates the configuration:
C.chart []
[ C.xTicks
[ CA.color "red" -- Change color
, CA.height 8 -- Change height
, CA.width 2 -- Change width
, CA.amount 15 -- Change amount of ticks
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each tick. This removes them.
, CA.ints -- Add ticks at "nice" ints
, CA.times Time.utc -- Add ticks at "nice" times
, CA.pinned .max -- Change what y position the ticks are set at
-- .max is at the very top
-- .min is at the very bottom
-- CA.zero is the closest you can go to zero
-- (always 3) is at y = 3.
, CA.limits
[ CA.lowest 2 CA.exactly
, CA.highest 8 CA.exactly
]
-- Change the upper and lower limit of your tick range.
-- The example will add ticks between x = 2 and 8.
]
]
-}
xTicks : List (Attribute Ticks) -> Element item msg
xTicks edits =
let config =
Helpers.apply edits
{ color = ""
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, height = 5
, flip = False
, grid = True
, width = 1
}
toTicks p =
List.foldl (\f x -> f x) p.x config.limits
|> generateValues config.amount config.generate Nothing
|> List.map .value
addTickValues p ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ toTicks p }
in
TicksElement addTickValues <| \p ->
let toTick x =
CS.xTick p
[ CA.color config.color
, CA.length (if config.flip then -config.height else config.height)
, CA.width config.width
]
{ x = x
, y = config.pinned p.y
}
in
S.g [ SA.class "elm-charts__x-ticks" ] <| List.map toTick (toTicks p)
{-| Produce a set of ticks at "nice" numbers on the y-axis of your chart.
The styling options are the same as for `xTicks`.
-}
yTicks : List (Attribute Ticks) -> Element item msg
yTicks edits =
let config =
Helpers.apply edits
{ color = ""
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, height = 5
, flip = False
, grid = True
, width = 1
}
toTicks p =
List.foldl (\f y -> f y) p.y config.limits
|> generateValues config.amount config.generate Nothing
|> List.map .value
addTickValues p ts =
{ ts | ys = ts.ys ++ toTicks p }
in
TicksElement addTickValues <| \p ->
let toTick y =
CS.yTick p
[ CA.color config.color
, CA.length (if config.flip then -config.height else config.height)
, CA.width config.width
]
{ x = config.pinned p.x
, y = y
}
in
S.g [ SA.class "elm-charts__y-ticks" ] <| List.map toTick (toTicks p)
type alias Labels =
{ color : String
, pinned : C.Axis -> Float
, limits : List (Attribute C.Axis)
, xOff : Float
, yOff : Float
, flip : Bool
, amount : Int
, anchor : Maybe IS.Anchor
, generate : IS.TickType
, fontSize : Maybe Int
, uppercase : Bool
, format : Maybe (Float -> String)
, rotate : Float
, grid : Bool
}
{-| Produce a set of labels at "nice" numbers on the x-axis of your chart.
The example below illustrates the configuration:
C.chart []
[ C.xLabels
[ CA.color "red" -- Change color
, CA.fontSize 12 -- Change font size
, CA.uppercase -- Make labels uppercase
, CA.rotate 90 -- Rotate labels
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.amount 15 -- Change amount of ticks
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each label. This removes them.
, CA.ints -- Add ticks at "nice" ints
, CA.times Time.utc -- Add ticks at "nice" times
, CA.format (\num -> String.fromFloat num ++ "°")
-- Format the "nice" number
, CA.pinned .max -- Change what y position the labels are set at
-- .max is at the very top
-- .min is at the very bottom
-- CA.zero is the closest you can go to zero
-- (always 3) is at y = 3.
, CA.limits
[ CA.lowest 2 CA.exactly
, CA.highest 8 CA.exactly
]
-- Change the upper and lower limit of your labels range.
-- The example will add labels between x = 2 and 8.
]
]
For more in depth and irregular customization, see `xLabel`.
-}
xLabels : List (Attribute Labels) -> Element item msg
xLabels edits =
let toConfig p =
Helpers.apply edits
{ color = "#808BAB"
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, flip = False
, anchor = Nothing
, xOff = 0
, yOff = 18
, grid = True
, format = Nothing
, uppercase = False
, rotate = 0
, fontSize = Nothing
}
toTicks p config =
List.foldl (\f x -> f x) p.x config.limits
|> generateValues config.amount config.generate config.format
toTickValues p config ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ List.map .value (toTicks p config) }
in
LabelsElement toConfig toTickValues <| \p config ->
let default = IS.defaultLabel
toLabel item =
IS.label p
{ default
| xOff = config.xOff
, yOff = if config.flip then -config.yOff + 10 else config.yOff
, color = config.color
, anchor = config.anchor
, fontSize = config.fontSize
, uppercase = config.uppercase
, rotate = config.rotate
}
[ S.text item.label ]
{ x = item.value
, y = config.pinned p.y
}
in
S.g [ SA.class "elm-charts__x-labels" ] (List.map toLabel (toTicks p config))
{-| Produce a set of labels at "nice" numbers on the y-axis of your chart.
The styling options are the same as for `xLabels`.
-}
yLabels : List (Attribute Labels) -> Element item msg
yLabels edits =
let toConfig p =
Helpers.apply edits
{ color = "#808BAB"
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, anchor = Nothing
, flip = False
, xOff = -10
, yOff = 3
, grid = True
, format = Nothing
, uppercase = False
, fontSize = Nothing
, rotate = 0
}
toTicks p config =
List.foldl (\f y -> f y) p.y config.limits
|> generateValues config.amount config.generate config.format
toTickValues p config ts =
if not config.grid then ts else
{ ts | ys = ts.ys ++ List.map .value (toTicks p config) }
in
LabelsElement toConfig toTickValues <| \p config ->
let default = IS.defaultLabel
toLabel item =
IS.label p
{ default
| xOff = if config.flip then -config.xOff else config.xOff
, yOff = config.yOff
, color = config.color
, fontSize = config.fontSize
, uppercase = config.uppercase
, rotate = config.rotate
, anchor =
case config.anchor of
Nothing -> Just (if config.flip then IS.Start else IS.End)
Just anchor -> Just anchor
}
[ S.text item.label ]
{ x = config.pinned p.x
, y = item.value
}
in
S.g [ SA.class "elm-charts__y-labels" ] (List.map toLabel (toTicks p config))
{-| -}
type alias Label =
{ x : Float
, y : Float
, xOff : Float
, yOff : Float
, border : String
, borderWidth : Float
, fontSize : Maybe Int
, color : String
, anchor : Maybe IS.Anchor
, rotate : Float
, uppercase : Bool
, flip : Bool
, grid : Bool
}
{-| Produce a single x label. This is typically for cases where you need
very custom labels and `xLabels` does not cut it. It is especially useful
in combination with the `generate` helper. An example use case:
C.chart []
[ -- Create labels for 10 "nice" integers on the x-axis
-- and highlight the label at x = 0.
C.generate 10 C.ints .x [] <| \plane int ->
let color = if int == 0 then "red" else "gray" in
[ C.xLabel
[ CA.x (toFloat int), CA.color color ]
[ S.text (String.fromInt int) ]
]
]
A full list of possible attributes:
C.chart []
[ C.xLabel
[ CA.x 5 -- Set x coordinate
, CA.y 8 -- Set y coordinate
, CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.border "white" -- Set stroke color
, CA.borderWidth 0.5 -- Set stroke width
, CA.fontSize 12 -- Set font size
, CA.color "red" -- Set color
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each label. This removes it.
]
[ S.text "hello!" ]
]
-}
xLabel : List (Attribute Label) -> List (S.Svg msg) -> Element data msg
xLabel edits inner =
let toConfig p =
Helpers.apply edits
{ x = CA.middle p.x
, y = CA.zero p.y
, xOff = 0
, yOff = 20
, border = "white"
, borderWidth = 0.1
, uppercase = False
, fontSize = Nothing
, color = "#808BAB"
, anchor = Nothing
, rotate = 0
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ [ config.x ] }
in
LabelElement toConfig toTickValues <| \p config ->
let string =
if inner == []
then [ S.text (String.fromFloat config.x) ]
else inner
in
IS.label p
{ xOff = config.xOff
, yOff = if config.flip then -config.yOff + 10 else config.yOff
, border = config.border
, borderWidth = config.borderWidth
, fontSize = config.fontSize
, uppercase = config.uppercase
, color = config.color
, anchor = config.anchor
, rotate = config.rotate
, attrs = []
}
string
{ x = config.x, y = config.y }
{-| Produce a single y label. This is typically for cases where you need
very custom labels and `yLabels` does not cut it. See `xLabel` for
usage and customization.
-}
yLabel : List (Attribute Label) -> List (S.Svg msg) -> Element data msg
yLabel edits inner =
let toConfig p =
Helpers.apply edits
{ x = CA.zero p.x
, y = CA.middle p.y
, xOff = -8
, yOff = 3
, border = "white"
, borderWidth = 0.1
, uppercase = False
, fontSize = Nothing
, color = "#808BAB"
, anchor = Nothing
, rotate = 0
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | ys = ts.ys ++ [ config.y ] }
in
LabelElement toConfig toTickValues <| \p config ->
let string =
if inner == []
then [ S.text (String.fromFloat config.y) ]
else inner
in
IS.label p
{ xOff = if config.flip then -config.xOff else config.xOff
, yOff = config.yOff
, border = config.border
, borderWidth = config.borderWidth
, fontSize = config.fontSize
, uppercase = config.uppercase
, color = config.color
, anchor =
case config.anchor of
Nothing -> Just (if config.flip then IS.Start else IS.End)
Just anchor -> Just anchor
, rotate = config.rotate
, attrs = []
}
string
{ x = config.x, y = config.y }
{-| -}
type alias Tick =
{ x : Float
, y : Float
, color : String
, width : Float
, length : Float
, flip : Bool
, grid : Bool
}
{-| Produce a single x tick. This is typically for cases where you need
very custom ticks and `xTicks` does not cut it. It is especially useful
in combination with the `generate` helper. An example use case:
C.chart []
[ -- Create ticks for 10 "nice" integers on the x-axis
-- and highlight the tick at x = 0.
C.generate 10 C.ints .x [] <| \plane int ->
let color = if int == 0 then "red" else "gray" in
[ C.xTick [ CA.x (toFloat int), CA.color color ] ]
]
A full list of possible attributes:
C.xTick
[ CA.x 5 -- Set x coordinate
, CA.y 8 -- Set y coordinate
, CA.color "red" -- Change color
, CA.height 8 -- Change height
, CA.width 2 -- Change width
, CA.amount 15 -- Change amount of ticks
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each tick. This removes them.
]
-}
xTick : List (Attribute Tick) -> Element data msg
xTick edits =
let toConfig p =
Helpers.apply edits
{ x = CA.middle p.x
, y = CA.zero p.y
, length = 5
, color = "rgb(210, 210, 210)"
, width = 1
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ [ config.x ] }
in
TickElement toConfig toTickValues <| \p config ->
CS.xTick p
[ CA.length (if config.flip then -config.length else config.length)
, CA.color config.color
, CA.width config.width
]
{ x = config.x, y = config.y }
{-| Produce a single y tick. This is typically for cases where you need
very custom ticks and `yTicks` does not cut it. See `xTick` for
usage and customization.
-}
yTick : List (Attribute Tick) -> Float -> Element data msg
yTick edits val =
let toConfig p =
Helpers.apply edits
{ x = CA.middle p.x
, y = CA.zero p.y
, length = 5
, color = "rgb(210, 210, 210)"
, width = 1
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | ys = ts.ys ++ [ config.y ] }
in
TickElement toConfig toTickValues <| \p config ->
CS.yTick p
[ CA.length (if config.flip then -config.length else config.length)
, CA.color config.color
, CA.width config.width
]
{ x = config.x, y = config.y }
type alias Grid =
{ color : String
, width : Float
, dotGrid : Bool
, dashed : List Float
}
{-| Add a grid to your chart.
C.chart []
[ C.grid []
, C.xLabels []
, C.yLabels []
]
Grid lines are added where labels or ticks are added.
Customizations:
C.grid
[ CA.color "blue" -- Change color
, CA.width 3 -- Change width
, CA.dashed [ 5, 5 ] -- Add dashing (only for line grids)
, CA.dotGrid -- Use dot grid instead of line grid
]
-}
grid : List (Attribute Grid) -> Element item msg
grid edits =
let config =
Helpers.apply edits
{ color = ""
, width = 0
, dotGrid = False
, dashed = []
}
color =
if String.isEmpty config.color then
if config.dotGrid then Helpers.darkGray else Helpers.gray
else
config.color
width =
if config.width == 0 then
if config.dotGrid then 0.5 else 1
else
config.width
toXGrid vs p v =
if List.member v vs.xAxis
then Nothing else Just <|
CS.line p [ CA.color color, CA.width width, CA.x1 v, CA.dashed config.dashed ]
toYGrid vs p v =
if List.member v vs.yAxis
then Nothing else Just <|
CS.line p [ CA.color color, CA.width width, CA.y1 v, CA.dashed config.dashed ]
toDot vs p x y =
if List.member x vs.xAxis || List.member y vs.yAxis
then Nothing
else Just <| CS.dot p .x .y [ CA.color color, CA.size width, CA.circle ] { x = x, y = y }
in
GridElement <| \p vs ->
S.g [ SA.class "elm-charts__grid" ] <|
if config.dotGrid then
List.concatMap (\x -> List.filterMap (toDot vs p x) vs.ys) vs.xs
else
[ S.g [ SA.class "elm-charts__x-grid" ] (List.filterMap (toXGrid vs p) vs.xs)
, S.g [ SA.class "elm-charts__y-grid" ] (List.filterMap (toYGrid vs p) vs.ys)
]
-- PROPERTIES
{-| A property of a bar, line, or scatter series.
-}
type alias Property data inter deco =
P.Property data String inter deco
{-| Specify the configuration of a bar. The first argument will determine the height of
your bar. The second is a list of styling attributes. The example below illustrates what
styling options are available.
C.chart []
[ C.bars []
[ C.bar .income
[ CA.color "blue" -- Change the color
, CA.border "darkblue" -- Change the border color
, CA.borderWidth 2 -- Change the border width
, CA.opacity 0.7 -- Change the border opacity
-- A bar can either be solid (default), striped, dotted, or gradient.
, CA.striped
[ CA.width 2 -- Width of each stripe
, CA.spacing 3 -- Spacing bewteen each stripe
, CA.color "blue" -- Color of stripe
, CA.rotate 90 -- Angle of stripe
]
, CA.dotted []
-- Same configurations as `striped`
, CA.gradient
[ "blue", "darkblue" ] -- List of colors in gradient
, CA.roundTop 0.2 -- Round the top corners
, CA.roundBottom 0.2 -- Round the bottom corners
-- You can highlight a bar or a set of bars by adding a kind of "aura" to it.
, CA.highlight 0.5 -- Determine the opacity of the aura
, CA.highlightWidth 5 -- Determine the width of the aura
, CA.highlightColor "blue" -- Determine the color of the aura
-- Add arbitrary SVG attributes to your bar
, CA.attrs [ SA.strokeOpacity "0.5" ]
]
]
[ { income = 10 }
, { income = 12 }
, { income = 18 }
]
]
-}
bar : (data -> Float) -> List (Attribute CS.Bar) -> Property data inter CS.Bar
bar y =
P.property (y >> Just) []
{-| Same as `bar`, but allows for missing data.
C.chart []
[ C.bars []
[ C.barMaybe .income [] ]
[ { income = Just 10 }
, { income = Nothing }
, { income = Just 18 }
]
]
-}
barMaybe : (data -> Maybe Float) -> List (Attribute CS.Bar) -> Property data inter CS.Bar
barMaybe y =
P.property y []
{-| Specify the configuration of a set of dots. The first argument will determine the y value of
your dots. The second is a list of styling attributes. The example below illustrates what styling
options are available.
C.series .year
[ C.scatter .income
[ CA.size 10 -- Change size of dot
, CA.color "blue" -- Change color
, CA.opacity 0.8 -- Change opacity
, CA.border "lightblue" -- Change border color
, CA.borderWidth 2 -- Change border width
-- You can highlight a dot or a set of dots by adding a kind of "aura" to it.
, CA.highlight 0.3 -- Determine the opacity of the aura
, CA.highlightWidth 6 -- Determine the width of the aura
, CA.highlightColor "blue" -- Determine the color of the aura
-- A dot is by default a circle, but you can change it to any
-- of the shapes below.
, CA.triangle
, CA.square
, CA.diamond
, CA.plus
, CA.cross
]
]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 57000 }
, { year = 2020, income = 62000 }
]
-}
scatter : (data -> Float) -> List (Attribute CS.Dot) -> Property data inter CS.Dot
scatter y =
P.property (y >> Just) []
{-| Same as `scatter`, but allows for missing data.
C.chart []
[ C.series .year
[ C.scatterMaybe .income [] ]
[ { year = 2000, income = Just 40000 }
, { year = 2010, income = Nothing }
, { year = 2020, income = Just 62000 }
]
]
-}
scatterMaybe : (data -> Maybe Float) -> List (Attribute CS.Dot) -> Property data inter CS.Dot
scatterMaybe y =
P.property y []
{-| Specify the configuration of a interpolated series (a line). The first argument will determine
the y value of your dots. The second is a list of attributes pertaining to your interpolation. The
third argument is a list of attributes pertaining to the dots of your series.
The example below illustrates what styling options are available.
C.series .age
[ C.interpolated .height
[ -- The following attributes allow alternatives to the default
-- linear interpolation.
CA.monotone -- Use a monotone interpolation (looks smooth)
, CA.stepped -- Use a stepped interpolation (looks like stairs)
, CA.color "blue"
, CA.width 2
, CA.dashed [ 4, 4 ]
-- The area beneath the curve is by default transparent, but you
-- can change the opacity of it, or make it striped, dotted, or gradient.
, CA.opacity 0.5
, CA.striped
[ CA.width 2 -- Width of each stripe
, CA.spacing 3 -- Spacing bewteen each stripe
, CA.color "blue" -- Color of stripe
, CA.rotate 90 -- Angle of stripe
]
, CA.dotted [] -- Same configurations as `striped`
, CA.gradient [ "blue", "darkblue" ] -- List of colors in gradient
-- Add arbitrary SVG attributes to your line
, CA.attrs [ SA.id "my-chart" ]
]
[]
]
[ { age = 0, height = 40 }
, { age = 5, height = 80 }
, { age = 10, height = 120 }
, { age = 15, height = 180 }
, { age = 20, height = 184 }
]
-}
interpolated : (data -> Float) -> List (Attribute CS.Interpolation) -> List (Attribute CS.Dot) -> Property data CS.Interpolation CS.Dot
interpolated y inter =
P.property (y >> Just) ([ CA.linear ] ++ inter)
{-| Same as `interpolated`, but allows for missing data.
C.chart []
[ C.series .age
[ C.interpolatedMaybe .height [] ]
[ { age = 0, height = Just 40 }
, { age = 5, height = Nothing }
, { age = 10, height = Just 120 }
, { age = 15, height = Just 180 }
, { age = 20, height = Just 184 }
]
]
-}
interpolatedMaybe : (data -> Maybe Float) -> List (Attribute CS.Interpolation) -> List (Attribute CS.Dot) -> Property data CS.Interpolation CS.Dot
interpolatedMaybe y inter =
P.property y ([ CA.linear ] ++ inter)
{-| Name a bar, scatter, or interpolated series. This name will show up
in the default tooltip, and you can use it to identify items from this series.
C.chart []
[ C.series .year
[ C.scatter .income []
|> C.named "Income"
]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 48000 }
, { year = 2020, income = 62000 }
]
]
-}
named : String -> Property data inter deco -> Property data inter deco
named name =
P.meta name
{-| Change the style of your bars or dots based on the index of its data point
and the data point itself.
C.chart []
[ C.series .year
[ C.scatter .income [ CA.opacity 0.6 ]
|> C.variation (\index datum -> [ CA.size datum.people ])
]
[ { year = 2000, income = 40000, people = 150 }
, { year = 2010, income = 48000, people = 98 }
, { year = 2020, income = 62000, people = 180 }
]
]
-}
variation : (Int -> data -> List (Attribute deco)) -> Property data inter deco -> Property data inter deco
variation func =
P.variation <| \_ _ index _ datum -> func index datum
{-| Change the style of your bars or dots based on whether it is a member
of the group of products which you list. A such group of products can be
attrained through events like `Chart.Events.onMouseMove` or similar.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.dot) ]
[ C.series .year
[ C.scatter .income [ CA.opacity 0.6 ]
|> C.amongst model.hovering (\datum -> [ CA.highlight 0.5 ])
]
[ { year = 2000, income = 40000, people = 150 }
, { year = 2010, income = 48000, people = 98 }
, { year = 2020, income = 62000, people = 180 }
]
]
-}
amongst : List (CE.Product config value data) -> (data -> List (Attribute deco)) -> Property data inter deco -> Property data inter deco
amongst inQuestion func =
P.variation <| \p s i meta d ->
let check product =
if Item.getPropertyIndex product == p &&
Item.getStackIndex product == s &&
Item.getDataIndex product == i &&
Item.getDatum product == d
then func d else []
in
List.concatMap check inQuestion
{-| Stack a set of bar or line series.
C.chart []
[ C.bars []
[ C.stacked
[ C.bar .cats []
, C.bar .dogs []
]
]
[ { cats = 2, dogs = 4 }
, { cats = 3, dogs = 2 }
, { cats = 6, dogs = 1 }
]
]
-}
stacked : List (Property data inter deco) -> Property data inter deco
stacked =
P.stacked
-- LABEL EXTRAS
{-| -}
type alias ItemLabel a =
{ xOff : Float
, yOff : Float
, border : String
, borderWidth : Float
, fontSize : Maybe Int
, color : String
, anchor : Maybe IS.Anchor
, rotate : Float
, uppercase : Bool
, attrs : List (S.Attribute Never)
, position : CS.Plane -> a -> CS.Point
, format : Maybe (a -> String)
}
defaultLabel : ItemLabel (CE.Item a)
defaultLabel =
{ xOff = IS.defaultLabel.xOff
, yOff = IS.defaultLabel.yOff
, border = IS.defaultLabel.border
, borderWidth = IS.defaultLabel.borderWidth
, fontSize = IS.defaultLabel.fontSize
, color = IS.defaultLabel.color
, anchor = IS.defaultLabel.anchor
, rotate = IS.defaultLabel.rotate
, uppercase = IS.defaultLabel.uppercase
, attrs = IS.defaultLabel.attrs
, position = CE.getBottom
, format = Nothing
}
toLabelFromItemLabel : ItemLabel (CE.Item a) -> CS.Label
toLabelFromItemLabel config =
{ xOff = config.xOff
, yOff = config.yOff
, color = config.color
, border = config.border
, borderWidth = config.borderWidth
, anchor = config.anchor
, fontSize = config.fontSize
, uppercase = config.uppercase
, rotate = config.rotate
, attrs = config.attrs
}
{-| Add labels by every bin.
C.chart []
[ C.bars [] [ C.bar .income [] ]
[ { name = "Anna", income = 60 }
, { name = "Karenina", income = 70 }
, { name = "Jane", income = 80 }
]
, C.binLabels .name [ CA.moveDown 15 ]
]
Attributes you can use:
C.binLabels .name
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-bin-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Given the entire bin item (not just the data)
-- produce a string.
, CA.format (\bin -> String.fromFloat (CE.getCommonality bin).start)
]
-}
binLabels : (data -> String) -> List (Attribute (ItemLabel (CE.Group (CE.Bin data) CE.Bar (Maybe Float) data))) -> Element data msg
binLabels toLabel edits =
eachCustom (CE.collect CE.bin CE.bar) <| \p item ->
let config =
Helpers.apply edits defaultLabel
text =
case config.format of
Just formatting -> formatting item
Nothing -> toLabel (CE.getCommonality item).datum
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
{-| Add labels by every bar.
C.chart []
[ C.bars []
[ C.bar .income [] ]
[ { name = "Anna", income = 60 }
, { name = "Karenina", income = 70 }
, { name = "Jane", income = 80 }
]
, C.barLabels [ CA.moveUp 6 ]
]
Attributes you can use:
C.barLabels
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-bar-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Change the text of the label
, CA.format (\bar -> String.fromFloat (CE.getDependent bar))
]
-}
barLabels : List (Attribute (ItemLabel (CE.Product CE.Bar Float data))) -> Element data msg
barLabels edits =
eachBar <| \p item ->
let config =
Helpers.apply edits { defaultLabel | position = CE.getTop }
text =
case config.format of
Just formatting -> formatting item
Nothing -> String.fromFloat (CE.getDependent item)
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
{-| Helper to add a label by a particular product.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.bar) ]
[ C.bars []
[ C.bar .income [] ]
[ { name = "Anna", income = 60 }
, { name = "Karenina", income = 70 }
, { name = "Jane", income = 80 }
]
, C.each model.hovering <| \_ bar ->
[ C.productLabel [ CA.moveUp 6 ] bar ]
]
Attributes you can use:
C.productLabel
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-bar-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Change the text of the label
, CA.format (\bar -> String.fromFloat (CE.getDependent bar))
]
product
-}
productLabel : List (Attribute (ItemLabel (CE.Product config value data))) -> CE.Product config value data -> Element data msg
productLabel edits item =
withPlane <| \p ->
let config =
Helpers.apply edits { defaultLabel | position = CE.getTop }
text =
case config.format of
Just formatting -> formatting item
Nothing -> String.fromFloat (Item.getDependentSafe item)
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
{-| Add labels by every bar.
C.chart []
[ C.series .age
[ C.scatter .income [] ]
[ { age = 34, income = 60 }
, { age = 42, income = 70 }
, { age = 48, income = 80 }
]
, C.dotLabels CE.getCenter [ CA.moveUp 6 ]
]
Attributes you can use:
C.dotLabels
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-dot-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Change the text of the label
, CA.format (\dot -> String.fromFloat (CE.getDependent dot))
]
-}
dotLabels : List (Attribute (ItemLabel (CE.Product CE.Dot Float data))) -> Element data msg
dotLabels edits =
eachDot <| \p item ->
let config =
Helpers.apply edits { defaultLabel | position = CE.getCenter }
text =
case config.format of
Just formatting -> formatting item
Nothing -> String.fromFloat (Item.getDependent item)
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
-- BARS
{-| -}
type alias Bars data =
{ spacing : Float
, margin : Float
, roundTop : Float
, roundBottom : Float
, grouped : Bool
, grid : Bool
, x1 : Maybe (data -> Float)
, x2 : Maybe (data -> Float)
}
{-| Add a bar series to your chart. Each `data` in your `List data` is a "bin". For
each "bin", whatever number of bars your have specified in the second argument will
show up, side-by-side.
C.bars []
[ C.bar .income []
, C.bar .spending []
]
[ { income = 10, spending = 2 }
, { income = 12, spending = 6 }
, { income = 18, spending = 16 }
]
The example above will thus produce three bins, each containing two bars. You can make
your bars show up overlapping instead of side-by-side by using the `CA.ungroup`
attribute:
C.bars
[ CA.ungroup ]
[ C.bar .total []
, C.bar .gross []
, C.bar .net []
]
[ { net = 10, gross = 20, total = 50 }
, { net = 13, gross = 28, total = 63 }
, { net = 16, gross = 21, total = 82 }
]
By default, the x value of each bin is set by a simple count. The first bin is set at
x = 1, the second at x = 2, and so on. If you'd like to control what the x values of
your bins are, e.g. you are making a histogram, you may use the `CA.x1` and `CA.x2`
attributes, as illustrated below.
C.bars
[ CA.x1 .score
, CA.x2 (\datum -> datum.score + 20)
]
[ C.bar .students [] ]
[ { score = 0, students = 1 }
, { score = 20, students = 10 }
, { score = 40, students = 30 }
, { score = 60, students = 20 }
, { score = 80, students = 1 }
]
In this case, you actually only need to specify either `x1` or `x2` because the library
estimates the unknown x value based on the size of the previous or next bin. However, it comes in
handy to specify both when you have bins of irregular sizes.
The rest of the configuration options concern styling:
C.bars
[ CA.spacing 0.1 -- The spacing _between_ the bars in each bin relative to the full length (1).
, CA.margin 0.2 -- The spacing _around_ the bars in each bin relative to the full length (1).
, CA.roundTop 0.2 -- The rounding of your bars' top corners. It gets weird after around 0.5.
, CA.roundBottom 0.2 -- The rounding of your bars' bottom corners. It gets weird after around 0.5.
, CA.noGrid -- Grid lines are by default added at the bin limits. This removes them.
]
[ C.bar .income []
, C.bar .spending []
]
[ { income = 10, spending = 2 }
, { income = 12, spending = 6 }
, { income = 18, spending = 16 }
]
-}
bars : List (Attribute (Bars data)) -> List (Property data () CS.Bar) -> List data -> Element data msg
bars edits properties data =
barsMap identity edits properties data
{-| This is just like `bars`, but it maps your `data`. This is useful if you have
several kinds of data types present in your chart.
type Datum
= Money { year : Float, income : Float }
| People { year : Float, people : Float }
view : Html msg
view =
C.chart []
[ C.barsMap Money
[ CA.x1 .year ]
[ C.bar .income [] ]
[ { year = 2000, income = 200 }
, { year = 2010, income = 300 }
, { year = 2020, income = 500 }
]
, C.barsMap People
[ CA.x1 .year ]
[ C.bar .people [] ]
[ { year = 2000, people = 21 }
, { year = 2010, people = 65 }
, { year = 2020, people = 93 }
]
]
-}
barsMap : (data -> a) -> List (Attribute (Bars data)) -> List (Property data () CS.Bar) -> List data -> Element a msg
barsMap mapData edits properties data =
Indexed <| \index ->
let barsConfig =
Helpers.apply edits Produce.defaultBars
items =
Produce.toBarSeries index edits properties data
generalized =
List.concatMap Group.getGenerals items
|> List.map (Item.map mapData)
bins =
CE.group CE.bin generalized
legends_ =
Legend.toBarLegends index edits properties
toTicks plane acc =
{ acc | xs = acc.xs ++
if barsConfig.grid then
List.concatMap (CE.getLimits >> \pos -> [ pos.x1, pos.x2 ]) bins
else
[]
}
toLimits =
List.map Item.getLimits bins
in
( BarsElement toLimits generalized legends_ toTicks <| \plane ->
S.g [ SA.class "elm-charts__bar-series" ] (List.map (Item.toSvg plane) items)
|> S.map never
, index + List.length (List.concatMap P.toConfigs properties)
)
-- SERIES
{-| Add a scatter or line series to your chart. Each `data` in your `List data` will result in one "dot".
The first argument of `series` determines the x value of each dot. The y value and all styling configuration
is determined by the list of `interpolated` or `scatter` properties defined in the second argument.
C.series .age
[ C.interpolated .height [] []
, C.interpolated .weight [] []
]
[ { age = 0, height = 40, weight = 4 }
, { age = 5, height = 80, weight = 24 }
, { age = 10, height = 120, weight = 36 }
, { age = 15, height = 180, weight = 54 }
, { age = 20, height = 184, weight = 60 }
]
See `interpolated` and `scatter` for styling options.
-}
series : (data -> Float) -> List (Property data CS.Interpolation CS.Dot) -> List data -> Element data msg
series toX properties data =
seriesMap identity toX properties data
{-| This is just like `series`, but it maps your `data`. This is useful if you have
several kinds of data types present in your chart.
type Datum
= Height { age : Float, height : Float }
| Weight { age : Float, weight : Float }
view : Html msg
view =
C.chart []
[ C.seriesMap Height .age
[ C.interpolated .height [] ]
[ { age = 0, height = 40 }
, { age = 5, height = 80 }
, { age = 10, height = 120 }
, { age = 15, height = 180 }
]
, C.seriesMap Weight .age
[ C.interpolated .weight [] ]
[ { age = 0, weight = 4 }
, { age = 5, weight = 24 }
, { age = 10, weight = 36 }
, { age = 15, weight = 54 }
]
]
-}
seriesMap : (data -> a) -> (data -> Float) -> List (Property data CS.Interpolation CS.Dot) -> List data -> Element a msg
seriesMap mapData toX properties data =
Indexed <| \index ->
let items =
Produce.toDotSeries index toX properties data
generalized =
List.concatMap Group.getGenerals items
|> List.map (Item.map mapData)
legends_ =
Legend.toDotLegends index properties
toLimits =
List.map Item.getLimits items
in
( SeriesElement toLimits generalized legends_ <| \p ->
S.g [ SA.class "elm-charts__dot-series" ] (List.map (Item.toSvg p) items)
|> S.map never
, index + List.length (List.concatMap P.toConfigs properties)
)
-- OTHER
{-| Using the information about your coordinate system, add a list
of elements.
-}
withPlane : (C.Plane -> List (Element data msg)) -> Element data msg
withPlane func =
SubElements <| \p is -> func p
{-| Given all your bins, add a list of elements.
Use helpers in `Chart.Events` to interact with bins.
-}
withBins : (C.Plane -> List (CE.Group (CE.Bin data) CE.Any (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withBins func =
SubElements <| \p is -> func p (CE.group CE.bin is)
{-| Given all your stacks, add a list of elements.
Use helpers in `Chart.Events` to interact with stacks.
-}
withStacks : (C.Plane -> List (CE.Group (CE.Stack data) CE.Any (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withStacks func =
SubElements <| \p is -> func p (CE.group CE.stack is)
{-| Given all your bars, add a list of elements.
Use helpers in `Chart.Events` to interact with bars.
-}
withBars : (C.Plane -> List (CE.Product CE.Bar (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withBars func =
SubElements <| \p is -> func p (CE.group CE.bar is)
{-| Given all your dots, add a list of elements.
Use helpers in `Chart.Events` to interact with dots.
-}
withDots : (C.Plane -> List (CE.Product CE.Dot (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withDots func =
SubElements <| \p is -> func p (CE.group CE.dot is)
{-| Given all your products, add a list of elements.
Use helpers in `Chart.Events` to interact with products.
-}
withProducts : (C.Plane -> List (CE.Product CE.Any (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withProducts func =
SubElements <| \p is -> func p is
{-| Add elements for each item of whatever list in the first argument.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.product) ]
[ C.series .year
[ C.scatter .income [] ]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 56000 }
, { year = 2020, income = 62000 }
]
, C.each model.hovering <| \plane product ->
[ C.tooltip product [] [] [] ]
]
-}
each : List a -> (C.Plane -> a -> List (Element data msg)) -> Element data msg
each items func =
SubElements <| \p _ -> List.concatMap (func p) items
{-| Add elements for each bin.
C.chart []
[ C.bars []
[ C.bar .income []
, C.bar .spending []
]
[ { country = "Denmark", income = 40000, spending = 10000 }
, { country = "Sweden", income = 56000, spending = 12000 }
, { country = "Norway", income = 62000, spending = 18000 }
]
, C.eachBin <| \plane bin ->
let common = CE.getCommonality bin in
[ C.label [] [ S.text common.datum.country ] (CE.getBottom plane bin) ]
]
Use the functions in `Chart.Events` to access information about your bins.
-}
eachBin : (C.Plane -> CE.Group (CE.Bin data) CE.Any Float data -> List (Element data msg)) -> Element data msg
eachBin func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.collect CE.bin <| CE.keep CE.realValues CE.product) is)
{-| Add elements for each stack.
C.chart []
[ C.bars []
[ C.stacked
[ C.bar .income []
, C.bar .savings []
]
]
[ { income = 40000, savings = 10000 }
, { income = 56000, savings = 12000 }
, { income = 62000, savings = 18000 }
]
, C.eachStack <| \plane stack ->
let total = List.sum (List.map CE.getDependent (CE.getProducts stack)) in
[ C.label [] [ S.text (String.fromFloat total) ] (CE.getTop plane stack) ]
]
Use the functions in `Chart.Events` to access information about your stacks.
-}
eachStack : (C.Plane -> CE.Group (CE.Stack data) CE.Any Float data -> List (Element data msg)) -> Element data msg
eachStack func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.collect CE.stack <| CE.keep CE.realValues CE.product) is)
{-| Add elements for each bar.
C.chart []
[ C.bars []
[ C.bar .income []
, C.bar .spending []
]
[ { income = 40000, spending = 10000 }
, { income = 56000, spending = 12000 }
, { income = 62000, spending = 18000 }
]
, C.eachBar <| \plane bar ->
let yValue = CE.getDependent bar in
[ C.label [] [ S.text (String.fromFloat yValue) ] (CE.getTop plane bar) ]
]
Use the functions in `Chart.Events` to access information about your bars.
-}
eachBar : (C.Plane -> CE.Product CE.Bar Float data -> List (Element data msg)) -> Element data msg
eachBar func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.keep CE.realValues CE.bar) is)
{-| Add elements for each dot.
C.chart []
[ C.series []
[ C.scatter .income []
, C.scatter .spending []
]
[ { income = 40000, spending = 10000 }
, { income = 56000, spending = 12000 }
, { income = 62000, spending = 18000 }
]
, C.eachBar <| \plane bar ->
let yValue = CE.getDependent bar in
[ C.label [] [ S.text (String.fromFloat yValue) ] (CE.getTop plane bar) ]
]
Use the functions in `Chart.Events` to access information about your dots.
-}
eachDot : (C.Plane -> CE.Product CE.Dot Float data -> List (Element data msg)) -> Element data msg
eachDot func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.keep CE.realValues CE.dot) is)
{-| Add elements for each product. Works like `eachBar` and `eachDot`, but includes both
bars and dots.
Use the functions in `Chart.Events` to access information about your products.
-}
eachProduct : (C.Plane -> CE.Product CE.Any Float data -> List (Element data msg)) -> Element data msg
eachProduct func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.keep CE.realValues CE.product) is)
{-| Filter and group products in any way you'd like and add elements for each of them.
C.chart []
[ C.eachCustom (CE.named "cats") <| \plane product ->
[ C.label [] [ S.text "hello" ] (CE.getTop plane product) ]
]
The above example adds a label for each product of the series named "cats".
Use the functions in `Chart.Events` to access information about your items.
-}
eachCustom : CE.Grouping (CE.Product CE.Any (Maybe Float) data) a -> (C.Plane -> a -> List (Element data msg)) -> Element data msg
eachCustom grouping func =
SubElements <| \p items ->
let processed = CE.group grouping items in
List.concatMap (func p) processed
{-| Add legends to your chart.
C.chart []
[ C.series .x
[ C.line .y [] []
|> C.named "cats"
, C.line .y [] []
|> C.named "dogs"
]
, C.legendsAt .min .max
[ CA.column -- Appear as column instead of row
, CA.alignRight -- Anchor legends to the right
, CA.alignLeft -- Anchor legends to the left
, CA.moveUp 5 -- Move 5px up
, CA.moveDown 5 -- Move 5px down
, CA.moveLeft 5 -- Move 5px left
, CA.moveRight 5 -- Move 5px right
, CA.spacing 20 -- Spacing between legends
, CA.background "beige" -- Color background
, CA.border "gray" -- Add border
, CA.borderWidth 1 -- Set border width
-- Add arbitrary HTML attributes. Convinient for extra styling.
, CA.htmlAttrs [ HA.class "my-legend" ]
]
[ CA.width 30 -- Change width of legend window
, CA.height 30 -- Change height of legend window
, CA.fontSize 12 -- Change font size
, CA.color "red" -- Change font color
, CA.spacing 12 -- Change spacing between window and title
, CA.htmlAttrs [ HA.class "my-legends" ] -- Add arbitrary HTML attributes.
]
]
-}
legendsAt : (C.Axis -> Float) -> (C.Axis -> Float) -> List (Attribute (CS.Legends msg)) -> List (Attribute (CS.Legend msg)) -> Element data msg
legendsAt toX toY attrs children =
HtmlElement <| \p legends_ ->
let viewLegend legend =
case legend of
Legend.BarLegend name barAttrs -> CS.barLegend (CA.title name :: children) barAttrs
Legend.LineLegend name interAttrs dotAttrs -> CS.lineLegend (CA.title name :: children) interAttrs dotAttrs
in
CS.legendsAt p (toX p.x) (toY p.y) attrs (List.map viewLegend legends_)
{-| Generate "nice" numbers. Useful in combination with `xLabel`, `yLabel`, `xTick`, and `yTick`.
C.chart []
[ C.generate 10 C.ints .x [ CA.lowest -5 CA.exactly, CA.highest 15 CA.exactly ] <| \plane int ->
[ C.xTick [ CA.x (toFloat int) ]
, C.xLabel [ CA.x (toFloat int) ] [ S.text (String.fromInt int) ]
]
]
The example above generates 10 ints on the x axis between x = -5 and x = 15. For each of those
ints, it adds a tick and a label.
-}
generate : Int -> CS.Generator a -> (C.Plane -> C.Axis) -> List (Attribute C.Axis) -> (C.Plane -> a -> List (Element data msg)) -> Element data msg
generate num gen limit attrs func =
SubElements <| \p _ ->
let items = CS.generate num gen (List.foldl (\f x -> f x) (limit p) attrs) in
List.concatMap (func p) items
{-| Generate "nice" floats.
-}
floats : CS.Generator Float
floats =
CS.floats
{-| Generate "nice" ints.
-}
ints : CS.Generator Int
ints =
CS.ints
{-| Generate "nice" times.
See the docs in [terezka/intervals](https://package.elm-lang.org/packages/terezka/intervals/2.0.0/Intervals#Time)
for more info about the properties of `Time`!
-}
times : Time.Zone -> CS.Generator I.Time
times =
CS.times
{-| Add a label, such as a chart title or other note, at a specific coordinate.
C.chart []
[ C.label [] [ S.text "Data from Fruits.com" ] { x = 5, y = 10 } ]
The example above adds your label at coordinates x = y and y = 10.
Other attributes you can use:
C.labelAt
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-label" ]
]
[ S.text "Data from Fruits.com" ]
{ x = 5, y = 10 }
-}
label : List (Attribute CS.Label) -> List (S.Svg msg) -> C.Point -> Element data msg
label attrs inner point =
SvgElement <| \p -> CS.label p attrs inner point
{-| Add a label, such as a chart title or other note, at a position relative to your axes.
C.chart []
[ C.labelAt (CA.percent 20) (CA.percent 90) [] [ S.text "Data from Fruits.com" ] ]
The example above adds your label at 20% the length of your range and 90% of your domain.
Other attributes you can use:
C.labelAt (CA.percent 20) (CA.percent 90)
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-label" ]
]
[ S.text "Data from Fruits.com" ]
-}
labelAt : (C.Axis -> Float) -> (C.Axis -> Float) -> List (Attribute CS.Label) -> List (S.Svg msg) -> Element data msg
labelAt toX toY attrs inner =
SvgElement <| \p -> CS.label p attrs inner { x = toX p.x, y = toY p.y }
{-| Add a line.
C.chart []
[ C.line
[ CA.x1 2 -- Set x1
, CA.x2 8 -- Set x2
, CA.y1 3 -- Set y1
, CA.y2 7 -- Set y2
-- Instead of specifying x2 and y2
-- you can use `x2Svg` and `y2Svg`
-- to specify the end coordinate in
-- terms of SVG units.
--
-- Useful if making little label pointers.
-- This makes a from ( x1, y1 ) to the point
-- ( x1 + 15 SVG units, y1 + 30 SVG units )
, CA.x2Svg 15
, CA.y2Svg 30
, CA.break -- "break" line, so it it has a 90° angle
, CA.tickLength -- Add "ticks" at the ends of the line
, CA.tickDirection -- The angle of the ticks
, CA.color "red" -- Change color
, CA.width 2 -- Change width
, CA.opacity 0.8 -- Change opacity
, CA.dashed [ 5, 5 ] -- Add dashing
-- Add arbitrary SVG attributes.
, CA.attrs [ SA.id "my-line" ]
]
]
-}
line : List (Attribute CS.Line) -> Element data msg
line attrs =
SvgElement <| \p -> CS.line p attrs
{-| Add a rectangle.
C.chart []
[ C.rect
[ CA.x1 2 -- Set x1
, CA.x2 8 -- Set x2
, CA.y1 3 -- Set y1
, CA.y2 7 -- Set y2
, CA.color "#aaa" -- Change fill color
, CA.opacity 0.8 -- Change fill opacity
, CA.border "#333" -- Change border color
, CA.borderWidth 2 -- Change border width
-- Add arbitrary SVG attributes.
, CA.attrs [ SA.id "my-rect" ]
]
]
-}
rect : List (Attribute CS.Rect) -> Element data msg
rect attrs =
SvgElement <| \p -> CS.rect p attrs
{-| Add arbitrary SVG. See `Chart.Svg` for handy SVG helpers.
-}
svg : (C.Plane -> S.Svg msg) -> Element data msg
svg func =
SvgElement <| \p -> func p
{-| Add arbitrary HTML.
-}
html : (C.Plane -> H.Html msg) -> Element data msg
html func =
HtmlElement <| \p _ -> func p
{-| Add arbitrary SVG at a specific location. See `Chart.Svg` for handy SVG helpers.
C.chart []
[ C.svgAt .min .max 10 20 [ .. ]
-- Add .. at x = the minumum value of your range (x-axis) + 12 SVG units
-- and y = the maximum value of your domain (y-axis) + 20 SVG units
]
-}
svgAt : (C.Axis -> Float) -> (C.Axis -> Float) -> Float -> Float -> List (S.Svg msg) -> Element data msg
svgAt toX toY xOff yOff view =
SvgElement <| \p ->
S.g [ CS.position p 0 (toX p.x) (toY p.y) xOff yOff ] view
{-| Add arbitrary HTML at a specific location.
-}
htmlAt : (C.Axis -> Float) -> (C.Axis -> Float) -> Float -> Float -> List (H.Attribute msg) -> List (H.Html msg) -> Element data msg
htmlAt toX toY xOff yOff att view =
HtmlElement <| \p _ ->
CS.positionHtml p (toX p.x) (toY p.y) xOff yOff att view
{-| No element.
-}
none : Element data msg
none =
HtmlElement <| \_ _ -> H.text ""
-- DATA HELPERS
{-| Gather data points into bins. Arguments:
1. The desired bin width.
2. The function to access the binned quality on the data
3. The list of data.
C.binned 10 .score
[ Result "Anna" 43
, Result "Maya" 65
, Result "Joan" 69
, Result "Tina" 98
]
== [ { bin = 40, data = [ Result "Anna" 43 ] }
, { bin = 60, data = [ Result "Maya" 65, Result "Joan" 69 ] }
, { bin = 90, data = [ Result "Tina" 98 ] }
]
type alias Result = { name : String, score : Float }
-}
binned : Float -> (data -> Float) -> List data -> List { bin : Float, data : List data }
binned binWidth func data =
let fold datum =
Dict.update (toBin datum) (updateDict datum)
updateDict datum maybePrev =
case maybePrev of
Just prev -> Just (datum :: prev)
Nothing -> Just [ datum ]
toBin datum =
floor (func datum / binWidth)
in
List.foldr fold Dict.empty data
|> Dict.toList
|> List.map (\( bin, ds ) -> { bin = toFloat bin * binWidth, data = ds })
-- HELPERS
type alias TickValue =
{ value : Float
, label : String
}
generateValues : Int -> IS.TickType -> Maybe (Float -> String) -> C.Axis -> List TickValue
generateValues amount tick maybeFormat axis =
let toTickValues toValue toString =
List.map <| \i ->
{ value = toValue i
, label =
case maybeFormat of
Just format -> format (toValue i)
Nothing -> toString i
}
in
case tick of
IS.Floats ->
toTickValues identity String.fromFloat
(CS.generate amount CS.floats axis)
IS.Ints ->
toTickValues toFloat String.fromInt
(CS.generate amount CS.ints axis)
IS.Times zone ->
toTickValues (toFloat << Time.posixToMillis << .timestamp) (CS.formatTime zone)
(CS.generate amount (CS.times zone) axis)
| 35077 | module Chart exposing
( chart
, Element, bars, series, seriesMap, barsMap
, Property, bar, scatter, interpolated
, barMaybe, scatterMaybe, interpolatedMaybe
, stacked, named, variation, amongst
, xAxis, yAxis, xTicks, yTicks, xLabels, yLabels, grid
, binLabels, barLabels, dotLabels, productLabel
, xLabel, yLabel, xTick, yTick
, generate, floats, ints, times
, label, labelAt, legendsAt
, tooltip, line, rect, none
, svg, svgAt, html, htmlAt
, each, eachBin, eachStack, eachBar, eachDot, eachProduct, eachCustom
, withPlane, withBins, withStacks, withBars, withDots, withProducts
, binned
)
{-| Alpha version!
**See also the visual catalog of
examples at [elm-charts.org](https://www.elm-charts.org/documentation).**
The configuration of this charting library mirrors the pattern of HTML elements
and attributes. It looks something like this:
import Html exposing (Html)
import Chart as C
import Chart.Attributes as CA
view : Html msg
view =
C.chart
[ CA.width 300
, CA.height 300
]
[ C.grid []
, C.xLabels []
, C.yLabels []
, C.bars []
[ C.bar .income [ CA.color "red" ]
, C.bar .spending [ CA.opacity 0.8 ]
]
data
]
All the elements, like `chart`, `grid`, `xLabels`, `yLabels`, `bars` and `bar` in the example
above, are defined in this module. All the attributes, like `width`, `height`, `color`, and `opacity`,
are defined in `Chart.Attributes`. Attributes and other functions related to events are located in
the `Chart.Events` module. Lastly, `Chart.Svg` holds charting primitives in case you have very special
needs.
NOTE: Some of the more advanced elements utilize helper functions in `Chart.Events`
too. If that is the case, I will make a note in the comment of the element.
In the following examples, I will assume the imports:
import Html as H exposing (Html)
import Html.Attributes as HA
import Html.Events as HE
import Svg as S
import Svg.Attributes as SA
import Svg.Events as SE
import Chart as C
import Chart.Attributes as CA
import Chart.Events as CE
# The frame
@docs chart
@docs Element
# Chart elements
## Bar charts
@docs bars, barsMap, bar, barMaybe
## Scatter and line charts
@docs series, seriesMap, scatter, scatterMaybe, interpolated, interpolatedMaybe
## Stacking, naming, and variation
@docs Property, stacked, named, variation, amongst
# Navigation elements
## Axis lines
@docs xAxis, yAxis
## Axis ticks
@docs xTicks, yTicks
## Axis labels
@docs xLabels, yLabels
## Grid
@docs grid
## Custom Axis labels and ticks
@docs xLabel, yLabel, xTick, yTick
@docs generate, floats, ints, times
## Data labels
@docs binLabels, barLabels, dotLabels, productLabel
## General labels
@docs label, labelAt
## Legends
@docs legendsAt
## Other navigation helpers
@docs tooltip, line, rect
# Arbitrary elements
@docs svgAt, htmlAt, svg, html, none
# Advanced elements
## For each item, do..
@docs eachBin, eachStack, eachBar, eachDot, eachProduct, each, eachCustom
## With all item, do..
@docs withBins, withStacks, withBars, withDots, withProducts
## Using the plane, do..
@docs withPlane
# Data helper
@docs binned
-}
import Internal.Coordinates as C
import Svg as S
import Svg.Attributes as SA
import Svg.Events as SE
import Html as H
import Html.Attributes as HA
import Intervals as I
import Internal.Property as P
import Time
import Dict exposing (Dict)
import Internal.Item as Item
import Internal.Produce as Produce
import Internal.Legend as Legend
import Internal.Group as Group
import Internal.Helpers as Helpers
import Internal.Svg as IS
import Internal.Events as IE
import Chart.Svg as CS
import Chart.Attributes as CA exposing (Attribute)
import Chart.Events as CE
{-| -}
type alias Container data msg =
{ width : Float
, height : Float
, margin : { top : Float, bottom : Float, left : Float, right : Float }
, padding : { top : Float, bottom : Float, left : Float, right : Float }
, responsive : Bool
, range : List (Attribute C.Axis)
, domain : List (Attribute C.Axis)
, events : List (CE.Event data msg)
, htmlAttrs : List (H.Attribute msg)
, attrs : List (S.Attribute msg)
}
{-| This is the root element of your chart. All your chart elements must be contained in
a `chart` element. The below example illustrates what configurations are available for
the `chart` element.
view : Html msg
view =
C.chart
[ CA.width 300 -- Sets width of chart
, CA.height 500 -- Sets height of chart
, CA.static -- Don't scale with parent container
, CA.margin { top = 10, bottom = 20, left = 20, right = 20 }
-- Add space around your chart.
-- Useful if you have labels which extend
-- outside the main chart area.
, CA.padding { top = 10, bottom = 10, left = 10, right = 10 }
-- Expand your domain / range by a set
-- amount of SVG units.
-- Useful if you have e.g. scatter dots
-- which extend beyond your main chart area,
-- and you'd like them to be within.
-- Control the range and domain of your chart.
-- Your range and domain is by default set to the limits of
-- your data, but you can change them like this:
, CA.range
[ CA.lowest -5 CA.orLower
-- Makes sure that your x-axis begins at -5 or lower, no matter
-- what your data is like.
, CA.highest 10 CA.orHigher
-- Makes sure that your x-axis ends at 10 or higher, no matter
-- what your data is like.
]
, CA.domain
[ CA.lowest 0 CA.exactly ]
-- Makes sure that your y-axis begins at exactly 0, no matter
-- what your data is like.
-- Add event triggers to your chart. Learn more about these in
-- the `Chart.Events` module.
, CE.onMouseMove OnHovering (CE.getNearest C.bar)
, CE.onMouseLeave (OnHovering [])
-- Add arbitrary HTML and SVG attributes to your chart.
, CA.htmlAttrs [ HA.style "background" "beige" ]
, CA.attrs [ SA.id "my-chart" ]
]
[ C.grid []
, C.xLabels []
, C.yLabels []
, ..
]
-}
chart : List (Attribute (Container data msg)) -> List (Element data msg) -> H.Html msg
chart edits unindexedElements =
let config =
Helpers.apply edits
{ width = 300
, height = 300
, margin = { top = 0, bottom = 0, left = 0, right = 0 }
, padding = { top = 0, bottom = 0, left = 0, right = 0 }
, responsive = True
, range = []
, domain = []
, events = []
, attrs = [ SA.style "overflow: visible;" ]
, htmlAttrs = []
}
elements =
let toIndexedEl el ( acc, index ) =
case el of
Indexed toElAndIndex ->
let ( newEl, newIndex ) = toElAndIndex index in
( acc ++ [ newEl ], newIndex )
_ ->
( acc ++ [ el ], index )
in
List.foldl toIndexedEl ( [], 0 ) unindexedElements
|> Tuple.first
plane =
definePlane config elements
items =
getItems plane elements
legends_ =
getLegends elements
tickValues =
getTickValues plane items elements
( beforeEls, chartEls, afterEls ) =
viewElements config plane tickValues items legends_ elements
toEvent (IE.Event event_) =
let (IE.Decoder decoder) = event_.decoder in
IS.Event event_.name (decoder items)
in
IS.container plane
{ attrs = config.attrs
, htmlAttrs = config.htmlAttrs
, responsive = config.responsive
, events = List.map toEvent config.events
}
beforeEls
chartEls
afterEls
-- ELEMENTS
{-| The representation of a chart element.
-}
type Element data msg
= Indexed (Int -> ( Element data msg, Int ))
| SeriesElement
(List C.Position)
(List (Item.Product CE.Any (Maybe Float) data))
(List Legend.Legend)
(C.Plane -> S.Svg msg)
| BarsElement
(List C.Position)
(List (Item.Product CE.Any (Maybe Float) data))
(List Legend.Legend)
(C.Plane -> TickValues -> TickValues)
(C.Plane -> S.Svg msg)
| AxisElement
(C.Plane -> TickValues -> TickValues)
(C.Plane -> S.Svg msg)
| TicksElement
(C.Plane -> TickValues -> TickValues)
(C.Plane -> S.Svg msg)
| TickElement
(C.Plane -> Tick)
(C.Plane -> Tick -> TickValues -> TickValues)
(C.Plane -> Tick -> S.Svg msg)
| LabelsElement
(C.Plane -> Labels)
(C.Plane -> Labels -> TickValues -> TickValues)
(C.Plane -> Labels -> S.Svg msg)
| LabelElement
(C.Plane -> Label)
(C.Plane -> Label -> TickValues -> TickValues)
(C.Plane -> Label -> S.Svg msg)
| GridElement
(C.Plane -> TickValues -> S.Svg msg)
| SubElements
(C.Plane -> List (Item.Product CE.Any (Maybe Float) data) -> List (Element data msg))
| ListOfElements
(List (Element data msg))
| SvgElement
(C.Plane -> S.Svg msg)
| HtmlElement
(C.Plane -> List Legend.Legend -> H.Html msg)
definePlane : Container data msg -> List (Element data msg) -> C.Plane
definePlane config elements =
let collectLimits el acc =
case el of
Indexed _ -> acc
SeriesElement lims _ _ _ -> acc ++ lims
BarsElement lims _ _ _ _ -> acc ++ lims
AxisElement _ _ -> acc
TicksElement _ _ -> acc
TickElement _ _ _ -> acc
LabelsElement _ _ _ -> acc
LabelElement _ _ _ -> acc
GridElement _ -> acc
SubElements _ -> acc
ListOfElements subs -> List.foldl collectLimits acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
limits_ =
List.foldl collectLimits [] elements
|> C.foldPosition identity
|> \pos -> { x = toLimit pos.x1 pos.x2, y = toLimit pos.y1 pos.y2 }
|> \{ x, y } -> { x = fixSingles x, y = fixSingles y }
toLimit min max =
{ min = min, max = max, dataMin = min, dataMax = max }
fixSingles bs =
if bs.min == bs.max then { bs | max = bs.min + 10 } else bs
calcRange =
case config.range of
[] -> limits_.x
some -> List.foldl (\f b -> f b) limits_.x some
calcDomain =
case config.domain of
[] -> CA.lowest 0 CA.orLower limits_.y
some -> List.foldl (\f b -> f b) limits_.y some
unpadded =
{ width = max 1 (config.width - config.padding.left - config.padding.right)
, height = max 1 (config.height - config.padding.bottom - config.padding.top)
, margin = config.margin
, x = calcRange
, y = calcDomain
}
scalePadX =
C.scaleCartesianX unpadded
scalePadY =
C.scaleCartesianY unpadded
xMin = calcRange.min - scalePadX config.padding.left
xMax = calcRange.max + scalePadX config.padding.right
yMin = calcDomain.min - scalePadY config.padding.bottom
yMax = calcDomain.max + scalePadY config.padding.top
in
{ width = config.width
, height = config.height
, margin = config.margin
, x =
{ calcRange
| min = min xMin xMax
, max = max xMin xMax
}
, y =
{ calcDomain
| min = min yMin yMax
, max = max yMin yMax
}
}
getItems : C.Plane -> List (Element data msg) -> List (Item.Product CE.Any (Maybe Float) data)
getItems plane elements =
let toItems el acc =
case el of
Indexed _ -> acc
SeriesElement _ items _ _ -> acc ++ items
BarsElement _ items _ _ _ -> acc ++ items
AxisElement func _ -> acc
TicksElement _ _ -> acc
TickElement _ _ _ -> acc
LabelsElement _ _ _ -> acc
LabelElement _ _ _ -> acc
GridElement _ -> acc
SubElements _ -> acc -- TODO add phantom type to only allow decorative els in this
ListOfElements subs -> List.foldl toItems acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
in
List.foldl toItems [] elements
getLegends : List (Element data msg) -> List Legend.Legend
getLegends elements =
let toLegends el acc =
case el of
Indexed _ -> acc
SeriesElement _ _ legends_ _ -> acc ++ legends_
BarsElement _ _ legends_ _ _ -> acc ++ legends_
AxisElement _ _ -> acc
TicksElement _ _ -> acc
TickElement _ _ _ -> acc
LabelsElement _ _ _ -> acc
LabelElement _ _ _ -> acc
GridElement _ -> acc
SubElements _ -> acc
ListOfElements subs -> List.foldl toLegends acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
in
List.foldl toLegends [] elements
{-| -}
type alias TickValues =
{ xAxis : List Float
, yAxis : List Float
, xs : List Float
, ys : List Float
}
getTickValues : C.Plane -> List (Item.Product CE.Any (Maybe Float) data) -> List (Element data msg) -> TickValues
getTickValues plane items elements =
let toValues el acc =
case el of
Indexed _ -> acc
SeriesElement _ _ _ _ -> acc
BarsElement _ _ _ func _ -> func plane acc
AxisElement func _ -> func plane acc
TicksElement func _ -> func plane acc
TickElement toC func _ -> func plane (toC plane) acc
LabelsElement toC func _ -> func plane (toC plane) acc
LabelElement toC func _ -> func plane (toC plane) acc
SubElements func -> List.foldl toValues acc (func plane items)
GridElement _ -> acc
ListOfElements subs -> List.foldl toValues acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
in
List.foldl toValues (TickValues [] [] [] []) elements
viewElements : Container data msg -> C.Plane -> TickValues -> List (Item.Product CE.Any (Maybe Float) data) -> List Legend.Legend -> List (Element data msg) -> ( List (H.Html msg), List (S.Svg msg), List (H.Html msg) )
viewElements config plane tickValues allItems allLegends elements =
let viewOne el ( before, chart_, after ) =
case el of
Indexed _ -> ( before,chart_, after )
SeriesElement _ _ _ view -> ( before, view plane :: chart_, after )
BarsElement _ _ _ _ view -> ( before, view plane :: chart_, after )
AxisElement _ view -> ( before, view plane :: chart_, after )
TicksElement _ view -> ( before, view plane :: chart_, after )
TickElement toC _ view -> ( before, view plane (toC plane) :: chart_, after )
LabelsElement toC _ view -> ( before, view plane (toC plane) :: chart_, after )
LabelElement toC _ view -> ( before, view plane (toC plane) :: chart_, after )
GridElement view -> ( before, view plane tickValues :: chart_, after )
SubElements func -> List.foldr viewOne ( before, chart_, after ) (func plane allItems)
ListOfElements els -> List.foldr viewOne ( before, chart_, after ) els
SvgElement view -> ( before, view plane :: chart_, after )
HtmlElement view ->
( if List.length chart_ > 0 then view plane allLegends :: before else before
, chart_
, if List.length chart_ > 0 then after else view plane allLegends :: after
)
in
List.foldr viewOne ([], [], []) elements
-- TOOLTIP
type alias Tooltip =
{ direction : Maybe IS.Direction
, focal : Maybe (C.Position -> C.Position)
, height : Float
, width : Float
, offset : Float
, arrow : Bool
, border : String
, background : String
}
{-| Add a tooltip for a specific item.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.product) ]
[ C.series .year
[ C.scatter .income [] ]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 56000 }
, { year = 2020, income = 62000 }
]
, C.each model.hovering <| \plane product ->
[ C.tooltip product [] [] [] ]
]
Customizations:
C.tooltip item
[ -- Change direction
CA.onTop -- Always place tooltip on top of the item
, CA.onBottom -- Always place tooltip below of the item
, CA.onRight -- Always place tooltip on the right of the item
, CA.onLeft -- Always place tooltip on the left of the item
, CA.onLeftOrRight -- Place tooltip on the left or right of the item,
-- depending on which side has more space available
, CA.onTopOrBottom -- Place tooltip on the top or bottom of the item,
-- depending on which side has more space available
-- Change focal point (where on the item the tooltip is achored)
, CA.top
, CA.bottom
, CA.left
, CA.right
, CA.center
, CA.topLeft
, CA.topRight
, CA.topCenter
, CA.bottomLeft
, CA.bottomRight
, CA.bottomCenter
, CA.leftCenter
, CA.rightCenter
, CA.offset 20 -- Change offset between focal point and tooltip
, CA.noArrow -- Remove little box arrow
, CA.border "blue" -- Change border color
, CA.background -- Change background color
]
[] -- Add any HTML attributes
[] -- Add any HTML children (Will be filled with default tooltip if left empty)
-}
tooltip : Item.Item a -> List (Attribute Tooltip) -> List (H.Attribute Never) -> List (H.Html Never) -> Element data msg
tooltip i edits attrs_ content =
html <| \p ->
let pos = Item.getLimits i
content_ = if content == [] then Item.toHtml i else content
in
if IS.isWithinPlane p pos.x1 pos.y2 -- TODO
then CS.tooltip p (Item.getPosition p i) edits attrs_ content_
else H.text ""
-- AXIS
{-| -}
type alias Axis =
{ limits : List (Attribute C.Axis)
, pinned : C.Axis -> Float
, arrow : Bool
, color : String
, width : Float
}
{-| Add an x-axis line to your chart. The example below illustrates
the styling options:
C.chart []
[ C.xAxis
[ CA.color "red" -- Change color of line
, CA.width 2 -- Change width of line
, CA.noArrow -- Remove arrow from line
, CA.pinned .max -- Change what y position the axis is set at
-- .max is at the very top
-- .min is at the very bottom
-- CA.zero is the closest you can go to zero
-- (always 3) is at y = 3.
, CA.limits
[ CA.lowest 2 CA.exactly
, CA.highest 8 CA.exactly
]
-- Change from where to where you line goes.
-- The example will make a line where x1 = 2 to x2 = 8
]
]
-}
xAxis : List (Attribute Axis) -> Element item msg
xAxis edits =
let config =
Helpers.apply edits
{ limits = []
, pinned = CA.zero
, color = ""
, arrow = True
, width = 1
}
addTickValues p ts =
{ ts | yAxis = config.pinned p.y :: ts.yAxis }
in
AxisElement addTickValues <| \p ->
let xLimit = List.foldl (\f x -> f x) p.x config.limits in
S.g
[ SA.class "elm-charts__x-axis" ]
[ CS.line p
[ CA.color config.color
, CA.width config.width
, CA.y1 (config.pinned p.y)
, CA.x1 (max p.x.min xLimit.min)
, CA.x2 (min p.x.max xLimit.max)
]
, if config.arrow then
CS.arrow p
[ CA.color config.color ]
{ x = xLimit.max
, y = config.pinned p.y
}
else
S.text ""
]
{-| Add an y-axis line to your chart. The styling options are the same
as for `xAxis`.
-}
yAxis : List (Attribute Axis) -> Element item msg
yAxis edits =
let config =
Helpers.apply edits
{ limits = []
, pinned = CA.zero
, color = ""
, arrow = True
, width = 1
}
addTickValues p ts =
{ ts | xAxis = config.pinned p.x :: ts.xAxis }
in
AxisElement addTickValues <| \p ->
let yLimit = List.foldl (\f y -> f y) p.y config.limits in
S.g
[ SA.class "elm-charts__y-axis" ]
[ CS.line p
[ CA.color config.color
, CA.width config.width
, CA.x1 (config.pinned p.x)
, CA.y1 (max p.y.min yLimit.min)
, CA.y2 (min p.y.max yLimit.max)
]
, if config.arrow then
CS.arrow p [ CA.color config.color, CA.rotate -90 ]
{ x = config.pinned p.x
, y = yLimit.max
}
else
S.text ""
]
type alias Ticks =
{ color : String
, height : Float
, width : Float
, pinned : C.Axis -> Float
, limits : List (Attribute C.Axis)
, amount : Int
, flip : Bool
, grid : Bool
, generate : IS.TickType
}
{-| Produce a set of ticks at "nice" numbers on the x-axis of your chart.
The example below illustrates the configuration:
C.chart []
[ C.xTicks
[ CA.color "red" -- Change color
, CA.height 8 -- Change height
, CA.width 2 -- Change width
, CA.amount 15 -- Change amount of ticks
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each tick. This removes them.
, CA.ints -- Add ticks at "nice" ints
, CA.times Time.utc -- Add ticks at "nice" times
, CA.pinned .max -- Change what y position the ticks are set at
-- .max is at the very top
-- .min is at the very bottom
-- CA.zero is the closest you can go to zero
-- (always 3) is at y = 3.
, CA.limits
[ CA.lowest 2 CA.exactly
, CA.highest 8 CA.exactly
]
-- Change the upper and lower limit of your tick range.
-- The example will add ticks between x = 2 and 8.
]
]
-}
xTicks : List (Attribute Ticks) -> Element item msg
xTicks edits =
let config =
Helpers.apply edits
{ color = ""
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, height = 5
, flip = False
, grid = True
, width = 1
}
toTicks p =
List.foldl (\f x -> f x) p.x config.limits
|> generateValues config.amount config.generate Nothing
|> List.map .value
addTickValues p ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ toTicks p }
in
TicksElement addTickValues <| \p ->
let toTick x =
CS.xTick p
[ CA.color config.color
, CA.length (if config.flip then -config.height else config.height)
, CA.width config.width
]
{ x = x
, y = config.pinned p.y
}
in
S.g [ SA.class "elm-charts__x-ticks" ] <| List.map toTick (toTicks p)
{-| Produce a set of ticks at "nice" numbers on the y-axis of your chart.
The styling options are the same as for `xTicks`.
-}
yTicks : List (Attribute Ticks) -> Element item msg
yTicks edits =
let config =
Helpers.apply edits
{ color = ""
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, height = 5
, flip = False
, grid = True
, width = 1
}
toTicks p =
List.foldl (\f y -> f y) p.y config.limits
|> generateValues config.amount config.generate Nothing
|> List.map .value
addTickValues p ts =
{ ts | ys = ts.ys ++ toTicks p }
in
TicksElement addTickValues <| \p ->
let toTick y =
CS.yTick p
[ CA.color config.color
, CA.length (if config.flip then -config.height else config.height)
, CA.width config.width
]
{ x = config.pinned p.x
, y = y
}
in
S.g [ SA.class "elm-charts__y-ticks" ] <| List.map toTick (toTicks p)
type alias Labels =
{ color : String
, pinned : C.Axis -> Float
, limits : List (Attribute C.Axis)
, xOff : Float
, yOff : Float
, flip : Bool
, amount : Int
, anchor : Maybe IS.Anchor
, generate : IS.TickType
, fontSize : Maybe Int
, uppercase : Bool
, format : Maybe (Float -> String)
, rotate : Float
, grid : Bool
}
{-| Produce a set of labels at "nice" numbers on the x-axis of your chart.
The example below illustrates the configuration:
C.chart []
[ C.xLabels
[ CA.color "red" -- Change color
, CA.fontSize 12 -- Change font size
, CA.uppercase -- Make labels uppercase
, CA.rotate 90 -- Rotate labels
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.amount 15 -- Change amount of ticks
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each label. This removes them.
, CA.ints -- Add ticks at "nice" ints
, CA.times Time.utc -- Add ticks at "nice" times
, CA.format (\num -> String.fromFloat num ++ "°")
-- Format the "nice" number
, CA.pinned .max -- Change what y position the labels are set at
-- .max is at the very top
-- .min is at the very bottom
-- CA.zero is the closest you can go to zero
-- (always 3) is at y = 3.
, CA.limits
[ CA.lowest 2 CA.exactly
, CA.highest 8 CA.exactly
]
-- Change the upper and lower limit of your labels range.
-- The example will add labels between x = 2 and 8.
]
]
For more in depth and irregular customization, see `xLabel`.
-}
xLabels : List (Attribute Labels) -> Element item msg
xLabels edits =
let toConfig p =
Helpers.apply edits
{ color = "#808BAB"
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, flip = False
, anchor = Nothing
, xOff = 0
, yOff = 18
, grid = True
, format = Nothing
, uppercase = False
, rotate = 0
, fontSize = Nothing
}
toTicks p config =
List.foldl (\f x -> f x) p.x config.limits
|> generateValues config.amount config.generate config.format
toTickValues p config ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ List.map .value (toTicks p config) }
in
LabelsElement toConfig toTickValues <| \p config ->
let default = IS.defaultLabel
toLabel item =
IS.label p
{ default
| xOff = config.xOff
, yOff = if config.flip then -config.yOff + 10 else config.yOff
, color = config.color
, anchor = config.anchor
, fontSize = config.fontSize
, uppercase = config.uppercase
, rotate = config.rotate
}
[ S.text item.label ]
{ x = item.value
, y = config.pinned p.y
}
in
S.g [ SA.class "elm-charts__x-labels" ] (List.map toLabel (toTicks p config))
{-| Produce a set of labels at "nice" numbers on the y-axis of your chart.
The styling options are the same as for `xLabels`.
-}
yLabels : List (Attribute Labels) -> Element item msg
yLabels edits =
let toConfig p =
Helpers.apply edits
{ color = "#808BAB"
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, anchor = Nothing
, flip = False
, xOff = -10
, yOff = 3
, grid = True
, format = Nothing
, uppercase = False
, fontSize = Nothing
, rotate = 0
}
toTicks p config =
List.foldl (\f y -> f y) p.y config.limits
|> generateValues config.amount config.generate config.format
toTickValues p config ts =
if not config.grid then ts else
{ ts | ys = ts.ys ++ List.map .value (toTicks p config) }
in
LabelsElement toConfig toTickValues <| \p config ->
let default = IS.defaultLabel
toLabel item =
IS.label p
{ default
| xOff = if config.flip then -config.xOff else config.xOff
, yOff = config.yOff
, color = config.color
, fontSize = config.fontSize
, uppercase = config.uppercase
, rotate = config.rotate
, anchor =
case config.anchor of
Nothing -> Just (if config.flip then IS.Start else IS.End)
Just anchor -> Just anchor
}
[ S.text item.label ]
{ x = config.pinned p.x
, y = item.value
}
in
S.g [ SA.class "elm-charts__y-labels" ] (List.map toLabel (toTicks p config))
{-| -}
type alias Label =
{ x : Float
, y : Float
, xOff : Float
, yOff : Float
, border : String
, borderWidth : Float
, fontSize : Maybe Int
, color : String
, anchor : Maybe IS.Anchor
, rotate : Float
, uppercase : Bool
, flip : Bool
, grid : Bool
}
{-| Produce a single x label. This is typically for cases where you need
very custom labels and `xLabels` does not cut it. It is especially useful
in combination with the `generate` helper. An example use case:
C.chart []
[ -- Create labels for 10 "nice" integers on the x-axis
-- and highlight the label at x = 0.
C.generate 10 C.ints .x [] <| \plane int ->
let color = if int == 0 then "red" else "gray" in
[ C.xLabel
[ CA.x (toFloat int), CA.color color ]
[ S.text (String.fromInt int) ]
]
]
A full list of possible attributes:
C.chart []
[ C.xLabel
[ CA.x 5 -- Set x coordinate
, CA.y 8 -- Set y coordinate
, CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.border "white" -- Set stroke color
, CA.borderWidth 0.5 -- Set stroke width
, CA.fontSize 12 -- Set font size
, CA.color "red" -- Set color
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each label. This removes it.
]
[ S.text "hello!" ]
]
-}
xLabel : List (Attribute Label) -> List (S.Svg msg) -> Element data msg
xLabel edits inner =
let toConfig p =
Helpers.apply edits
{ x = CA.middle p.x
, y = CA.zero p.y
, xOff = 0
, yOff = 20
, border = "white"
, borderWidth = 0.1
, uppercase = False
, fontSize = Nothing
, color = "#808BAB"
, anchor = Nothing
, rotate = 0
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ [ config.x ] }
in
LabelElement toConfig toTickValues <| \p config ->
let string =
if inner == []
then [ S.text (String.fromFloat config.x) ]
else inner
in
IS.label p
{ xOff = config.xOff
, yOff = if config.flip then -config.yOff + 10 else config.yOff
, border = config.border
, borderWidth = config.borderWidth
, fontSize = config.fontSize
, uppercase = config.uppercase
, color = config.color
, anchor = config.anchor
, rotate = config.rotate
, attrs = []
}
string
{ x = config.x, y = config.y }
{-| Produce a single y label. This is typically for cases where you need
very custom labels and `yLabels` does not cut it. See `xLabel` for
usage and customization.
-}
yLabel : List (Attribute Label) -> List (S.Svg msg) -> Element data msg
yLabel edits inner =
let toConfig p =
Helpers.apply edits
{ x = CA.zero p.x
, y = CA.middle p.y
, xOff = -8
, yOff = 3
, border = "white"
, borderWidth = 0.1
, uppercase = False
, fontSize = Nothing
, color = "#808BAB"
, anchor = Nothing
, rotate = 0
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | ys = ts.ys ++ [ config.y ] }
in
LabelElement toConfig toTickValues <| \p config ->
let string =
if inner == []
then [ S.text (String.fromFloat config.y) ]
else inner
in
IS.label p
{ xOff = if config.flip then -config.xOff else config.xOff
, yOff = config.yOff
, border = config.border
, borderWidth = config.borderWidth
, fontSize = config.fontSize
, uppercase = config.uppercase
, color = config.color
, anchor =
case config.anchor of
Nothing -> Just (if config.flip then IS.Start else IS.End)
Just anchor -> Just anchor
, rotate = config.rotate
, attrs = []
}
string
{ x = config.x, y = config.y }
{-| -}
type alias Tick =
{ x : Float
, y : Float
, color : String
, width : Float
, length : Float
, flip : Bool
, grid : Bool
}
{-| Produce a single x tick. This is typically for cases where you need
very custom ticks and `xTicks` does not cut it. It is especially useful
in combination with the `generate` helper. An example use case:
C.chart []
[ -- Create ticks for 10 "nice" integers on the x-axis
-- and highlight the tick at x = 0.
C.generate 10 C.ints .x [] <| \plane int ->
let color = if int == 0 then "red" else "gray" in
[ C.xTick [ CA.x (toFloat int), CA.color color ] ]
]
A full list of possible attributes:
C.xTick
[ CA.x 5 -- Set x coordinate
, CA.y 8 -- Set y coordinate
, CA.color "red" -- Change color
, CA.height 8 -- Change height
, CA.width 2 -- Change width
, CA.amount 15 -- Change amount of ticks
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each tick. This removes them.
]
-}
xTick : List (Attribute Tick) -> Element data msg
xTick edits =
let toConfig p =
Helpers.apply edits
{ x = CA.middle p.x
, y = CA.zero p.y
, length = 5
, color = "rgb(210, 210, 210)"
, width = 1
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ [ config.x ] }
in
TickElement toConfig toTickValues <| \p config ->
CS.xTick p
[ CA.length (if config.flip then -config.length else config.length)
, CA.color config.color
, CA.width config.width
]
{ x = config.x, y = config.y }
{-| Produce a single y tick. This is typically for cases where you need
very custom ticks and `yTicks` does not cut it. See `xTick` for
usage and customization.
-}
yTick : List (Attribute Tick) -> Float -> Element data msg
yTick edits val =
let toConfig p =
Helpers.apply edits
{ x = CA.middle p.x
, y = CA.zero p.y
, length = 5
, color = "rgb(210, 210, 210)"
, width = 1
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | ys = ts.ys ++ [ config.y ] }
in
TickElement toConfig toTickValues <| \p config ->
CS.yTick p
[ CA.length (if config.flip then -config.length else config.length)
, CA.color config.color
, CA.width config.width
]
{ x = config.x, y = config.y }
type alias Grid =
{ color : String
, width : Float
, dotGrid : Bool
, dashed : List Float
}
{-| Add a grid to your chart.
C.chart []
[ C.grid []
, C.xLabels []
, C.yLabels []
]
Grid lines are added where labels or ticks are added.
Customizations:
C.grid
[ CA.color "blue" -- Change color
, CA.width 3 -- Change width
, CA.dashed [ 5, 5 ] -- Add dashing (only for line grids)
, CA.dotGrid -- Use dot grid instead of line grid
]
-}
grid : List (Attribute Grid) -> Element item msg
grid edits =
let config =
Helpers.apply edits
{ color = ""
, width = 0
, dotGrid = False
, dashed = []
}
color =
if String.isEmpty config.color then
if config.dotGrid then Helpers.darkGray else Helpers.gray
else
config.color
width =
if config.width == 0 then
if config.dotGrid then 0.5 else 1
else
config.width
toXGrid vs p v =
if List.member v vs.xAxis
then Nothing else Just <|
CS.line p [ CA.color color, CA.width width, CA.x1 v, CA.dashed config.dashed ]
toYGrid vs p v =
if List.member v vs.yAxis
then Nothing else Just <|
CS.line p [ CA.color color, CA.width width, CA.y1 v, CA.dashed config.dashed ]
toDot vs p x y =
if List.member x vs.xAxis || List.member y vs.yAxis
then Nothing
else Just <| CS.dot p .x .y [ CA.color color, CA.size width, CA.circle ] { x = x, y = y }
in
GridElement <| \p vs ->
S.g [ SA.class "elm-charts__grid" ] <|
if config.dotGrid then
List.concatMap (\x -> List.filterMap (toDot vs p x) vs.ys) vs.xs
else
[ S.g [ SA.class "elm-charts__x-grid" ] (List.filterMap (toXGrid vs p) vs.xs)
, S.g [ SA.class "elm-charts__y-grid" ] (List.filterMap (toYGrid vs p) vs.ys)
]
-- PROPERTIES
{-| A property of a bar, line, or scatter series.
-}
type alias Property data inter deco =
P.Property data String inter deco
{-| Specify the configuration of a bar. The first argument will determine the height of
your bar. The second is a list of styling attributes. The example below illustrates what
styling options are available.
C.chart []
[ C.bars []
[ C.bar .income
[ CA.color "blue" -- Change the color
, CA.border "darkblue" -- Change the border color
, CA.borderWidth 2 -- Change the border width
, CA.opacity 0.7 -- Change the border opacity
-- A bar can either be solid (default), striped, dotted, or gradient.
, CA.striped
[ CA.width 2 -- Width of each stripe
, CA.spacing 3 -- Spacing bewteen each stripe
, CA.color "blue" -- Color of stripe
, CA.rotate 90 -- Angle of stripe
]
, CA.dotted []
-- Same configurations as `striped`
, CA.gradient
[ "blue", "darkblue" ] -- List of colors in gradient
, CA.roundTop 0.2 -- Round the top corners
, CA.roundBottom 0.2 -- Round the bottom corners
-- You can highlight a bar or a set of bars by adding a kind of "aura" to it.
, CA.highlight 0.5 -- Determine the opacity of the aura
, CA.highlightWidth 5 -- Determine the width of the aura
, CA.highlightColor "blue" -- Determine the color of the aura
-- Add arbitrary SVG attributes to your bar
, CA.attrs [ SA.strokeOpacity "0.5" ]
]
]
[ { income = 10 }
, { income = 12 }
, { income = 18 }
]
]
-}
bar : (data -> Float) -> List (Attribute CS.Bar) -> Property data inter CS.Bar
bar y =
P.property (y >> Just) []
{-| Same as `bar`, but allows for missing data.
C.chart []
[ C.bars []
[ C.barMaybe .income [] ]
[ { income = Just 10 }
, { income = Nothing }
, { income = Just 18 }
]
]
-}
barMaybe : (data -> Maybe Float) -> List (Attribute CS.Bar) -> Property data inter CS.Bar
barMaybe y =
P.property y []
{-| Specify the configuration of a set of dots. The first argument will determine the y value of
your dots. The second is a list of styling attributes. The example below illustrates what styling
options are available.
C.series .year
[ C.scatter .income
[ CA.size 10 -- Change size of dot
, CA.color "blue" -- Change color
, CA.opacity 0.8 -- Change opacity
, CA.border "lightblue" -- Change border color
, CA.borderWidth 2 -- Change border width
-- You can highlight a dot or a set of dots by adding a kind of "aura" to it.
, CA.highlight 0.3 -- Determine the opacity of the aura
, CA.highlightWidth 6 -- Determine the width of the aura
, CA.highlightColor "blue" -- Determine the color of the aura
-- A dot is by default a circle, but you can change it to any
-- of the shapes below.
, CA.triangle
, CA.square
, CA.diamond
, CA.plus
, CA.cross
]
]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 57000 }
, { year = 2020, income = 62000 }
]
-}
scatter : (data -> Float) -> List (Attribute CS.Dot) -> Property data inter CS.Dot
scatter y =
P.property (y >> Just) []
{-| Same as `scatter`, but allows for missing data.
C.chart []
[ C.series .year
[ C.scatterMaybe .income [] ]
[ { year = 2000, income = Just 40000 }
, { year = 2010, income = Nothing }
, { year = 2020, income = Just 62000 }
]
]
-}
scatterMaybe : (data -> Maybe Float) -> List (Attribute CS.Dot) -> Property data inter CS.Dot
scatterMaybe y =
P.property y []
{-| Specify the configuration of a interpolated series (a line). The first argument will determine
the y value of your dots. The second is a list of attributes pertaining to your interpolation. The
third argument is a list of attributes pertaining to the dots of your series.
The example below illustrates what styling options are available.
C.series .age
[ C.interpolated .height
[ -- The following attributes allow alternatives to the default
-- linear interpolation.
CA.monotone -- Use a monotone interpolation (looks smooth)
, CA.stepped -- Use a stepped interpolation (looks like stairs)
, CA.color "blue"
, CA.width 2
, CA.dashed [ 4, 4 ]
-- The area beneath the curve is by default transparent, but you
-- can change the opacity of it, or make it striped, dotted, or gradient.
, CA.opacity 0.5
, CA.striped
[ CA.width 2 -- Width of each stripe
, CA.spacing 3 -- Spacing bewteen each stripe
, CA.color "blue" -- Color of stripe
, CA.rotate 90 -- Angle of stripe
]
, CA.dotted [] -- Same configurations as `striped`
, CA.gradient [ "blue", "darkblue" ] -- List of colors in gradient
-- Add arbitrary SVG attributes to your line
, CA.attrs [ SA.id "my-chart" ]
]
[]
]
[ { age = 0, height = 40 }
, { age = 5, height = 80 }
, { age = 10, height = 120 }
, { age = 15, height = 180 }
, { age = 20, height = 184 }
]
-}
interpolated : (data -> Float) -> List (Attribute CS.Interpolation) -> List (Attribute CS.Dot) -> Property data CS.Interpolation CS.Dot
interpolated y inter =
P.property (y >> Just) ([ CA.linear ] ++ inter)
{-| Same as `interpolated`, but allows for missing data.
C.chart []
[ C.series .age
[ C.interpolatedMaybe .height [] ]
[ { age = 0, height = Just 40 }
, { age = 5, height = Nothing }
, { age = 10, height = Just 120 }
, { age = 15, height = Just 180 }
, { age = 20, height = Just 184 }
]
]
-}
interpolatedMaybe : (data -> Maybe Float) -> List (Attribute CS.Interpolation) -> List (Attribute CS.Dot) -> Property data CS.Interpolation CS.Dot
interpolatedMaybe y inter =
P.property y ([ CA.linear ] ++ inter)
{-| Name a bar, scatter, or interpolated series. This name will show up
in the default tooltip, and you can use it to identify items from this series.
C.chart []
[ C.series .year
[ C.scatter .income []
|> C.named "Income"
]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 48000 }
, { year = 2020, income = 62000 }
]
]
-}
named : String -> Property data inter deco -> Property data inter deco
named name =
P.meta name
{-| Change the style of your bars or dots based on the index of its data point
and the data point itself.
C.chart []
[ C.series .year
[ C.scatter .income [ CA.opacity 0.6 ]
|> C.variation (\index datum -> [ CA.size datum.people ])
]
[ { year = 2000, income = 40000, people = 150 }
, { year = 2010, income = 48000, people = 98 }
, { year = 2020, income = 62000, people = 180 }
]
]
-}
variation : (Int -> data -> List (Attribute deco)) -> Property data inter deco -> Property data inter deco
variation func =
P.variation <| \_ _ index _ datum -> func index datum
{-| Change the style of your bars or dots based on whether it is a member
of the group of products which you list. A such group of products can be
attrained through events like `Chart.Events.onMouseMove` or similar.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.dot) ]
[ C.series .year
[ C.scatter .income [ CA.opacity 0.6 ]
|> C.amongst model.hovering (\datum -> [ CA.highlight 0.5 ])
]
[ { year = 2000, income = 40000, people = 150 }
, { year = 2010, income = 48000, people = 98 }
, { year = 2020, income = 62000, people = 180 }
]
]
-}
amongst : List (CE.Product config value data) -> (data -> List (Attribute deco)) -> Property data inter deco -> Property data inter deco
amongst inQuestion func =
P.variation <| \p s i meta d ->
let check product =
if Item.getPropertyIndex product == p &&
Item.getStackIndex product == s &&
Item.getDataIndex product == i &&
Item.getDatum product == d
then func d else []
in
List.concatMap check inQuestion
{-| Stack a set of bar or line series.
C.chart []
[ C.bars []
[ C.stacked
[ C.bar .cats []
, C.bar .dogs []
]
]
[ { cats = 2, dogs = 4 }
, { cats = 3, dogs = 2 }
, { cats = 6, dogs = 1 }
]
]
-}
stacked : List (Property data inter deco) -> Property data inter deco
stacked =
P.stacked
-- LABEL EXTRAS
{-| -}
type alias ItemLabel a =
{ xOff : Float
, yOff : Float
, border : String
, borderWidth : Float
, fontSize : Maybe Int
, color : String
, anchor : Maybe IS.Anchor
, rotate : Float
, uppercase : Bool
, attrs : List (S.Attribute Never)
, position : CS.Plane -> a -> CS.Point
, format : Maybe (a -> String)
}
defaultLabel : ItemLabel (CE.Item a)
defaultLabel =
{ xOff = IS.defaultLabel.xOff
, yOff = IS.defaultLabel.yOff
, border = IS.defaultLabel.border
, borderWidth = IS.defaultLabel.borderWidth
, fontSize = IS.defaultLabel.fontSize
, color = IS.defaultLabel.color
, anchor = IS.defaultLabel.anchor
, rotate = IS.defaultLabel.rotate
, uppercase = IS.defaultLabel.uppercase
, attrs = IS.defaultLabel.attrs
, position = CE.getBottom
, format = Nothing
}
toLabelFromItemLabel : ItemLabel (CE.Item a) -> CS.Label
toLabelFromItemLabel config =
{ xOff = config.xOff
, yOff = config.yOff
, color = config.color
, border = config.border
, borderWidth = config.borderWidth
, anchor = config.anchor
, fontSize = config.fontSize
, uppercase = config.uppercase
, rotate = config.rotate
, attrs = config.attrs
}
{-| Add labels by every bin.
C.chart []
[ C.bars [] [ C.bar .income [] ]
[ { name = "<NAME>", income = 60 }
, { name = "<NAME>", income = 70 }
, { name = "<NAME>", income = 80 }
]
, C.binLabels .name [ CA.moveDown 15 ]
]
Attributes you can use:
C.binLabels .name
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-bin-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Given the entire bin item (not just the data)
-- produce a string.
, CA.format (\bin -> String.fromFloat (CE.getCommonality bin).start)
]
-}
binLabels : (data -> String) -> List (Attribute (ItemLabel (CE.Group (CE.Bin data) CE.Bar (Maybe Float) data))) -> Element data msg
binLabels toLabel edits =
eachCustom (CE.collect CE.bin CE.bar) <| \p item ->
let config =
Helpers.apply edits defaultLabel
text =
case config.format of
Just formatting -> formatting item
Nothing -> toLabel (CE.getCommonality item).datum
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
{-| Add labels by every bar.
C.chart []
[ C.bars []
[ C.bar .income [] ]
[ { name = "<NAME>", income = 60 }
, { name = "<NAME>", income = 70 }
, { name = "<NAME>", income = 80 }
]
, C.barLabels [ CA.moveUp 6 ]
]
Attributes you can use:
C.barLabels
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-bar-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Change the text of the label
, CA.format (\bar -> String.fromFloat (CE.getDependent bar))
]
-}
barLabels : List (Attribute (ItemLabel (CE.Product CE.Bar Float data))) -> Element data msg
barLabels edits =
eachBar <| \p item ->
let config =
Helpers.apply edits { defaultLabel | position = CE.getTop }
text =
case config.format of
Just formatting -> formatting item
Nothing -> String.fromFloat (CE.getDependent item)
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
{-| Helper to add a label by a particular product.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.bar) ]
[ C.bars []
[ C.bar .income [] ]
[ { name = "<NAME>", income = 60 }
, { name = "<NAME>", income = 70 }
, { name = "<NAME>", income = 80 }
]
, C.each model.hovering <| \_ bar ->
[ C.productLabel [ CA.moveUp 6 ] bar ]
]
Attributes you can use:
C.productLabel
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-bar-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Change the text of the label
, CA.format (\bar -> String.fromFloat (CE.getDependent bar))
]
product
-}
productLabel : List (Attribute (ItemLabel (CE.Product config value data))) -> CE.Product config value data -> Element data msg
productLabel edits item =
withPlane <| \p ->
let config =
Helpers.apply edits { defaultLabel | position = CE.getTop }
text =
case config.format of
Just formatting -> formatting item
Nothing -> String.fromFloat (Item.getDependentSafe item)
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
{-| Add labels by every bar.
C.chart []
[ C.series .age
[ C.scatter .income [] ]
[ { age = 34, income = 60 }
, { age = 42, income = 70 }
, { age = 48, income = 80 }
]
, C.dotLabels CE.getCenter [ CA.moveUp 6 ]
]
Attributes you can use:
C.dotLabels
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-dot-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Change the text of the label
, CA.format (\dot -> String.fromFloat (CE.getDependent dot))
]
-}
dotLabels : List (Attribute (ItemLabel (CE.Product CE.Dot Float data))) -> Element data msg
dotLabels edits =
eachDot <| \p item ->
let config =
Helpers.apply edits { defaultLabel | position = CE.getCenter }
text =
case config.format of
Just formatting -> formatting item
Nothing -> String.fromFloat (Item.getDependent item)
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
-- BARS
{-| -}
type alias Bars data =
{ spacing : Float
, margin : Float
, roundTop : Float
, roundBottom : Float
, grouped : Bool
, grid : Bool
, x1 : Maybe (data -> Float)
, x2 : Maybe (data -> Float)
}
{-| Add a bar series to your chart. Each `data` in your `List data` is a "bin". For
each "bin", whatever number of bars your have specified in the second argument will
show up, side-by-side.
C.bars []
[ C.bar .income []
, C.bar .spending []
]
[ { income = 10, spending = 2 }
, { income = 12, spending = 6 }
, { income = 18, spending = 16 }
]
The example above will thus produce three bins, each containing two bars. You can make
your bars show up overlapping instead of side-by-side by using the `CA.ungroup`
attribute:
C.bars
[ CA.ungroup ]
[ C.bar .total []
, C.bar .gross []
, C.bar .net []
]
[ { net = 10, gross = 20, total = 50 }
, { net = 13, gross = 28, total = 63 }
, { net = 16, gross = 21, total = 82 }
]
By default, the x value of each bin is set by a simple count. The first bin is set at
x = 1, the second at x = 2, and so on. If you'd like to control what the x values of
your bins are, e.g. you are making a histogram, you may use the `CA.x1` and `CA.x2`
attributes, as illustrated below.
C.bars
[ CA.x1 .score
, CA.x2 (\datum -> datum.score + 20)
]
[ C.bar .students [] ]
[ { score = 0, students = 1 }
, { score = 20, students = 10 }
, { score = 40, students = 30 }
, { score = 60, students = 20 }
, { score = 80, students = 1 }
]
In this case, you actually only need to specify either `x1` or `x2` because the library
estimates the unknown x value based on the size of the previous or next bin. However, it comes in
handy to specify both when you have bins of irregular sizes.
The rest of the configuration options concern styling:
C.bars
[ CA.spacing 0.1 -- The spacing _between_ the bars in each bin relative to the full length (1).
, CA.margin 0.2 -- The spacing _around_ the bars in each bin relative to the full length (1).
, CA.roundTop 0.2 -- The rounding of your bars' top corners. It gets weird after around 0.5.
, CA.roundBottom 0.2 -- The rounding of your bars' bottom corners. It gets weird after around 0.5.
, CA.noGrid -- Grid lines are by default added at the bin limits. This removes them.
]
[ C.bar .income []
, C.bar .spending []
]
[ { income = 10, spending = 2 }
, { income = 12, spending = 6 }
, { income = 18, spending = 16 }
]
-}
bars : List (Attribute (Bars data)) -> List (Property data () CS.Bar) -> List data -> Element data msg
bars edits properties data =
barsMap identity edits properties data
{-| This is just like `bars`, but it maps your `data`. This is useful if you have
several kinds of data types present in your chart.
type Datum
= Money { year : Float, income : Float }
| People { year : Float, people : Float }
view : Html msg
view =
C.chart []
[ C.barsMap Money
[ CA.x1 .year ]
[ C.bar .income [] ]
[ { year = 2000, income = 200 }
, { year = 2010, income = 300 }
, { year = 2020, income = 500 }
]
, C.barsMap People
[ CA.x1 .year ]
[ C.bar .people [] ]
[ { year = 2000, people = 21 }
, { year = 2010, people = 65 }
, { year = 2020, people = 93 }
]
]
-}
barsMap : (data -> a) -> List (Attribute (Bars data)) -> List (Property data () CS.Bar) -> List data -> Element a msg
barsMap mapData edits properties data =
Indexed <| \index ->
let barsConfig =
Helpers.apply edits Produce.defaultBars
items =
Produce.toBarSeries index edits properties data
generalized =
List.concatMap Group.getGenerals items
|> List.map (Item.map mapData)
bins =
CE.group CE.bin generalized
legends_ =
Legend.toBarLegends index edits properties
toTicks plane acc =
{ acc | xs = acc.xs ++
if barsConfig.grid then
List.concatMap (CE.getLimits >> \pos -> [ pos.x1, pos.x2 ]) bins
else
[]
}
toLimits =
List.map Item.getLimits bins
in
( BarsElement toLimits generalized legends_ toTicks <| \plane ->
S.g [ SA.class "elm-charts__bar-series" ] (List.map (Item.toSvg plane) items)
|> S.map never
, index + List.length (List.concatMap P.toConfigs properties)
)
-- SERIES
{-| Add a scatter or line series to your chart. Each `data` in your `List data` will result in one "dot".
The first argument of `series` determines the x value of each dot. The y value and all styling configuration
is determined by the list of `interpolated` or `scatter` properties defined in the second argument.
C.series .age
[ C.interpolated .height [] []
, C.interpolated .weight [] []
]
[ { age = 0, height = 40, weight = 4 }
, { age = 5, height = 80, weight = 24 }
, { age = 10, height = 120, weight = 36 }
, { age = 15, height = 180, weight = 54 }
, { age = 20, height = 184, weight = 60 }
]
See `interpolated` and `scatter` for styling options.
-}
series : (data -> Float) -> List (Property data CS.Interpolation CS.Dot) -> List data -> Element data msg
series toX properties data =
seriesMap identity toX properties data
{-| This is just like `series`, but it maps your `data`. This is useful if you have
several kinds of data types present in your chart.
type Datum
= Height { age : Float, height : Float }
| Weight { age : Float, weight : Float }
view : Html msg
view =
C.chart []
[ C.seriesMap Height .age
[ C.interpolated .height [] ]
[ { age = 0, height = 40 }
, { age = 5, height = 80 }
, { age = 10, height = 120 }
, { age = 15, height = 180 }
]
, C.seriesMap Weight .age
[ C.interpolated .weight [] ]
[ { age = 0, weight = 4 }
, { age = 5, weight = 24 }
, { age = 10, weight = 36 }
, { age = 15, weight = 54 }
]
]
-}
seriesMap : (data -> a) -> (data -> Float) -> List (Property data CS.Interpolation CS.Dot) -> List data -> Element a msg
seriesMap mapData toX properties data =
Indexed <| \index ->
let items =
Produce.toDotSeries index toX properties data
generalized =
List.concatMap Group.getGenerals items
|> List.map (Item.map mapData)
legends_ =
Legend.toDotLegends index properties
toLimits =
List.map Item.getLimits items
in
( SeriesElement toLimits generalized legends_ <| \p ->
S.g [ SA.class "elm-charts__dot-series" ] (List.map (Item.toSvg p) items)
|> S.map never
, index + List.length (List.concatMap P.toConfigs properties)
)
-- OTHER
{-| Using the information about your coordinate system, add a list
of elements.
-}
withPlane : (C.Plane -> List (Element data msg)) -> Element data msg
withPlane func =
SubElements <| \p is -> func p
{-| Given all your bins, add a list of elements.
Use helpers in `Chart.Events` to interact with bins.
-}
withBins : (C.Plane -> List (CE.Group (CE.Bin data) CE.Any (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withBins func =
SubElements <| \p is -> func p (CE.group CE.bin is)
{-| Given all your stacks, add a list of elements.
Use helpers in `Chart.Events` to interact with stacks.
-}
withStacks : (C.Plane -> List (CE.Group (CE.Stack data) CE.Any (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withStacks func =
SubElements <| \p is -> func p (CE.group CE.stack is)
{-| Given all your bars, add a list of elements.
Use helpers in `Chart.Events` to interact with bars.
-}
withBars : (C.Plane -> List (CE.Product CE.Bar (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withBars func =
SubElements <| \p is -> func p (CE.group CE.bar is)
{-| Given all your dots, add a list of elements.
Use helpers in `Chart.Events` to interact with dots.
-}
withDots : (C.Plane -> List (CE.Product CE.Dot (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withDots func =
SubElements <| \p is -> func p (CE.group CE.dot is)
{-| Given all your products, add a list of elements.
Use helpers in `Chart.Events` to interact with products.
-}
withProducts : (C.Plane -> List (CE.Product CE.Any (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withProducts func =
SubElements <| \p is -> func p is
{-| Add elements for each item of whatever list in the first argument.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.product) ]
[ C.series .year
[ C.scatter .income [] ]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 56000 }
, { year = 2020, income = 62000 }
]
, C.each model.hovering <| \plane product ->
[ C.tooltip product [] [] [] ]
]
-}
each : List a -> (C.Plane -> a -> List (Element data msg)) -> Element data msg
each items func =
SubElements <| \p _ -> List.concatMap (func p) items
{-| Add elements for each bin.
C.chart []
[ C.bars []
[ C.bar .income []
, C.bar .spending []
]
[ { country = "Denmark", income = 40000, spending = 10000 }
, { country = "Sweden", income = 56000, spending = 12000 }
, { country = "Norway", income = 62000, spending = 18000 }
]
, C.eachBin <| \plane bin ->
let common = CE.getCommonality bin in
[ C.label [] [ S.text common.datum.country ] (CE.getBottom plane bin) ]
]
Use the functions in `Chart.Events` to access information about your bins.
-}
eachBin : (C.Plane -> CE.Group (CE.Bin data) CE.Any Float data -> List (Element data msg)) -> Element data msg
eachBin func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.collect CE.bin <| CE.keep CE.realValues CE.product) is)
{-| Add elements for each stack.
C.chart []
[ C.bars []
[ C.stacked
[ C.bar .income []
, C.bar .savings []
]
]
[ { income = 40000, savings = 10000 }
, { income = 56000, savings = 12000 }
, { income = 62000, savings = 18000 }
]
, C.eachStack <| \plane stack ->
let total = List.sum (List.map CE.getDependent (CE.getProducts stack)) in
[ C.label [] [ S.text (String.fromFloat total) ] (CE.getTop plane stack) ]
]
Use the functions in `Chart.Events` to access information about your stacks.
-}
eachStack : (C.Plane -> CE.Group (CE.Stack data) CE.Any Float data -> List (Element data msg)) -> Element data msg
eachStack func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.collect CE.stack <| CE.keep CE.realValues CE.product) is)
{-| Add elements for each bar.
C.chart []
[ C.bars []
[ C.bar .income []
, C.bar .spending []
]
[ { income = 40000, spending = 10000 }
, { income = 56000, spending = 12000 }
, { income = 62000, spending = 18000 }
]
, C.eachBar <| \plane bar ->
let yValue = CE.getDependent bar in
[ C.label [] [ S.text (String.fromFloat yValue) ] (CE.getTop plane bar) ]
]
Use the functions in `Chart.Events` to access information about your bars.
-}
eachBar : (C.Plane -> CE.Product CE.Bar Float data -> List (Element data msg)) -> Element data msg
eachBar func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.keep CE.realValues CE.bar) is)
{-| Add elements for each dot.
C.chart []
[ C.series []
[ C.scatter .income []
, C.scatter .spending []
]
[ { income = 40000, spending = 10000 }
, { income = 56000, spending = 12000 }
, { income = 62000, spending = 18000 }
]
, C.eachBar <| \plane bar ->
let yValue = CE.getDependent bar in
[ C.label [] [ S.text (String.fromFloat yValue) ] (CE.getTop plane bar) ]
]
Use the functions in `Chart.Events` to access information about your dots.
-}
eachDot : (C.Plane -> CE.Product CE.Dot Float data -> List (Element data msg)) -> Element data msg
eachDot func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.keep CE.realValues CE.dot) is)
{-| Add elements for each product. Works like `eachBar` and `eachDot`, but includes both
bars and dots.
Use the functions in `Chart.Events` to access information about your products.
-}
eachProduct : (C.Plane -> CE.Product CE.Any Float data -> List (Element data msg)) -> Element data msg
eachProduct func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.keep CE.realValues CE.product) is)
{-| Filter and group products in any way you'd like and add elements for each of them.
C.chart []
[ C.eachCustom (CE.named "cats") <| \plane product ->
[ C.label [] [ S.text "hello" ] (CE.getTop plane product) ]
]
The above example adds a label for each product of the series named "cats".
Use the functions in `Chart.Events` to access information about your items.
-}
eachCustom : CE.Grouping (CE.Product CE.Any (Maybe Float) data) a -> (C.Plane -> a -> List (Element data msg)) -> Element data msg
eachCustom grouping func =
SubElements <| \p items ->
let processed = CE.group grouping items in
List.concatMap (func p) processed
{-| Add legends to your chart.
C.chart []
[ C.series .x
[ C.line .y [] []
|> C.named "cats"
, C.line .y [] []
|> C.named "dogs"
]
, C.legendsAt .min .max
[ CA.column -- Appear as column instead of row
, CA.alignRight -- Anchor legends to the right
, CA.alignLeft -- Anchor legends to the left
, CA.moveUp 5 -- Move 5px up
, CA.moveDown 5 -- Move 5px down
, CA.moveLeft 5 -- Move 5px left
, CA.moveRight 5 -- Move 5px right
, CA.spacing 20 -- Spacing between legends
, CA.background "beige" -- Color background
, CA.border "gray" -- Add border
, CA.borderWidth 1 -- Set border width
-- Add arbitrary HTML attributes. Convinient for extra styling.
, CA.htmlAttrs [ HA.class "my-legend" ]
]
[ CA.width 30 -- Change width of legend window
, CA.height 30 -- Change height of legend window
, CA.fontSize 12 -- Change font size
, CA.color "red" -- Change font color
, CA.spacing 12 -- Change spacing between window and title
, CA.htmlAttrs [ HA.class "my-legends" ] -- Add arbitrary HTML attributes.
]
]
-}
legendsAt : (C.Axis -> Float) -> (C.Axis -> Float) -> List (Attribute (CS.Legends msg)) -> List (Attribute (CS.Legend msg)) -> Element data msg
legendsAt toX toY attrs children =
HtmlElement <| \p legends_ ->
let viewLegend legend =
case legend of
Legend.BarLegend name barAttrs -> CS.barLegend (CA.title name :: children) barAttrs
Legend.LineLegend name interAttrs dotAttrs -> CS.lineLegend (CA.title name :: children) interAttrs dotAttrs
in
CS.legendsAt p (toX p.x) (toY p.y) attrs (List.map viewLegend legends_)
{-| Generate "nice" numbers. Useful in combination with `xLabel`, `yLabel`, `xTick`, and `yTick`.
C.chart []
[ C.generate 10 C.ints .x [ CA.lowest -5 CA.exactly, CA.highest 15 CA.exactly ] <| \plane int ->
[ C.xTick [ CA.x (toFloat int) ]
, C.xLabel [ CA.x (toFloat int) ] [ S.text (String.fromInt int) ]
]
]
The example above generates 10 ints on the x axis between x = -5 and x = 15. For each of those
ints, it adds a tick and a label.
-}
generate : Int -> CS.Generator a -> (C.Plane -> C.Axis) -> List (Attribute C.Axis) -> (C.Plane -> a -> List (Element data msg)) -> Element data msg
generate num gen limit attrs func =
SubElements <| \p _ ->
let items = CS.generate num gen (List.foldl (\f x -> f x) (limit p) attrs) in
List.concatMap (func p) items
{-| Generate "nice" floats.
-}
floats : CS.Generator Float
floats =
CS.floats
{-| Generate "nice" ints.
-}
ints : CS.Generator Int
ints =
CS.ints
{-| Generate "nice" times.
See the docs in [terezka/intervals](https://package.elm-lang.org/packages/terezka/intervals/2.0.0/Intervals#Time)
for more info about the properties of `Time`!
-}
times : Time.Zone -> CS.Generator I.Time
times =
CS.times
{-| Add a label, such as a chart title or other note, at a specific coordinate.
C.chart []
[ C.label [] [ S.text "Data from Fruits.com" ] { x = 5, y = 10 } ]
The example above adds your label at coordinates x = y and y = 10.
Other attributes you can use:
C.labelAt
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-label" ]
]
[ S.text "Data from Fruits.com" ]
{ x = 5, y = 10 }
-}
label : List (Attribute CS.Label) -> List (S.Svg msg) -> C.Point -> Element data msg
label attrs inner point =
SvgElement <| \p -> CS.label p attrs inner point
{-| Add a label, such as a chart title or other note, at a position relative to your axes.
C.chart []
[ C.labelAt (CA.percent 20) (CA.percent 90) [] [ S.text "Data from Fruits.com" ] ]
The example above adds your label at 20% the length of your range and 90% of your domain.
Other attributes you can use:
C.labelAt (CA.percent 20) (CA.percent 90)
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-label" ]
]
[ S.text "Data from Fruits.com" ]
-}
labelAt : (C.Axis -> Float) -> (C.Axis -> Float) -> List (Attribute CS.Label) -> List (S.Svg msg) -> Element data msg
labelAt toX toY attrs inner =
SvgElement <| \p -> CS.label p attrs inner { x = toX p.x, y = toY p.y }
{-| Add a line.
C.chart []
[ C.line
[ CA.x1 2 -- Set x1
, CA.x2 8 -- Set x2
, CA.y1 3 -- Set y1
, CA.y2 7 -- Set y2
-- Instead of specifying x2 and y2
-- you can use `x2Svg` and `y2Svg`
-- to specify the end coordinate in
-- terms of SVG units.
--
-- Useful if making little label pointers.
-- This makes a from ( x1, y1 ) to the point
-- ( x1 + 15 SVG units, y1 + 30 SVG units )
, CA.x2Svg 15
, CA.y2Svg 30
, CA.break -- "break" line, so it it has a 90° angle
, CA.tickLength -- Add "ticks" at the ends of the line
, CA.tickDirection -- The angle of the ticks
, CA.color "red" -- Change color
, CA.width 2 -- Change width
, CA.opacity 0.8 -- Change opacity
, CA.dashed [ 5, 5 ] -- Add dashing
-- Add arbitrary SVG attributes.
, CA.attrs [ SA.id "my-line" ]
]
]
-}
line : List (Attribute CS.Line) -> Element data msg
line attrs =
SvgElement <| \p -> CS.line p attrs
{-| Add a rectangle.
C.chart []
[ C.rect
[ CA.x1 2 -- Set x1
, CA.x2 8 -- Set x2
, CA.y1 3 -- Set y1
, CA.y2 7 -- Set y2
, CA.color "#aaa" -- Change fill color
, CA.opacity 0.8 -- Change fill opacity
, CA.border "#333" -- Change border color
, CA.borderWidth 2 -- Change border width
-- Add arbitrary SVG attributes.
, CA.attrs [ SA.id "my-rect" ]
]
]
-}
rect : List (Attribute CS.Rect) -> Element data msg
rect attrs =
SvgElement <| \p -> CS.rect p attrs
{-| Add arbitrary SVG. See `Chart.Svg` for handy SVG helpers.
-}
svg : (C.Plane -> S.Svg msg) -> Element data msg
svg func =
SvgElement <| \p -> func p
{-| Add arbitrary HTML.
-}
html : (C.Plane -> H.Html msg) -> Element data msg
html func =
HtmlElement <| \p _ -> func p
{-| Add arbitrary SVG at a specific location. See `Chart.Svg` for handy SVG helpers.
C.chart []
[ C.svgAt .min .max 10 20 [ .. ]
-- Add .. at x = the minumum value of your range (x-axis) + 12 SVG units
-- and y = the maximum value of your domain (y-axis) + 20 SVG units
]
-}
svgAt : (C.Axis -> Float) -> (C.Axis -> Float) -> Float -> Float -> List (S.Svg msg) -> Element data msg
svgAt toX toY xOff yOff view =
SvgElement <| \p ->
S.g [ CS.position p 0 (toX p.x) (toY p.y) xOff yOff ] view
{-| Add arbitrary HTML at a specific location.
-}
htmlAt : (C.Axis -> Float) -> (C.Axis -> Float) -> Float -> Float -> List (H.Attribute msg) -> List (H.Html msg) -> Element data msg
htmlAt toX toY xOff yOff att view =
HtmlElement <| \p _ ->
CS.positionHtml p (toX p.x) (toY p.y) xOff yOff att view
{-| No element.
-}
none : Element data msg
none =
HtmlElement <| \_ _ -> H.text ""
-- DATA HELPERS
{-| Gather data points into bins. Arguments:
1. The desired bin width.
2. The function to access the binned quality on the data
3. The list of data.
C.binned 10 .score
[ Result "<NAME>" 43
, Result "<NAME>" 65
, Result "<NAME>" 69
, Result "<NAME>" 98
]
== [ { bin = 40, data = [ Result "<NAME>" 43 ] }
, { bin = 60, data = [ Result "<NAME>" 65, Result "<NAME>" 69 ] }
, { bin = 90, data = [ Result "<NAME>" 98 ] }
]
type alias Result = { name : String, score : Float }
-}
binned : Float -> (data -> Float) -> List data -> List { bin : Float, data : List data }
binned binWidth func data =
let fold datum =
Dict.update (toBin datum) (updateDict datum)
updateDict datum maybePrev =
case maybePrev of
Just prev -> Just (datum :: prev)
Nothing -> Just [ datum ]
toBin datum =
floor (func datum / binWidth)
in
List.foldr fold Dict.empty data
|> Dict.toList
|> List.map (\( bin, ds ) -> { bin = toFloat bin * binWidth, data = ds })
-- HELPERS
type alias TickValue =
{ value : Float
, label : String
}
generateValues : Int -> IS.TickType -> Maybe (Float -> String) -> C.Axis -> List TickValue
generateValues amount tick maybeFormat axis =
let toTickValues toValue toString =
List.map <| \i ->
{ value = toValue i
, label =
case maybeFormat of
Just format -> format (toValue i)
Nothing -> toString i
}
in
case tick of
IS.Floats ->
toTickValues identity String.fromFloat
(CS.generate amount CS.floats axis)
IS.Ints ->
toTickValues toFloat String.fromInt
(CS.generate amount CS.ints axis)
IS.Times zone ->
toTickValues (toFloat << Time.posixToMillis << .timestamp) (CS.formatTime zone)
(CS.generate amount (CS.times zone) axis)
| true | module Chart exposing
( chart
, Element, bars, series, seriesMap, barsMap
, Property, bar, scatter, interpolated
, barMaybe, scatterMaybe, interpolatedMaybe
, stacked, named, variation, amongst
, xAxis, yAxis, xTicks, yTicks, xLabels, yLabels, grid
, binLabels, barLabels, dotLabels, productLabel
, xLabel, yLabel, xTick, yTick
, generate, floats, ints, times
, label, labelAt, legendsAt
, tooltip, line, rect, none
, svg, svgAt, html, htmlAt
, each, eachBin, eachStack, eachBar, eachDot, eachProduct, eachCustom
, withPlane, withBins, withStacks, withBars, withDots, withProducts
, binned
)
{-| Alpha version!
**See also the visual catalog of
examples at [elm-charts.org](https://www.elm-charts.org/documentation).**
The configuration of this charting library mirrors the pattern of HTML elements
and attributes. It looks something like this:
import Html exposing (Html)
import Chart as C
import Chart.Attributes as CA
view : Html msg
view =
C.chart
[ CA.width 300
, CA.height 300
]
[ C.grid []
, C.xLabels []
, C.yLabels []
, C.bars []
[ C.bar .income [ CA.color "red" ]
, C.bar .spending [ CA.opacity 0.8 ]
]
data
]
All the elements, like `chart`, `grid`, `xLabels`, `yLabels`, `bars` and `bar` in the example
above, are defined in this module. All the attributes, like `width`, `height`, `color`, and `opacity`,
are defined in `Chart.Attributes`. Attributes and other functions related to events are located in
the `Chart.Events` module. Lastly, `Chart.Svg` holds charting primitives in case you have very special
needs.
NOTE: Some of the more advanced elements utilize helper functions in `Chart.Events`
too. If that is the case, I will make a note in the comment of the element.
In the following examples, I will assume the imports:
import Html as H exposing (Html)
import Html.Attributes as HA
import Html.Events as HE
import Svg as S
import Svg.Attributes as SA
import Svg.Events as SE
import Chart as C
import Chart.Attributes as CA
import Chart.Events as CE
# The frame
@docs chart
@docs Element
# Chart elements
## Bar charts
@docs bars, barsMap, bar, barMaybe
## Scatter and line charts
@docs series, seriesMap, scatter, scatterMaybe, interpolated, interpolatedMaybe
## Stacking, naming, and variation
@docs Property, stacked, named, variation, amongst
# Navigation elements
## Axis lines
@docs xAxis, yAxis
## Axis ticks
@docs xTicks, yTicks
## Axis labels
@docs xLabels, yLabels
## Grid
@docs grid
## Custom Axis labels and ticks
@docs xLabel, yLabel, xTick, yTick
@docs generate, floats, ints, times
## Data labels
@docs binLabels, barLabels, dotLabels, productLabel
## General labels
@docs label, labelAt
## Legends
@docs legendsAt
## Other navigation helpers
@docs tooltip, line, rect
# Arbitrary elements
@docs svgAt, htmlAt, svg, html, none
# Advanced elements
## For each item, do..
@docs eachBin, eachStack, eachBar, eachDot, eachProduct, each, eachCustom
## With all item, do..
@docs withBins, withStacks, withBars, withDots, withProducts
## Using the plane, do..
@docs withPlane
# Data helper
@docs binned
-}
import Internal.Coordinates as C
import Svg as S
import Svg.Attributes as SA
import Svg.Events as SE
import Html as H
import Html.Attributes as HA
import Intervals as I
import Internal.Property as P
import Time
import Dict exposing (Dict)
import Internal.Item as Item
import Internal.Produce as Produce
import Internal.Legend as Legend
import Internal.Group as Group
import Internal.Helpers as Helpers
import Internal.Svg as IS
import Internal.Events as IE
import Chart.Svg as CS
import Chart.Attributes as CA exposing (Attribute)
import Chart.Events as CE
{-| -}
type alias Container data msg =
{ width : Float
, height : Float
, margin : { top : Float, bottom : Float, left : Float, right : Float }
, padding : { top : Float, bottom : Float, left : Float, right : Float }
, responsive : Bool
, range : List (Attribute C.Axis)
, domain : List (Attribute C.Axis)
, events : List (CE.Event data msg)
, htmlAttrs : List (H.Attribute msg)
, attrs : List (S.Attribute msg)
}
{-| This is the root element of your chart. All your chart elements must be contained in
a `chart` element. The below example illustrates what configurations are available for
the `chart` element.
view : Html msg
view =
C.chart
[ CA.width 300 -- Sets width of chart
, CA.height 500 -- Sets height of chart
, CA.static -- Don't scale with parent container
, CA.margin { top = 10, bottom = 20, left = 20, right = 20 }
-- Add space around your chart.
-- Useful if you have labels which extend
-- outside the main chart area.
, CA.padding { top = 10, bottom = 10, left = 10, right = 10 }
-- Expand your domain / range by a set
-- amount of SVG units.
-- Useful if you have e.g. scatter dots
-- which extend beyond your main chart area,
-- and you'd like them to be within.
-- Control the range and domain of your chart.
-- Your range and domain is by default set to the limits of
-- your data, but you can change them like this:
, CA.range
[ CA.lowest -5 CA.orLower
-- Makes sure that your x-axis begins at -5 or lower, no matter
-- what your data is like.
, CA.highest 10 CA.orHigher
-- Makes sure that your x-axis ends at 10 or higher, no matter
-- what your data is like.
]
, CA.domain
[ CA.lowest 0 CA.exactly ]
-- Makes sure that your y-axis begins at exactly 0, no matter
-- what your data is like.
-- Add event triggers to your chart. Learn more about these in
-- the `Chart.Events` module.
, CE.onMouseMove OnHovering (CE.getNearest C.bar)
, CE.onMouseLeave (OnHovering [])
-- Add arbitrary HTML and SVG attributes to your chart.
, CA.htmlAttrs [ HA.style "background" "beige" ]
, CA.attrs [ SA.id "my-chart" ]
]
[ C.grid []
, C.xLabels []
, C.yLabels []
, ..
]
-}
chart : List (Attribute (Container data msg)) -> List (Element data msg) -> H.Html msg
chart edits unindexedElements =
let config =
Helpers.apply edits
{ width = 300
, height = 300
, margin = { top = 0, bottom = 0, left = 0, right = 0 }
, padding = { top = 0, bottom = 0, left = 0, right = 0 }
, responsive = True
, range = []
, domain = []
, events = []
, attrs = [ SA.style "overflow: visible;" ]
, htmlAttrs = []
}
elements =
let toIndexedEl el ( acc, index ) =
case el of
Indexed toElAndIndex ->
let ( newEl, newIndex ) = toElAndIndex index in
( acc ++ [ newEl ], newIndex )
_ ->
( acc ++ [ el ], index )
in
List.foldl toIndexedEl ( [], 0 ) unindexedElements
|> Tuple.first
plane =
definePlane config elements
items =
getItems plane elements
legends_ =
getLegends elements
tickValues =
getTickValues plane items elements
( beforeEls, chartEls, afterEls ) =
viewElements config plane tickValues items legends_ elements
toEvent (IE.Event event_) =
let (IE.Decoder decoder) = event_.decoder in
IS.Event event_.name (decoder items)
in
IS.container plane
{ attrs = config.attrs
, htmlAttrs = config.htmlAttrs
, responsive = config.responsive
, events = List.map toEvent config.events
}
beforeEls
chartEls
afterEls
-- ELEMENTS
{-| The representation of a chart element.
-}
type Element data msg
= Indexed (Int -> ( Element data msg, Int ))
| SeriesElement
(List C.Position)
(List (Item.Product CE.Any (Maybe Float) data))
(List Legend.Legend)
(C.Plane -> S.Svg msg)
| BarsElement
(List C.Position)
(List (Item.Product CE.Any (Maybe Float) data))
(List Legend.Legend)
(C.Plane -> TickValues -> TickValues)
(C.Plane -> S.Svg msg)
| AxisElement
(C.Plane -> TickValues -> TickValues)
(C.Plane -> S.Svg msg)
| TicksElement
(C.Plane -> TickValues -> TickValues)
(C.Plane -> S.Svg msg)
| TickElement
(C.Plane -> Tick)
(C.Plane -> Tick -> TickValues -> TickValues)
(C.Plane -> Tick -> S.Svg msg)
| LabelsElement
(C.Plane -> Labels)
(C.Plane -> Labels -> TickValues -> TickValues)
(C.Plane -> Labels -> S.Svg msg)
| LabelElement
(C.Plane -> Label)
(C.Plane -> Label -> TickValues -> TickValues)
(C.Plane -> Label -> S.Svg msg)
| GridElement
(C.Plane -> TickValues -> S.Svg msg)
| SubElements
(C.Plane -> List (Item.Product CE.Any (Maybe Float) data) -> List (Element data msg))
| ListOfElements
(List (Element data msg))
| SvgElement
(C.Plane -> S.Svg msg)
| HtmlElement
(C.Plane -> List Legend.Legend -> H.Html msg)
definePlane : Container data msg -> List (Element data msg) -> C.Plane
definePlane config elements =
let collectLimits el acc =
case el of
Indexed _ -> acc
SeriesElement lims _ _ _ -> acc ++ lims
BarsElement lims _ _ _ _ -> acc ++ lims
AxisElement _ _ -> acc
TicksElement _ _ -> acc
TickElement _ _ _ -> acc
LabelsElement _ _ _ -> acc
LabelElement _ _ _ -> acc
GridElement _ -> acc
SubElements _ -> acc
ListOfElements subs -> List.foldl collectLimits acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
limits_ =
List.foldl collectLimits [] elements
|> C.foldPosition identity
|> \pos -> { x = toLimit pos.x1 pos.x2, y = toLimit pos.y1 pos.y2 }
|> \{ x, y } -> { x = fixSingles x, y = fixSingles y }
toLimit min max =
{ min = min, max = max, dataMin = min, dataMax = max }
fixSingles bs =
if bs.min == bs.max then { bs | max = bs.min + 10 } else bs
calcRange =
case config.range of
[] -> limits_.x
some -> List.foldl (\f b -> f b) limits_.x some
calcDomain =
case config.domain of
[] -> CA.lowest 0 CA.orLower limits_.y
some -> List.foldl (\f b -> f b) limits_.y some
unpadded =
{ width = max 1 (config.width - config.padding.left - config.padding.right)
, height = max 1 (config.height - config.padding.bottom - config.padding.top)
, margin = config.margin
, x = calcRange
, y = calcDomain
}
scalePadX =
C.scaleCartesianX unpadded
scalePadY =
C.scaleCartesianY unpadded
xMin = calcRange.min - scalePadX config.padding.left
xMax = calcRange.max + scalePadX config.padding.right
yMin = calcDomain.min - scalePadY config.padding.bottom
yMax = calcDomain.max + scalePadY config.padding.top
in
{ width = config.width
, height = config.height
, margin = config.margin
, x =
{ calcRange
| min = min xMin xMax
, max = max xMin xMax
}
, y =
{ calcDomain
| min = min yMin yMax
, max = max yMin yMax
}
}
getItems : C.Plane -> List (Element data msg) -> List (Item.Product CE.Any (Maybe Float) data)
getItems plane elements =
let toItems el acc =
case el of
Indexed _ -> acc
SeriesElement _ items _ _ -> acc ++ items
BarsElement _ items _ _ _ -> acc ++ items
AxisElement func _ -> acc
TicksElement _ _ -> acc
TickElement _ _ _ -> acc
LabelsElement _ _ _ -> acc
LabelElement _ _ _ -> acc
GridElement _ -> acc
SubElements _ -> acc -- TODO add phantom type to only allow decorative els in this
ListOfElements subs -> List.foldl toItems acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
in
List.foldl toItems [] elements
getLegends : List (Element data msg) -> List Legend.Legend
getLegends elements =
let toLegends el acc =
case el of
Indexed _ -> acc
SeriesElement _ _ legends_ _ -> acc ++ legends_
BarsElement _ _ legends_ _ _ -> acc ++ legends_
AxisElement _ _ -> acc
TicksElement _ _ -> acc
TickElement _ _ _ -> acc
LabelsElement _ _ _ -> acc
LabelElement _ _ _ -> acc
GridElement _ -> acc
SubElements _ -> acc
ListOfElements subs -> List.foldl toLegends acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
in
List.foldl toLegends [] elements
{-| -}
type alias TickValues =
{ xAxis : List Float
, yAxis : List Float
, xs : List Float
, ys : List Float
}
getTickValues : C.Plane -> List (Item.Product CE.Any (Maybe Float) data) -> List (Element data msg) -> TickValues
getTickValues plane items elements =
let toValues el acc =
case el of
Indexed _ -> acc
SeriesElement _ _ _ _ -> acc
BarsElement _ _ _ func _ -> func plane acc
AxisElement func _ -> func plane acc
TicksElement func _ -> func plane acc
TickElement toC func _ -> func plane (toC plane) acc
LabelsElement toC func _ -> func plane (toC plane) acc
LabelElement toC func _ -> func plane (toC plane) acc
SubElements func -> List.foldl toValues acc (func plane items)
GridElement _ -> acc
ListOfElements subs -> List.foldl toValues acc subs
SvgElement _ -> acc
HtmlElement _ -> acc
in
List.foldl toValues (TickValues [] [] [] []) elements
viewElements : Container data msg -> C.Plane -> TickValues -> List (Item.Product CE.Any (Maybe Float) data) -> List Legend.Legend -> List (Element data msg) -> ( List (H.Html msg), List (S.Svg msg), List (H.Html msg) )
viewElements config plane tickValues allItems allLegends elements =
let viewOne el ( before, chart_, after ) =
case el of
Indexed _ -> ( before,chart_, after )
SeriesElement _ _ _ view -> ( before, view plane :: chart_, after )
BarsElement _ _ _ _ view -> ( before, view plane :: chart_, after )
AxisElement _ view -> ( before, view plane :: chart_, after )
TicksElement _ view -> ( before, view plane :: chart_, after )
TickElement toC _ view -> ( before, view plane (toC plane) :: chart_, after )
LabelsElement toC _ view -> ( before, view plane (toC plane) :: chart_, after )
LabelElement toC _ view -> ( before, view plane (toC plane) :: chart_, after )
GridElement view -> ( before, view plane tickValues :: chart_, after )
SubElements func -> List.foldr viewOne ( before, chart_, after ) (func plane allItems)
ListOfElements els -> List.foldr viewOne ( before, chart_, after ) els
SvgElement view -> ( before, view plane :: chart_, after )
HtmlElement view ->
( if List.length chart_ > 0 then view plane allLegends :: before else before
, chart_
, if List.length chart_ > 0 then after else view plane allLegends :: after
)
in
List.foldr viewOne ([], [], []) elements
-- TOOLTIP
type alias Tooltip =
{ direction : Maybe IS.Direction
, focal : Maybe (C.Position -> C.Position)
, height : Float
, width : Float
, offset : Float
, arrow : Bool
, border : String
, background : String
}
{-| Add a tooltip for a specific item.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.product) ]
[ C.series .year
[ C.scatter .income [] ]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 56000 }
, { year = 2020, income = 62000 }
]
, C.each model.hovering <| \plane product ->
[ C.tooltip product [] [] [] ]
]
Customizations:
C.tooltip item
[ -- Change direction
CA.onTop -- Always place tooltip on top of the item
, CA.onBottom -- Always place tooltip below of the item
, CA.onRight -- Always place tooltip on the right of the item
, CA.onLeft -- Always place tooltip on the left of the item
, CA.onLeftOrRight -- Place tooltip on the left or right of the item,
-- depending on which side has more space available
, CA.onTopOrBottom -- Place tooltip on the top or bottom of the item,
-- depending on which side has more space available
-- Change focal point (where on the item the tooltip is achored)
, CA.top
, CA.bottom
, CA.left
, CA.right
, CA.center
, CA.topLeft
, CA.topRight
, CA.topCenter
, CA.bottomLeft
, CA.bottomRight
, CA.bottomCenter
, CA.leftCenter
, CA.rightCenter
, CA.offset 20 -- Change offset between focal point and tooltip
, CA.noArrow -- Remove little box arrow
, CA.border "blue" -- Change border color
, CA.background -- Change background color
]
[] -- Add any HTML attributes
[] -- Add any HTML children (Will be filled with default tooltip if left empty)
-}
tooltip : Item.Item a -> List (Attribute Tooltip) -> List (H.Attribute Never) -> List (H.Html Never) -> Element data msg
tooltip i edits attrs_ content =
html <| \p ->
let pos = Item.getLimits i
content_ = if content == [] then Item.toHtml i else content
in
if IS.isWithinPlane p pos.x1 pos.y2 -- TODO
then CS.tooltip p (Item.getPosition p i) edits attrs_ content_
else H.text ""
-- AXIS
{-| -}
type alias Axis =
{ limits : List (Attribute C.Axis)
, pinned : C.Axis -> Float
, arrow : Bool
, color : String
, width : Float
}
{-| Add an x-axis line to your chart. The example below illustrates
the styling options:
C.chart []
[ C.xAxis
[ CA.color "red" -- Change color of line
, CA.width 2 -- Change width of line
, CA.noArrow -- Remove arrow from line
, CA.pinned .max -- Change what y position the axis is set at
-- .max is at the very top
-- .min is at the very bottom
-- CA.zero is the closest you can go to zero
-- (always 3) is at y = 3.
, CA.limits
[ CA.lowest 2 CA.exactly
, CA.highest 8 CA.exactly
]
-- Change from where to where you line goes.
-- The example will make a line where x1 = 2 to x2 = 8
]
]
-}
xAxis : List (Attribute Axis) -> Element item msg
xAxis edits =
let config =
Helpers.apply edits
{ limits = []
, pinned = CA.zero
, color = ""
, arrow = True
, width = 1
}
addTickValues p ts =
{ ts | yAxis = config.pinned p.y :: ts.yAxis }
in
AxisElement addTickValues <| \p ->
let xLimit = List.foldl (\f x -> f x) p.x config.limits in
S.g
[ SA.class "elm-charts__x-axis" ]
[ CS.line p
[ CA.color config.color
, CA.width config.width
, CA.y1 (config.pinned p.y)
, CA.x1 (max p.x.min xLimit.min)
, CA.x2 (min p.x.max xLimit.max)
]
, if config.arrow then
CS.arrow p
[ CA.color config.color ]
{ x = xLimit.max
, y = config.pinned p.y
}
else
S.text ""
]
{-| Add an y-axis line to your chart. The styling options are the same
as for `xAxis`.
-}
yAxis : List (Attribute Axis) -> Element item msg
yAxis edits =
let config =
Helpers.apply edits
{ limits = []
, pinned = CA.zero
, color = ""
, arrow = True
, width = 1
}
addTickValues p ts =
{ ts | xAxis = config.pinned p.x :: ts.xAxis }
in
AxisElement addTickValues <| \p ->
let yLimit = List.foldl (\f y -> f y) p.y config.limits in
S.g
[ SA.class "elm-charts__y-axis" ]
[ CS.line p
[ CA.color config.color
, CA.width config.width
, CA.x1 (config.pinned p.x)
, CA.y1 (max p.y.min yLimit.min)
, CA.y2 (min p.y.max yLimit.max)
]
, if config.arrow then
CS.arrow p [ CA.color config.color, CA.rotate -90 ]
{ x = config.pinned p.x
, y = yLimit.max
}
else
S.text ""
]
type alias Ticks =
{ color : String
, height : Float
, width : Float
, pinned : C.Axis -> Float
, limits : List (Attribute C.Axis)
, amount : Int
, flip : Bool
, grid : Bool
, generate : IS.TickType
}
{-| Produce a set of ticks at "nice" numbers on the x-axis of your chart.
The example below illustrates the configuration:
C.chart []
[ C.xTicks
[ CA.color "red" -- Change color
, CA.height 8 -- Change height
, CA.width 2 -- Change width
, CA.amount 15 -- Change amount of ticks
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each tick. This removes them.
, CA.ints -- Add ticks at "nice" ints
, CA.times Time.utc -- Add ticks at "nice" times
, CA.pinned .max -- Change what y position the ticks are set at
-- .max is at the very top
-- .min is at the very bottom
-- CA.zero is the closest you can go to zero
-- (always 3) is at y = 3.
, CA.limits
[ CA.lowest 2 CA.exactly
, CA.highest 8 CA.exactly
]
-- Change the upper and lower limit of your tick range.
-- The example will add ticks between x = 2 and 8.
]
]
-}
xTicks : List (Attribute Ticks) -> Element item msg
xTicks edits =
let config =
Helpers.apply edits
{ color = ""
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, height = 5
, flip = False
, grid = True
, width = 1
}
toTicks p =
List.foldl (\f x -> f x) p.x config.limits
|> generateValues config.amount config.generate Nothing
|> List.map .value
addTickValues p ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ toTicks p }
in
TicksElement addTickValues <| \p ->
let toTick x =
CS.xTick p
[ CA.color config.color
, CA.length (if config.flip then -config.height else config.height)
, CA.width config.width
]
{ x = x
, y = config.pinned p.y
}
in
S.g [ SA.class "elm-charts__x-ticks" ] <| List.map toTick (toTicks p)
{-| Produce a set of ticks at "nice" numbers on the y-axis of your chart.
The styling options are the same as for `xTicks`.
-}
yTicks : List (Attribute Ticks) -> Element item msg
yTicks edits =
let config =
Helpers.apply edits
{ color = ""
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, height = 5
, flip = False
, grid = True
, width = 1
}
toTicks p =
List.foldl (\f y -> f y) p.y config.limits
|> generateValues config.amount config.generate Nothing
|> List.map .value
addTickValues p ts =
{ ts | ys = ts.ys ++ toTicks p }
in
TicksElement addTickValues <| \p ->
let toTick y =
CS.yTick p
[ CA.color config.color
, CA.length (if config.flip then -config.height else config.height)
, CA.width config.width
]
{ x = config.pinned p.x
, y = y
}
in
S.g [ SA.class "elm-charts__y-ticks" ] <| List.map toTick (toTicks p)
type alias Labels =
{ color : String
, pinned : C.Axis -> Float
, limits : List (Attribute C.Axis)
, xOff : Float
, yOff : Float
, flip : Bool
, amount : Int
, anchor : Maybe IS.Anchor
, generate : IS.TickType
, fontSize : Maybe Int
, uppercase : Bool
, format : Maybe (Float -> String)
, rotate : Float
, grid : Bool
}
{-| Produce a set of labels at "nice" numbers on the x-axis of your chart.
The example below illustrates the configuration:
C.chart []
[ C.xLabels
[ CA.color "red" -- Change color
, CA.fontSize 12 -- Change font size
, CA.uppercase -- Make labels uppercase
, CA.rotate 90 -- Rotate labels
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.amount 15 -- Change amount of ticks
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each label. This removes them.
, CA.ints -- Add ticks at "nice" ints
, CA.times Time.utc -- Add ticks at "nice" times
, CA.format (\num -> String.fromFloat num ++ "°")
-- Format the "nice" number
, CA.pinned .max -- Change what y position the labels are set at
-- .max is at the very top
-- .min is at the very bottom
-- CA.zero is the closest you can go to zero
-- (always 3) is at y = 3.
, CA.limits
[ CA.lowest 2 CA.exactly
, CA.highest 8 CA.exactly
]
-- Change the upper and lower limit of your labels range.
-- The example will add labels between x = 2 and 8.
]
]
For more in depth and irregular customization, see `xLabel`.
-}
xLabels : List (Attribute Labels) -> Element item msg
xLabels edits =
let toConfig p =
Helpers.apply edits
{ color = "#808BAB"
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, flip = False
, anchor = Nothing
, xOff = 0
, yOff = 18
, grid = True
, format = Nothing
, uppercase = False
, rotate = 0
, fontSize = Nothing
}
toTicks p config =
List.foldl (\f x -> f x) p.x config.limits
|> generateValues config.amount config.generate config.format
toTickValues p config ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ List.map .value (toTicks p config) }
in
LabelsElement toConfig toTickValues <| \p config ->
let default = IS.defaultLabel
toLabel item =
IS.label p
{ default
| xOff = config.xOff
, yOff = if config.flip then -config.yOff + 10 else config.yOff
, color = config.color
, anchor = config.anchor
, fontSize = config.fontSize
, uppercase = config.uppercase
, rotate = config.rotate
}
[ S.text item.label ]
{ x = item.value
, y = config.pinned p.y
}
in
S.g [ SA.class "elm-charts__x-labels" ] (List.map toLabel (toTicks p config))
{-| Produce a set of labels at "nice" numbers on the y-axis of your chart.
The styling options are the same as for `xLabels`.
-}
yLabels : List (Attribute Labels) -> Element item msg
yLabels edits =
let toConfig p =
Helpers.apply edits
{ color = "#808BAB"
, limits = []
, pinned = CA.zero
, amount = 5
, generate = IS.Floats
, anchor = Nothing
, flip = False
, xOff = -10
, yOff = 3
, grid = True
, format = Nothing
, uppercase = False
, fontSize = Nothing
, rotate = 0
}
toTicks p config =
List.foldl (\f y -> f y) p.y config.limits
|> generateValues config.amount config.generate config.format
toTickValues p config ts =
if not config.grid then ts else
{ ts | ys = ts.ys ++ List.map .value (toTicks p config) }
in
LabelsElement toConfig toTickValues <| \p config ->
let default = IS.defaultLabel
toLabel item =
IS.label p
{ default
| xOff = if config.flip then -config.xOff else config.xOff
, yOff = config.yOff
, color = config.color
, fontSize = config.fontSize
, uppercase = config.uppercase
, rotate = config.rotate
, anchor =
case config.anchor of
Nothing -> Just (if config.flip then IS.Start else IS.End)
Just anchor -> Just anchor
}
[ S.text item.label ]
{ x = config.pinned p.x
, y = item.value
}
in
S.g [ SA.class "elm-charts__y-labels" ] (List.map toLabel (toTicks p config))
{-| -}
type alias Label =
{ x : Float
, y : Float
, xOff : Float
, yOff : Float
, border : String
, borderWidth : Float
, fontSize : Maybe Int
, color : String
, anchor : Maybe IS.Anchor
, rotate : Float
, uppercase : Bool
, flip : Bool
, grid : Bool
}
{-| Produce a single x label. This is typically for cases where you need
very custom labels and `xLabels` does not cut it. It is especially useful
in combination with the `generate` helper. An example use case:
C.chart []
[ -- Create labels for 10 "nice" integers on the x-axis
-- and highlight the label at x = 0.
C.generate 10 C.ints .x [] <| \plane int ->
let color = if int == 0 then "red" else "gray" in
[ C.xLabel
[ CA.x (toFloat int), CA.color color ]
[ S.text (String.fromInt int) ]
]
]
A full list of possible attributes:
C.chart []
[ C.xLabel
[ CA.x 5 -- Set x coordinate
, CA.y 8 -- Set y coordinate
, CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.border "white" -- Set stroke color
, CA.borderWidth 0.5 -- Set stroke width
, CA.fontSize 12 -- Set font size
, CA.color "red" -- Set color
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each label. This removes it.
]
[ S.text "hello!" ]
]
-}
xLabel : List (Attribute Label) -> List (S.Svg msg) -> Element data msg
xLabel edits inner =
let toConfig p =
Helpers.apply edits
{ x = CA.middle p.x
, y = CA.zero p.y
, xOff = 0
, yOff = 20
, border = "white"
, borderWidth = 0.1
, uppercase = False
, fontSize = Nothing
, color = "#808BAB"
, anchor = Nothing
, rotate = 0
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ [ config.x ] }
in
LabelElement toConfig toTickValues <| \p config ->
let string =
if inner == []
then [ S.text (String.fromFloat config.x) ]
else inner
in
IS.label p
{ xOff = config.xOff
, yOff = if config.flip then -config.yOff + 10 else config.yOff
, border = config.border
, borderWidth = config.borderWidth
, fontSize = config.fontSize
, uppercase = config.uppercase
, color = config.color
, anchor = config.anchor
, rotate = config.rotate
, attrs = []
}
string
{ x = config.x, y = config.y }
{-| Produce a single y label. This is typically for cases where you need
very custom labels and `yLabels` does not cut it. See `xLabel` for
usage and customization.
-}
yLabel : List (Attribute Label) -> List (S.Svg msg) -> Element data msg
yLabel edits inner =
let toConfig p =
Helpers.apply edits
{ x = CA.zero p.x
, y = CA.middle p.y
, xOff = -8
, yOff = 3
, border = "white"
, borderWidth = 0.1
, uppercase = False
, fontSize = Nothing
, color = "#808BAB"
, anchor = Nothing
, rotate = 0
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | ys = ts.ys ++ [ config.y ] }
in
LabelElement toConfig toTickValues <| \p config ->
let string =
if inner == []
then [ S.text (String.fromFloat config.y) ]
else inner
in
IS.label p
{ xOff = if config.flip then -config.xOff else config.xOff
, yOff = config.yOff
, border = config.border
, borderWidth = config.borderWidth
, fontSize = config.fontSize
, uppercase = config.uppercase
, color = config.color
, anchor =
case config.anchor of
Nothing -> Just (if config.flip then IS.Start else IS.End)
Just anchor -> Just anchor
, rotate = config.rotate
, attrs = []
}
string
{ x = config.x, y = config.y }
{-| -}
type alias Tick =
{ x : Float
, y : Float
, color : String
, width : Float
, length : Float
, flip : Bool
, grid : Bool
}
{-| Produce a single x tick. This is typically for cases where you need
very custom ticks and `xTicks` does not cut it. It is especially useful
in combination with the `generate` helper. An example use case:
C.chart []
[ -- Create ticks for 10 "nice" integers on the x-axis
-- and highlight the tick at x = 0.
C.generate 10 C.ints .x [] <| \plane int ->
let color = if int == 0 then "red" else "gray" in
[ C.xTick [ CA.x (toFloat int), CA.color color ] ]
]
A full list of possible attributes:
C.xTick
[ CA.x 5 -- Set x coordinate
, CA.y 8 -- Set y coordinate
, CA.color "red" -- Change color
, CA.height 8 -- Change height
, CA.width 2 -- Change width
, CA.amount 15 -- Change amount of ticks
, CA.flip -- Flip to opposite direction
, CA.noGrid -- By default a grid line is added
-- for each tick. This removes them.
]
-}
xTick : List (Attribute Tick) -> Element data msg
xTick edits =
let toConfig p =
Helpers.apply edits
{ x = CA.middle p.x
, y = CA.zero p.y
, length = 5
, color = "rgb(210, 210, 210)"
, width = 1
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | xs = ts.xs ++ [ config.x ] }
in
TickElement toConfig toTickValues <| \p config ->
CS.xTick p
[ CA.length (if config.flip then -config.length else config.length)
, CA.color config.color
, CA.width config.width
]
{ x = config.x, y = config.y }
{-| Produce a single y tick. This is typically for cases where you need
very custom ticks and `yTicks` does not cut it. See `xTick` for
usage and customization.
-}
yTick : List (Attribute Tick) -> Float -> Element data msg
yTick edits val =
let toConfig p =
Helpers.apply edits
{ x = CA.middle p.x
, y = CA.zero p.y
, length = 5
, color = "rgb(210, 210, 210)"
, width = 1
, flip = False
, grid = True
}
toTickValues p config ts =
if not config.grid then ts else
{ ts | ys = ts.ys ++ [ config.y ] }
in
TickElement toConfig toTickValues <| \p config ->
CS.yTick p
[ CA.length (if config.flip then -config.length else config.length)
, CA.color config.color
, CA.width config.width
]
{ x = config.x, y = config.y }
type alias Grid =
{ color : String
, width : Float
, dotGrid : Bool
, dashed : List Float
}
{-| Add a grid to your chart.
C.chart []
[ C.grid []
, C.xLabels []
, C.yLabels []
]
Grid lines are added where labels or ticks are added.
Customizations:
C.grid
[ CA.color "blue" -- Change color
, CA.width 3 -- Change width
, CA.dashed [ 5, 5 ] -- Add dashing (only for line grids)
, CA.dotGrid -- Use dot grid instead of line grid
]
-}
grid : List (Attribute Grid) -> Element item msg
grid edits =
let config =
Helpers.apply edits
{ color = ""
, width = 0
, dotGrid = False
, dashed = []
}
color =
if String.isEmpty config.color then
if config.dotGrid then Helpers.darkGray else Helpers.gray
else
config.color
width =
if config.width == 0 then
if config.dotGrid then 0.5 else 1
else
config.width
toXGrid vs p v =
if List.member v vs.xAxis
then Nothing else Just <|
CS.line p [ CA.color color, CA.width width, CA.x1 v, CA.dashed config.dashed ]
toYGrid vs p v =
if List.member v vs.yAxis
then Nothing else Just <|
CS.line p [ CA.color color, CA.width width, CA.y1 v, CA.dashed config.dashed ]
toDot vs p x y =
if List.member x vs.xAxis || List.member y vs.yAxis
then Nothing
else Just <| CS.dot p .x .y [ CA.color color, CA.size width, CA.circle ] { x = x, y = y }
in
GridElement <| \p vs ->
S.g [ SA.class "elm-charts__grid" ] <|
if config.dotGrid then
List.concatMap (\x -> List.filterMap (toDot vs p x) vs.ys) vs.xs
else
[ S.g [ SA.class "elm-charts__x-grid" ] (List.filterMap (toXGrid vs p) vs.xs)
, S.g [ SA.class "elm-charts__y-grid" ] (List.filterMap (toYGrid vs p) vs.ys)
]
-- PROPERTIES
{-| A property of a bar, line, or scatter series.
-}
type alias Property data inter deco =
P.Property data String inter deco
{-| Specify the configuration of a bar. The first argument will determine the height of
your bar. The second is a list of styling attributes. The example below illustrates what
styling options are available.
C.chart []
[ C.bars []
[ C.bar .income
[ CA.color "blue" -- Change the color
, CA.border "darkblue" -- Change the border color
, CA.borderWidth 2 -- Change the border width
, CA.opacity 0.7 -- Change the border opacity
-- A bar can either be solid (default), striped, dotted, or gradient.
, CA.striped
[ CA.width 2 -- Width of each stripe
, CA.spacing 3 -- Spacing bewteen each stripe
, CA.color "blue" -- Color of stripe
, CA.rotate 90 -- Angle of stripe
]
, CA.dotted []
-- Same configurations as `striped`
, CA.gradient
[ "blue", "darkblue" ] -- List of colors in gradient
, CA.roundTop 0.2 -- Round the top corners
, CA.roundBottom 0.2 -- Round the bottom corners
-- You can highlight a bar or a set of bars by adding a kind of "aura" to it.
, CA.highlight 0.5 -- Determine the opacity of the aura
, CA.highlightWidth 5 -- Determine the width of the aura
, CA.highlightColor "blue" -- Determine the color of the aura
-- Add arbitrary SVG attributes to your bar
, CA.attrs [ SA.strokeOpacity "0.5" ]
]
]
[ { income = 10 }
, { income = 12 }
, { income = 18 }
]
]
-}
bar : (data -> Float) -> List (Attribute CS.Bar) -> Property data inter CS.Bar
bar y =
P.property (y >> Just) []
{-| Same as `bar`, but allows for missing data.
C.chart []
[ C.bars []
[ C.barMaybe .income [] ]
[ { income = Just 10 }
, { income = Nothing }
, { income = Just 18 }
]
]
-}
barMaybe : (data -> Maybe Float) -> List (Attribute CS.Bar) -> Property data inter CS.Bar
barMaybe y =
P.property y []
{-| Specify the configuration of a set of dots. The first argument will determine the y value of
your dots. The second is a list of styling attributes. The example below illustrates what styling
options are available.
C.series .year
[ C.scatter .income
[ CA.size 10 -- Change size of dot
, CA.color "blue" -- Change color
, CA.opacity 0.8 -- Change opacity
, CA.border "lightblue" -- Change border color
, CA.borderWidth 2 -- Change border width
-- You can highlight a dot or a set of dots by adding a kind of "aura" to it.
, CA.highlight 0.3 -- Determine the opacity of the aura
, CA.highlightWidth 6 -- Determine the width of the aura
, CA.highlightColor "blue" -- Determine the color of the aura
-- A dot is by default a circle, but you can change it to any
-- of the shapes below.
, CA.triangle
, CA.square
, CA.diamond
, CA.plus
, CA.cross
]
]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 57000 }
, { year = 2020, income = 62000 }
]
-}
scatter : (data -> Float) -> List (Attribute CS.Dot) -> Property data inter CS.Dot
scatter y =
P.property (y >> Just) []
{-| Same as `scatter`, but allows for missing data.
C.chart []
[ C.series .year
[ C.scatterMaybe .income [] ]
[ { year = 2000, income = Just 40000 }
, { year = 2010, income = Nothing }
, { year = 2020, income = Just 62000 }
]
]
-}
scatterMaybe : (data -> Maybe Float) -> List (Attribute CS.Dot) -> Property data inter CS.Dot
scatterMaybe y =
P.property y []
{-| Specify the configuration of a interpolated series (a line). The first argument will determine
the y value of your dots. The second is a list of attributes pertaining to your interpolation. The
third argument is a list of attributes pertaining to the dots of your series.
The example below illustrates what styling options are available.
C.series .age
[ C.interpolated .height
[ -- The following attributes allow alternatives to the default
-- linear interpolation.
CA.monotone -- Use a monotone interpolation (looks smooth)
, CA.stepped -- Use a stepped interpolation (looks like stairs)
, CA.color "blue"
, CA.width 2
, CA.dashed [ 4, 4 ]
-- The area beneath the curve is by default transparent, but you
-- can change the opacity of it, or make it striped, dotted, or gradient.
, CA.opacity 0.5
, CA.striped
[ CA.width 2 -- Width of each stripe
, CA.spacing 3 -- Spacing bewteen each stripe
, CA.color "blue" -- Color of stripe
, CA.rotate 90 -- Angle of stripe
]
, CA.dotted [] -- Same configurations as `striped`
, CA.gradient [ "blue", "darkblue" ] -- List of colors in gradient
-- Add arbitrary SVG attributes to your line
, CA.attrs [ SA.id "my-chart" ]
]
[]
]
[ { age = 0, height = 40 }
, { age = 5, height = 80 }
, { age = 10, height = 120 }
, { age = 15, height = 180 }
, { age = 20, height = 184 }
]
-}
interpolated : (data -> Float) -> List (Attribute CS.Interpolation) -> List (Attribute CS.Dot) -> Property data CS.Interpolation CS.Dot
interpolated y inter =
P.property (y >> Just) ([ CA.linear ] ++ inter)
{-| Same as `interpolated`, but allows for missing data.
C.chart []
[ C.series .age
[ C.interpolatedMaybe .height [] ]
[ { age = 0, height = Just 40 }
, { age = 5, height = Nothing }
, { age = 10, height = Just 120 }
, { age = 15, height = Just 180 }
, { age = 20, height = Just 184 }
]
]
-}
interpolatedMaybe : (data -> Maybe Float) -> List (Attribute CS.Interpolation) -> List (Attribute CS.Dot) -> Property data CS.Interpolation CS.Dot
interpolatedMaybe y inter =
P.property y ([ CA.linear ] ++ inter)
{-| Name a bar, scatter, or interpolated series. This name will show up
in the default tooltip, and you can use it to identify items from this series.
C.chart []
[ C.series .year
[ C.scatter .income []
|> C.named "Income"
]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 48000 }
, { year = 2020, income = 62000 }
]
]
-}
named : String -> Property data inter deco -> Property data inter deco
named name =
P.meta name
{-| Change the style of your bars or dots based on the index of its data point
and the data point itself.
C.chart []
[ C.series .year
[ C.scatter .income [ CA.opacity 0.6 ]
|> C.variation (\index datum -> [ CA.size datum.people ])
]
[ { year = 2000, income = 40000, people = 150 }
, { year = 2010, income = 48000, people = 98 }
, { year = 2020, income = 62000, people = 180 }
]
]
-}
variation : (Int -> data -> List (Attribute deco)) -> Property data inter deco -> Property data inter deco
variation func =
P.variation <| \_ _ index _ datum -> func index datum
{-| Change the style of your bars or dots based on whether it is a member
of the group of products which you list. A such group of products can be
attrained through events like `Chart.Events.onMouseMove` or similar.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.dot) ]
[ C.series .year
[ C.scatter .income [ CA.opacity 0.6 ]
|> C.amongst model.hovering (\datum -> [ CA.highlight 0.5 ])
]
[ { year = 2000, income = 40000, people = 150 }
, { year = 2010, income = 48000, people = 98 }
, { year = 2020, income = 62000, people = 180 }
]
]
-}
amongst : List (CE.Product config value data) -> (data -> List (Attribute deco)) -> Property data inter deco -> Property data inter deco
amongst inQuestion func =
P.variation <| \p s i meta d ->
let check product =
if Item.getPropertyIndex product == p &&
Item.getStackIndex product == s &&
Item.getDataIndex product == i &&
Item.getDatum product == d
then func d else []
in
List.concatMap check inQuestion
{-| Stack a set of bar or line series.
C.chart []
[ C.bars []
[ C.stacked
[ C.bar .cats []
, C.bar .dogs []
]
]
[ { cats = 2, dogs = 4 }
, { cats = 3, dogs = 2 }
, { cats = 6, dogs = 1 }
]
]
-}
stacked : List (Property data inter deco) -> Property data inter deco
stacked =
P.stacked
-- LABEL EXTRAS
{-| -}
type alias ItemLabel a =
{ xOff : Float
, yOff : Float
, border : String
, borderWidth : Float
, fontSize : Maybe Int
, color : String
, anchor : Maybe IS.Anchor
, rotate : Float
, uppercase : Bool
, attrs : List (S.Attribute Never)
, position : CS.Plane -> a -> CS.Point
, format : Maybe (a -> String)
}
defaultLabel : ItemLabel (CE.Item a)
defaultLabel =
{ xOff = IS.defaultLabel.xOff
, yOff = IS.defaultLabel.yOff
, border = IS.defaultLabel.border
, borderWidth = IS.defaultLabel.borderWidth
, fontSize = IS.defaultLabel.fontSize
, color = IS.defaultLabel.color
, anchor = IS.defaultLabel.anchor
, rotate = IS.defaultLabel.rotate
, uppercase = IS.defaultLabel.uppercase
, attrs = IS.defaultLabel.attrs
, position = CE.getBottom
, format = Nothing
}
toLabelFromItemLabel : ItemLabel (CE.Item a) -> CS.Label
toLabelFromItemLabel config =
{ xOff = config.xOff
, yOff = config.yOff
, color = config.color
, border = config.border
, borderWidth = config.borderWidth
, anchor = config.anchor
, fontSize = config.fontSize
, uppercase = config.uppercase
, rotate = config.rotate
, attrs = config.attrs
}
{-| Add labels by every bin.
C.chart []
[ C.bars [] [ C.bar .income [] ]
[ { name = "PI:NAME:<NAME>END_PI", income = 60 }
, { name = "PI:NAME:<NAME>END_PI", income = 70 }
, { name = "PI:NAME:<NAME>END_PI", income = 80 }
]
, C.binLabels .name [ CA.moveDown 15 ]
]
Attributes you can use:
C.binLabels .name
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-bin-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Given the entire bin item (not just the data)
-- produce a string.
, CA.format (\bin -> String.fromFloat (CE.getCommonality bin).start)
]
-}
binLabels : (data -> String) -> List (Attribute (ItemLabel (CE.Group (CE.Bin data) CE.Bar (Maybe Float) data))) -> Element data msg
binLabels toLabel edits =
eachCustom (CE.collect CE.bin CE.bar) <| \p item ->
let config =
Helpers.apply edits defaultLabel
text =
case config.format of
Just formatting -> formatting item
Nothing -> toLabel (CE.getCommonality item).datum
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
{-| Add labels by every bar.
C.chart []
[ C.bars []
[ C.bar .income [] ]
[ { name = "PI:NAME:<NAME>END_PI", income = 60 }
, { name = "PI:NAME:<NAME>END_PI", income = 70 }
, { name = "PI:NAME:<NAME>END_PI", income = 80 }
]
, C.barLabels [ CA.moveUp 6 ]
]
Attributes you can use:
C.barLabels
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-bar-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Change the text of the label
, CA.format (\bar -> String.fromFloat (CE.getDependent bar))
]
-}
barLabels : List (Attribute (ItemLabel (CE.Product CE.Bar Float data))) -> Element data msg
barLabels edits =
eachBar <| \p item ->
let config =
Helpers.apply edits { defaultLabel | position = CE.getTop }
text =
case config.format of
Just formatting -> formatting item
Nothing -> String.fromFloat (CE.getDependent item)
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
{-| Helper to add a label by a particular product.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.bar) ]
[ C.bars []
[ C.bar .income [] ]
[ { name = "PI:NAME:<NAME>END_PI", income = 60 }
, { name = "PI:NAME:<NAME>END_PI", income = 70 }
, { name = "PI:NAME:<NAME>END_PI", income = 80 }
]
, C.each model.hovering <| \_ bar ->
[ C.productLabel [ CA.moveUp 6 ] bar ]
]
Attributes you can use:
C.productLabel
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-bar-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Change the text of the label
, CA.format (\bar -> String.fromFloat (CE.getDependent bar))
]
product
-}
productLabel : List (Attribute (ItemLabel (CE.Product config value data))) -> CE.Product config value data -> Element data msg
productLabel edits item =
withPlane <| \p ->
let config =
Helpers.apply edits { defaultLabel | position = CE.getTop }
text =
case config.format of
Just formatting -> formatting item
Nothing -> String.fromFloat (Item.getDependentSafe item)
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
{-| Add labels by every bar.
C.chart []
[ C.series .age
[ C.scatter .income [] ]
[ { age = 34, income = 60 }
, { age = 42, income = 70 }
, { age = 48, income = 80 }
]
, C.dotLabels CE.getCenter [ CA.moveUp 6 ]
]
Attributes you can use:
C.dotLabels
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-dot-labels" ]
-- Edit the position of the label
, CA.position CE.getTop
-- Change the text of the label
, CA.format (\dot -> String.fromFloat (CE.getDependent dot))
]
-}
dotLabels : List (Attribute (ItemLabel (CE.Product CE.Dot Float data))) -> Element data msg
dotLabels edits =
eachDot <| \p item ->
let config =
Helpers.apply edits { defaultLabel | position = CE.getCenter }
text =
case config.format of
Just formatting -> formatting item
Nothing -> String.fromFloat (Item.getDependent item)
in
[ svg <| \_ ->
IS.label p (toLabelFromItemLabel config) [ S.text text ] (config.position p item)
]
-- BARS
{-| -}
type alias Bars data =
{ spacing : Float
, margin : Float
, roundTop : Float
, roundBottom : Float
, grouped : Bool
, grid : Bool
, x1 : Maybe (data -> Float)
, x2 : Maybe (data -> Float)
}
{-| Add a bar series to your chart. Each `data` in your `List data` is a "bin". For
each "bin", whatever number of bars your have specified in the second argument will
show up, side-by-side.
C.bars []
[ C.bar .income []
, C.bar .spending []
]
[ { income = 10, spending = 2 }
, { income = 12, spending = 6 }
, { income = 18, spending = 16 }
]
The example above will thus produce three bins, each containing two bars. You can make
your bars show up overlapping instead of side-by-side by using the `CA.ungroup`
attribute:
C.bars
[ CA.ungroup ]
[ C.bar .total []
, C.bar .gross []
, C.bar .net []
]
[ { net = 10, gross = 20, total = 50 }
, { net = 13, gross = 28, total = 63 }
, { net = 16, gross = 21, total = 82 }
]
By default, the x value of each bin is set by a simple count. The first bin is set at
x = 1, the second at x = 2, and so on. If you'd like to control what the x values of
your bins are, e.g. you are making a histogram, you may use the `CA.x1` and `CA.x2`
attributes, as illustrated below.
C.bars
[ CA.x1 .score
, CA.x2 (\datum -> datum.score + 20)
]
[ C.bar .students [] ]
[ { score = 0, students = 1 }
, { score = 20, students = 10 }
, { score = 40, students = 30 }
, { score = 60, students = 20 }
, { score = 80, students = 1 }
]
In this case, you actually only need to specify either `x1` or `x2` because the library
estimates the unknown x value based on the size of the previous or next bin. However, it comes in
handy to specify both when you have bins of irregular sizes.
The rest of the configuration options concern styling:
C.bars
[ CA.spacing 0.1 -- The spacing _between_ the bars in each bin relative to the full length (1).
, CA.margin 0.2 -- The spacing _around_ the bars in each bin relative to the full length (1).
, CA.roundTop 0.2 -- The rounding of your bars' top corners. It gets weird after around 0.5.
, CA.roundBottom 0.2 -- The rounding of your bars' bottom corners. It gets weird after around 0.5.
, CA.noGrid -- Grid lines are by default added at the bin limits. This removes them.
]
[ C.bar .income []
, C.bar .spending []
]
[ { income = 10, spending = 2 }
, { income = 12, spending = 6 }
, { income = 18, spending = 16 }
]
-}
bars : List (Attribute (Bars data)) -> List (Property data () CS.Bar) -> List data -> Element data msg
bars edits properties data =
barsMap identity edits properties data
{-| This is just like `bars`, but it maps your `data`. This is useful if you have
several kinds of data types present in your chart.
type Datum
= Money { year : Float, income : Float }
| People { year : Float, people : Float }
view : Html msg
view =
C.chart []
[ C.barsMap Money
[ CA.x1 .year ]
[ C.bar .income [] ]
[ { year = 2000, income = 200 }
, { year = 2010, income = 300 }
, { year = 2020, income = 500 }
]
, C.barsMap People
[ CA.x1 .year ]
[ C.bar .people [] ]
[ { year = 2000, people = 21 }
, { year = 2010, people = 65 }
, { year = 2020, people = 93 }
]
]
-}
barsMap : (data -> a) -> List (Attribute (Bars data)) -> List (Property data () CS.Bar) -> List data -> Element a msg
barsMap mapData edits properties data =
Indexed <| \index ->
let barsConfig =
Helpers.apply edits Produce.defaultBars
items =
Produce.toBarSeries index edits properties data
generalized =
List.concatMap Group.getGenerals items
|> List.map (Item.map mapData)
bins =
CE.group CE.bin generalized
legends_ =
Legend.toBarLegends index edits properties
toTicks plane acc =
{ acc | xs = acc.xs ++
if barsConfig.grid then
List.concatMap (CE.getLimits >> \pos -> [ pos.x1, pos.x2 ]) bins
else
[]
}
toLimits =
List.map Item.getLimits bins
in
( BarsElement toLimits generalized legends_ toTicks <| \plane ->
S.g [ SA.class "elm-charts__bar-series" ] (List.map (Item.toSvg plane) items)
|> S.map never
, index + List.length (List.concatMap P.toConfigs properties)
)
-- SERIES
{-| Add a scatter or line series to your chart. Each `data` in your `List data` will result in one "dot".
The first argument of `series` determines the x value of each dot. The y value and all styling configuration
is determined by the list of `interpolated` or `scatter` properties defined in the second argument.
C.series .age
[ C.interpolated .height [] []
, C.interpolated .weight [] []
]
[ { age = 0, height = 40, weight = 4 }
, { age = 5, height = 80, weight = 24 }
, { age = 10, height = 120, weight = 36 }
, { age = 15, height = 180, weight = 54 }
, { age = 20, height = 184, weight = 60 }
]
See `interpolated` and `scatter` for styling options.
-}
series : (data -> Float) -> List (Property data CS.Interpolation CS.Dot) -> List data -> Element data msg
series toX properties data =
seriesMap identity toX properties data
{-| This is just like `series`, but it maps your `data`. This is useful if you have
several kinds of data types present in your chart.
type Datum
= Height { age : Float, height : Float }
| Weight { age : Float, weight : Float }
view : Html msg
view =
C.chart []
[ C.seriesMap Height .age
[ C.interpolated .height [] ]
[ { age = 0, height = 40 }
, { age = 5, height = 80 }
, { age = 10, height = 120 }
, { age = 15, height = 180 }
]
, C.seriesMap Weight .age
[ C.interpolated .weight [] ]
[ { age = 0, weight = 4 }
, { age = 5, weight = 24 }
, { age = 10, weight = 36 }
, { age = 15, weight = 54 }
]
]
-}
seriesMap : (data -> a) -> (data -> Float) -> List (Property data CS.Interpolation CS.Dot) -> List data -> Element a msg
seriesMap mapData toX properties data =
Indexed <| \index ->
let items =
Produce.toDotSeries index toX properties data
generalized =
List.concatMap Group.getGenerals items
|> List.map (Item.map mapData)
legends_ =
Legend.toDotLegends index properties
toLimits =
List.map Item.getLimits items
in
( SeriesElement toLimits generalized legends_ <| \p ->
S.g [ SA.class "elm-charts__dot-series" ] (List.map (Item.toSvg p) items)
|> S.map never
, index + List.length (List.concatMap P.toConfigs properties)
)
-- OTHER
{-| Using the information about your coordinate system, add a list
of elements.
-}
withPlane : (C.Plane -> List (Element data msg)) -> Element data msg
withPlane func =
SubElements <| \p is -> func p
{-| Given all your bins, add a list of elements.
Use helpers in `Chart.Events` to interact with bins.
-}
withBins : (C.Plane -> List (CE.Group (CE.Bin data) CE.Any (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withBins func =
SubElements <| \p is -> func p (CE.group CE.bin is)
{-| Given all your stacks, add a list of elements.
Use helpers in `Chart.Events` to interact with stacks.
-}
withStacks : (C.Plane -> List (CE.Group (CE.Stack data) CE.Any (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withStacks func =
SubElements <| \p is -> func p (CE.group CE.stack is)
{-| Given all your bars, add a list of elements.
Use helpers in `Chart.Events` to interact with bars.
-}
withBars : (C.Plane -> List (CE.Product CE.Bar (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withBars func =
SubElements <| \p is -> func p (CE.group CE.bar is)
{-| Given all your dots, add a list of elements.
Use helpers in `Chart.Events` to interact with dots.
-}
withDots : (C.Plane -> List (CE.Product CE.Dot (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withDots func =
SubElements <| \p is -> func p (CE.group CE.dot is)
{-| Given all your products, add a list of elements.
Use helpers in `Chart.Events` to interact with products.
-}
withProducts : (C.Plane -> List (CE.Product CE.Any (Maybe Float) data) -> List (Element data msg)) -> Element data msg
withProducts func =
SubElements <| \p is -> func p is
{-| Add elements for each item of whatever list in the first argument.
C.chart
[ CE.onMouseMove OnHover (CE.getNearest CE.product) ]
[ C.series .year
[ C.scatter .income [] ]
[ { year = 2000, income = 40000 }
, { year = 2010, income = 56000 }
, { year = 2020, income = 62000 }
]
, C.each model.hovering <| \plane product ->
[ C.tooltip product [] [] [] ]
]
-}
each : List a -> (C.Plane -> a -> List (Element data msg)) -> Element data msg
each items func =
SubElements <| \p _ -> List.concatMap (func p) items
{-| Add elements for each bin.
C.chart []
[ C.bars []
[ C.bar .income []
, C.bar .spending []
]
[ { country = "Denmark", income = 40000, spending = 10000 }
, { country = "Sweden", income = 56000, spending = 12000 }
, { country = "Norway", income = 62000, spending = 18000 }
]
, C.eachBin <| \plane bin ->
let common = CE.getCommonality bin in
[ C.label [] [ S.text common.datum.country ] (CE.getBottom plane bin) ]
]
Use the functions in `Chart.Events` to access information about your bins.
-}
eachBin : (C.Plane -> CE.Group (CE.Bin data) CE.Any Float data -> List (Element data msg)) -> Element data msg
eachBin func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.collect CE.bin <| CE.keep CE.realValues CE.product) is)
{-| Add elements for each stack.
C.chart []
[ C.bars []
[ C.stacked
[ C.bar .income []
, C.bar .savings []
]
]
[ { income = 40000, savings = 10000 }
, { income = 56000, savings = 12000 }
, { income = 62000, savings = 18000 }
]
, C.eachStack <| \plane stack ->
let total = List.sum (List.map CE.getDependent (CE.getProducts stack)) in
[ C.label [] [ S.text (String.fromFloat total) ] (CE.getTop plane stack) ]
]
Use the functions in `Chart.Events` to access information about your stacks.
-}
eachStack : (C.Plane -> CE.Group (CE.Stack data) CE.Any Float data -> List (Element data msg)) -> Element data msg
eachStack func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.collect CE.stack <| CE.keep CE.realValues CE.product) is)
{-| Add elements for each bar.
C.chart []
[ C.bars []
[ C.bar .income []
, C.bar .spending []
]
[ { income = 40000, spending = 10000 }
, { income = 56000, spending = 12000 }
, { income = 62000, spending = 18000 }
]
, C.eachBar <| \plane bar ->
let yValue = CE.getDependent bar in
[ C.label [] [ S.text (String.fromFloat yValue) ] (CE.getTop plane bar) ]
]
Use the functions in `Chart.Events` to access information about your bars.
-}
eachBar : (C.Plane -> CE.Product CE.Bar Float data -> List (Element data msg)) -> Element data msg
eachBar func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.keep CE.realValues CE.bar) is)
{-| Add elements for each dot.
C.chart []
[ C.series []
[ C.scatter .income []
, C.scatter .spending []
]
[ { income = 40000, spending = 10000 }
, { income = 56000, spending = 12000 }
, { income = 62000, spending = 18000 }
]
, C.eachBar <| \plane bar ->
let yValue = CE.getDependent bar in
[ C.label [] [ S.text (String.fromFloat yValue) ] (CE.getTop plane bar) ]
]
Use the functions in `Chart.Events` to access information about your dots.
-}
eachDot : (C.Plane -> CE.Product CE.Dot Float data -> List (Element data msg)) -> Element data msg
eachDot func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.keep CE.realValues CE.dot) is)
{-| Add elements for each product. Works like `eachBar` and `eachDot`, but includes both
bars and dots.
Use the functions in `Chart.Events` to access information about your products.
-}
eachProduct : (C.Plane -> CE.Product CE.Any Float data -> List (Element data msg)) -> Element data msg
eachProduct func =
SubElements <| \p is -> List.concatMap (func p) (CE.group (CE.keep CE.realValues CE.product) is)
{-| Filter and group products in any way you'd like and add elements for each of them.
C.chart []
[ C.eachCustom (CE.named "cats") <| \plane product ->
[ C.label [] [ S.text "hello" ] (CE.getTop plane product) ]
]
The above example adds a label for each product of the series named "cats".
Use the functions in `Chart.Events` to access information about your items.
-}
eachCustom : CE.Grouping (CE.Product CE.Any (Maybe Float) data) a -> (C.Plane -> a -> List (Element data msg)) -> Element data msg
eachCustom grouping func =
SubElements <| \p items ->
let processed = CE.group grouping items in
List.concatMap (func p) processed
{-| Add legends to your chart.
C.chart []
[ C.series .x
[ C.line .y [] []
|> C.named "cats"
, C.line .y [] []
|> C.named "dogs"
]
, C.legendsAt .min .max
[ CA.column -- Appear as column instead of row
, CA.alignRight -- Anchor legends to the right
, CA.alignLeft -- Anchor legends to the left
, CA.moveUp 5 -- Move 5px up
, CA.moveDown 5 -- Move 5px down
, CA.moveLeft 5 -- Move 5px left
, CA.moveRight 5 -- Move 5px right
, CA.spacing 20 -- Spacing between legends
, CA.background "beige" -- Color background
, CA.border "gray" -- Add border
, CA.borderWidth 1 -- Set border width
-- Add arbitrary HTML attributes. Convinient for extra styling.
, CA.htmlAttrs [ HA.class "my-legend" ]
]
[ CA.width 30 -- Change width of legend window
, CA.height 30 -- Change height of legend window
, CA.fontSize 12 -- Change font size
, CA.color "red" -- Change font color
, CA.spacing 12 -- Change spacing between window and title
, CA.htmlAttrs [ HA.class "my-legends" ] -- Add arbitrary HTML attributes.
]
]
-}
legendsAt : (C.Axis -> Float) -> (C.Axis -> Float) -> List (Attribute (CS.Legends msg)) -> List (Attribute (CS.Legend msg)) -> Element data msg
legendsAt toX toY attrs children =
HtmlElement <| \p legends_ ->
let viewLegend legend =
case legend of
Legend.BarLegend name barAttrs -> CS.barLegend (CA.title name :: children) barAttrs
Legend.LineLegend name interAttrs dotAttrs -> CS.lineLegend (CA.title name :: children) interAttrs dotAttrs
in
CS.legendsAt p (toX p.x) (toY p.y) attrs (List.map viewLegend legends_)
{-| Generate "nice" numbers. Useful in combination with `xLabel`, `yLabel`, `xTick`, and `yTick`.
C.chart []
[ C.generate 10 C.ints .x [ CA.lowest -5 CA.exactly, CA.highest 15 CA.exactly ] <| \plane int ->
[ C.xTick [ CA.x (toFloat int) ]
, C.xLabel [ CA.x (toFloat int) ] [ S.text (String.fromInt int) ]
]
]
The example above generates 10 ints on the x axis between x = -5 and x = 15. For each of those
ints, it adds a tick and a label.
-}
generate : Int -> CS.Generator a -> (C.Plane -> C.Axis) -> List (Attribute C.Axis) -> (C.Plane -> a -> List (Element data msg)) -> Element data msg
generate num gen limit attrs func =
SubElements <| \p _ ->
let items = CS.generate num gen (List.foldl (\f x -> f x) (limit p) attrs) in
List.concatMap (func p) items
{-| Generate "nice" floats.
-}
floats : CS.Generator Float
floats =
CS.floats
{-| Generate "nice" ints.
-}
ints : CS.Generator Int
ints =
CS.ints
{-| Generate "nice" times.
See the docs in [terezka/intervals](https://package.elm-lang.org/packages/terezka/intervals/2.0.0/Intervals#Time)
for more info about the properties of `Time`!
-}
times : Time.Zone -> CS.Generator I.Time
times =
CS.times
{-| Add a label, such as a chart title or other note, at a specific coordinate.
C.chart []
[ C.label [] [ S.text "Data from Fruits.com" ] { x = 5, y = 10 } ]
The example above adds your label at coordinates x = y and y = 10.
Other attributes you can use:
C.labelAt
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-label" ]
]
[ S.text "Data from Fruits.com" ]
{ x = 5, y = 10 }
-}
label : List (Attribute CS.Label) -> List (S.Svg msg) -> C.Point -> Element data msg
label attrs inner point =
SvgElement <| \p -> CS.label p attrs inner point
{-| Add a label, such as a chart title or other note, at a position relative to your axes.
C.chart []
[ C.labelAt (CA.percent 20) (CA.percent 90) [] [ S.text "Data from Fruits.com" ] ]
The example above adds your label at 20% the length of your range and 90% of your domain.
Other attributes you can use:
C.labelAt (CA.percent 20) (CA.percent 90)
[ CA.moveUp 5 -- Move 5 SVG units up
, CA.moveDown 5 -- Move 5 SVG units down
, CA.moveLeft 5 -- Move 5 SVG units left
, CA.moveRight 5 -- Move 5 SVG units right
, CA.color "#333"
, CA.border "white"
, CA.borderWidth 1
, CA.fontSize 12
, CA.alignRight -- Anchor labels to the right
, CA.alignLeft -- Anchor labels to the left
, CA.rotate 90 -- Rotate label 90 degrees
, CA.uppercase -- Make uppercase
-- Add arbitrary SVG attributes to your labels.
, CA.attrs [ SA.class "my-label" ]
]
[ S.text "Data from Fruits.com" ]
-}
labelAt : (C.Axis -> Float) -> (C.Axis -> Float) -> List (Attribute CS.Label) -> List (S.Svg msg) -> Element data msg
labelAt toX toY attrs inner =
SvgElement <| \p -> CS.label p attrs inner { x = toX p.x, y = toY p.y }
{-| Add a line.
C.chart []
[ C.line
[ CA.x1 2 -- Set x1
, CA.x2 8 -- Set x2
, CA.y1 3 -- Set y1
, CA.y2 7 -- Set y2
-- Instead of specifying x2 and y2
-- you can use `x2Svg` and `y2Svg`
-- to specify the end coordinate in
-- terms of SVG units.
--
-- Useful if making little label pointers.
-- This makes a from ( x1, y1 ) to the point
-- ( x1 + 15 SVG units, y1 + 30 SVG units )
, CA.x2Svg 15
, CA.y2Svg 30
, CA.break -- "break" line, so it it has a 90° angle
, CA.tickLength -- Add "ticks" at the ends of the line
, CA.tickDirection -- The angle of the ticks
, CA.color "red" -- Change color
, CA.width 2 -- Change width
, CA.opacity 0.8 -- Change opacity
, CA.dashed [ 5, 5 ] -- Add dashing
-- Add arbitrary SVG attributes.
, CA.attrs [ SA.id "my-line" ]
]
]
-}
line : List (Attribute CS.Line) -> Element data msg
line attrs =
SvgElement <| \p -> CS.line p attrs
{-| Add a rectangle.
C.chart []
[ C.rect
[ CA.x1 2 -- Set x1
, CA.x2 8 -- Set x2
, CA.y1 3 -- Set y1
, CA.y2 7 -- Set y2
, CA.color "#aaa" -- Change fill color
, CA.opacity 0.8 -- Change fill opacity
, CA.border "#333" -- Change border color
, CA.borderWidth 2 -- Change border width
-- Add arbitrary SVG attributes.
, CA.attrs [ SA.id "my-rect" ]
]
]
-}
rect : List (Attribute CS.Rect) -> Element data msg
rect attrs =
SvgElement <| \p -> CS.rect p attrs
{-| Add arbitrary SVG. See `Chart.Svg` for handy SVG helpers.
-}
svg : (C.Plane -> S.Svg msg) -> Element data msg
svg func =
SvgElement <| \p -> func p
{-| Add arbitrary HTML.
-}
html : (C.Plane -> H.Html msg) -> Element data msg
html func =
HtmlElement <| \p _ -> func p
{-| Add arbitrary SVG at a specific location. See `Chart.Svg` for handy SVG helpers.
C.chart []
[ C.svgAt .min .max 10 20 [ .. ]
-- Add .. at x = the minumum value of your range (x-axis) + 12 SVG units
-- and y = the maximum value of your domain (y-axis) + 20 SVG units
]
-}
svgAt : (C.Axis -> Float) -> (C.Axis -> Float) -> Float -> Float -> List (S.Svg msg) -> Element data msg
svgAt toX toY xOff yOff view =
SvgElement <| \p ->
S.g [ CS.position p 0 (toX p.x) (toY p.y) xOff yOff ] view
{-| Add arbitrary HTML at a specific location.
-}
htmlAt : (C.Axis -> Float) -> (C.Axis -> Float) -> Float -> Float -> List (H.Attribute msg) -> List (H.Html msg) -> Element data msg
htmlAt toX toY xOff yOff att view =
HtmlElement <| \p _ ->
CS.positionHtml p (toX p.x) (toY p.y) xOff yOff att view
{-| No element.
-}
none : Element data msg
none =
HtmlElement <| \_ _ -> H.text ""
-- DATA HELPERS
{-| Gather data points into bins. Arguments:
1. The desired bin width.
2. The function to access the binned quality on the data
3. The list of data.
C.binned 10 .score
[ Result "PI:NAME:<NAME>END_PI" 43
, Result "PI:NAME:<NAME>END_PI" 65
, Result "PI:NAME:<NAME>END_PI" 69
, Result "PI:NAME:<NAME>END_PI" 98
]
== [ { bin = 40, data = [ Result "PI:NAME:<NAME>END_PI" 43 ] }
, { bin = 60, data = [ Result "PI:NAME:<NAME>END_PI" 65, Result "PI:NAME:<NAME>END_PI" 69 ] }
, { bin = 90, data = [ Result "PI:NAME:<NAME>END_PI" 98 ] }
]
type alias Result = { name : String, score : Float }
-}
binned : Float -> (data -> Float) -> List data -> List { bin : Float, data : List data }
binned binWidth func data =
let fold datum =
Dict.update (toBin datum) (updateDict datum)
updateDict datum maybePrev =
case maybePrev of
Just prev -> Just (datum :: prev)
Nothing -> Just [ datum ]
toBin datum =
floor (func datum / binWidth)
in
List.foldr fold Dict.empty data
|> Dict.toList
|> List.map (\( bin, ds ) -> { bin = toFloat bin * binWidth, data = ds })
-- HELPERS
type alias TickValue =
{ value : Float
, label : String
}
generateValues : Int -> IS.TickType -> Maybe (Float -> String) -> C.Axis -> List TickValue
generateValues amount tick maybeFormat axis =
let toTickValues toValue toString =
List.map <| \i ->
{ value = toValue i
, label =
case maybeFormat of
Just format -> format (toValue i)
Nothing -> toString i
}
in
case tick of
IS.Floats ->
toTickValues identity String.fromFloat
(CS.generate amount CS.floats axis)
IS.Ints ->
toTickValues toFloat String.fromInt
(CS.generate amount CS.ints axis)
IS.Times zone ->
toTickValues (toFloat << Time.posixToMillis << .timestamp) (CS.formatTime zone)
(CS.generate amount (CS.times zone) axis)
| elm |
[
{
"context": "id = \"test\"\n , userName = \"test\"\n , name = \"test\"\n ",
"end": 726,
"score": 0.9973354936,
"start": 722,
"tag": "USERNAME",
"value": "test"
},
{
"context": "erName = \"test\"\n , name = \"test\"\n , email = \"test\"\n ",
"end": 766,
"score": 0.9996765256,
"start": 762,
"tag": "NAME",
"value": "test"
}
] | web/elm/tests/PauseToggleTests.elm | Caprowni/concourse | 6,675 | module PauseToggleTests exposing (all)
import ColorValues
import Data
import Dict
import Message.Message exposing (DomID(..), PipelinesSection(..))
import Test exposing (Test, describe, test)
import Test.Html.Query as Query
import Test.Html.Selector exposing (containing, style, tag, text)
import UserState exposing (UserState(..))
import Views.PauseToggle as PauseToggle
import Views.Styles as Styles
all : Test
all =
describe "pause toggle"
[ describe "when user is unauthorized" <|
let
pipeline =
Data.pipelineId
userState =
UserStateLoggedIn
{ id = "test"
, userName = "test"
, name = "test"
, email = "test"
, isAdmin = False
, teams = Dict.fromList [ ( "team", [ "viewer" ] ) ]
, displayUserId = "test"
}
in
[ test "has very low opacity" <|
\_ ->
PauseToggle.view
{ isPaused = False
, pipeline = pipeline
, isToggleHovered = False
, isToggleLoading = False
, margin = ""
, userState = userState
, tooltipPosition = Styles.Above
, domID = PipelineCardPauseToggle AllPipelinesSection 1
}
|> Query.fromHtml
|> Query.has [ style "opacity" "0.2" ]
, test "has tooltip above" <|
\_ ->
PauseToggle.view
{ isPaused = False
, pipeline = pipeline
, isToggleHovered = True
, isToggleLoading = False
, margin = ""
, userState = userState
, tooltipPosition = Styles.Above
, domID = PipelineCardPauseToggle AllPipelinesSection 1
}
|> Query.fromHtml
|> Query.has
[ style "position" "relative"
, containing
[ tag "div"
, containing [ text "not authorized" ]
, style "background-color" ColorValues.grey20
, style "position" "absolute"
, style "bottom" "100%"
, style "white-space" "nowrap"
, style "padding" "2.5px"
, style "margin-bottom" "5px"
, style "right" "-150%"
, style "z-index" "1"
]
]
, test "has tooltip below" <|
\_ ->
PauseToggle.view
{ isPaused = False
, pipeline = pipeline
, isToggleHovered = True
, isToggleLoading = False
, margin = ""
, userState = userState
, tooltipPosition = Styles.Below
, domID = PipelineCardPauseToggle AllPipelinesSection 1
}
|> Query.fromHtml
|> Query.has
[ style "position" "relative"
, containing
[ tag "div"
, containing [ text "not authorized" ]
, style "background-color" ColorValues.grey20
, style "position" "absolute"
, style "top" "100%"
, style "white-space" "nowrap"
, style "padding" "2.5px"
, style "margin-bottom" "5px"
, style "right" "-150%"
, style "z-index" "1"
]
]
]
]
| 23940 | module PauseToggleTests exposing (all)
import ColorValues
import Data
import Dict
import Message.Message exposing (DomID(..), PipelinesSection(..))
import Test exposing (Test, describe, test)
import Test.Html.Query as Query
import Test.Html.Selector exposing (containing, style, tag, text)
import UserState exposing (UserState(..))
import Views.PauseToggle as PauseToggle
import Views.Styles as Styles
all : Test
all =
describe "pause toggle"
[ describe "when user is unauthorized" <|
let
pipeline =
Data.pipelineId
userState =
UserStateLoggedIn
{ id = "test"
, userName = "test"
, name = "<NAME>"
, email = "test"
, isAdmin = False
, teams = Dict.fromList [ ( "team", [ "viewer" ] ) ]
, displayUserId = "test"
}
in
[ test "has very low opacity" <|
\_ ->
PauseToggle.view
{ isPaused = False
, pipeline = pipeline
, isToggleHovered = False
, isToggleLoading = False
, margin = ""
, userState = userState
, tooltipPosition = Styles.Above
, domID = PipelineCardPauseToggle AllPipelinesSection 1
}
|> Query.fromHtml
|> Query.has [ style "opacity" "0.2" ]
, test "has tooltip above" <|
\_ ->
PauseToggle.view
{ isPaused = False
, pipeline = pipeline
, isToggleHovered = True
, isToggleLoading = False
, margin = ""
, userState = userState
, tooltipPosition = Styles.Above
, domID = PipelineCardPauseToggle AllPipelinesSection 1
}
|> Query.fromHtml
|> Query.has
[ style "position" "relative"
, containing
[ tag "div"
, containing [ text "not authorized" ]
, style "background-color" ColorValues.grey20
, style "position" "absolute"
, style "bottom" "100%"
, style "white-space" "nowrap"
, style "padding" "2.5px"
, style "margin-bottom" "5px"
, style "right" "-150%"
, style "z-index" "1"
]
]
, test "has tooltip below" <|
\_ ->
PauseToggle.view
{ isPaused = False
, pipeline = pipeline
, isToggleHovered = True
, isToggleLoading = False
, margin = ""
, userState = userState
, tooltipPosition = Styles.Below
, domID = PipelineCardPauseToggle AllPipelinesSection 1
}
|> Query.fromHtml
|> Query.has
[ style "position" "relative"
, containing
[ tag "div"
, containing [ text "not authorized" ]
, style "background-color" ColorValues.grey20
, style "position" "absolute"
, style "top" "100%"
, style "white-space" "nowrap"
, style "padding" "2.5px"
, style "margin-bottom" "5px"
, style "right" "-150%"
, style "z-index" "1"
]
]
]
]
| true | module PauseToggleTests exposing (all)
import ColorValues
import Data
import Dict
import Message.Message exposing (DomID(..), PipelinesSection(..))
import Test exposing (Test, describe, test)
import Test.Html.Query as Query
import Test.Html.Selector exposing (containing, style, tag, text)
import UserState exposing (UserState(..))
import Views.PauseToggle as PauseToggle
import Views.Styles as Styles
all : Test
all =
describe "pause toggle"
[ describe "when user is unauthorized" <|
let
pipeline =
Data.pipelineId
userState =
UserStateLoggedIn
{ id = "test"
, userName = "test"
, name = "PI:NAME:<NAME>END_PI"
, email = "test"
, isAdmin = False
, teams = Dict.fromList [ ( "team", [ "viewer" ] ) ]
, displayUserId = "test"
}
in
[ test "has very low opacity" <|
\_ ->
PauseToggle.view
{ isPaused = False
, pipeline = pipeline
, isToggleHovered = False
, isToggleLoading = False
, margin = ""
, userState = userState
, tooltipPosition = Styles.Above
, domID = PipelineCardPauseToggle AllPipelinesSection 1
}
|> Query.fromHtml
|> Query.has [ style "opacity" "0.2" ]
, test "has tooltip above" <|
\_ ->
PauseToggle.view
{ isPaused = False
, pipeline = pipeline
, isToggleHovered = True
, isToggleLoading = False
, margin = ""
, userState = userState
, tooltipPosition = Styles.Above
, domID = PipelineCardPauseToggle AllPipelinesSection 1
}
|> Query.fromHtml
|> Query.has
[ style "position" "relative"
, containing
[ tag "div"
, containing [ text "not authorized" ]
, style "background-color" ColorValues.grey20
, style "position" "absolute"
, style "bottom" "100%"
, style "white-space" "nowrap"
, style "padding" "2.5px"
, style "margin-bottom" "5px"
, style "right" "-150%"
, style "z-index" "1"
]
]
, test "has tooltip below" <|
\_ ->
PauseToggle.view
{ isPaused = False
, pipeline = pipeline
, isToggleHovered = True
, isToggleLoading = False
, margin = ""
, userState = userState
, tooltipPosition = Styles.Below
, domID = PipelineCardPauseToggle AllPipelinesSection 1
}
|> Query.fromHtml
|> Query.has
[ style "position" "relative"
, containing
[ tag "div"
, containing [ text "not authorized" ]
, style "background-color" ColorValues.grey20
, style "position" "absolute"
, style "top" "100%"
, style "white-space" "nowrap"
, style "padding" "2.5px"
, style "margin-bottom" "5px"
, style "right" "-150%"
, style "z-index" "1"
]
]
]
]
| elm |
[
{
"context": "-- Elm-chat\n-- Developed by Christian Visintin <christian.visintin1997@gmail.com>\n-- Copyright ",
"end": 48,
"score": 0.999890089,
"start": 30,
"tag": "NAME",
"value": "Christian Visintin"
},
{
"context": "-- Elm-chat\n-- Developed by Christian Visintin <christian.visintin1997@gmail.com>\n-- Copyright (C) 2021 - Christian Visintin\n-- ",
"end": 82,
"score": 0.9999250174,
"start": 50,
"tag": "EMAIL",
"value": "christian.visintin1997@gmail.com"
},
{
"context": "n.visintin1997@gmail.com>\n-- Copyright (C) 2021 - Christian Visintin\n-- Distribuited under \"The Unlicense\" license\n--",
"end": 127,
"score": 0.9998785853,
"start": 109,
"tag": "NAME",
"value": "Christian Visintin"
}
] | src/Request/Auth.elm | veeso/elm-chat | 0 | -- Elm-chat
-- Developed by Christian Visintin <christian.visintin1997@gmail.com>
-- Copyright (C) 2021 - Christian Visintin
-- Distribuited under "The Unlicense" license
-- for more information, please refer to <https://unlicense.org>
module Request.Auth exposing (authed, signin, signout, signup)
import Data.Auth exposing (Authorization, authDecoder)
import File exposing (File)
import Http exposing (emptyBody, filePart, multipartBody, stringPart)
import Json.Encode as Encode
{-| Send a POST request to sign in
-}
signin : String -> String -> (Result Http.Error Authorization -> msg) -> Cmd msg
signin username password msg =
let
user =
Encode.object
[ ( "username", Encode.string username )
, ( "secret", Encode.string password )
]
in
Http.post
{ url = "/api/auth/signIn"
, body = Http.jsonBody user
, expect = Http.expectJson msg authDecoder
}
{-| Send a POST request to sign up
-}
signup : String -> String -> Maybe File -> (Result Http.Error Authorization -> msg) -> Cmd msg
signup username password avatar msg =
let
user =
Encode.object
[ ( "username", Encode.string username )
, ( "secret", Encode.string password )
]
in
Http.post
{ url = "/api/auth/signUp"
, body =
multipartBody
((stringPart "data" <| Encode.encode 0 user)
:: (case avatar of
Just file ->
[ filePart "avatar" file ]
Nothing ->
[]
)
)
, expect = Http.expectJson msg authDecoder
}
{-| Send a GET request to check whether the user is authed
-}
authed : (Result Http.Error Authorization -> msg) -> Cmd msg
authed msg =
Http.get
{ url = "/api/auth/authed"
, expect = Http.expectJson msg authDecoder
}
{-| Send a POST request to sign out
-}
signout : (Result Http.Error () -> msg) -> Cmd msg
signout msg =
Http.post
{ url = "/api/auth/signOut"
, body = emptyBody
, expect = Http.expectWhatever msg
}
| 17444 | -- Elm-chat
-- Developed by <NAME> <<EMAIL>>
-- Copyright (C) 2021 - <NAME>
-- Distribuited under "The Unlicense" license
-- for more information, please refer to <https://unlicense.org>
module Request.Auth exposing (authed, signin, signout, signup)
import Data.Auth exposing (Authorization, authDecoder)
import File exposing (File)
import Http exposing (emptyBody, filePart, multipartBody, stringPart)
import Json.Encode as Encode
{-| Send a POST request to sign in
-}
signin : String -> String -> (Result Http.Error Authorization -> msg) -> Cmd msg
signin username password msg =
let
user =
Encode.object
[ ( "username", Encode.string username )
, ( "secret", Encode.string password )
]
in
Http.post
{ url = "/api/auth/signIn"
, body = Http.jsonBody user
, expect = Http.expectJson msg authDecoder
}
{-| Send a POST request to sign up
-}
signup : String -> String -> Maybe File -> (Result Http.Error Authorization -> msg) -> Cmd msg
signup username password avatar msg =
let
user =
Encode.object
[ ( "username", Encode.string username )
, ( "secret", Encode.string password )
]
in
Http.post
{ url = "/api/auth/signUp"
, body =
multipartBody
((stringPart "data" <| Encode.encode 0 user)
:: (case avatar of
Just file ->
[ filePart "avatar" file ]
Nothing ->
[]
)
)
, expect = Http.expectJson msg authDecoder
}
{-| Send a GET request to check whether the user is authed
-}
authed : (Result Http.Error Authorization -> msg) -> Cmd msg
authed msg =
Http.get
{ url = "/api/auth/authed"
, expect = Http.expectJson msg authDecoder
}
{-| Send a POST request to sign out
-}
signout : (Result Http.Error () -> msg) -> Cmd msg
signout msg =
Http.post
{ url = "/api/auth/signOut"
, body = emptyBody
, expect = Http.expectWhatever msg
}
| true | -- Elm-chat
-- Developed by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
-- Copyright (C) 2021 - PI:NAME:<NAME>END_PI
-- Distribuited under "The Unlicense" license
-- for more information, please refer to <https://unlicense.org>
module Request.Auth exposing (authed, signin, signout, signup)
import Data.Auth exposing (Authorization, authDecoder)
import File exposing (File)
import Http exposing (emptyBody, filePart, multipartBody, stringPart)
import Json.Encode as Encode
{-| Send a POST request to sign in
-}
signin : String -> String -> (Result Http.Error Authorization -> msg) -> Cmd msg
signin username password msg =
let
user =
Encode.object
[ ( "username", Encode.string username )
, ( "secret", Encode.string password )
]
in
Http.post
{ url = "/api/auth/signIn"
, body = Http.jsonBody user
, expect = Http.expectJson msg authDecoder
}
{-| Send a POST request to sign up
-}
signup : String -> String -> Maybe File -> (Result Http.Error Authorization -> msg) -> Cmd msg
signup username password avatar msg =
let
user =
Encode.object
[ ( "username", Encode.string username )
, ( "secret", Encode.string password )
]
in
Http.post
{ url = "/api/auth/signUp"
, body =
multipartBody
((stringPart "data" <| Encode.encode 0 user)
:: (case avatar of
Just file ->
[ filePart "avatar" file ]
Nothing ->
[]
)
)
, expect = Http.expectJson msg authDecoder
}
{-| Send a GET request to check whether the user is authed
-}
authed : (Result Http.Error Authorization -> msg) -> Cmd msg
authed msg =
Http.get
{ url = "/api/auth/authed"
, expect = Http.expectJson msg authDecoder
}
{-| Send a POST request to sign out
-}
signout : (Result Http.Error () -> msg) -> Cmd msg
signout msg =
Http.post
{ url = "/api/auth/signOut"
, body = emptyBody
, expect = Http.expectWhatever msg
}
| elm |
[
{
"context": " from a tuple.\n\n first (3, 4) == 3\n first (\"john\", \"doe\") == \"john\"\n\nfirst: ( a, b ) -> a\n-}\nfirst",
"end": 1036,
"score": 0.7565465569,
"start": 1032,
"tag": "NAME",
"value": "john"
},
{
"context": "tuple.\n\n first (3, 4) == 3\n first (\"john\", \"doe\") == \"john\"\n\nfirst: ( a, b ) -> a\n-}\nfirst : Elm.",
"end": 1043,
"score": 0.7786464095,
"start": 1040,
"tag": "NAME",
"value": "doe"
},
{
"context": " first (3, 4) == 3\n first (\"john\", \"doe\") == \"john\"\n\nfirst: ( a, b ) -> a\n-}\nfirst : Elm.Expression ",
"end": 1054,
"score": 0.9586151242,
"start": 1050,
"tag": "NAME",
"value": "john"
},
{
"context": "rom a tuple.\n\n second (3, 4) == 4\n second (\"john\", \"doe\") == \"doe\"\n\nsecond: ( a, b ) -> b\n-}\nsecon",
"end": 1574,
"score": 0.6014621854,
"start": 1570,
"tag": "NAME",
"value": "john"
},
{
"context": "ple.\n\n second (3, 4) == 4\n second (\"john\", \"doe\") == \"doe\"\n\nsecond: ( a, b ) -> b\n-}\nsecond : Elm",
"end": 1581,
"score": 0.7230533957,
"start": 1578,
"tag": "NAME",
"value": "doe"
}
] | cli/gen-package/codegen/Gen/Tuple.elm | miniBill/elm-prefab | 19 | module Gen.Tuple exposing (call_, first, mapBoth, mapFirst, mapSecond, moduleName_, pair, second, values_)
{-|
@docs moduleName_, pair, first, second, mapFirst, mapSecond, mapBoth, call_, values_
-}
import Elm
import Elm.Annotation as Type
{-| The name of this module. -}
moduleName_ : List String
moduleName_ =
[ "Tuple" ]
{-| Create a 2-tuple.
-- pair 3 4 == (3, 4)
zip : List a -> List b -> List (a, b)
zip xs ys =
List.map2 Tuple.pair xs ys
pair: a -> b -> ( a, b )
-}
pair : Elm.Expression -> Elm.Expression -> Elm.Expression
pair arg arg0 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "pair"
, annotation =
Just
(Type.function
[ Type.var "a", Type.var "b" ]
(Type.tuple (Type.var "a") (Type.var "b"))
)
}
)
[ arg, arg0 ]
{-| Extract the first value from a tuple.
first (3, 4) == 3
first ("john", "doe") == "john"
first: ( a, b ) -> a
-}
first : Elm.Expression -> Elm.Expression
first arg =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "first"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "a")
)
}
)
[ arg ]
{-| Extract the second value from a tuple.
second (3, 4) == 4
second ("john", "doe") == "doe"
second: ( a, b ) -> b
-}
second : Elm.Expression -> Elm.Expression
second arg =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "second"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "b")
)
}
)
[ arg ]
{-| Transform the first value in a tuple.
import String
mapFirst String.reverse ("stressed", 16) == ("desserts", 16)
mapFirst String.length ("stressed", 16) == (8, 16)
mapFirst: (a -> x) -> ( a, b ) -> ( x, b )
-}
mapFirst :
(Elm.Expression -> Elm.Expression) -> Elm.Expression -> Elm.Expression
mapFirst arg arg0 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapFirst"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "b"))
)
}
)
[ Elm.functionReduced "unpack" arg, arg0 ]
{-| Transform the second value in a tuple.
mapSecond sqrt ("stressed", 16) == ("stressed", 4)
mapSecond negate ("stressed", 16) == ("stressed", -16)
mapSecond: (b -> y) -> ( a, b ) -> ( a, y )
-}
mapSecond :
(Elm.Expression -> Elm.Expression) -> Elm.Expression -> Elm.Expression
mapSecond arg arg0 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapSecond"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "a") (Type.var "y"))
)
}
)
[ Elm.functionReduced "unpack" arg, arg0 ]
{-| Transform both parts of a tuple.
import String
mapBoth String.reverse sqrt ("stressed", 16) == ("desserts", 4)
mapBoth String.length negate ("stressed", 16) == (8, -16)
mapBoth: (a -> x) -> (b -> y) -> ( a, b ) -> ( x, y )
-}
mapBoth :
(Elm.Expression -> Elm.Expression)
-> (Elm.Expression -> Elm.Expression)
-> Elm.Expression
-> Elm.Expression
mapBoth arg arg0 arg1 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapBoth"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "y"))
)
}
)
[ Elm.functionReduced "unpack" arg
, Elm.functionReduced "unpack" arg0
, arg1
]
call_ :
{ pair : Elm.Expression -> Elm.Expression -> Elm.Expression
, first : Elm.Expression -> Elm.Expression
, second : Elm.Expression -> Elm.Expression
, mapFirst : Elm.Expression -> Elm.Expression -> Elm.Expression
, mapSecond : Elm.Expression -> Elm.Expression -> Elm.Expression
, mapBoth :
Elm.Expression -> Elm.Expression -> Elm.Expression -> Elm.Expression
}
call_ =
{ pair =
\arg arg0 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "pair"
, annotation =
Just
(Type.function
[ Type.var "a", Type.var "b" ]
(Type.tuple (Type.var "a") (Type.var "b"))
)
}
)
[ arg, arg0 ]
, first =
\arg ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "first"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "a")
)
}
)
[ arg ]
, second =
\arg ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "second"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "b")
)
}
)
[ arg ]
, mapFirst =
\arg arg3 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapFirst"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "b"))
)
}
)
[ arg, arg3 ]
, mapSecond =
\arg arg4 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapSecond"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "a") (Type.var "y"))
)
}
)
[ arg, arg4 ]
, mapBoth =
\arg arg5 arg6 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapBoth"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "y"))
)
}
)
[ arg, arg5, arg6 ]
}
values_ :
{ pair : Elm.Expression
, first : Elm.Expression
, second : Elm.Expression
, mapFirst : Elm.Expression
, mapSecond : Elm.Expression
, mapBoth : Elm.Expression
}
values_ =
{ pair =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "pair"
, annotation =
Just
(Type.function
[ Type.var "a", Type.var "b" ]
(Type.tuple (Type.var "a") (Type.var "b"))
)
}
, first =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "first"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "a")
)
}
, second =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "second"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "b")
)
}
, mapFirst =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapFirst"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "b"))
)
}
, mapSecond =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapSecond"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "a") (Type.var "y"))
)
}
, mapBoth =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapBoth"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "y"))
)
}
}
| 18223 | module Gen.Tuple exposing (call_, first, mapBoth, mapFirst, mapSecond, moduleName_, pair, second, values_)
{-|
@docs moduleName_, pair, first, second, mapFirst, mapSecond, mapBoth, call_, values_
-}
import Elm
import Elm.Annotation as Type
{-| The name of this module. -}
moduleName_ : List String
moduleName_ =
[ "Tuple" ]
{-| Create a 2-tuple.
-- pair 3 4 == (3, 4)
zip : List a -> List b -> List (a, b)
zip xs ys =
List.map2 Tuple.pair xs ys
pair: a -> b -> ( a, b )
-}
pair : Elm.Expression -> Elm.Expression -> Elm.Expression
pair arg arg0 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "pair"
, annotation =
Just
(Type.function
[ Type.var "a", Type.var "b" ]
(Type.tuple (Type.var "a") (Type.var "b"))
)
}
)
[ arg, arg0 ]
{-| Extract the first value from a tuple.
first (3, 4) == 3
first ("<NAME>", "<NAME>") == "<NAME>"
first: ( a, b ) -> a
-}
first : Elm.Expression -> Elm.Expression
first arg =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "first"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "a")
)
}
)
[ arg ]
{-| Extract the second value from a tuple.
second (3, 4) == 4
second ("<NAME>", "<NAME>") == "doe"
second: ( a, b ) -> b
-}
second : Elm.Expression -> Elm.Expression
second arg =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "second"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "b")
)
}
)
[ arg ]
{-| Transform the first value in a tuple.
import String
mapFirst String.reverse ("stressed", 16) == ("desserts", 16)
mapFirst String.length ("stressed", 16) == (8, 16)
mapFirst: (a -> x) -> ( a, b ) -> ( x, b )
-}
mapFirst :
(Elm.Expression -> Elm.Expression) -> Elm.Expression -> Elm.Expression
mapFirst arg arg0 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapFirst"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "b"))
)
}
)
[ Elm.functionReduced "unpack" arg, arg0 ]
{-| Transform the second value in a tuple.
mapSecond sqrt ("stressed", 16) == ("stressed", 4)
mapSecond negate ("stressed", 16) == ("stressed", -16)
mapSecond: (b -> y) -> ( a, b ) -> ( a, y )
-}
mapSecond :
(Elm.Expression -> Elm.Expression) -> Elm.Expression -> Elm.Expression
mapSecond arg arg0 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapSecond"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "a") (Type.var "y"))
)
}
)
[ Elm.functionReduced "unpack" arg, arg0 ]
{-| Transform both parts of a tuple.
import String
mapBoth String.reverse sqrt ("stressed", 16) == ("desserts", 4)
mapBoth String.length negate ("stressed", 16) == (8, -16)
mapBoth: (a -> x) -> (b -> y) -> ( a, b ) -> ( x, y )
-}
mapBoth :
(Elm.Expression -> Elm.Expression)
-> (Elm.Expression -> Elm.Expression)
-> Elm.Expression
-> Elm.Expression
mapBoth arg arg0 arg1 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapBoth"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "y"))
)
}
)
[ Elm.functionReduced "unpack" arg
, Elm.functionReduced "unpack" arg0
, arg1
]
call_ :
{ pair : Elm.Expression -> Elm.Expression -> Elm.Expression
, first : Elm.Expression -> Elm.Expression
, second : Elm.Expression -> Elm.Expression
, mapFirst : Elm.Expression -> Elm.Expression -> Elm.Expression
, mapSecond : Elm.Expression -> Elm.Expression -> Elm.Expression
, mapBoth :
Elm.Expression -> Elm.Expression -> Elm.Expression -> Elm.Expression
}
call_ =
{ pair =
\arg arg0 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "pair"
, annotation =
Just
(Type.function
[ Type.var "a", Type.var "b" ]
(Type.tuple (Type.var "a") (Type.var "b"))
)
}
)
[ arg, arg0 ]
, first =
\arg ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "first"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "a")
)
}
)
[ arg ]
, second =
\arg ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "second"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "b")
)
}
)
[ arg ]
, mapFirst =
\arg arg3 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapFirst"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "b"))
)
}
)
[ arg, arg3 ]
, mapSecond =
\arg arg4 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapSecond"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "a") (Type.var "y"))
)
}
)
[ arg, arg4 ]
, mapBoth =
\arg arg5 arg6 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapBoth"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "y"))
)
}
)
[ arg, arg5, arg6 ]
}
values_ :
{ pair : Elm.Expression
, first : Elm.Expression
, second : Elm.Expression
, mapFirst : Elm.Expression
, mapSecond : Elm.Expression
, mapBoth : Elm.Expression
}
values_ =
{ pair =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "pair"
, annotation =
Just
(Type.function
[ Type.var "a", Type.var "b" ]
(Type.tuple (Type.var "a") (Type.var "b"))
)
}
, first =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "first"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "a")
)
}
, second =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "second"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "b")
)
}
, mapFirst =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapFirst"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "b"))
)
}
, mapSecond =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapSecond"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "a") (Type.var "y"))
)
}
, mapBoth =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapBoth"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "y"))
)
}
}
| true | module Gen.Tuple exposing (call_, first, mapBoth, mapFirst, mapSecond, moduleName_, pair, second, values_)
{-|
@docs moduleName_, pair, first, second, mapFirst, mapSecond, mapBoth, call_, values_
-}
import Elm
import Elm.Annotation as Type
{-| The name of this module. -}
moduleName_ : List String
moduleName_ =
[ "Tuple" ]
{-| Create a 2-tuple.
-- pair 3 4 == (3, 4)
zip : List a -> List b -> List (a, b)
zip xs ys =
List.map2 Tuple.pair xs ys
pair: a -> b -> ( a, b )
-}
pair : Elm.Expression -> Elm.Expression -> Elm.Expression
pair arg arg0 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "pair"
, annotation =
Just
(Type.function
[ Type.var "a", Type.var "b" ]
(Type.tuple (Type.var "a") (Type.var "b"))
)
}
)
[ arg, arg0 ]
{-| Extract the first value from a tuple.
first (3, 4) == 3
first ("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI") == "PI:NAME:<NAME>END_PI"
first: ( a, b ) -> a
-}
first : Elm.Expression -> Elm.Expression
first arg =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "first"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "a")
)
}
)
[ arg ]
{-| Extract the second value from a tuple.
second (3, 4) == 4
second ("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI") == "doe"
second: ( a, b ) -> b
-}
second : Elm.Expression -> Elm.Expression
second arg =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "second"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "b")
)
}
)
[ arg ]
{-| Transform the first value in a tuple.
import String
mapFirst String.reverse ("stressed", 16) == ("desserts", 16)
mapFirst String.length ("stressed", 16) == (8, 16)
mapFirst: (a -> x) -> ( a, b ) -> ( x, b )
-}
mapFirst :
(Elm.Expression -> Elm.Expression) -> Elm.Expression -> Elm.Expression
mapFirst arg arg0 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapFirst"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "b"))
)
}
)
[ Elm.functionReduced "unpack" arg, arg0 ]
{-| Transform the second value in a tuple.
mapSecond sqrt ("stressed", 16) == ("stressed", 4)
mapSecond negate ("stressed", 16) == ("stressed", -16)
mapSecond: (b -> y) -> ( a, b ) -> ( a, y )
-}
mapSecond :
(Elm.Expression -> Elm.Expression) -> Elm.Expression -> Elm.Expression
mapSecond arg arg0 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapSecond"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "a") (Type.var "y"))
)
}
)
[ Elm.functionReduced "unpack" arg, arg0 ]
{-| Transform both parts of a tuple.
import String
mapBoth String.reverse sqrt ("stressed", 16) == ("desserts", 4)
mapBoth String.length negate ("stressed", 16) == (8, -16)
mapBoth: (a -> x) -> (b -> y) -> ( a, b ) -> ( x, y )
-}
mapBoth :
(Elm.Expression -> Elm.Expression)
-> (Elm.Expression -> Elm.Expression)
-> Elm.Expression
-> Elm.Expression
mapBoth arg arg0 arg1 =
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapBoth"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "y"))
)
}
)
[ Elm.functionReduced "unpack" arg
, Elm.functionReduced "unpack" arg0
, arg1
]
call_ :
{ pair : Elm.Expression -> Elm.Expression -> Elm.Expression
, first : Elm.Expression -> Elm.Expression
, second : Elm.Expression -> Elm.Expression
, mapFirst : Elm.Expression -> Elm.Expression -> Elm.Expression
, mapSecond : Elm.Expression -> Elm.Expression -> Elm.Expression
, mapBoth :
Elm.Expression -> Elm.Expression -> Elm.Expression -> Elm.Expression
}
call_ =
{ pair =
\arg arg0 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "pair"
, annotation =
Just
(Type.function
[ Type.var "a", Type.var "b" ]
(Type.tuple (Type.var "a") (Type.var "b"))
)
}
)
[ arg, arg0 ]
, first =
\arg ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "first"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "a")
)
}
)
[ arg ]
, second =
\arg ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "second"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "b")
)
}
)
[ arg ]
, mapFirst =
\arg arg3 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapFirst"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "b"))
)
}
)
[ arg, arg3 ]
, mapSecond =
\arg arg4 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapSecond"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "a") (Type.var "y"))
)
}
)
[ arg, arg4 ]
, mapBoth =
\arg arg5 arg6 ->
Elm.apply
(Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapBoth"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "y"))
)
}
)
[ arg, arg5, arg6 ]
}
values_ :
{ pair : Elm.Expression
, first : Elm.Expression
, second : Elm.Expression
, mapFirst : Elm.Expression
, mapSecond : Elm.Expression
, mapBoth : Elm.Expression
}
values_ =
{ pair =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "pair"
, annotation =
Just
(Type.function
[ Type.var "a", Type.var "b" ]
(Type.tuple (Type.var "a") (Type.var "b"))
)
}
, first =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "first"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "a")
)
}
, second =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "second"
, annotation =
Just
(Type.function
[ Type.tuple (Type.var "a") (Type.var "b") ]
(Type.var "b")
)
}
, mapFirst =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapFirst"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "b"))
)
}
, mapSecond =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapSecond"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "a") (Type.var "y"))
)
}
, mapBoth =
Elm.value
{ importFrom = [ "Tuple" ]
, name = "mapBoth"
, annotation =
Just
(Type.function
[ Type.function [ Type.var "a" ] (Type.var "x")
, Type.function [ Type.var "b" ] (Type.var "y")
, Type.tuple (Type.var "a") (Type.var "b")
]
(Type.tuple (Type.var "x") (Type.var "y"))
)
}
}
| elm |
[
{
"context": " \"\"\"\n {\n \"id\": 123,\n \"name\": \"NAME SURNAME\",\n \"aliases\": [],\n \"district_id\": 1",
"end": 219,
"score": 0.9996350408,
"start": 207,
"tag": "NAME",
"value": "NAME SURNAME"
},
{
"context": "ey\nminimalAttorney =\n { id = 123\n , name = \"NAME SURNAME\"\n , aliases = []\n }\n\n\nmaximumJson =\n \"\"\"",
"end": 372,
"score": 0.9996433854,
"start": 360,
"tag": "NAME",
"value": "NAME SURNAME"
},
{
"context": " \"\"\"\n {\n \"id\": 123,\n \"name\": \"NAME SURNAME\",\n \"aliases\": [ \"UNNAME\" ],\n \"distr",
"end": 477,
"score": 0.9996460676,
"start": 465,
"tag": "NAME",
"value": "NAME SURNAME"
},
{
"context": "ey\nmaximumAttorney =\n { id = 123\n , name = \"NAME SURNAME\"\n , aliases = [ \"UNNAME\" ]\n }\n\n\nall : Test\n",
"end": 640,
"score": 0.9996818304,
"start": 628,
"tag": "NAME",
"value": "NAME SURNAME"
}
] | pages/tests/TestAttorney.elm | gregziegan/eviction-tracker | 5 | module TestAttorney exposing (all)
import Attorney exposing (Attorney)
import Expect
import Json.Decode as Decode
import Test exposing (..)
minimalJson =
"""
{
"id": 123,
"name": "NAME SURNAME",
"aliases": [],
"district_id": 1
}
"""
minimalAttorney : Attorney
minimalAttorney =
{ id = 123
, name = "NAME SURNAME"
, aliases = []
}
maximumJson =
"""
{
"id": 123,
"name": "NAME SURNAME",
"aliases": [ "UNNAME" ],
"district_id": 1
}
"""
maximumAttorney : Attorney
maximumAttorney =
{ id = 123
, name = "NAME SURNAME"
, aliases = [ "UNNAME" ]
}
all : Test
all =
describe "Creation"
[ test "decodes with nulls" <|
\() ->
Expect.equal
(Result.Ok minimalAttorney)
(Decode.decodeString Attorney.decoder minimalJson)
, test "decodes with values" <|
\() ->
Expect.equal
(Result.Ok maximumAttorney)
(Decode.decodeString Attorney.decoder maximumJson)
]
| 4363 | module TestAttorney exposing (all)
import Attorney exposing (Attorney)
import Expect
import Json.Decode as Decode
import Test exposing (..)
minimalJson =
"""
{
"id": 123,
"name": "<NAME>",
"aliases": [],
"district_id": 1
}
"""
minimalAttorney : Attorney
minimalAttorney =
{ id = 123
, name = "<NAME>"
, aliases = []
}
maximumJson =
"""
{
"id": 123,
"name": "<NAME>",
"aliases": [ "UNNAME" ],
"district_id": 1
}
"""
maximumAttorney : Attorney
maximumAttorney =
{ id = 123
, name = "<NAME>"
, aliases = [ "UNNAME" ]
}
all : Test
all =
describe "Creation"
[ test "decodes with nulls" <|
\() ->
Expect.equal
(Result.Ok minimalAttorney)
(Decode.decodeString Attorney.decoder minimalJson)
, test "decodes with values" <|
\() ->
Expect.equal
(Result.Ok maximumAttorney)
(Decode.decodeString Attorney.decoder maximumJson)
]
| true | module TestAttorney exposing (all)
import Attorney exposing (Attorney)
import Expect
import Json.Decode as Decode
import Test exposing (..)
minimalJson =
"""
{
"id": 123,
"name": "PI:NAME:<NAME>END_PI",
"aliases": [],
"district_id": 1
}
"""
minimalAttorney : Attorney
minimalAttorney =
{ id = 123
, name = "PI:NAME:<NAME>END_PI"
, aliases = []
}
maximumJson =
"""
{
"id": 123,
"name": "PI:NAME:<NAME>END_PI",
"aliases": [ "UNNAME" ],
"district_id": 1
}
"""
maximumAttorney : Attorney
maximumAttorney =
{ id = 123
, name = "PI:NAME:<NAME>END_PI"
, aliases = [ "UNNAME" ]
}
all : Test
all =
describe "Creation"
[ test "decodes with nulls" <|
\() ->
Expect.equal
(Result.Ok minimalAttorney)
(Decode.decodeString Attorney.decoder minimalJson)
, test "decodes with values" <|
\() ->
Expect.equal
(Result.Ok maximumAttorney)
(Decode.decodeString Attorney.decoder maximumJson)
]
| elm |
[
{
"context": "=\n Graph.fromNodeLabelsAndEdgePairs\n [ \"Myriel\"\n , \"Napoleon\"\n , \"Mlle.Baptistine\"",
"end": 6531,
"score": 0.9997555017,
"start": 6525,
"tag": "NAME",
"value": "Myriel"
},
{
"context": "eLabelsAndEdgePairs\n [ \"Myriel\"\n , \"Napoleon\"\n , \"Mlle.Baptistine\"\n , \"Mme.Maglo",
"end": 6552,
"score": 0.9998341203,
"start": 6544,
"tag": "NAME",
"value": "Napoleon"
},
{
"context": " [ \"Myriel\"\n , \"Napoleon\"\n , \"Mlle.Baptistine\"\n , \"Mme.Magloire\"\n , \"CountessdeLo",
"end": 6580,
"score": 0.9994770288,
"start": 6565,
"tag": "NAME",
"value": "Mlle.Baptistine"
},
{
"context": "\"Napoleon\"\n , \"Mlle.Baptistine\"\n , \"Mme.Magloire\"\n , \"CountessdeLo\"\n , \"Geborand\"\n ",
"end": 6605,
"score": 0.9918524623,
"start": 6593,
"tag": "NAME",
"value": "Mme.Magloire"
},
{
"context": "e.Baptistine\"\n , \"Mme.Magloire\"\n , \"CountessdeLo\"\n , \"Geborand\"\n , \"Champtercier\"\n ",
"end": 6630,
"score": 0.999328196,
"start": 6618,
"tag": "NAME",
"value": "CountessdeLo"
},
{
"context": "Mme.Magloire\"\n , \"CountessdeLo\"\n , \"Geborand\"\n , \"Champtercier\"\n , \"Cravatte\"\n ",
"end": 6651,
"score": 0.9998426437,
"start": 6643,
"tag": "NAME",
"value": "Geborand"
},
{
"context": " , \"CountessdeLo\"\n , \"Geborand\"\n , \"Champtercier\"\n , \"Cravatte\"\n , \"Count\"\n ,",
"end": 6676,
"score": 0.999841392,
"start": 6664,
"tag": "NAME",
"value": "Champtercier"
},
{
"context": " , \"Geborand\"\n , \"Champtercier\"\n , \"Cravatte\"\n , \"Count\"\n , \"OldMan\"\n , \"",
"end": 6697,
"score": 0.9998457432,
"start": 6689,
"tag": "NAME",
"value": "Cravatte"
},
{
"context": " , \"Champtercier\"\n , \"Cravatte\"\n , \"Count\"\n , \"OldMan\"\n , \"Labarre\"\n ,",
"end": 6715,
"score": 0.9994864464,
"start": 6710,
"tag": "NAME",
"value": "Count"
},
{
"context": " , \"Cravatte\"\n , \"Count\"\n , \"OldMan\"\n , \"Labarre\"\n , \"Valjean\"\n ",
"end": 6734,
"score": 0.9992432594,
"start": 6728,
"tag": "NAME",
"value": "OldMan"
},
{
"context": "\"\n , \"Count\"\n , \"OldMan\"\n , \"Labarre\"\n , \"Valjean\"\n , \"Marguerite\"\n ",
"end": 6754,
"score": 0.9998138547,
"start": 6747,
"tag": "NAME",
"value": "Labarre"
},
{
"context": " , \"OldMan\"\n , \"Labarre\"\n , \"Valjean\"\n , \"Marguerite\"\n , \"Mme.deR\"\n ",
"end": 6774,
"score": 0.9998300076,
"start": 6767,
"tag": "NAME",
"value": "Valjean"
},
{
"context": " , \"Labarre\"\n , \"Valjean\"\n , \"Marguerite\"\n , \"Mme.deR\"\n , \"Isabeau\"\n ",
"end": 6797,
"score": 0.9998449087,
"start": 6787,
"tag": "NAME",
"value": "Marguerite"
},
{
"context": " , \"Valjean\"\n , \"Marguerite\"\n , \"Mme.deR\"\n , \"Isabeau\"\n , \"Gervais\"\n ",
"end": 6817,
"score": 0.718500495,
"start": 6810,
"tag": "NAME",
"value": "Mme.deR"
},
{
"context": " , \"Marguerite\"\n , \"Mme.deR\"\n , \"Isabeau\"\n , \"Gervais\"\n , \"Tholomyes\"\n ",
"end": 6837,
"score": 0.9997739196,
"start": 6830,
"tag": "NAME",
"value": "Isabeau"
},
{
"context": " , \"Mme.deR\"\n , \"Isabeau\"\n , \"Gervais\"\n , \"Tholomyes\"\n , \"Listolier\"\n ",
"end": 6857,
"score": 0.9998381138,
"start": 6850,
"tag": "NAME",
"value": "Gervais"
},
{
"context": " , \"Isabeau\"\n , \"Gervais\"\n , \"Tholomyes\"\n , \"Listolier\"\n , \"Fameuil\"\n ",
"end": 6879,
"score": 0.9998518825,
"start": 6870,
"tag": "NAME",
"value": "Tholomyes"
},
{
"context": " , \"Gervais\"\n , \"Tholomyes\"\n , \"Listolier\"\n , \"Fameuil\"\n , \"Blacheville\"\n ",
"end": 6901,
"score": 0.9998251796,
"start": 6892,
"tag": "NAME",
"value": "Listolier"
},
{
"context": " , \"Tholomyes\"\n , \"Listolier\"\n , \"Fameuil\"\n , \"Blacheville\"\n , \"Favourite\"\n ",
"end": 6921,
"score": 0.9998452067,
"start": 6914,
"tag": "NAME",
"value": "Fameuil"
},
{
"context": " , \"Listolier\"\n , \"Fameuil\"\n , \"Blacheville\"\n , \"Favourite\"\n , \"Dahlia\"\n ",
"end": 6945,
"score": 0.9998357892,
"start": 6934,
"tag": "NAME",
"value": "Blacheville"
},
{
"context": " , \"Fameuil\"\n , \"Blacheville\"\n , \"Favourite\"\n , \"Dahlia\"\n , \"Zephine\"\n ,",
"end": 6967,
"score": 0.9997984767,
"start": 6958,
"tag": "NAME",
"value": "Favourite"
},
{
"context": " , \"Blacheville\"\n , \"Favourite\"\n , \"Dahlia\"\n , \"Zephine\"\n , \"Fantine\"\n ",
"end": 6986,
"score": 0.9998280406,
"start": 6980,
"tag": "NAME",
"value": "Dahlia"
},
{
"context": " , \"Favourite\"\n , \"Dahlia\"\n , \"Zephine\"\n , \"Fantine\"\n , \"Mme.Thenardier\"\n ",
"end": 7006,
"score": 0.9998309612,
"start": 6999,
"tag": "NAME",
"value": "Zephine"
},
{
"context": " , \"Dahlia\"\n , \"Zephine\"\n , \"Fantine\"\n , \"Mme.Thenardier\"\n , \"Thenardier",
"end": 7026,
"score": 0.9998364449,
"start": 7019,
"tag": "NAME",
"value": "Fantine"
},
{
"context": " , \"Zephine\"\n , \"Fantine\"\n , \"Mme.Thenardier\"\n , \"Thenardier\"\n , \"Cosette\"\n ",
"end": 7053,
"score": 0.9961306453,
"start": 7039,
"tag": "NAME",
"value": "Mme.Thenardier"
},
{
"context": ", \"Fantine\"\n , \"Mme.Thenardier\"\n , \"Thenardier\"\n , \"Cosette\"\n , \"Javert\"\n ,",
"end": 7076,
"score": 0.9998273253,
"start": 7066,
"tag": "NAME",
"value": "Thenardier"
},
{
"context": "Mme.Thenardier\"\n , \"Thenardier\"\n , \"Cosette\"\n , \"Javert\"\n , \"Fauchelevent\"\n ",
"end": 7096,
"score": 0.9998426437,
"start": 7089,
"tag": "NAME",
"value": "Cosette"
},
{
"context": " , \"Thenardier\"\n , \"Cosette\"\n , \"Javert\"\n , \"Fauchelevent\"\n , \"Bamatabois\"\n",
"end": 7115,
"score": 0.9998270273,
"start": 7109,
"tag": "NAME",
"value": "Javert"
},
{
"context": " , \"Cosette\"\n , \"Javert\"\n , \"Fauchelevent\"\n , \"Bamatabois\"\n , \"Perpetue\"\n ",
"end": 7140,
"score": 0.9998317957,
"start": 7128,
"tag": "NAME",
"value": "Fauchelevent"
},
{
"context": " , \"Javert\"\n , \"Fauchelevent\"\n , \"Bamatabois\"\n , \"Perpetue\"\n , \"Simplice\"\n ",
"end": 7163,
"score": 0.9998451471,
"start": 7153,
"tag": "NAME",
"value": "Bamatabois"
},
{
"context": " \"Fauchelevent\"\n , \"Bamatabois\"\n , \"Perpetue\"\n , \"Simplice\"\n , \"Scaufflaire\"\n ",
"end": 7184,
"score": 0.9998233318,
"start": 7176,
"tag": "NAME",
"value": "Perpetue"
},
{
"context": " , \"Bamatabois\"\n , \"Perpetue\"\n , \"Simplice\"\n , \"Scaufflaire\"\n , \"Woman1\"\n ",
"end": 7205,
"score": 0.9998396635,
"start": 7197,
"tag": "NAME",
"value": "Simplice"
},
{
"context": " , \"Perpetue\"\n , \"Simplice\"\n , \"Scaufflaire\"\n , \"Woman1\"\n , \"Judge\"\n , \"",
"end": 7229,
"score": 0.9998335242,
"start": 7218,
"tag": "NAME",
"value": "Scaufflaire"
},
{
"context": " , \"Scaufflaire\"\n , \"Woman1\"\n , \"Judge\"\n , \"Champmathieu\"\n , \"Brevet\"\n ",
"end": 7266,
"score": 0.99982059,
"start": 7261,
"tag": "NAME",
"value": "Judge"
},
{
"context": "\"\n , \"Woman1\"\n , \"Judge\"\n , \"Champmathieu\"\n , \"Brevet\"\n , \"Chenildieu\"\n ",
"end": 7291,
"score": 0.9998347163,
"start": 7279,
"tag": "NAME",
"value": "Champmathieu"
},
{
"context": " , \"Judge\"\n , \"Champmathieu\"\n , \"Brevet\"\n , \"Chenildieu\"\n , \"Cochepaille\"\n ",
"end": 7310,
"score": 0.9998332858,
"start": 7304,
"tag": "NAME",
"value": "Brevet"
},
{
"context": " , \"Champmathieu\"\n , \"Brevet\"\n , \"Chenildieu\"\n , \"Cochepaille\"\n , \"Pontmercy\"\n ",
"end": 7333,
"score": 0.999827683,
"start": 7323,
"tag": "NAME",
"value": "Chenildieu"
},
{
"context": " , \"Brevet\"\n , \"Chenildieu\"\n , \"Cochepaille\"\n , \"Pontmercy\"\n , \"Boulatruelle\"\n ",
"end": 7357,
"score": 0.9998522997,
"start": 7346,
"tag": "NAME",
"value": "Cochepaille"
},
{
"context": ", \"Chenildieu\"\n , \"Cochepaille\"\n , \"Pontmercy\"\n , \"Boulatruelle\"\n , \"Eponine\"\n ",
"end": 7379,
"score": 0.9998250008,
"start": 7370,
"tag": "NAME",
"value": "Pontmercy"
},
{
"context": " , \"Cochepaille\"\n , \"Pontmercy\"\n , \"Boulatruelle\"\n , \"Eponine\"\n , \"Anzelma\"\n ",
"end": 7404,
"score": 0.999843955,
"start": 7392,
"tag": "NAME",
"value": "Boulatruelle"
},
{
"context": ", \"Pontmercy\"\n , \"Boulatruelle\"\n , \"Eponine\"\n , \"Anzelma\"\n , \"Woman2\"\n ,",
"end": 7424,
"score": 0.999833405,
"start": 7417,
"tag": "NAME",
"value": "Eponine"
},
{
"context": " , \"Boulatruelle\"\n , \"Eponine\"\n , \"Anzelma\"\n , \"Woman2\"\n , \"MotherInnocent\"\n ",
"end": 7444,
"score": 0.9998421669,
"start": 7437,
"tag": "NAME",
"value": "Anzelma"
},
{
"context": " , \"Anzelma\"\n , \"Woman2\"\n , \"MotherInnocent\"\n , \"Gribier\"\n , \"Jondrette\"\n ",
"end": 7490,
"score": 0.9129907489,
"start": 7476,
"tag": "NAME",
"value": "MotherInnocent"
},
{
"context": " , \"Woman2\"\n , \"MotherInnocent\"\n , \"Gribier\"\n , \"Jondrette\"\n , \"Mme.Burgon\"\n ",
"end": 7510,
"score": 0.9998247027,
"start": 7503,
"tag": "NAME",
"value": "Gribier"
},
{
"context": ", \"MotherInnocent\"\n , \"Gribier\"\n , \"Jondrette\"\n , \"Mme.Burgon\"\n , \"Gavroche\"\n ",
"end": 7532,
"score": 0.9998497963,
"start": 7523,
"tag": "NAME",
"value": "Jondrette"
},
{
"context": " , \"Gribier\"\n , \"Jondrette\"\n , \"Mme.Burgon\"\n , \"Gavroche\"\n , \"Gillenormand\"\n ",
"end": 7555,
"score": 0.9764089584,
"start": 7545,
"tag": "NAME",
"value": "Mme.Burgon"
},
{
"context": " , \"Jondrette\"\n , \"Mme.Burgon\"\n , \"Gavroche\"\n , \"Gillenormand\"\n , \"Magnon\"\n ",
"end": 7576,
"score": 0.9998502731,
"start": 7568,
"tag": "NAME",
"value": "Gavroche"
},
{
"context": " , \"Mme.Burgon\"\n , \"Gavroche\"\n , \"Gillenormand\"\n , \"Magnon\"\n , \"Mlle.Gillenormand\"",
"end": 7601,
"score": 0.9995679855,
"start": 7589,
"tag": "NAME",
"value": "Gillenormand"
},
{
"context": " , \"Gavroche\"\n , \"Gillenormand\"\n , \"Magnon\"\n , \"Mlle.Gillenormand\"\n , \"Mme.Pon",
"end": 7620,
"score": 0.9997763634,
"start": 7614,
"tag": "NAME",
"value": "Magnon"
},
{
"context": " , \"Gillenormand\"\n , \"Magnon\"\n , \"Mlle.Gillenormand\"\n , \"Mme.Pontmercy\"\n , \"Mlle.Vauboi",
"end": 7650,
"score": 0.979329586,
"start": 7633,
"tag": "NAME",
"value": "Mlle.Gillenormand"
},
{
"context": "\"Magnon\"\n , \"Mlle.Gillenormand\"\n , \"Mme.Pontmercy\"\n , \"Mlle.Vaubois\"\n , \"Lt.Gillenorm",
"end": 7676,
"score": 0.9804472327,
"start": 7663,
"tag": "NAME",
"value": "Mme.Pontmercy"
},
{
"context": "illenormand\"\n , \"Mme.Pontmercy\"\n , \"Mlle.Vaubois\"\n , \"Lt.Gillenormand\"\n , \"Marius\"\n ",
"end": 7701,
"score": 0.9962900281,
"start": 7689,
"tag": "NAME",
"value": "Mlle.Vaubois"
},
{
"context": "\"\n , \"Mlle.Vaubois\"\n , \"Lt.Gillenormand\"\n , \"Marius\"\n , \"BaronessT\"\n ",
"end": 7729,
"score": 0.6288927794,
"start": 7726,
"tag": "NAME",
"value": "and"
},
{
"context": "e.Vaubois\"\n , \"Lt.Gillenormand\"\n , \"Marius\"\n , \"BaronessT\"\n , \"Mabeuf\"\n ",
"end": 7748,
"score": 0.999848485,
"start": 7742,
"tag": "NAME",
"value": "Marius"
},
{
"context": ", \"Lt.Gillenormand\"\n , \"Marius\"\n , \"BaronessT\"\n , \"Mabeuf\"\n , \"Enjolras\"\n ",
"end": 7770,
"score": 0.9998324513,
"start": 7761,
"tag": "NAME",
"value": "BaronessT"
},
{
"context": " , \"Marius\"\n , \"BaronessT\"\n , \"Mabeuf\"\n , \"Enjolras\"\n , \"Combeferre\"\n ",
"end": 7789,
"score": 0.9997921586,
"start": 7783,
"tag": "NAME",
"value": "Mabeuf"
},
{
"context": " , \"BaronessT\"\n , \"Mabeuf\"\n , \"Enjolras\"\n , \"Combeferre\"\n , \"Prouvaire\"\n ",
"end": 7810,
"score": 0.9998090267,
"start": 7802,
"tag": "NAME",
"value": "Enjolras"
},
{
"context": " , \"Mabeuf\"\n , \"Enjolras\"\n , \"Combeferre\"\n , \"Prouvaire\"\n , \"Feuilly\"\n ",
"end": 7833,
"score": 0.999826014,
"start": 7823,
"tag": "NAME",
"value": "Combeferre"
},
{
"context": " , \"Enjolras\"\n , \"Combeferre\"\n , \"Prouvaire\"\n , \"Feuilly\"\n , \"Courfeyrac\"\n ",
"end": 7855,
"score": 0.9998085499,
"start": 7846,
"tag": "NAME",
"value": "Prouvaire"
},
{
"context": " , \"Combeferre\"\n , \"Prouvaire\"\n , \"Feuilly\"\n , \"Courfeyrac\"\n , \"Bahorel\"\n ",
"end": 7875,
"score": 0.9998133779,
"start": 7868,
"tag": "NAME",
"value": "Feuilly"
},
{
"context": " , \"Prouvaire\"\n , \"Feuilly\"\n , \"Courfeyrac\"\n , \"Bahorel\"\n , \"Bossuet\"\n ",
"end": 7898,
"score": 0.9992046356,
"start": 7888,
"tag": "NAME",
"value": "Courfeyrac"
},
{
"context": " , \"Feuilly\"\n , \"Courfeyrac\"\n , \"Bahorel\"\n , \"Bossuet\"\n , \"Joly\"\n , \"",
"end": 7918,
"score": 0.9998132586,
"start": 7911,
"tag": "NAME",
"value": "Bahorel"
},
{
"context": " , \"Courfeyrac\"\n , \"Bahorel\"\n , \"Bossuet\"\n , \"Joly\"\n , \"Grantaire\"\n ,",
"end": 7938,
"score": 0.9998367429,
"start": 7931,
"tag": "NAME",
"value": "Bossuet"
},
{
"context": " , \"Bahorel\"\n , \"Bossuet\"\n , \"Joly\"\n , \"Grantaire\"\n , \"MotherPlutarch\"",
"end": 7955,
"score": 0.9997886419,
"start": 7951,
"tag": "NAME",
"value": "Joly"
},
{
"context": "\"\n , \"Bossuet\"\n , \"Joly\"\n , \"Grantaire\"\n , \"MotherPlutarch\"\n , \"Gueulemer\"",
"end": 7977,
"score": 0.999818027,
"start": 7968,
"tag": "NAME",
"value": "Grantaire"
},
{
"context": " , \"Joly\"\n , \"Grantaire\"\n , \"MotherPlutarch\"\n , \"Gueulemer\"\n , \"Babet\"\n ",
"end": 8004,
"score": 0.999848187,
"start": 7990,
"tag": "NAME",
"value": "MotherPlutarch"
},
{
"context": "\"Grantaire\"\n , \"MotherPlutarch\"\n , \"Gueulemer\"\n , \"Babet\"\n , \"Claquesous\"\n ",
"end": 8026,
"score": 0.9998528957,
"start": 8017,
"tag": "NAME",
"value": "Gueulemer"
},
{
"context": "\"MotherPlutarch\"\n , \"Gueulemer\"\n , \"Babet\"\n , \"Claquesous\"\n , \"Montparnasse\"\n",
"end": 8044,
"score": 0.9998095632,
"start": 8039,
"tag": "NAME",
"value": "Babet"
},
{
"context": " , \"Gueulemer\"\n , \"Babet\"\n , \"Claquesous\"\n , \"Montparnasse\"\n , \"Toussaint\"\n ",
"end": 8067,
"score": 0.9998403788,
"start": 8057,
"tag": "NAME",
"value": "Claquesous"
},
{
"context": " , \"Babet\"\n , \"Claquesous\"\n , \"Montparnasse\"\n , \"Toussaint\"\n , \"Child1\"\n ",
"end": 8092,
"score": 0.9998524189,
"start": 8080,
"tag": "NAME",
"value": "Montparnasse"
},
{
"context": " \"Claquesous\"\n , \"Montparnasse\"\n , \"Toussaint\"\n , \"Child1\"\n , \"Child2\"\n , ",
"end": 8114,
"score": 0.9998431206,
"start": 8105,
"tag": "NAME",
"value": "Toussaint"
},
{
"context": "\n , \"Child1\"\n , \"Child2\"\n , \"Brujon\"\n , \"Mme.Hucheloup\"\n ]\n [ ( ",
"end": 8171,
"score": 0.9998605847,
"start": 8165,
"tag": "NAME",
"value": "Brujon"
},
{
"context": "\n , \"Child2\"\n , \"Brujon\"\n , \"Mme.Hucheloup\"\n ]\n [ ( 1, 0 )\n , ( 2, 0 )\n",
"end": 8197,
"score": 0.9998751283,
"start": 8184,
"tag": "NAME",
"value": "Mme.Hucheloup"
}
] | examples/ForceDirectedGraph.elm | megapctr/elm-visualization | 0 | module ForceDirectedGraph exposing (main)
{-| This demonstrates laying out the characters in Les Miserables
based on their co-occurence in a scene. Try dragging the nodes!
@delay 5
@category Basics
-}
import Browser
import Browser.Events
import Color
import Force exposing (State)
import Graph exposing (Edge, Graph, Node, NodeContext, NodeId)
import Html
import Html.Events exposing (on)
import Html.Events.Extra.Mouse as Mouse
import Json.Decode as Decode
import Time
import TypedSvg exposing (circle, g, line, svg, title)
import TypedSvg.Attributes exposing (class, fill, stroke, viewBox)
import TypedSvg.Attributes.InPx exposing (cx, cy, r, strokeWidth, x1, x2, y1, y2)
import TypedSvg.Core exposing (Attribute, Svg, text)
import TypedSvg.Types exposing (Paint(..))
w : Float
w =
990
h : Float
h =
504
type Msg
= DragStart NodeId ( Float, Float )
| DragAt ( Float, Float )
| DragEnd ( Float, Float )
| Tick Time.Posix
type alias Model =
{ drag : Maybe Drag
, graph : Graph Entity ()
, simulation : Force.State NodeId
}
type alias Drag =
{ start : ( Float, Float )
, current : ( Float, Float )
, index : NodeId
}
type alias Entity =
Force.Entity NodeId { value : String }
initializeNode : NodeContext String () -> NodeContext Entity ()
initializeNode ctx =
{ node = { label = Force.entity ctx.node.id ctx.node.label, id = ctx.node.id }
, incoming = ctx.incoming
, outgoing = ctx.outgoing
}
init : () -> ( Model, Cmd Msg )
init _ =
let
graph =
Graph.mapContexts initializeNode miserablesGraph
link { from, to } =
( from, to )
forces =
[ Force.links <| List.map link <| Graph.edges graph
, Force.manyBody <| List.map .id <| Graph.nodes graph
, Force.center (w / 2) (h / 2)
]
in
( Model Nothing graph (Force.simulation forces), Cmd.none )
updateNode : ( Float, Float ) -> NodeContext Entity () -> NodeContext Entity ()
updateNode ( x, y ) nodeCtx =
let
nodeValue =
nodeCtx.node.label
in
updateContextWithValue nodeCtx { nodeValue | x = x, y = y }
updateContextWithValue : NodeContext Entity () -> Entity -> NodeContext Entity ()
updateContextWithValue nodeCtx value =
let
node =
nodeCtx.node
in
{ nodeCtx | node = { node | label = value } }
updateGraphWithList : Graph Entity () -> List Entity -> Graph Entity ()
updateGraphWithList =
let
graphUpdater value =
Maybe.map (\ctx -> updateContextWithValue ctx value)
in
List.foldr (\node graph -> Graph.update node.id (graphUpdater node) graph)
update : Msg -> Model -> Model
update msg ({ drag, graph, simulation } as model) =
case msg of
Tick t ->
let
( newState, list ) =
Force.tick simulation <| List.map .label <| Graph.nodes graph
in
case drag of
Nothing ->
Model drag (updateGraphWithList graph list) newState
Just { current, index } ->
Model drag
(Graph.update index
(Maybe.map (updateNode current))
(updateGraphWithList graph list)
)
newState
DragStart index xy ->
Model (Just (Drag xy xy index)) graph simulation
DragAt xy ->
case drag of
Just { start, index } ->
Model (Just (Drag start xy index))
(Graph.update index (Maybe.map (updateNode xy)) graph)
(Force.reheat simulation)
Nothing ->
Model Nothing graph simulation
DragEnd xy ->
case drag of
Just { start, index } ->
Model Nothing
(Graph.update index (Maybe.map (updateNode xy)) graph)
simulation
Nothing ->
Model Nothing graph simulation
subscriptions : Model -> Sub Msg
subscriptions model =
case model.drag of
Nothing ->
-- This allows us to save resources, as if the simulation is done, there is no point in subscribing
-- to the rAF.
if Force.isCompleted model.simulation then
Sub.none
else
Browser.Events.onAnimationFrame Tick
Just _ ->
Sub.batch
[ Browser.Events.onMouseMove (Decode.map (.clientPos >> DragAt) Mouse.eventDecoder)
, Browser.Events.onMouseUp (Decode.map (.clientPos >> DragEnd) Mouse.eventDecoder)
, Browser.Events.onAnimationFrame Tick
]
onMouseDown : NodeId -> Attribute Msg
onMouseDown index =
Mouse.onDown (.clientPos >> DragStart index)
linkElement : Graph Entity () -> Edge () -> Svg msg
linkElement graph edge =
let
source =
Maybe.withDefault (Force.entity 0 "") <| Maybe.map (.node >> .label) <| Graph.get edge.from graph
target =
Maybe.withDefault (Force.entity 0 "") <| Maybe.map (.node >> .label) <| Graph.get edge.to graph
in
line
[ strokeWidth 1
, stroke <| Paint <| Color.rgb255 170 170 170
, x1 source.x
, y1 source.y
, x2 target.x
, y2 target.y
]
[]
nodeElement : { a | id : NodeId, label : { b | x : Float, y : Float, value : String } } -> Svg Msg
nodeElement node =
circle
[ r 2.5
, fill <| Paint Color.black
, stroke <| Paint <| Color.rgba 0 0 0 0
, strokeWidth 7
, onMouseDown node.id
, cx node.label.x
, cy node.label.y
]
[ title [] [ text node.label.value ] ]
view : Model -> Svg Msg
view model =
svg [ viewBox 0 0 w h ]
[ Graph.edges model.graph
|> List.map (linkElement model.graph)
|> g [ class [ "links" ] ]
, Graph.nodes model.graph
|> List.map nodeElement
|> g [ class [ "nodes" ] ]
]
main : Program () Model Msg
main =
Browser.element
{ init = init
, view = view
, update = \msg model -> ( update msg model, Cmd.none )
, subscriptions = subscriptions
}
miserablesGraph : Graph String ()
miserablesGraph =
Graph.fromNodeLabelsAndEdgePairs
[ "Myriel"
, "Napoleon"
, "Mlle.Baptistine"
, "Mme.Magloire"
, "CountessdeLo"
, "Geborand"
, "Champtercier"
, "Cravatte"
, "Count"
, "OldMan"
, "Labarre"
, "Valjean"
, "Marguerite"
, "Mme.deR"
, "Isabeau"
, "Gervais"
, "Tholomyes"
, "Listolier"
, "Fameuil"
, "Blacheville"
, "Favourite"
, "Dahlia"
, "Zephine"
, "Fantine"
, "Mme.Thenardier"
, "Thenardier"
, "Cosette"
, "Javert"
, "Fauchelevent"
, "Bamatabois"
, "Perpetue"
, "Simplice"
, "Scaufflaire"
, "Woman1"
, "Judge"
, "Champmathieu"
, "Brevet"
, "Chenildieu"
, "Cochepaille"
, "Pontmercy"
, "Boulatruelle"
, "Eponine"
, "Anzelma"
, "Woman2"
, "MotherInnocent"
, "Gribier"
, "Jondrette"
, "Mme.Burgon"
, "Gavroche"
, "Gillenormand"
, "Magnon"
, "Mlle.Gillenormand"
, "Mme.Pontmercy"
, "Mlle.Vaubois"
, "Lt.Gillenormand"
, "Marius"
, "BaronessT"
, "Mabeuf"
, "Enjolras"
, "Combeferre"
, "Prouvaire"
, "Feuilly"
, "Courfeyrac"
, "Bahorel"
, "Bossuet"
, "Joly"
, "Grantaire"
, "MotherPlutarch"
, "Gueulemer"
, "Babet"
, "Claquesous"
, "Montparnasse"
, "Toussaint"
, "Child1"
, "Child2"
, "Brujon"
, "Mme.Hucheloup"
]
[ ( 1, 0 )
, ( 2, 0 )
, ( 3, 0 )
, ( 3, 2 )
, ( 4, 0 )
, ( 5, 0 )
, ( 6, 0 )
, ( 7, 0 )
, ( 8, 0 )
, ( 9, 0 )
, ( 11, 10 )
, ( 11, 3 )
, ( 11, 2 )
, ( 11, 0 )
, ( 12, 11 )
, ( 13, 11 )
, ( 14, 11 )
, ( 15, 11 )
, ( 17, 16 )
, ( 18, 16 )
, ( 18, 17 )
, ( 19, 16 )
, ( 19, 17 )
, ( 19, 18 )
, ( 20, 16 )
, ( 20, 17 )
, ( 20, 18 )
, ( 20, 19 )
, ( 21, 16 )
, ( 21, 17 )
, ( 21, 18 )
, ( 21, 19 )
, ( 21, 20 )
, ( 22, 16 )
, ( 22, 17 )
, ( 22, 18 )
, ( 22, 19 )
, ( 22, 20 )
, ( 22, 21 )
, ( 23, 16 )
, ( 23, 17 )
, ( 23, 18 )
, ( 23, 19 )
, ( 23, 20 )
, ( 23, 21 )
, ( 23, 22 )
, ( 23, 12 )
, ( 23, 11 )
, ( 24, 23 )
, ( 24, 11 )
, ( 25, 24 )
, ( 25, 23 )
, ( 25, 11 )
, ( 26, 24 )
, ( 26, 11 )
, ( 26, 16 )
, ( 26, 25 )
, ( 27, 11 )
, ( 27, 23 )
, ( 27, 25 )
, ( 27, 24 )
, ( 27, 26 )
, ( 28, 11 )
, ( 28, 27 )
, ( 29, 23 )
, ( 29, 27 )
, ( 29, 11 )
, ( 30, 23 )
, ( 31, 30 )
, ( 31, 11 )
, ( 31, 23 )
, ( 31, 27 )
, ( 32, 11 )
, ( 33, 11 )
, ( 33, 27 )
, ( 34, 11 )
, ( 34, 29 )
, ( 35, 11 )
, ( 35, 34 )
, ( 35, 29 )
, ( 36, 34 )
, ( 36, 35 )
, ( 36, 11 )
, ( 36, 29 )
, ( 37, 34 )
, ( 37, 35 )
, ( 37, 36 )
, ( 37, 11 )
, ( 37, 29 )
, ( 38, 34 )
, ( 38, 35 )
, ( 38, 36 )
, ( 38, 37 )
, ( 38, 11 )
, ( 38, 29 )
, ( 39, 25 )
, ( 40, 25 )
, ( 41, 24 )
, ( 41, 25 )
, ( 42, 41 )
, ( 42, 25 )
, ( 42, 24 )
, ( 43, 11 )
, ( 43, 26 )
, ( 43, 27 )
, ( 44, 28 )
, ( 44, 11 )
, ( 45, 28 )
, ( 47, 46 )
, ( 48, 47 )
, ( 48, 25 )
, ( 48, 27 )
, ( 48, 11 )
, ( 49, 26 )
, ( 49, 11 )
, ( 50, 49 )
, ( 50, 24 )
, ( 51, 49 )
, ( 51, 26 )
, ( 51, 11 )
, ( 52, 51 )
, ( 52, 39 )
, ( 53, 51 )
, ( 54, 51 )
, ( 54, 49 )
, ( 54, 26 )
, ( 55, 51 )
, ( 55, 49 )
, ( 55, 39 )
, ( 55, 54 )
, ( 55, 26 )
, ( 55, 11 )
, ( 55, 16 )
, ( 55, 25 )
, ( 55, 41 )
, ( 55, 48 )
, ( 56, 49 )
, ( 56, 55 )
, ( 57, 55 )
, ( 57, 41 )
, ( 57, 48 )
, ( 58, 55 )
, ( 58, 48 )
, ( 58, 27 )
, ( 58, 57 )
, ( 58, 11 )
, ( 59, 58 )
, ( 59, 55 )
, ( 59, 48 )
, ( 59, 57 )
, ( 60, 48 )
, ( 60, 58 )
, ( 60, 59 )
, ( 61, 48 )
, ( 61, 58 )
, ( 61, 60 )
, ( 61, 59 )
, ( 61, 57 )
, ( 61, 55 )
, ( 62, 55 )
, ( 62, 58 )
, ( 62, 59 )
, ( 62, 48 )
, ( 62, 57 )
, ( 62, 41 )
, ( 62, 61 )
, ( 62, 60 )
, ( 63, 59 )
, ( 63, 48 )
, ( 63, 62 )
, ( 63, 57 )
, ( 63, 58 )
, ( 63, 61 )
, ( 63, 60 )
, ( 63, 55 )
, ( 64, 55 )
, ( 64, 62 )
, ( 64, 48 )
, ( 64, 63 )
, ( 64, 58 )
, ( 64, 61 )
, ( 64, 60 )
, ( 64, 59 )
, ( 64, 57 )
, ( 64, 11 )
, ( 65, 63 )
, ( 65, 64 )
, ( 65, 48 )
, ( 65, 62 )
, ( 65, 58 )
, ( 65, 61 )
, ( 65, 60 )
, ( 65, 59 )
, ( 65, 57 )
, ( 65, 55 )
, ( 66, 64 )
, ( 66, 58 )
, ( 66, 59 )
, ( 66, 62 )
, ( 66, 65 )
, ( 66, 48 )
, ( 66, 63 )
, ( 66, 61 )
, ( 66, 60 )
, ( 67, 57 )
, ( 68, 25 )
, ( 68, 11 )
, ( 68, 24 )
, ( 68, 27 )
, ( 68, 48 )
, ( 68, 41 )
, ( 69, 25 )
, ( 69, 68 )
, ( 69, 11 )
, ( 69, 24 )
, ( 69, 27 )
, ( 69, 48 )
, ( 69, 41 )
, ( 70, 25 )
, ( 70, 69 )
, ( 70, 68 )
, ( 70, 11 )
, ( 70, 24 )
, ( 70, 27 )
, ( 70, 41 )
, ( 70, 58 )
, ( 71, 27 )
, ( 71, 69 )
, ( 71, 68 )
, ( 71, 70 )
, ( 71, 11 )
, ( 71, 48 )
, ( 71, 41 )
, ( 71, 25 )
, ( 72, 26 )
, ( 72, 27 )
, ( 72, 11 )
, ( 73, 48 )
, ( 74, 48 )
, ( 74, 73 )
, ( 75, 69 )
, ( 75, 68 )
, ( 75, 25 )
, ( 75, 48 )
, ( 75, 41 )
, ( 75, 70 )
, ( 75, 71 )
, ( 76, 64 )
, ( 76, 65 )
, ( 76, 66 )
, ( 76, 63 )
, ( 76, 62 )
, ( 76, 48 )
, ( 76, 58 )
]
{- {"delay": 5} -}
| 17928 | module ForceDirectedGraph exposing (main)
{-| This demonstrates laying out the characters in Les Miserables
based on their co-occurence in a scene. Try dragging the nodes!
@delay 5
@category Basics
-}
import Browser
import Browser.Events
import Color
import Force exposing (State)
import Graph exposing (Edge, Graph, Node, NodeContext, NodeId)
import Html
import Html.Events exposing (on)
import Html.Events.Extra.Mouse as Mouse
import Json.Decode as Decode
import Time
import TypedSvg exposing (circle, g, line, svg, title)
import TypedSvg.Attributes exposing (class, fill, stroke, viewBox)
import TypedSvg.Attributes.InPx exposing (cx, cy, r, strokeWidth, x1, x2, y1, y2)
import TypedSvg.Core exposing (Attribute, Svg, text)
import TypedSvg.Types exposing (Paint(..))
w : Float
w =
990
h : Float
h =
504
type Msg
= DragStart NodeId ( Float, Float )
| DragAt ( Float, Float )
| DragEnd ( Float, Float )
| Tick Time.Posix
type alias Model =
{ drag : Maybe Drag
, graph : Graph Entity ()
, simulation : Force.State NodeId
}
type alias Drag =
{ start : ( Float, Float )
, current : ( Float, Float )
, index : NodeId
}
type alias Entity =
Force.Entity NodeId { value : String }
initializeNode : NodeContext String () -> NodeContext Entity ()
initializeNode ctx =
{ node = { label = Force.entity ctx.node.id ctx.node.label, id = ctx.node.id }
, incoming = ctx.incoming
, outgoing = ctx.outgoing
}
init : () -> ( Model, Cmd Msg )
init _ =
let
graph =
Graph.mapContexts initializeNode miserablesGraph
link { from, to } =
( from, to )
forces =
[ Force.links <| List.map link <| Graph.edges graph
, Force.manyBody <| List.map .id <| Graph.nodes graph
, Force.center (w / 2) (h / 2)
]
in
( Model Nothing graph (Force.simulation forces), Cmd.none )
updateNode : ( Float, Float ) -> NodeContext Entity () -> NodeContext Entity ()
updateNode ( x, y ) nodeCtx =
let
nodeValue =
nodeCtx.node.label
in
updateContextWithValue nodeCtx { nodeValue | x = x, y = y }
updateContextWithValue : NodeContext Entity () -> Entity -> NodeContext Entity ()
updateContextWithValue nodeCtx value =
let
node =
nodeCtx.node
in
{ nodeCtx | node = { node | label = value } }
updateGraphWithList : Graph Entity () -> List Entity -> Graph Entity ()
updateGraphWithList =
let
graphUpdater value =
Maybe.map (\ctx -> updateContextWithValue ctx value)
in
List.foldr (\node graph -> Graph.update node.id (graphUpdater node) graph)
update : Msg -> Model -> Model
update msg ({ drag, graph, simulation } as model) =
case msg of
Tick t ->
let
( newState, list ) =
Force.tick simulation <| List.map .label <| Graph.nodes graph
in
case drag of
Nothing ->
Model drag (updateGraphWithList graph list) newState
Just { current, index } ->
Model drag
(Graph.update index
(Maybe.map (updateNode current))
(updateGraphWithList graph list)
)
newState
DragStart index xy ->
Model (Just (Drag xy xy index)) graph simulation
DragAt xy ->
case drag of
Just { start, index } ->
Model (Just (Drag start xy index))
(Graph.update index (Maybe.map (updateNode xy)) graph)
(Force.reheat simulation)
Nothing ->
Model Nothing graph simulation
DragEnd xy ->
case drag of
Just { start, index } ->
Model Nothing
(Graph.update index (Maybe.map (updateNode xy)) graph)
simulation
Nothing ->
Model Nothing graph simulation
subscriptions : Model -> Sub Msg
subscriptions model =
case model.drag of
Nothing ->
-- This allows us to save resources, as if the simulation is done, there is no point in subscribing
-- to the rAF.
if Force.isCompleted model.simulation then
Sub.none
else
Browser.Events.onAnimationFrame Tick
Just _ ->
Sub.batch
[ Browser.Events.onMouseMove (Decode.map (.clientPos >> DragAt) Mouse.eventDecoder)
, Browser.Events.onMouseUp (Decode.map (.clientPos >> DragEnd) Mouse.eventDecoder)
, Browser.Events.onAnimationFrame Tick
]
onMouseDown : NodeId -> Attribute Msg
onMouseDown index =
Mouse.onDown (.clientPos >> DragStart index)
linkElement : Graph Entity () -> Edge () -> Svg msg
linkElement graph edge =
let
source =
Maybe.withDefault (Force.entity 0 "") <| Maybe.map (.node >> .label) <| Graph.get edge.from graph
target =
Maybe.withDefault (Force.entity 0 "") <| Maybe.map (.node >> .label) <| Graph.get edge.to graph
in
line
[ strokeWidth 1
, stroke <| Paint <| Color.rgb255 170 170 170
, x1 source.x
, y1 source.y
, x2 target.x
, y2 target.y
]
[]
nodeElement : { a | id : NodeId, label : { b | x : Float, y : Float, value : String } } -> Svg Msg
nodeElement node =
circle
[ r 2.5
, fill <| Paint Color.black
, stroke <| Paint <| Color.rgba 0 0 0 0
, strokeWidth 7
, onMouseDown node.id
, cx node.label.x
, cy node.label.y
]
[ title [] [ text node.label.value ] ]
view : Model -> Svg Msg
view model =
svg [ viewBox 0 0 w h ]
[ Graph.edges model.graph
|> List.map (linkElement model.graph)
|> g [ class [ "links" ] ]
, Graph.nodes model.graph
|> List.map nodeElement
|> g [ class [ "nodes" ] ]
]
main : Program () Model Msg
main =
Browser.element
{ init = init
, view = view
, update = \msg model -> ( update msg model, Cmd.none )
, subscriptions = subscriptions
}
miserablesGraph : Graph String ()
miserablesGraph =
Graph.fromNodeLabelsAndEdgePairs
[ "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "Woman1"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "Woman2"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "Lt.Gillenorm<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "Child1"
, "Child2"
, "<NAME>"
, "<NAME>"
]
[ ( 1, 0 )
, ( 2, 0 )
, ( 3, 0 )
, ( 3, 2 )
, ( 4, 0 )
, ( 5, 0 )
, ( 6, 0 )
, ( 7, 0 )
, ( 8, 0 )
, ( 9, 0 )
, ( 11, 10 )
, ( 11, 3 )
, ( 11, 2 )
, ( 11, 0 )
, ( 12, 11 )
, ( 13, 11 )
, ( 14, 11 )
, ( 15, 11 )
, ( 17, 16 )
, ( 18, 16 )
, ( 18, 17 )
, ( 19, 16 )
, ( 19, 17 )
, ( 19, 18 )
, ( 20, 16 )
, ( 20, 17 )
, ( 20, 18 )
, ( 20, 19 )
, ( 21, 16 )
, ( 21, 17 )
, ( 21, 18 )
, ( 21, 19 )
, ( 21, 20 )
, ( 22, 16 )
, ( 22, 17 )
, ( 22, 18 )
, ( 22, 19 )
, ( 22, 20 )
, ( 22, 21 )
, ( 23, 16 )
, ( 23, 17 )
, ( 23, 18 )
, ( 23, 19 )
, ( 23, 20 )
, ( 23, 21 )
, ( 23, 22 )
, ( 23, 12 )
, ( 23, 11 )
, ( 24, 23 )
, ( 24, 11 )
, ( 25, 24 )
, ( 25, 23 )
, ( 25, 11 )
, ( 26, 24 )
, ( 26, 11 )
, ( 26, 16 )
, ( 26, 25 )
, ( 27, 11 )
, ( 27, 23 )
, ( 27, 25 )
, ( 27, 24 )
, ( 27, 26 )
, ( 28, 11 )
, ( 28, 27 )
, ( 29, 23 )
, ( 29, 27 )
, ( 29, 11 )
, ( 30, 23 )
, ( 31, 30 )
, ( 31, 11 )
, ( 31, 23 )
, ( 31, 27 )
, ( 32, 11 )
, ( 33, 11 )
, ( 33, 27 )
, ( 34, 11 )
, ( 34, 29 )
, ( 35, 11 )
, ( 35, 34 )
, ( 35, 29 )
, ( 36, 34 )
, ( 36, 35 )
, ( 36, 11 )
, ( 36, 29 )
, ( 37, 34 )
, ( 37, 35 )
, ( 37, 36 )
, ( 37, 11 )
, ( 37, 29 )
, ( 38, 34 )
, ( 38, 35 )
, ( 38, 36 )
, ( 38, 37 )
, ( 38, 11 )
, ( 38, 29 )
, ( 39, 25 )
, ( 40, 25 )
, ( 41, 24 )
, ( 41, 25 )
, ( 42, 41 )
, ( 42, 25 )
, ( 42, 24 )
, ( 43, 11 )
, ( 43, 26 )
, ( 43, 27 )
, ( 44, 28 )
, ( 44, 11 )
, ( 45, 28 )
, ( 47, 46 )
, ( 48, 47 )
, ( 48, 25 )
, ( 48, 27 )
, ( 48, 11 )
, ( 49, 26 )
, ( 49, 11 )
, ( 50, 49 )
, ( 50, 24 )
, ( 51, 49 )
, ( 51, 26 )
, ( 51, 11 )
, ( 52, 51 )
, ( 52, 39 )
, ( 53, 51 )
, ( 54, 51 )
, ( 54, 49 )
, ( 54, 26 )
, ( 55, 51 )
, ( 55, 49 )
, ( 55, 39 )
, ( 55, 54 )
, ( 55, 26 )
, ( 55, 11 )
, ( 55, 16 )
, ( 55, 25 )
, ( 55, 41 )
, ( 55, 48 )
, ( 56, 49 )
, ( 56, 55 )
, ( 57, 55 )
, ( 57, 41 )
, ( 57, 48 )
, ( 58, 55 )
, ( 58, 48 )
, ( 58, 27 )
, ( 58, 57 )
, ( 58, 11 )
, ( 59, 58 )
, ( 59, 55 )
, ( 59, 48 )
, ( 59, 57 )
, ( 60, 48 )
, ( 60, 58 )
, ( 60, 59 )
, ( 61, 48 )
, ( 61, 58 )
, ( 61, 60 )
, ( 61, 59 )
, ( 61, 57 )
, ( 61, 55 )
, ( 62, 55 )
, ( 62, 58 )
, ( 62, 59 )
, ( 62, 48 )
, ( 62, 57 )
, ( 62, 41 )
, ( 62, 61 )
, ( 62, 60 )
, ( 63, 59 )
, ( 63, 48 )
, ( 63, 62 )
, ( 63, 57 )
, ( 63, 58 )
, ( 63, 61 )
, ( 63, 60 )
, ( 63, 55 )
, ( 64, 55 )
, ( 64, 62 )
, ( 64, 48 )
, ( 64, 63 )
, ( 64, 58 )
, ( 64, 61 )
, ( 64, 60 )
, ( 64, 59 )
, ( 64, 57 )
, ( 64, 11 )
, ( 65, 63 )
, ( 65, 64 )
, ( 65, 48 )
, ( 65, 62 )
, ( 65, 58 )
, ( 65, 61 )
, ( 65, 60 )
, ( 65, 59 )
, ( 65, 57 )
, ( 65, 55 )
, ( 66, 64 )
, ( 66, 58 )
, ( 66, 59 )
, ( 66, 62 )
, ( 66, 65 )
, ( 66, 48 )
, ( 66, 63 )
, ( 66, 61 )
, ( 66, 60 )
, ( 67, 57 )
, ( 68, 25 )
, ( 68, 11 )
, ( 68, 24 )
, ( 68, 27 )
, ( 68, 48 )
, ( 68, 41 )
, ( 69, 25 )
, ( 69, 68 )
, ( 69, 11 )
, ( 69, 24 )
, ( 69, 27 )
, ( 69, 48 )
, ( 69, 41 )
, ( 70, 25 )
, ( 70, 69 )
, ( 70, 68 )
, ( 70, 11 )
, ( 70, 24 )
, ( 70, 27 )
, ( 70, 41 )
, ( 70, 58 )
, ( 71, 27 )
, ( 71, 69 )
, ( 71, 68 )
, ( 71, 70 )
, ( 71, 11 )
, ( 71, 48 )
, ( 71, 41 )
, ( 71, 25 )
, ( 72, 26 )
, ( 72, 27 )
, ( 72, 11 )
, ( 73, 48 )
, ( 74, 48 )
, ( 74, 73 )
, ( 75, 69 )
, ( 75, 68 )
, ( 75, 25 )
, ( 75, 48 )
, ( 75, 41 )
, ( 75, 70 )
, ( 75, 71 )
, ( 76, 64 )
, ( 76, 65 )
, ( 76, 66 )
, ( 76, 63 )
, ( 76, 62 )
, ( 76, 48 )
, ( 76, 58 )
]
{- {"delay": 5} -}
| true | module ForceDirectedGraph exposing (main)
{-| This demonstrates laying out the characters in Les Miserables
based on their co-occurence in a scene. Try dragging the nodes!
@delay 5
@category Basics
-}
import Browser
import Browser.Events
import Color
import Force exposing (State)
import Graph exposing (Edge, Graph, Node, NodeContext, NodeId)
import Html
import Html.Events exposing (on)
import Html.Events.Extra.Mouse as Mouse
import Json.Decode as Decode
import Time
import TypedSvg exposing (circle, g, line, svg, title)
import TypedSvg.Attributes exposing (class, fill, stroke, viewBox)
import TypedSvg.Attributes.InPx exposing (cx, cy, r, strokeWidth, x1, x2, y1, y2)
import TypedSvg.Core exposing (Attribute, Svg, text)
import TypedSvg.Types exposing (Paint(..))
w : Float
w =
990
h : Float
h =
504
type Msg
= DragStart NodeId ( Float, Float )
| DragAt ( Float, Float )
| DragEnd ( Float, Float )
| Tick Time.Posix
type alias Model =
{ drag : Maybe Drag
, graph : Graph Entity ()
, simulation : Force.State NodeId
}
type alias Drag =
{ start : ( Float, Float )
, current : ( Float, Float )
, index : NodeId
}
type alias Entity =
Force.Entity NodeId { value : String }
initializeNode : NodeContext String () -> NodeContext Entity ()
initializeNode ctx =
{ node = { label = Force.entity ctx.node.id ctx.node.label, id = ctx.node.id }
, incoming = ctx.incoming
, outgoing = ctx.outgoing
}
init : () -> ( Model, Cmd Msg )
init _ =
let
graph =
Graph.mapContexts initializeNode miserablesGraph
link { from, to } =
( from, to )
forces =
[ Force.links <| List.map link <| Graph.edges graph
, Force.manyBody <| List.map .id <| Graph.nodes graph
, Force.center (w / 2) (h / 2)
]
in
( Model Nothing graph (Force.simulation forces), Cmd.none )
updateNode : ( Float, Float ) -> NodeContext Entity () -> NodeContext Entity ()
updateNode ( x, y ) nodeCtx =
let
nodeValue =
nodeCtx.node.label
in
updateContextWithValue nodeCtx { nodeValue | x = x, y = y }
updateContextWithValue : NodeContext Entity () -> Entity -> NodeContext Entity ()
updateContextWithValue nodeCtx value =
let
node =
nodeCtx.node
in
{ nodeCtx | node = { node | label = value } }
updateGraphWithList : Graph Entity () -> List Entity -> Graph Entity ()
updateGraphWithList =
let
graphUpdater value =
Maybe.map (\ctx -> updateContextWithValue ctx value)
in
List.foldr (\node graph -> Graph.update node.id (graphUpdater node) graph)
update : Msg -> Model -> Model
update msg ({ drag, graph, simulation } as model) =
case msg of
Tick t ->
let
( newState, list ) =
Force.tick simulation <| List.map .label <| Graph.nodes graph
in
case drag of
Nothing ->
Model drag (updateGraphWithList graph list) newState
Just { current, index } ->
Model drag
(Graph.update index
(Maybe.map (updateNode current))
(updateGraphWithList graph list)
)
newState
DragStart index xy ->
Model (Just (Drag xy xy index)) graph simulation
DragAt xy ->
case drag of
Just { start, index } ->
Model (Just (Drag start xy index))
(Graph.update index (Maybe.map (updateNode xy)) graph)
(Force.reheat simulation)
Nothing ->
Model Nothing graph simulation
DragEnd xy ->
case drag of
Just { start, index } ->
Model Nothing
(Graph.update index (Maybe.map (updateNode xy)) graph)
simulation
Nothing ->
Model Nothing graph simulation
subscriptions : Model -> Sub Msg
subscriptions model =
case model.drag of
Nothing ->
-- This allows us to save resources, as if the simulation is done, there is no point in subscribing
-- to the rAF.
if Force.isCompleted model.simulation then
Sub.none
else
Browser.Events.onAnimationFrame Tick
Just _ ->
Sub.batch
[ Browser.Events.onMouseMove (Decode.map (.clientPos >> DragAt) Mouse.eventDecoder)
, Browser.Events.onMouseUp (Decode.map (.clientPos >> DragEnd) Mouse.eventDecoder)
, Browser.Events.onAnimationFrame Tick
]
onMouseDown : NodeId -> Attribute Msg
onMouseDown index =
Mouse.onDown (.clientPos >> DragStart index)
linkElement : Graph Entity () -> Edge () -> Svg msg
linkElement graph edge =
let
source =
Maybe.withDefault (Force.entity 0 "") <| Maybe.map (.node >> .label) <| Graph.get edge.from graph
target =
Maybe.withDefault (Force.entity 0 "") <| Maybe.map (.node >> .label) <| Graph.get edge.to graph
in
line
[ strokeWidth 1
, stroke <| Paint <| Color.rgb255 170 170 170
, x1 source.x
, y1 source.y
, x2 target.x
, y2 target.y
]
[]
nodeElement : { a | id : NodeId, label : { b | x : Float, y : Float, value : String } } -> Svg Msg
nodeElement node =
circle
[ r 2.5
, fill <| Paint Color.black
, stroke <| Paint <| Color.rgba 0 0 0 0
, strokeWidth 7
, onMouseDown node.id
, cx node.label.x
, cy node.label.y
]
[ title [] [ text node.label.value ] ]
view : Model -> Svg Msg
view model =
svg [ viewBox 0 0 w h ]
[ Graph.edges model.graph
|> List.map (linkElement model.graph)
|> g [ class [ "links" ] ]
, Graph.nodes model.graph
|> List.map nodeElement
|> g [ class [ "nodes" ] ]
]
main : Program () Model Msg
main =
Browser.element
{ init = init
, view = view
, update = \msg model -> ( update msg model, Cmd.none )
, subscriptions = subscriptions
}
miserablesGraph : Graph String ()
miserablesGraph =
Graph.fromNodeLabelsAndEdgePairs
[ "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "Woman1"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "Woman2"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "Lt.GillenormPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "Child1"
, "Child2"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
]
[ ( 1, 0 )
, ( 2, 0 )
, ( 3, 0 )
, ( 3, 2 )
, ( 4, 0 )
, ( 5, 0 )
, ( 6, 0 )
, ( 7, 0 )
, ( 8, 0 )
, ( 9, 0 )
, ( 11, 10 )
, ( 11, 3 )
, ( 11, 2 )
, ( 11, 0 )
, ( 12, 11 )
, ( 13, 11 )
, ( 14, 11 )
, ( 15, 11 )
, ( 17, 16 )
, ( 18, 16 )
, ( 18, 17 )
, ( 19, 16 )
, ( 19, 17 )
, ( 19, 18 )
, ( 20, 16 )
, ( 20, 17 )
, ( 20, 18 )
, ( 20, 19 )
, ( 21, 16 )
, ( 21, 17 )
, ( 21, 18 )
, ( 21, 19 )
, ( 21, 20 )
, ( 22, 16 )
, ( 22, 17 )
, ( 22, 18 )
, ( 22, 19 )
, ( 22, 20 )
, ( 22, 21 )
, ( 23, 16 )
, ( 23, 17 )
, ( 23, 18 )
, ( 23, 19 )
, ( 23, 20 )
, ( 23, 21 )
, ( 23, 22 )
, ( 23, 12 )
, ( 23, 11 )
, ( 24, 23 )
, ( 24, 11 )
, ( 25, 24 )
, ( 25, 23 )
, ( 25, 11 )
, ( 26, 24 )
, ( 26, 11 )
, ( 26, 16 )
, ( 26, 25 )
, ( 27, 11 )
, ( 27, 23 )
, ( 27, 25 )
, ( 27, 24 )
, ( 27, 26 )
, ( 28, 11 )
, ( 28, 27 )
, ( 29, 23 )
, ( 29, 27 )
, ( 29, 11 )
, ( 30, 23 )
, ( 31, 30 )
, ( 31, 11 )
, ( 31, 23 )
, ( 31, 27 )
, ( 32, 11 )
, ( 33, 11 )
, ( 33, 27 )
, ( 34, 11 )
, ( 34, 29 )
, ( 35, 11 )
, ( 35, 34 )
, ( 35, 29 )
, ( 36, 34 )
, ( 36, 35 )
, ( 36, 11 )
, ( 36, 29 )
, ( 37, 34 )
, ( 37, 35 )
, ( 37, 36 )
, ( 37, 11 )
, ( 37, 29 )
, ( 38, 34 )
, ( 38, 35 )
, ( 38, 36 )
, ( 38, 37 )
, ( 38, 11 )
, ( 38, 29 )
, ( 39, 25 )
, ( 40, 25 )
, ( 41, 24 )
, ( 41, 25 )
, ( 42, 41 )
, ( 42, 25 )
, ( 42, 24 )
, ( 43, 11 )
, ( 43, 26 )
, ( 43, 27 )
, ( 44, 28 )
, ( 44, 11 )
, ( 45, 28 )
, ( 47, 46 )
, ( 48, 47 )
, ( 48, 25 )
, ( 48, 27 )
, ( 48, 11 )
, ( 49, 26 )
, ( 49, 11 )
, ( 50, 49 )
, ( 50, 24 )
, ( 51, 49 )
, ( 51, 26 )
, ( 51, 11 )
, ( 52, 51 )
, ( 52, 39 )
, ( 53, 51 )
, ( 54, 51 )
, ( 54, 49 )
, ( 54, 26 )
, ( 55, 51 )
, ( 55, 49 )
, ( 55, 39 )
, ( 55, 54 )
, ( 55, 26 )
, ( 55, 11 )
, ( 55, 16 )
, ( 55, 25 )
, ( 55, 41 )
, ( 55, 48 )
, ( 56, 49 )
, ( 56, 55 )
, ( 57, 55 )
, ( 57, 41 )
, ( 57, 48 )
, ( 58, 55 )
, ( 58, 48 )
, ( 58, 27 )
, ( 58, 57 )
, ( 58, 11 )
, ( 59, 58 )
, ( 59, 55 )
, ( 59, 48 )
, ( 59, 57 )
, ( 60, 48 )
, ( 60, 58 )
, ( 60, 59 )
, ( 61, 48 )
, ( 61, 58 )
, ( 61, 60 )
, ( 61, 59 )
, ( 61, 57 )
, ( 61, 55 )
, ( 62, 55 )
, ( 62, 58 )
, ( 62, 59 )
, ( 62, 48 )
, ( 62, 57 )
, ( 62, 41 )
, ( 62, 61 )
, ( 62, 60 )
, ( 63, 59 )
, ( 63, 48 )
, ( 63, 62 )
, ( 63, 57 )
, ( 63, 58 )
, ( 63, 61 )
, ( 63, 60 )
, ( 63, 55 )
, ( 64, 55 )
, ( 64, 62 )
, ( 64, 48 )
, ( 64, 63 )
, ( 64, 58 )
, ( 64, 61 )
, ( 64, 60 )
, ( 64, 59 )
, ( 64, 57 )
, ( 64, 11 )
, ( 65, 63 )
, ( 65, 64 )
, ( 65, 48 )
, ( 65, 62 )
, ( 65, 58 )
, ( 65, 61 )
, ( 65, 60 )
, ( 65, 59 )
, ( 65, 57 )
, ( 65, 55 )
, ( 66, 64 )
, ( 66, 58 )
, ( 66, 59 )
, ( 66, 62 )
, ( 66, 65 )
, ( 66, 48 )
, ( 66, 63 )
, ( 66, 61 )
, ( 66, 60 )
, ( 67, 57 )
, ( 68, 25 )
, ( 68, 11 )
, ( 68, 24 )
, ( 68, 27 )
, ( 68, 48 )
, ( 68, 41 )
, ( 69, 25 )
, ( 69, 68 )
, ( 69, 11 )
, ( 69, 24 )
, ( 69, 27 )
, ( 69, 48 )
, ( 69, 41 )
, ( 70, 25 )
, ( 70, 69 )
, ( 70, 68 )
, ( 70, 11 )
, ( 70, 24 )
, ( 70, 27 )
, ( 70, 41 )
, ( 70, 58 )
, ( 71, 27 )
, ( 71, 69 )
, ( 71, 68 )
, ( 71, 70 )
, ( 71, 11 )
, ( 71, 48 )
, ( 71, 41 )
, ( 71, 25 )
, ( 72, 26 )
, ( 72, 27 )
, ( 72, 11 )
, ( 73, 48 )
, ( 74, 48 )
, ( 74, 73 )
, ( 75, 69 )
, ( 75, 68 )
, ( 75, 25 )
, ( 75, 48 )
, ( 75, 41 )
, ( 75, 70 )
, ( 75, 71 )
, ( 76, 64 )
, ( 76, 65 )
, ( 76, 66 )
, ( 76, 63 )
, ( 76, 62 )
, ( 76, 48 )
, ( 76, 58 )
]
{- {"delay": 5} -}
| elm |
[
{
"context": " id = user.id\n , name = user.name\n , image = user.image\n",
"end": 9953,
"score": 0.8958616257,
"start": 9944,
"tag": "NAME",
"value": "user.name"
},
{
"context": " id = user.id\n , name = user.name\n , image = user.image\n",
"end": 10703,
"score": 0.9031738639,
"start": 10694,
"tag": "NAME",
"value": "user.name"
}
] | client/Main.elm | fujiy/Gaufre | 0 | port module Main exposing (..)
import Browser exposing (Document, application)
import Browser.Navigation as Nav
import Data exposing (Auth, Data, User)
import Data.Client as Client
import Firestore as Firestore exposing (Firestore)
import Firestore.Access as Access exposing (Accessor)
import Firestore.Update as Update
import Html exposing (..)
import Page
import Page.Entrance as Entrance
import Task
import Time
import Url exposing (Url)
port setLocalStorage : ( String, String ) -> Cmd msg
port signIn : () -> Cmd msg
port signOut : () -> Cmd msg
port authorized : ({ auth : { uid : String, token : String }, user : { id : String, name : String, image : String, email : String } } -> msg) -> Sub msg
port firestoreSubPort : Firestore.SubPort msg
port firestoreCmdPort : Firestore.CmdPort msg
port newTab : String -> Cmd msg
-- Model -----------------------------------------------------------------------
type Model
= NotSignedIn
{ navKey : Nav.Key
, url : Url
, zone : Time.Zone
, now : Time.Posix
}
| SignedIn
{ auth : Data.Auth
, page : Page.Model
, firestore : Firestore Data.Data Msg
, view : Document Msg
, url : Url
}
init : () -> Url -> Nav.Key -> ( Model, Cmd Msg )
init flags origin navKey =
( NotSignedIn
{ navKey = navKey
, url = origin
, zone = Time.utc
, now = Time.millisToPosix 0
}
, Cmd.batch
[ Task.perform SetTimeZone Time.here
, Task.perform Clock Time.now
]
)
-- Update ----------------------------------------------------------------------
type Msg
= UrlChanged Url
| LinkClicked Browser.UrlRequest
| SignIn
| SignOut
| Authorized Auth User
| SetTimeZone Time.Zone
| Clock Time.Posix
| Firestore (Firestore.FirestoreSub Data Msg)
| Page Page.Msg
| None
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case model of
NotSignedIn m ->
case msg of
SignIn ->
( model, signIn () )
Authorized auth user ->
let
( firestore, mview, cmd ) =
Firestore.update
firestoreCmdPort
(Client.init auth user
|> Update.map (\_ -> None)
)
(pageView auth <| Page.init m.url)
(Firestore.init Data.desc)
page =
Page.init m.url
in
( SignedIn
{ auth = auth
, page = page
, firestore = firestore
, view =
Maybe.withDefault (Document "Gaufre" []) mview
, url = m.url
}
, Cmd.batch
[ cmd
, Page.initialize auth page |> Cmd.map Page
]
)
SetTimeZone zone ->
( NotSignedIn { m | zone = zone }, Cmd.none )
Clock t ->
( NotSignedIn { m | now = t }, Cmd.none )
_ ->
( model, Cmd.none )
SignedIn r ->
case msg of
Authorized auth _ ->
let
( fs, mview, cmd ) =
Firestore.update
firestoreCmdPort
Update.none
(pageView auth r.page)
r.firestore
in
( SignedIn
{ r
| auth = auth
, firestore = fs
, view = Maybe.withDefault r.view mview
}
, cmd
)
SignOut ->
( NotSignedIn
{ navKey = r.auth.navKey
, url = r.url
, zone = r.auth.zone
, now = r.auth.now
}
, signOut ()
)
Firestore sub ->
let
( firestore, mview, cmd ) =
Firestore.apply firestoreCmdPort
(pageView r.auth r.page)
sub
in
( SignedIn
{ r
| firestore = firestore
, view = Maybe.withDefault r.view mview
}
, cmd
)
Page Page.SignOut ->
( NotSignedIn
{ navKey = r.auth.navKey
, url = r.url
, zone = r.auth.zone
, now = r.auth.now
}
, Cmd.batch
[ signOut (), Nav.load "/" ]
)
Page m ->
let
( page, upd ) =
Page.update r.auth m r.page
( fs, mview, cmd ) =
Firestore.update
firestoreCmdPort
(Update.map Page upd)
(pageView r.auth page)
r.firestore
in
( SignedIn
{ r
| page = page
, firestore = fs
, view = Maybe.withDefault r.view mview
}
, cmd
)
LinkClicked urlRequest ->
case urlRequest of
Browser.Internal url ->
( model
, Nav.pushUrl r.auth.navKey (Url.toString url)
)
Browser.External "" ->
( model, Cmd.none )
Browser.External href ->
( model, newTab href )
UrlChanged url ->
let
page =
Page.urlChanged r.page url
( fs, mview, cmd ) =
Firestore.render
firestoreCmdPort
(pageView r.auth page)
r.firestore
in
( SignedIn
{ r
| page = page
, firestore = fs
, view = Maybe.withDefault r.view mview
, url = url
}
, Cmd.batch
[ Page.initialize r.auth page |> Cmd.map Page
, cmd
]
)
Clock t ->
let
auth_ =
r.auth
auth =
{ auth_ | now = t }
( fs, mview, cmd ) =
Firestore.update
firestoreCmdPort
Update.none
(pageView auth r.page)
r.firestore
in
( SignedIn
{ r
| auth = auth
, firestore = fs
, view = Maybe.withDefault r.view mview
}
, cmd
)
_ ->
( model, Cmd.none )
https : Url
https =
{ protocol = Url.Https
, host = ""
, path = ""
, port_ = Nothing
, query = Nothing
, fragment = Nothing
}
endpoint =
{ authorization =
{ https | host = "accounts.google.com", path = "/o/oauth2/v2/auth" }
, token =
{ https | host = "oauth2.googleapis.com", path = "/token" }
}
-- View ------------------------------------------------------------------------
appView : Model -> Document Msg
appView model =
case model of
NotSignedIn _ ->
{ title = "Gaufre"
, body = [ Html.map (always SignIn) Entrance.view ]
}
SignedIn { view } ->
view
pageView : Auth -> Page.Model -> Data -> Accessor Data (Document Msg)
pageView auth page data =
Access.map
(\{ title, body } ->
{ title = title, body = List.map (Html.map Page) body }
)
<|
Page.view auth page data
-- Subscriptions ---------------------------------------------------------------
subscriptions : Model -> Sub Msg
subscriptions model =
case model of
NotSignedIn m ->
Sub.batch
[ authorized <|
\{ auth, user } ->
Authorized
{ uid = auth.uid
, token = auth.token
, navKey = m.navKey
, zone = m.zone
, now = m.now
}
{ id = user.id
, name = user.name
, image = user.image
, email = user.email
, profile = ""
}
, Time.every (60 * 1000) Clock
]
SignedIn s ->
Sub.batch
[ authorized <|
\{ auth, user } ->
Authorized
{ uid = auth.uid
, token = auth.token
, navKey = s.auth.navKey
, zone = s.auth.zone
, now = s.auth.now
}
{ id = user.id
, name = user.name
, image = user.image
, email = user.email
, profile = ""
}
, Firestore.watch firestoreSubPort s.firestore
|> Sub.map Firestore
, Time.every (60 * 1000) Clock
]
-- Main ------------------------------------------------------------------------
main : Program () Model Msg
main =
application
{ init = init
, view = appView
, update = update
, subscriptions = subscriptions
, onUrlRequest = LinkClicked
, onUrlChange = UrlChanged
}
| 59570 | port module Main exposing (..)
import Browser exposing (Document, application)
import Browser.Navigation as Nav
import Data exposing (Auth, Data, User)
import Data.Client as Client
import Firestore as Firestore exposing (Firestore)
import Firestore.Access as Access exposing (Accessor)
import Firestore.Update as Update
import Html exposing (..)
import Page
import Page.Entrance as Entrance
import Task
import Time
import Url exposing (Url)
port setLocalStorage : ( String, String ) -> Cmd msg
port signIn : () -> Cmd msg
port signOut : () -> Cmd msg
port authorized : ({ auth : { uid : String, token : String }, user : { id : String, name : String, image : String, email : String } } -> msg) -> Sub msg
port firestoreSubPort : Firestore.SubPort msg
port firestoreCmdPort : Firestore.CmdPort msg
port newTab : String -> Cmd msg
-- Model -----------------------------------------------------------------------
type Model
= NotSignedIn
{ navKey : Nav.Key
, url : Url
, zone : Time.Zone
, now : Time.Posix
}
| SignedIn
{ auth : Data.Auth
, page : Page.Model
, firestore : Firestore Data.Data Msg
, view : Document Msg
, url : Url
}
init : () -> Url -> Nav.Key -> ( Model, Cmd Msg )
init flags origin navKey =
( NotSignedIn
{ navKey = navKey
, url = origin
, zone = Time.utc
, now = Time.millisToPosix 0
}
, Cmd.batch
[ Task.perform SetTimeZone Time.here
, Task.perform Clock Time.now
]
)
-- Update ----------------------------------------------------------------------
type Msg
= UrlChanged Url
| LinkClicked Browser.UrlRequest
| SignIn
| SignOut
| Authorized Auth User
| SetTimeZone Time.Zone
| Clock Time.Posix
| Firestore (Firestore.FirestoreSub Data Msg)
| Page Page.Msg
| None
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case model of
NotSignedIn m ->
case msg of
SignIn ->
( model, signIn () )
Authorized auth user ->
let
( firestore, mview, cmd ) =
Firestore.update
firestoreCmdPort
(Client.init auth user
|> Update.map (\_ -> None)
)
(pageView auth <| Page.init m.url)
(Firestore.init Data.desc)
page =
Page.init m.url
in
( SignedIn
{ auth = auth
, page = page
, firestore = firestore
, view =
Maybe.withDefault (Document "Gaufre" []) mview
, url = m.url
}
, Cmd.batch
[ cmd
, Page.initialize auth page |> Cmd.map Page
]
)
SetTimeZone zone ->
( NotSignedIn { m | zone = zone }, Cmd.none )
Clock t ->
( NotSignedIn { m | now = t }, Cmd.none )
_ ->
( model, Cmd.none )
SignedIn r ->
case msg of
Authorized auth _ ->
let
( fs, mview, cmd ) =
Firestore.update
firestoreCmdPort
Update.none
(pageView auth r.page)
r.firestore
in
( SignedIn
{ r
| auth = auth
, firestore = fs
, view = Maybe.withDefault r.view mview
}
, cmd
)
SignOut ->
( NotSignedIn
{ navKey = r.auth.navKey
, url = r.url
, zone = r.auth.zone
, now = r.auth.now
}
, signOut ()
)
Firestore sub ->
let
( firestore, mview, cmd ) =
Firestore.apply firestoreCmdPort
(pageView r.auth r.page)
sub
in
( SignedIn
{ r
| firestore = firestore
, view = Maybe.withDefault r.view mview
}
, cmd
)
Page Page.SignOut ->
( NotSignedIn
{ navKey = r.auth.navKey
, url = r.url
, zone = r.auth.zone
, now = r.auth.now
}
, Cmd.batch
[ signOut (), Nav.load "/" ]
)
Page m ->
let
( page, upd ) =
Page.update r.auth m r.page
( fs, mview, cmd ) =
Firestore.update
firestoreCmdPort
(Update.map Page upd)
(pageView r.auth page)
r.firestore
in
( SignedIn
{ r
| page = page
, firestore = fs
, view = Maybe.withDefault r.view mview
}
, cmd
)
LinkClicked urlRequest ->
case urlRequest of
Browser.Internal url ->
( model
, Nav.pushUrl r.auth.navKey (Url.toString url)
)
Browser.External "" ->
( model, Cmd.none )
Browser.External href ->
( model, newTab href )
UrlChanged url ->
let
page =
Page.urlChanged r.page url
( fs, mview, cmd ) =
Firestore.render
firestoreCmdPort
(pageView r.auth page)
r.firestore
in
( SignedIn
{ r
| page = page
, firestore = fs
, view = Maybe.withDefault r.view mview
, url = url
}
, Cmd.batch
[ Page.initialize r.auth page |> Cmd.map Page
, cmd
]
)
Clock t ->
let
auth_ =
r.auth
auth =
{ auth_ | now = t }
( fs, mview, cmd ) =
Firestore.update
firestoreCmdPort
Update.none
(pageView auth r.page)
r.firestore
in
( SignedIn
{ r
| auth = auth
, firestore = fs
, view = Maybe.withDefault r.view mview
}
, cmd
)
_ ->
( model, Cmd.none )
https : Url
https =
{ protocol = Url.Https
, host = ""
, path = ""
, port_ = Nothing
, query = Nothing
, fragment = Nothing
}
endpoint =
{ authorization =
{ https | host = "accounts.google.com", path = "/o/oauth2/v2/auth" }
, token =
{ https | host = "oauth2.googleapis.com", path = "/token" }
}
-- View ------------------------------------------------------------------------
appView : Model -> Document Msg
appView model =
case model of
NotSignedIn _ ->
{ title = "Gaufre"
, body = [ Html.map (always SignIn) Entrance.view ]
}
SignedIn { view } ->
view
pageView : Auth -> Page.Model -> Data -> Accessor Data (Document Msg)
pageView auth page data =
Access.map
(\{ title, body } ->
{ title = title, body = List.map (Html.map Page) body }
)
<|
Page.view auth page data
-- Subscriptions ---------------------------------------------------------------
subscriptions : Model -> Sub Msg
subscriptions model =
case model of
NotSignedIn m ->
Sub.batch
[ authorized <|
\{ auth, user } ->
Authorized
{ uid = auth.uid
, token = auth.token
, navKey = m.navKey
, zone = m.zone
, now = m.now
}
{ id = user.id
, name = <NAME>
, image = user.image
, email = user.email
, profile = ""
}
, Time.every (60 * 1000) Clock
]
SignedIn s ->
Sub.batch
[ authorized <|
\{ auth, user } ->
Authorized
{ uid = auth.uid
, token = auth.token
, navKey = s.auth.navKey
, zone = s.auth.zone
, now = s.auth.now
}
{ id = user.id
, name = <NAME>
, image = user.image
, email = user.email
, profile = ""
}
, Firestore.watch firestoreSubPort s.firestore
|> Sub.map Firestore
, Time.every (60 * 1000) Clock
]
-- Main ------------------------------------------------------------------------
main : Program () Model Msg
main =
application
{ init = init
, view = appView
, update = update
, subscriptions = subscriptions
, onUrlRequest = LinkClicked
, onUrlChange = UrlChanged
}
| true | port module Main exposing (..)
import Browser exposing (Document, application)
import Browser.Navigation as Nav
import Data exposing (Auth, Data, User)
import Data.Client as Client
import Firestore as Firestore exposing (Firestore)
import Firestore.Access as Access exposing (Accessor)
import Firestore.Update as Update
import Html exposing (..)
import Page
import Page.Entrance as Entrance
import Task
import Time
import Url exposing (Url)
port setLocalStorage : ( String, String ) -> Cmd msg
port signIn : () -> Cmd msg
port signOut : () -> Cmd msg
port authorized : ({ auth : { uid : String, token : String }, user : { id : String, name : String, image : String, email : String } } -> msg) -> Sub msg
port firestoreSubPort : Firestore.SubPort msg
port firestoreCmdPort : Firestore.CmdPort msg
port newTab : String -> Cmd msg
-- Model -----------------------------------------------------------------------
type Model
= NotSignedIn
{ navKey : Nav.Key
, url : Url
, zone : Time.Zone
, now : Time.Posix
}
| SignedIn
{ auth : Data.Auth
, page : Page.Model
, firestore : Firestore Data.Data Msg
, view : Document Msg
, url : Url
}
init : () -> Url -> Nav.Key -> ( Model, Cmd Msg )
init flags origin navKey =
( NotSignedIn
{ navKey = navKey
, url = origin
, zone = Time.utc
, now = Time.millisToPosix 0
}
, Cmd.batch
[ Task.perform SetTimeZone Time.here
, Task.perform Clock Time.now
]
)
-- Update ----------------------------------------------------------------------
type Msg
= UrlChanged Url
| LinkClicked Browser.UrlRequest
| SignIn
| SignOut
| Authorized Auth User
| SetTimeZone Time.Zone
| Clock Time.Posix
| Firestore (Firestore.FirestoreSub Data Msg)
| Page Page.Msg
| None
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case model of
NotSignedIn m ->
case msg of
SignIn ->
( model, signIn () )
Authorized auth user ->
let
( firestore, mview, cmd ) =
Firestore.update
firestoreCmdPort
(Client.init auth user
|> Update.map (\_ -> None)
)
(pageView auth <| Page.init m.url)
(Firestore.init Data.desc)
page =
Page.init m.url
in
( SignedIn
{ auth = auth
, page = page
, firestore = firestore
, view =
Maybe.withDefault (Document "Gaufre" []) mview
, url = m.url
}
, Cmd.batch
[ cmd
, Page.initialize auth page |> Cmd.map Page
]
)
SetTimeZone zone ->
( NotSignedIn { m | zone = zone }, Cmd.none )
Clock t ->
( NotSignedIn { m | now = t }, Cmd.none )
_ ->
( model, Cmd.none )
SignedIn r ->
case msg of
Authorized auth _ ->
let
( fs, mview, cmd ) =
Firestore.update
firestoreCmdPort
Update.none
(pageView auth r.page)
r.firestore
in
( SignedIn
{ r
| auth = auth
, firestore = fs
, view = Maybe.withDefault r.view mview
}
, cmd
)
SignOut ->
( NotSignedIn
{ navKey = r.auth.navKey
, url = r.url
, zone = r.auth.zone
, now = r.auth.now
}
, signOut ()
)
Firestore sub ->
let
( firestore, mview, cmd ) =
Firestore.apply firestoreCmdPort
(pageView r.auth r.page)
sub
in
( SignedIn
{ r
| firestore = firestore
, view = Maybe.withDefault r.view mview
}
, cmd
)
Page Page.SignOut ->
( NotSignedIn
{ navKey = r.auth.navKey
, url = r.url
, zone = r.auth.zone
, now = r.auth.now
}
, Cmd.batch
[ signOut (), Nav.load "/" ]
)
Page m ->
let
( page, upd ) =
Page.update r.auth m r.page
( fs, mview, cmd ) =
Firestore.update
firestoreCmdPort
(Update.map Page upd)
(pageView r.auth page)
r.firestore
in
( SignedIn
{ r
| page = page
, firestore = fs
, view = Maybe.withDefault r.view mview
}
, cmd
)
LinkClicked urlRequest ->
case urlRequest of
Browser.Internal url ->
( model
, Nav.pushUrl r.auth.navKey (Url.toString url)
)
Browser.External "" ->
( model, Cmd.none )
Browser.External href ->
( model, newTab href )
UrlChanged url ->
let
page =
Page.urlChanged r.page url
( fs, mview, cmd ) =
Firestore.render
firestoreCmdPort
(pageView r.auth page)
r.firestore
in
( SignedIn
{ r
| page = page
, firestore = fs
, view = Maybe.withDefault r.view mview
, url = url
}
, Cmd.batch
[ Page.initialize r.auth page |> Cmd.map Page
, cmd
]
)
Clock t ->
let
auth_ =
r.auth
auth =
{ auth_ | now = t }
( fs, mview, cmd ) =
Firestore.update
firestoreCmdPort
Update.none
(pageView auth r.page)
r.firestore
in
( SignedIn
{ r
| auth = auth
, firestore = fs
, view = Maybe.withDefault r.view mview
}
, cmd
)
_ ->
( model, Cmd.none )
https : Url
https =
{ protocol = Url.Https
, host = ""
, path = ""
, port_ = Nothing
, query = Nothing
, fragment = Nothing
}
endpoint =
{ authorization =
{ https | host = "accounts.google.com", path = "/o/oauth2/v2/auth" }
, token =
{ https | host = "oauth2.googleapis.com", path = "/token" }
}
-- View ------------------------------------------------------------------------
appView : Model -> Document Msg
appView model =
case model of
NotSignedIn _ ->
{ title = "Gaufre"
, body = [ Html.map (always SignIn) Entrance.view ]
}
SignedIn { view } ->
view
pageView : Auth -> Page.Model -> Data -> Accessor Data (Document Msg)
pageView auth page data =
Access.map
(\{ title, body } ->
{ title = title, body = List.map (Html.map Page) body }
)
<|
Page.view auth page data
-- Subscriptions ---------------------------------------------------------------
subscriptions : Model -> Sub Msg
subscriptions model =
case model of
NotSignedIn m ->
Sub.batch
[ authorized <|
\{ auth, user } ->
Authorized
{ uid = auth.uid
, token = auth.token
, navKey = m.navKey
, zone = m.zone
, now = m.now
}
{ id = user.id
, name = PI:NAME:<NAME>END_PI
, image = user.image
, email = user.email
, profile = ""
}
, Time.every (60 * 1000) Clock
]
SignedIn s ->
Sub.batch
[ authorized <|
\{ auth, user } ->
Authorized
{ uid = auth.uid
, token = auth.token
, navKey = s.auth.navKey
, zone = s.auth.zone
, now = s.auth.now
}
{ id = user.id
, name = PI:NAME:<NAME>END_PI
, image = user.image
, email = user.email
, profile = ""
}
, Firestore.watch firestoreSubPort s.firestore
|> Sub.map Firestore
, Time.every (60 * 1000) Clock
]
-- Main ------------------------------------------------------------------------
main : Program () Model Msg
main =
application
{ init = init
, view = appView
, update = update
, subscriptions = subscriptions
, onUrlRequest = LinkClicked
, onUrlChange = UrlChanged
}
| elm |
[
{
"context": "v [] \n [ input [ type_ \"text\", placeholder \"Name\", value model.name, onInput UpdateName] []\n , ",
"end": 2367,
"score": 0.9621911645,
"start": 2363,
"tag": "NAME",
"value": "Name"
}
] | frontend/src/Main.elm | kenota/grpc-elm | 0 | module Main exposing (main)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Request.HelloWorldService exposing (sayHello)
import Html.Events exposing (onClick, onInput)
import Data.GreetingType exposing (GreetingType(..))
import Data.ElmTalkRequest exposing (ElmTalkRequest)
import Data.ElmTalkResponse exposing (ElmTalkResponse)
import Http exposing (send, Error(..) )
main : Program () Model Msg
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ value : Int
, name: String
, greetingType: GreetingType
, response: String
}
init : () -> ( Model, Cmd Msg )
init _ =
( Model 0 "" GREETINGTYPEUNSPECIFIED "", Cmd.none )
-- UPDATE
type Msg
= Init
| LoadHello (Result Http.Error ElmTalkResponse)
| SendRequest
| UpdateName String
| Select GreetingType
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Init ->
( model, Cmd.none )
LoadHello (Err resp) ->
(updateModelWithError resp model, Cmd.none)
LoadHello (Ok resp) ->
(updateModelWithReply resp model, Cmd.none)
SendRequest ->
(model, sendApiRequest model)
UpdateName name ->
({model | name = name}, Cmd.none)
Select greeting ->
({model | greetingType = greeting}, Cmd.none)
-- Helpers
updateModelWithReply : ElmTalkResponse -> Model -> Model
updateModelWithReply resp model =
case resp.greeting of
Nothing ->
{model | response = "Nothing from server "}
Just text ->
{model | response = "Server says: " ++ text}
updateModelWithError : Http.Error -> Model -> Model
updateModelWithError err model =
case err of
BadPayload text something -> { model | response = "bad payload: " ++ text}
NetworkError -> { model | response = "network error " }
BadStatus r -> { model | response = "bad status " ++ r.status.message}
_ -> {model | response = "some other error"}
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [ type_ "text", placeholder "Name", value model.name, onInput UpdateName] []
, br [] []
, br [] []
, fieldset []
[ label []
[ input [ type_ "radio", onClick (Select ELMWAY), checked (model.greetingType == ELMWAY)] []
, text "ELMWAY"
]
, label []
[ input [ type_ "radio", onClick (Select NORMAL), checked (model.greetingType == NORMAL)] []
, text "NORMAL"
]
, label []
[ input [ type_ "radio", onClick (Select GREETINGTYPEUNSPECIFIED), checked (model.greetingType == GREETINGTYPEUNSPECIFIED)] []
, text "UNSPECIFIED"
]
]
, br [] []
, button [ onClick SendRequest ] [ text "call sayHello()" ]
, br [][]
, br [] []
, div [] [ text model.response ]
]
-- Api
-- sendRequest : Model -> Cmd Msg
-- sendRequest model =
-- Http.send (sayHello
-- { name = model.name
-- , greetingType = model.greetingType
-- }
sendApiRequest : Model -> Cmd Msg
sendApiRequest model =
sayHello (ElmTalkRequest (Just model.name) (Just model.greetingType))
|> Http.send LoadHello | 19987 | module Main exposing (main)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Request.HelloWorldService exposing (sayHello)
import Html.Events exposing (onClick, onInput)
import Data.GreetingType exposing (GreetingType(..))
import Data.ElmTalkRequest exposing (ElmTalkRequest)
import Data.ElmTalkResponse exposing (ElmTalkResponse)
import Http exposing (send, Error(..) )
main : Program () Model Msg
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ value : Int
, name: String
, greetingType: GreetingType
, response: String
}
init : () -> ( Model, Cmd Msg )
init _ =
( Model 0 "" GREETINGTYPEUNSPECIFIED "", Cmd.none )
-- UPDATE
type Msg
= Init
| LoadHello (Result Http.Error ElmTalkResponse)
| SendRequest
| UpdateName String
| Select GreetingType
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Init ->
( model, Cmd.none )
LoadHello (Err resp) ->
(updateModelWithError resp model, Cmd.none)
LoadHello (Ok resp) ->
(updateModelWithReply resp model, Cmd.none)
SendRequest ->
(model, sendApiRequest model)
UpdateName name ->
({model | name = name}, Cmd.none)
Select greeting ->
({model | greetingType = greeting}, Cmd.none)
-- Helpers
updateModelWithReply : ElmTalkResponse -> Model -> Model
updateModelWithReply resp model =
case resp.greeting of
Nothing ->
{model | response = "Nothing from server "}
Just text ->
{model | response = "Server says: " ++ text}
updateModelWithError : Http.Error -> Model -> Model
updateModelWithError err model =
case err of
BadPayload text something -> { model | response = "bad payload: " ++ text}
NetworkError -> { model | response = "network error " }
BadStatus r -> { model | response = "bad status " ++ r.status.message}
_ -> {model | response = "some other error"}
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [ type_ "text", placeholder "<NAME>", value model.name, onInput UpdateName] []
, br [] []
, br [] []
, fieldset []
[ label []
[ input [ type_ "radio", onClick (Select ELMWAY), checked (model.greetingType == ELMWAY)] []
, text "ELMWAY"
]
, label []
[ input [ type_ "radio", onClick (Select NORMAL), checked (model.greetingType == NORMAL)] []
, text "NORMAL"
]
, label []
[ input [ type_ "radio", onClick (Select GREETINGTYPEUNSPECIFIED), checked (model.greetingType == GREETINGTYPEUNSPECIFIED)] []
, text "UNSPECIFIED"
]
]
, br [] []
, button [ onClick SendRequest ] [ text "call sayHello()" ]
, br [][]
, br [] []
, div [] [ text model.response ]
]
-- Api
-- sendRequest : Model -> Cmd Msg
-- sendRequest model =
-- Http.send (sayHello
-- { name = model.name
-- , greetingType = model.greetingType
-- }
sendApiRequest : Model -> Cmd Msg
sendApiRequest model =
sayHello (ElmTalkRequest (Just model.name) (Just model.greetingType))
|> Http.send LoadHello | true | module Main exposing (main)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Request.HelloWorldService exposing (sayHello)
import Html.Events exposing (onClick, onInput)
import Data.GreetingType exposing (GreetingType(..))
import Data.ElmTalkRequest exposing (ElmTalkRequest)
import Data.ElmTalkResponse exposing (ElmTalkResponse)
import Http exposing (send, Error(..) )
main : Program () Model Msg
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ value : Int
, name: String
, greetingType: GreetingType
, response: String
}
init : () -> ( Model, Cmd Msg )
init _ =
( Model 0 "" GREETINGTYPEUNSPECIFIED "", Cmd.none )
-- UPDATE
type Msg
= Init
| LoadHello (Result Http.Error ElmTalkResponse)
| SendRequest
| UpdateName String
| Select GreetingType
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Init ->
( model, Cmd.none )
LoadHello (Err resp) ->
(updateModelWithError resp model, Cmd.none)
LoadHello (Ok resp) ->
(updateModelWithReply resp model, Cmd.none)
SendRequest ->
(model, sendApiRequest model)
UpdateName name ->
({model | name = name}, Cmd.none)
Select greeting ->
({model | greetingType = greeting}, Cmd.none)
-- Helpers
updateModelWithReply : ElmTalkResponse -> Model -> Model
updateModelWithReply resp model =
case resp.greeting of
Nothing ->
{model | response = "Nothing from server "}
Just text ->
{model | response = "Server says: " ++ text}
updateModelWithError : Http.Error -> Model -> Model
updateModelWithError err model =
case err of
BadPayload text something -> { model | response = "bad payload: " ++ text}
NetworkError -> { model | response = "network error " }
BadStatus r -> { model | response = "bad status " ++ r.status.message}
_ -> {model | response = "some other error"}
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [ type_ "text", placeholder "PI:NAME:<NAME>END_PI", value model.name, onInput UpdateName] []
, br [] []
, br [] []
, fieldset []
[ label []
[ input [ type_ "radio", onClick (Select ELMWAY), checked (model.greetingType == ELMWAY)] []
, text "ELMWAY"
]
, label []
[ input [ type_ "radio", onClick (Select NORMAL), checked (model.greetingType == NORMAL)] []
, text "NORMAL"
]
, label []
[ input [ type_ "radio", onClick (Select GREETINGTYPEUNSPECIFIED), checked (model.greetingType == GREETINGTYPEUNSPECIFIED)] []
, text "UNSPECIFIED"
]
]
, br [] []
, button [ onClick SendRequest ] [ text "call sayHello()" ]
, br [][]
, br [] []
, div [] [ text model.response ]
]
-- Api
-- sendRequest : Model -> Cmd Msg
-- sendRequest model =
-- Http.send (sayHello
-- { name = model.name
-- , greetingType = model.greetingType
-- }
sendApiRequest : Model -> Cmd Msg
sendApiRequest model =
sayHello (ElmTalkRequest (Just model.name) (Just model.greetingType))
|> Http.send LoadHello | elm |
[
{
"context": "le\r\n@docs searchIndexExample\r\n\r\nCopyright (c) 2016 Robin Luiten\r\n-}\r\n\r\nimport Lunrelm\r\nimport IndexDefaults\r\nimpo",
"end": 449,
"score": 0.9998725653,
"start": 437,
"tag": "NAME",
"value": "Robin Luiten"
},
{
"context": "he Pawpaw Harvester Model G45\"\r\n , author = \"Pawpaw Fan\"\r\n , body = \"It can help you harvest pawpaws",
"end": 1483,
"score": 0.9998852611,
"start": 1473,
"tag": "NAME",
"value": "Pawpaw Fan"
},
{
"context": "he Pawpaw Harvester Model G45\"\r\n , author = \"Pawpaw Fan\"\r\n , body = \"It can help you harvest pawpaws",
"end": 3821,
"score": 0.9998446107,
"start": 3811,
"tag": "NAME",
"value": "Pawpaw Fan"
}
] | examples/LunrelmNewWith.elm | rluiten/lunrelm | 1 | module Examples.LunrelmNewWith
( codeForLunrelmNewWithExample
, ExampleDocType
, createNewWithIndexExample
, addDocToIndexExample
, searchIndexExample
) where
{-| Create an index with customized
stop word filter using Lunrelm.newWith
@docs codeForLunrelmNewWithExample
@docs ExampleDocType
@docs createNewWithIndexExample
@docs addDocToIndexExample
@docs searchIndexExample
Copyright (c) 2016 Robin Luiten
-}
import Lunrelm
import IndexDefaults
import StopWordFilter
{-| Code for this example.
```
import Lunrelm
import IndexDefaults
import StopWordFilter
type alias ExampleDocType =
{ cid : String
, title : String
, author : String
, body : String
}
createMyStopWordFilter =
StopWordFilter.createFilterFuncWith
[ "electronic" ]
createNewWithIndexExample : Lunrelm.Index ExampleDocType
createNewWithIndexExample =
Lunrelm.newWith
{ indexType = "Lunrelm - For paw paw automation index v1"
, ref = .cid
, fields =
[ ( .title, 5.0 )
, ( .body, 1.0 )
]
, transformFactories = IndexDefaults.defaultTransformFactories
, filterFactories = [ createMyStopWordFilter ]
}
addDocToIndexExample : Result String (Lunrelm.Index ExampleDocType)
addDocToIndexExample =
Lunrelm.add
createNewWithIndexExample
{ cid = "id1"
, title = "The Pawpaw Harvester Model G45"
, author = "Pawpaw Fan"
, body = "It can help you harvest pawpaws. It also does avocado."
}
searchIndexExample :
Result
String
( Result
String
( Lunrelm.Index ExampleDocType, List (String, Float) )
)
searchIndexExample =
Result.map
(\index ->
Lunrelm.search
index
"avocado"
)
addDocToIndexExample
```
-}
codeForLunrelmNewWithExample : String
codeForLunrelmNewWithExample = "Place holder variable to add documentation."
{-| Example document type. -}
type alias ExampleDocType =
{ cid : String
, title : String
, author : String
, body : String
}
{-| Create an extended stop word filter.
Be careful about adding words to your stop word list, as any stop word
will not be indexed and you will not be able to search for the word in
documents as it will not be found.
It is possible to completely replace the stop word list.
-}
createMyStopWordFilter =
StopWordFilter.createFilterFuncWith
[ "electronic" ]
{-| Create a Lunrelm index with extra options.
In this case a customized stop word filter is provided.
This example is replacing the stop word filter only.
It is still supplying the default transform factories.
Supply an index type for your customized index config. This
becomes important when loading back saved index.
It is a good idea to include a version in your index type string
in case you update things and might still have old versions
around that you need to work with.
See Examples.LunrelmNew for informatoin about the `ref` and `fields` fields.
-}
createNewWithIndexExample : Lunrelm.Index ExampleDocType
createNewWithIndexExample =
Lunrelm.newWith
{ indexType = "Lunrelm - For paw paw automation index v1"
, ref = .cid
, fields =
[ ( .title, 5.0 )
, ( .body, 1.0 )
]
, transformFactories = IndexDefaults.defaultTransformFactories
, filterFactories = [ createMyStopWordFilter ]
}
{-| Adding a document to the index. -}
addDocToIndexExample : Result String (Lunrelm.Index ExampleDocType)
addDocToIndexExample =
Lunrelm.add
createNewWithIndexExample
{ cid = "id1"
, title = "The Pawpaw Harvester Model G45"
, author = "Pawpaw Fan"
, body = "It can help you harvest pawpaws. It also does avocado."
}
{-| Search the index.
The result includes an updated Index because a search causes internal
caches to be updated to improve overall performance.
-}
searchIndexExample :
Result
String
( Result
String
( Lunrelm.Index ExampleDocType, List (String, Float) )
)
searchIndexExample =
Result.map
(\index ->
Lunrelm.search
index
"avocado"
)
addDocToIndexExample
| 33746 | module Examples.LunrelmNewWith
( codeForLunrelmNewWithExample
, ExampleDocType
, createNewWithIndexExample
, addDocToIndexExample
, searchIndexExample
) where
{-| Create an index with customized
stop word filter using Lunrelm.newWith
@docs codeForLunrelmNewWithExample
@docs ExampleDocType
@docs createNewWithIndexExample
@docs addDocToIndexExample
@docs searchIndexExample
Copyright (c) 2016 <NAME>
-}
import Lunrelm
import IndexDefaults
import StopWordFilter
{-| Code for this example.
```
import Lunrelm
import IndexDefaults
import StopWordFilter
type alias ExampleDocType =
{ cid : String
, title : String
, author : String
, body : String
}
createMyStopWordFilter =
StopWordFilter.createFilterFuncWith
[ "electronic" ]
createNewWithIndexExample : Lunrelm.Index ExampleDocType
createNewWithIndexExample =
Lunrelm.newWith
{ indexType = "Lunrelm - For paw paw automation index v1"
, ref = .cid
, fields =
[ ( .title, 5.0 )
, ( .body, 1.0 )
]
, transformFactories = IndexDefaults.defaultTransformFactories
, filterFactories = [ createMyStopWordFilter ]
}
addDocToIndexExample : Result String (Lunrelm.Index ExampleDocType)
addDocToIndexExample =
Lunrelm.add
createNewWithIndexExample
{ cid = "id1"
, title = "The Pawpaw Harvester Model G45"
, author = "<NAME>"
, body = "It can help you harvest pawpaws. It also does avocado."
}
searchIndexExample :
Result
String
( Result
String
( Lunrelm.Index ExampleDocType, List (String, Float) )
)
searchIndexExample =
Result.map
(\index ->
Lunrelm.search
index
"avocado"
)
addDocToIndexExample
```
-}
codeForLunrelmNewWithExample : String
codeForLunrelmNewWithExample = "Place holder variable to add documentation."
{-| Example document type. -}
type alias ExampleDocType =
{ cid : String
, title : String
, author : String
, body : String
}
{-| Create an extended stop word filter.
Be careful about adding words to your stop word list, as any stop word
will not be indexed and you will not be able to search for the word in
documents as it will not be found.
It is possible to completely replace the stop word list.
-}
createMyStopWordFilter =
StopWordFilter.createFilterFuncWith
[ "electronic" ]
{-| Create a Lunrelm index with extra options.
In this case a customized stop word filter is provided.
This example is replacing the stop word filter only.
It is still supplying the default transform factories.
Supply an index type for your customized index config. This
becomes important when loading back saved index.
It is a good idea to include a version in your index type string
in case you update things and might still have old versions
around that you need to work with.
See Examples.LunrelmNew for informatoin about the `ref` and `fields` fields.
-}
createNewWithIndexExample : Lunrelm.Index ExampleDocType
createNewWithIndexExample =
Lunrelm.newWith
{ indexType = "Lunrelm - For paw paw automation index v1"
, ref = .cid
, fields =
[ ( .title, 5.0 )
, ( .body, 1.0 )
]
, transformFactories = IndexDefaults.defaultTransformFactories
, filterFactories = [ createMyStopWordFilter ]
}
{-| Adding a document to the index. -}
addDocToIndexExample : Result String (Lunrelm.Index ExampleDocType)
addDocToIndexExample =
Lunrelm.add
createNewWithIndexExample
{ cid = "id1"
, title = "The Pawpaw Harvester Model G45"
, author = "<NAME>"
, body = "It can help you harvest pawpaws. It also does avocado."
}
{-| Search the index.
The result includes an updated Index because a search causes internal
caches to be updated to improve overall performance.
-}
searchIndexExample :
Result
String
( Result
String
( Lunrelm.Index ExampleDocType, List (String, Float) )
)
searchIndexExample =
Result.map
(\index ->
Lunrelm.search
index
"avocado"
)
addDocToIndexExample
| true | module Examples.LunrelmNewWith
( codeForLunrelmNewWithExample
, ExampleDocType
, createNewWithIndexExample
, addDocToIndexExample
, searchIndexExample
) where
{-| Create an index with customized
stop word filter using Lunrelm.newWith
@docs codeForLunrelmNewWithExample
@docs ExampleDocType
@docs createNewWithIndexExample
@docs addDocToIndexExample
@docs searchIndexExample
Copyright (c) 2016 PI:NAME:<NAME>END_PI
-}
import Lunrelm
import IndexDefaults
import StopWordFilter
{-| Code for this example.
```
import Lunrelm
import IndexDefaults
import StopWordFilter
type alias ExampleDocType =
{ cid : String
, title : String
, author : String
, body : String
}
createMyStopWordFilter =
StopWordFilter.createFilterFuncWith
[ "electronic" ]
createNewWithIndexExample : Lunrelm.Index ExampleDocType
createNewWithIndexExample =
Lunrelm.newWith
{ indexType = "Lunrelm - For paw paw automation index v1"
, ref = .cid
, fields =
[ ( .title, 5.0 )
, ( .body, 1.0 )
]
, transformFactories = IndexDefaults.defaultTransformFactories
, filterFactories = [ createMyStopWordFilter ]
}
addDocToIndexExample : Result String (Lunrelm.Index ExampleDocType)
addDocToIndexExample =
Lunrelm.add
createNewWithIndexExample
{ cid = "id1"
, title = "The Pawpaw Harvester Model G45"
, author = "PI:NAME:<NAME>END_PI"
, body = "It can help you harvest pawpaws. It also does avocado."
}
searchIndexExample :
Result
String
( Result
String
( Lunrelm.Index ExampleDocType, List (String, Float) )
)
searchIndexExample =
Result.map
(\index ->
Lunrelm.search
index
"avocado"
)
addDocToIndexExample
```
-}
codeForLunrelmNewWithExample : String
codeForLunrelmNewWithExample = "Place holder variable to add documentation."
{-| Example document type. -}
type alias ExampleDocType =
{ cid : String
, title : String
, author : String
, body : String
}
{-| Create an extended stop word filter.
Be careful about adding words to your stop word list, as any stop word
will not be indexed and you will not be able to search for the word in
documents as it will not be found.
It is possible to completely replace the stop word list.
-}
createMyStopWordFilter =
StopWordFilter.createFilterFuncWith
[ "electronic" ]
{-| Create a Lunrelm index with extra options.
In this case a customized stop word filter is provided.
This example is replacing the stop word filter only.
It is still supplying the default transform factories.
Supply an index type for your customized index config. This
becomes important when loading back saved index.
It is a good idea to include a version in your index type string
in case you update things and might still have old versions
around that you need to work with.
See Examples.LunrelmNew for informatoin about the `ref` and `fields` fields.
-}
createNewWithIndexExample : Lunrelm.Index ExampleDocType
createNewWithIndexExample =
Lunrelm.newWith
{ indexType = "Lunrelm - For paw paw automation index v1"
, ref = .cid
, fields =
[ ( .title, 5.0 )
, ( .body, 1.0 )
]
, transformFactories = IndexDefaults.defaultTransformFactories
, filterFactories = [ createMyStopWordFilter ]
}
{-| Adding a document to the index. -}
addDocToIndexExample : Result String (Lunrelm.Index ExampleDocType)
addDocToIndexExample =
Lunrelm.add
createNewWithIndexExample
{ cid = "id1"
, title = "The Pawpaw Harvester Model G45"
, author = "PI:NAME:<NAME>END_PI"
, body = "It can help you harvest pawpaws. It also does avocado."
}
{-| Search the index.
The result includes an updated Index because a search causes internal
caches to be updated to improve overall performance.
-}
searchIndexExample :
Result
String
( Result
String
( Lunrelm.Index ExampleDocType, List (String, Float) )
)
searchIndexExample =
Result.map
(\index ->
Lunrelm.search
index
"avocado"
)
addDocToIndexExample
| elm |
[
{
"context": "he URI spec](https://tools.ietf.org/html/rfc3986), Tim Berners-Lee\nsays a URL looks like this:\n\n```\n https://exampl",
"end": 209,
"score": 0.9996228218,
"start": 194,
"tag": "NAME",
"value": "Tim Berners-Lee"
},
{
"context": ":\n\n```\n https://example.com:8042/over/there?name=ferret#nose\n \\___/ \\______________/\\_________/ \\_____",
"end": 292,
"score": 0.623521924,
"start": 286,
"tag": "NAME",
"value": "ferret"
},
{
"context": "\n -- /user/bob/comment/42 ==> Just { user = \"bob\", id = 42 }\n -- /user/tom/comment/35 ==> Jus",
"end": 4114,
"score": 0.699148953,
"start": 4111,
"tag": "USERNAME",
"value": "bob"
},
{
"context": "\n -- /user/tom/comment/35 ==> Just { user = \"tom\", id = 35 }\n -- /user/sam/ ==> No",
"end": 4179,
"score": 0.9690360427,
"start": 4176,
"tag": "USERNAME",
"value": "tom"
},
{
"context": "g\n\n -- /user/sam/ ==> Just (User \"sam\")\n -- /user/bob/comment/42 ==> Just (Comment",
"end": 5280,
"score": 0.9434915185,
"start": 5277,
"tag": "USERNAME",
"value": "sam"
},
{
"context": "\n -- /user/bob/comment/42 ==> Just (Comment \"bob\" 42)\n -- /user/tom/comment/35 ==> Just (Comm",
"end": 5335,
"score": 0.9412266612,
"start": 5332,
"tag": "NAME",
"value": "bob"
},
{
"context": "\n -- /user/tom/comment/35 ==> Just (Comment \"tom\" 35)\n -- /user/ ==> Nothing\n\n",
"end": 5393,
"score": 0.7604948878,
"start": 5390,
"tag": "NAME",
"value": "tom"
}
] | fixtures/elm-home/0.19.0/package/elm/url/1.0.0/src/Url/Parser.elm | kazk/node-test-runner | 4 | module Url.Parser exposing
( Parser, string, int, s
, (</>), map, oneOf, top, custom
, (<?>), query
, fragment
, parse
)
{-| In [the URI spec](https://tools.ietf.org/html/rfc3986), Tim Berners-Lee
says a URL looks like this:
```
https://example.com:8042/over/there?name=ferret#nose
\___/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
```
This module is primarily for parsing the `path` part.
# Primitives
@docs Parser, string, int, s
# Path
@docs (</>), map, oneOf, top, custom
# Query
@docs (<?>), query
# Fragment
@docs fragment
# Run Parsers
@docs parse
-}
import Dict exposing (Dict)
import Url exposing (Url)
import Url.Parser.Query as Query
import Url.Parser.Internal as Q
-- INFIX TABLE
infix right 7 (</>) = slash
infix left 8 (<?>) = questionMark
-- PARSERS
{-| Turn URLs like `/blog/42/cat-herding-techniques` into nice Elm data.
-}
type Parser a b =
Parser (State a -> List (State b))
type alias State value =
{ visited : List String
, unvisited : List String
, params : Dict String (List String)
, frag : Maybe String
, value : value
}
-- PARSE SEGMENTS
{-| Parse a segment of the path as a `String`.
-- /alice/ ==> Just "alice"
-- /bob ==> Just "bob"
-- /42/ ==> Just "42"
-- / ==> Nothing
-}
string : Parser (String -> a) a
string =
custom "STRING" Just
{-| Parse a segment of the path as an `Int`.
-- /alice/ ==> Nothing
-- /bob ==> Nothing
-- /42/ ==> Just 42
-- / ==> Nothing
-}
int : Parser (Int -> a) a
int =
custom "NUMBER" String.toInt
{-| Parse a segment of the path if it matches a given string. It is almost
always used with [`</>`](#</>) or [`oneOf`](#oneOf). For example:
blog : Parser (Int -> a) a
blog =
s "blog" </> int
-- /blog/42 ==> Just 42
-- /tree/42 ==> Nothing
The path segment must be an exact match!
-}
s : String -> Parser a a
s str =
Parser <| \{ visited, unvisited, params, frag, value } ->
case unvisited of
[] ->
[]
next :: rest ->
if next == str then
[ State (next :: visited) rest params frag value ]
else
[]
{-| Create a custom path segment parser. Here is how it is used to define the
`int` parser:
int : Parser (Int -> a) a
int =
custom "NUMBER" String.toInt
You can use it to define something like “only CSS files” like this:
css : Parser (String -> a) a
css =
custom "CSS_FILE" <| \segment ->
if String.endsWith ".css" segment then
Just segment
else
Nothing
-}
custom : String -> (String -> Maybe a) -> Parser (a -> b) b
custom tipe stringToSomething =
Parser <| \{ visited, unvisited, params, frag, value } ->
case unvisited of
[] ->
[]
next :: rest ->
case stringToSomething next of
Just nextValue ->
[ State (next :: visited) rest params frag (value nextValue) ]
Nothing ->
[]
-- COMBINING PARSERS
{-| Parse a path with multiple segments.
blog : Parser (Int -> a) a
blog =
s "blog" </> int
-- /blog/35/ ==> Just 35
-- /blog/42 ==> Just 42
-- /blog/ ==> Nothing
-- /42/ ==> Nothing
search : Parser (String -> a) a
search =
s "search" </> string
-- /search/wolf/ ==> Just "wolf"
-- /search/frog ==> Just "frog"
-- /search/ ==> Nothing
-- /wolf/ ==> Nothing
-}
slash : Parser a b -> Parser b c -> Parser a c
slash (Parser parseBefore) (Parser parseAfter) =
Parser <| \state ->
List.concatMap parseAfter (parseBefore state)
{-| Transform a path parser.
type alias Comment = { user : String, id : Int }
userAndId : Parser (String -> Int -> a) a
userAndId =
s "user" </> string </> s "comment" </> int
comment : Parser (Comment -> a) a
comment =
map Comment userAndId
-- /user/bob/comment/42 ==> Just { user = "bob", id = 42 }
-- /user/tom/comment/35 ==> Just { user = "tom", id = 35 }
-- /user/sam/ ==> Nothing
-}
map : a -> Parser a b -> Parser (b -> c) c
map subValue (Parser parseArg) =
Parser <| \{ visited, unvisited, params, frag, value } ->
List.map (mapState value) <| parseArg <|
State visited unvisited params frag subValue
mapState : (a -> b) -> State a -> State b
mapState func { visited, unvisited, params, frag, value } =
State visited unvisited params frag (func value)
{-| Try a bunch of different path parsers.
type Route
= Topic String
| Blog Int
| User String
| Comment String Int
route : Parser (Route -> a) a
route =
oneOf
[ map Topic (s "topic" </> string)
, map Blog (s "blog" </> int)
, map User (s "user" </> string)
, map Comment (s "user" </> string </> s "comment" </> int)
]
-- /topic/wolf ==> Just (Topic "wolf")
-- /topic/ ==> Nothing
-- /blog/42 ==> Just (Blog 42)
-- /blog/wolf ==> Nothing
-- /user/sam/ ==> Just (User "sam")
-- /user/bob/comment/42 ==> Just (Comment "bob" 42)
-- /user/tom/comment/35 ==> Just (Comment "tom" 35)
-- /user/ ==> Nothing
If there are multiple parsers that could succeed, the first one wins.
-}
oneOf : List (Parser a b) -> Parser a b
oneOf parsers =
Parser <| \state ->
List.concatMap (\(Parser parser) -> parser state) parsers
{-| A parser that does not consume any path segments.
type Route = Overview | Post Int
blog : Parser (BlogRoute -> a) a
blog =
s "blog" </>
oneOf
[ map Overview top
, map Post (s "post" </> int)
]
-- /blog/ ==> Just Overview
-- /blog/post/42 ==> Just (Post 42)
-}
top : Parser a a
top =
Parser <| \state -> [state]
-- QUERY
{-| The [`Url.Parser.Query`](Url-Parser-Query) module defines its own
[`Parser`](Url-Parser-Query#Parser) type. This function helps you use those
with normal parsers. For example, maybe you want to add a search feature to
your blog website:
import Url.Parser.Query as Query
type Route
= Overview (Maybe String)
| Post Int
blog : Parser (Route -> a) a
blog =
oneOf
[ map Overview (s "blog" <?> Query.string "q")
, map Post (s "blog" </> int)
]
-- /blog/ ==> Just (Overview Nothing)
-- /blog/?q=wolf ==> Just (Overview (Just "wolf"))
-- /blog/wolf ==> Nothing
-- /blog/42 ==> Just (Post 42)
-- /blog/42?q=wolf ==> Just (Post 42)
-- /blog/42/wolf ==> Nothing
-}
questionMark : Parser a (query -> b) -> Query.Parser query -> Parser a b
questionMark parser queryParser =
slash parser (query queryParser)
{-| The [`Url.Parser.Query`](Url-Parser-Query) module defines its own
[`Parser`](Url-Parser-Query#Parser) type. This function is a helper to convert
those into normal parsers.
import Url.Parser.Query as Query
-- the following expressions are both the same!
--
-- s "blog" <?> Query.string "search"
-- s "blog" </> query (Query.string "search")
This may be handy if you need query parameters but are not parsing any path
segments.
-}
query : Query.Parser query -> Parser (query -> a) a
query (Q.Parser queryParser) =
Parser <| \{ visited, unvisited, params, frag, value } ->
[ State visited unvisited params frag (value (queryParser params))
]
-- FRAGMENT
{-| Create a parser for the URL fragment, the stuff after the `#`. This can
be handy for handling links to DOM elements within a page. Pages like this one!
type alias Docs =
(String, Maybe String)
docs : Parser (Docs -> a) a
docs =
map Tuple.pair (string </> fragment identity)
-- /List/map ==> Nothing
-- /List/#map ==> Just ("List", Just "map")
-- /List#map ==> Just ("List", Just "map")
-- /List# ==> Just ("List", Just "")
-- /List ==> Just ("List", Nothing)
-- / ==> Nothing
-}
fragment : (Maybe String -> fragment) -> Parser (fragment -> a) a
fragment toFrag =
Parser <| \{ visited, unvisited, params, frag, value } ->
[ State visited unvisited params frag (value (toFrag frag))
]
-- PARSE
{-| Actually run a parser! You provide some [`Url`](Url#Url) that
represent a valid URL. From there `parse` runs your parser on the path, query
parameters, and fragment.
import Url
import Url.Parser exposing (Parser, parse, int, map, oneOf, s, top)
type Route = Home | Blog Int | NotFound
route : Parser (Route -> a) a
route =
oneOf
[ map Home top
, map Blog (s "blog" </> int)
]
toRoute : String -> Route
toRoute string =
case Url.fromString string of
Nothing ->
NotFound
Just url ->
Maybe.withDefault NotFound (parse route url)
-- toRoute "/blog/42" == NotFound
-- toRoute "https://example.com/" == Home
-- toRoute "https://example.com/blog" == NotFound
-- toRoute "https://example.com/blog/42" == Blog 42
-- toRoute "https://example.com/blog/42/" == Blog 42
-- toRoute "https://example.com/blog/42#wolf" == Blog 42
-- toRoute "https://example.com/blog/42?q=wolf" == Blog 42
-- toRoute "https://example.com/settings" == NotFound
Functions like `toRoute` are useful when creating single-page apps with
[`Browser.fullscreen`][fs]. I use them in `init` and `onNavigation` to handle
the initial URL and any changes.
[fs]: /packages/elm/browser/latest/Browser#fullscreen
-}
parse : Parser (a -> a) a -> Url -> Maybe a
parse (Parser parser) url =
getFirstMatch <| parser <|
State [] (preparePath url.path) (prepareQuery url.query) url.fragment identity
getFirstMatch : List (State a) -> Maybe a
getFirstMatch states =
case states of
[] ->
Nothing
state :: rest ->
case state.unvisited of
[] ->
Just state.value
[""] ->
Just state.value
_ ->
getFirstMatch rest
-- PREPARE PATH
preparePath : String -> List String
preparePath path =
case String.split "/" path of
"" :: segments ->
removeFinalEmpty segments
segments ->
removeFinalEmpty segments
removeFinalEmpty : List String -> List String
removeFinalEmpty segments =
case segments of
[] ->
[]
"" :: [] ->
[]
segment :: rest ->
segment :: removeFinalEmpty rest
-- PREPARE QUERY
prepareQuery : Maybe String -> Dict String (List String)
prepareQuery maybeQuery =
case maybeQuery of
Nothing ->
Dict.empty
Just qry ->
List.foldr addParam Dict.empty (String.split "&" qry)
addParam : String -> Dict String (List String) -> Dict String (List String)
addParam segment dict =
case String.split "=" segment of
[rawKey, rawValue] ->
case Url.percentDecode rawKey of
Nothing ->
dict
Just key ->
case Url.percentDecode rawValue of
Nothing ->
dict
Just value ->
Dict.update key (addToParametersHelp value) dict
_ ->
dict
addToParametersHelp : a -> Maybe (List a) -> Maybe (List a)
addToParametersHelp value maybeList =
case maybeList of
Nothing ->
Just [value]
Just list ->
Just (value :: list)
| 51258 | module Url.Parser exposing
( Parser, string, int, s
, (</>), map, oneOf, top, custom
, (<?>), query
, fragment
, parse
)
{-| In [the URI spec](https://tools.ietf.org/html/rfc3986), <NAME>
says a URL looks like this:
```
https://example.com:8042/over/there?name=<NAME>#nose
\___/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
```
This module is primarily for parsing the `path` part.
# Primitives
@docs Parser, string, int, s
# Path
@docs (</>), map, oneOf, top, custom
# Query
@docs (<?>), query
# Fragment
@docs fragment
# Run Parsers
@docs parse
-}
import Dict exposing (Dict)
import Url exposing (Url)
import Url.Parser.Query as Query
import Url.Parser.Internal as Q
-- INFIX TABLE
infix right 7 (</>) = slash
infix left 8 (<?>) = questionMark
-- PARSERS
{-| Turn URLs like `/blog/42/cat-herding-techniques` into nice Elm data.
-}
type Parser a b =
Parser (State a -> List (State b))
type alias State value =
{ visited : List String
, unvisited : List String
, params : Dict String (List String)
, frag : Maybe String
, value : value
}
-- PARSE SEGMENTS
{-| Parse a segment of the path as a `String`.
-- /alice/ ==> Just "alice"
-- /bob ==> Just "bob"
-- /42/ ==> Just "42"
-- / ==> Nothing
-}
string : Parser (String -> a) a
string =
custom "STRING" Just
{-| Parse a segment of the path as an `Int`.
-- /alice/ ==> Nothing
-- /bob ==> Nothing
-- /42/ ==> Just 42
-- / ==> Nothing
-}
int : Parser (Int -> a) a
int =
custom "NUMBER" String.toInt
{-| Parse a segment of the path if it matches a given string. It is almost
always used with [`</>`](#</>) or [`oneOf`](#oneOf). For example:
blog : Parser (Int -> a) a
blog =
s "blog" </> int
-- /blog/42 ==> Just 42
-- /tree/42 ==> Nothing
The path segment must be an exact match!
-}
s : String -> Parser a a
s str =
Parser <| \{ visited, unvisited, params, frag, value } ->
case unvisited of
[] ->
[]
next :: rest ->
if next == str then
[ State (next :: visited) rest params frag value ]
else
[]
{-| Create a custom path segment parser. Here is how it is used to define the
`int` parser:
int : Parser (Int -> a) a
int =
custom "NUMBER" String.toInt
You can use it to define something like “only CSS files” like this:
css : Parser (String -> a) a
css =
custom "CSS_FILE" <| \segment ->
if String.endsWith ".css" segment then
Just segment
else
Nothing
-}
custom : String -> (String -> Maybe a) -> Parser (a -> b) b
custom tipe stringToSomething =
Parser <| \{ visited, unvisited, params, frag, value } ->
case unvisited of
[] ->
[]
next :: rest ->
case stringToSomething next of
Just nextValue ->
[ State (next :: visited) rest params frag (value nextValue) ]
Nothing ->
[]
-- COMBINING PARSERS
{-| Parse a path with multiple segments.
blog : Parser (Int -> a) a
blog =
s "blog" </> int
-- /blog/35/ ==> Just 35
-- /blog/42 ==> Just 42
-- /blog/ ==> Nothing
-- /42/ ==> Nothing
search : Parser (String -> a) a
search =
s "search" </> string
-- /search/wolf/ ==> Just "wolf"
-- /search/frog ==> Just "frog"
-- /search/ ==> Nothing
-- /wolf/ ==> Nothing
-}
slash : Parser a b -> Parser b c -> Parser a c
slash (Parser parseBefore) (Parser parseAfter) =
Parser <| \state ->
List.concatMap parseAfter (parseBefore state)
{-| Transform a path parser.
type alias Comment = { user : String, id : Int }
userAndId : Parser (String -> Int -> a) a
userAndId =
s "user" </> string </> s "comment" </> int
comment : Parser (Comment -> a) a
comment =
map Comment userAndId
-- /user/bob/comment/42 ==> Just { user = "bob", id = 42 }
-- /user/tom/comment/35 ==> Just { user = "tom", id = 35 }
-- /user/sam/ ==> Nothing
-}
map : a -> Parser a b -> Parser (b -> c) c
map subValue (Parser parseArg) =
Parser <| \{ visited, unvisited, params, frag, value } ->
List.map (mapState value) <| parseArg <|
State visited unvisited params frag subValue
mapState : (a -> b) -> State a -> State b
mapState func { visited, unvisited, params, frag, value } =
State visited unvisited params frag (func value)
{-| Try a bunch of different path parsers.
type Route
= Topic String
| Blog Int
| User String
| Comment String Int
route : Parser (Route -> a) a
route =
oneOf
[ map Topic (s "topic" </> string)
, map Blog (s "blog" </> int)
, map User (s "user" </> string)
, map Comment (s "user" </> string </> s "comment" </> int)
]
-- /topic/wolf ==> Just (Topic "wolf")
-- /topic/ ==> Nothing
-- /blog/42 ==> Just (Blog 42)
-- /blog/wolf ==> Nothing
-- /user/sam/ ==> Just (User "sam")
-- /user/bob/comment/42 ==> Just (Comment "<NAME>" 42)
-- /user/tom/comment/35 ==> Just (Comment "<NAME>" 35)
-- /user/ ==> Nothing
If there are multiple parsers that could succeed, the first one wins.
-}
oneOf : List (Parser a b) -> Parser a b
oneOf parsers =
Parser <| \state ->
List.concatMap (\(Parser parser) -> parser state) parsers
{-| A parser that does not consume any path segments.
type Route = Overview | Post Int
blog : Parser (BlogRoute -> a) a
blog =
s "blog" </>
oneOf
[ map Overview top
, map Post (s "post" </> int)
]
-- /blog/ ==> Just Overview
-- /blog/post/42 ==> Just (Post 42)
-}
top : Parser a a
top =
Parser <| \state -> [state]
-- QUERY
{-| The [`Url.Parser.Query`](Url-Parser-Query) module defines its own
[`Parser`](Url-Parser-Query#Parser) type. This function helps you use those
with normal parsers. For example, maybe you want to add a search feature to
your blog website:
import Url.Parser.Query as Query
type Route
= Overview (Maybe String)
| Post Int
blog : Parser (Route -> a) a
blog =
oneOf
[ map Overview (s "blog" <?> Query.string "q")
, map Post (s "blog" </> int)
]
-- /blog/ ==> Just (Overview Nothing)
-- /blog/?q=wolf ==> Just (Overview (Just "wolf"))
-- /blog/wolf ==> Nothing
-- /blog/42 ==> Just (Post 42)
-- /blog/42?q=wolf ==> Just (Post 42)
-- /blog/42/wolf ==> Nothing
-}
questionMark : Parser a (query -> b) -> Query.Parser query -> Parser a b
questionMark parser queryParser =
slash parser (query queryParser)
{-| The [`Url.Parser.Query`](Url-Parser-Query) module defines its own
[`Parser`](Url-Parser-Query#Parser) type. This function is a helper to convert
those into normal parsers.
import Url.Parser.Query as Query
-- the following expressions are both the same!
--
-- s "blog" <?> Query.string "search"
-- s "blog" </> query (Query.string "search")
This may be handy if you need query parameters but are not parsing any path
segments.
-}
query : Query.Parser query -> Parser (query -> a) a
query (Q.Parser queryParser) =
Parser <| \{ visited, unvisited, params, frag, value } ->
[ State visited unvisited params frag (value (queryParser params))
]
-- FRAGMENT
{-| Create a parser for the URL fragment, the stuff after the `#`. This can
be handy for handling links to DOM elements within a page. Pages like this one!
type alias Docs =
(String, Maybe String)
docs : Parser (Docs -> a) a
docs =
map Tuple.pair (string </> fragment identity)
-- /List/map ==> Nothing
-- /List/#map ==> Just ("List", Just "map")
-- /List#map ==> Just ("List", Just "map")
-- /List# ==> Just ("List", Just "")
-- /List ==> Just ("List", Nothing)
-- / ==> Nothing
-}
fragment : (Maybe String -> fragment) -> Parser (fragment -> a) a
fragment toFrag =
Parser <| \{ visited, unvisited, params, frag, value } ->
[ State visited unvisited params frag (value (toFrag frag))
]
-- PARSE
{-| Actually run a parser! You provide some [`Url`](Url#Url) that
represent a valid URL. From there `parse` runs your parser on the path, query
parameters, and fragment.
import Url
import Url.Parser exposing (Parser, parse, int, map, oneOf, s, top)
type Route = Home | Blog Int | NotFound
route : Parser (Route -> a) a
route =
oneOf
[ map Home top
, map Blog (s "blog" </> int)
]
toRoute : String -> Route
toRoute string =
case Url.fromString string of
Nothing ->
NotFound
Just url ->
Maybe.withDefault NotFound (parse route url)
-- toRoute "/blog/42" == NotFound
-- toRoute "https://example.com/" == Home
-- toRoute "https://example.com/blog" == NotFound
-- toRoute "https://example.com/blog/42" == Blog 42
-- toRoute "https://example.com/blog/42/" == Blog 42
-- toRoute "https://example.com/blog/42#wolf" == Blog 42
-- toRoute "https://example.com/blog/42?q=wolf" == Blog 42
-- toRoute "https://example.com/settings" == NotFound
Functions like `toRoute` are useful when creating single-page apps with
[`Browser.fullscreen`][fs]. I use them in `init` and `onNavigation` to handle
the initial URL and any changes.
[fs]: /packages/elm/browser/latest/Browser#fullscreen
-}
parse : Parser (a -> a) a -> Url -> Maybe a
parse (Parser parser) url =
getFirstMatch <| parser <|
State [] (preparePath url.path) (prepareQuery url.query) url.fragment identity
getFirstMatch : List (State a) -> Maybe a
getFirstMatch states =
case states of
[] ->
Nothing
state :: rest ->
case state.unvisited of
[] ->
Just state.value
[""] ->
Just state.value
_ ->
getFirstMatch rest
-- PREPARE PATH
preparePath : String -> List String
preparePath path =
case String.split "/" path of
"" :: segments ->
removeFinalEmpty segments
segments ->
removeFinalEmpty segments
removeFinalEmpty : List String -> List String
removeFinalEmpty segments =
case segments of
[] ->
[]
"" :: [] ->
[]
segment :: rest ->
segment :: removeFinalEmpty rest
-- PREPARE QUERY
prepareQuery : Maybe String -> Dict String (List String)
prepareQuery maybeQuery =
case maybeQuery of
Nothing ->
Dict.empty
Just qry ->
List.foldr addParam Dict.empty (String.split "&" qry)
addParam : String -> Dict String (List String) -> Dict String (List String)
addParam segment dict =
case String.split "=" segment of
[rawKey, rawValue] ->
case Url.percentDecode rawKey of
Nothing ->
dict
Just key ->
case Url.percentDecode rawValue of
Nothing ->
dict
Just value ->
Dict.update key (addToParametersHelp value) dict
_ ->
dict
addToParametersHelp : a -> Maybe (List a) -> Maybe (List a)
addToParametersHelp value maybeList =
case maybeList of
Nothing ->
Just [value]
Just list ->
Just (value :: list)
| true | module Url.Parser exposing
( Parser, string, int, s
, (</>), map, oneOf, top, custom
, (<?>), query
, fragment
, parse
)
{-| In [the URI spec](https://tools.ietf.org/html/rfc3986), PI:NAME:<NAME>END_PI
says a URL looks like this:
```
https://example.com:8042/over/there?name=PI:NAME:<NAME>END_PI#nose
\___/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
```
This module is primarily for parsing the `path` part.
# Primitives
@docs Parser, string, int, s
# Path
@docs (</>), map, oneOf, top, custom
# Query
@docs (<?>), query
# Fragment
@docs fragment
# Run Parsers
@docs parse
-}
import Dict exposing (Dict)
import Url exposing (Url)
import Url.Parser.Query as Query
import Url.Parser.Internal as Q
-- INFIX TABLE
infix right 7 (</>) = slash
infix left 8 (<?>) = questionMark
-- PARSERS
{-| Turn URLs like `/blog/42/cat-herding-techniques` into nice Elm data.
-}
type Parser a b =
Parser (State a -> List (State b))
type alias State value =
{ visited : List String
, unvisited : List String
, params : Dict String (List String)
, frag : Maybe String
, value : value
}
-- PARSE SEGMENTS
{-| Parse a segment of the path as a `String`.
-- /alice/ ==> Just "alice"
-- /bob ==> Just "bob"
-- /42/ ==> Just "42"
-- / ==> Nothing
-}
string : Parser (String -> a) a
string =
custom "STRING" Just
{-| Parse a segment of the path as an `Int`.
-- /alice/ ==> Nothing
-- /bob ==> Nothing
-- /42/ ==> Just 42
-- / ==> Nothing
-}
int : Parser (Int -> a) a
int =
custom "NUMBER" String.toInt
{-| Parse a segment of the path if it matches a given string. It is almost
always used with [`</>`](#</>) or [`oneOf`](#oneOf). For example:
blog : Parser (Int -> a) a
blog =
s "blog" </> int
-- /blog/42 ==> Just 42
-- /tree/42 ==> Nothing
The path segment must be an exact match!
-}
s : String -> Parser a a
s str =
Parser <| \{ visited, unvisited, params, frag, value } ->
case unvisited of
[] ->
[]
next :: rest ->
if next == str then
[ State (next :: visited) rest params frag value ]
else
[]
{-| Create a custom path segment parser. Here is how it is used to define the
`int` parser:
int : Parser (Int -> a) a
int =
custom "NUMBER" String.toInt
You can use it to define something like “only CSS files” like this:
css : Parser (String -> a) a
css =
custom "CSS_FILE" <| \segment ->
if String.endsWith ".css" segment then
Just segment
else
Nothing
-}
custom : String -> (String -> Maybe a) -> Parser (a -> b) b
custom tipe stringToSomething =
Parser <| \{ visited, unvisited, params, frag, value } ->
case unvisited of
[] ->
[]
next :: rest ->
case stringToSomething next of
Just nextValue ->
[ State (next :: visited) rest params frag (value nextValue) ]
Nothing ->
[]
-- COMBINING PARSERS
{-| Parse a path with multiple segments.
blog : Parser (Int -> a) a
blog =
s "blog" </> int
-- /blog/35/ ==> Just 35
-- /blog/42 ==> Just 42
-- /blog/ ==> Nothing
-- /42/ ==> Nothing
search : Parser (String -> a) a
search =
s "search" </> string
-- /search/wolf/ ==> Just "wolf"
-- /search/frog ==> Just "frog"
-- /search/ ==> Nothing
-- /wolf/ ==> Nothing
-}
slash : Parser a b -> Parser b c -> Parser a c
slash (Parser parseBefore) (Parser parseAfter) =
Parser <| \state ->
List.concatMap parseAfter (parseBefore state)
{-| Transform a path parser.
type alias Comment = { user : String, id : Int }
userAndId : Parser (String -> Int -> a) a
userAndId =
s "user" </> string </> s "comment" </> int
comment : Parser (Comment -> a) a
comment =
map Comment userAndId
-- /user/bob/comment/42 ==> Just { user = "bob", id = 42 }
-- /user/tom/comment/35 ==> Just { user = "tom", id = 35 }
-- /user/sam/ ==> Nothing
-}
map : a -> Parser a b -> Parser (b -> c) c
map subValue (Parser parseArg) =
Parser <| \{ visited, unvisited, params, frag, value } ->
List.map (mapState value) <| parseArg <|
State visited unvisited params frag subValue
mapState : (a -> b) -> State a -> State b
mapState func { visited, unvisited, params, frag, value } =
State visited unvisited params frag (func value)
{-| Try a bunch of different path parsers.
type Route
= Topic String
| Blog Int
| User String
| Comment String Int
route : Parser (Route -> a) a
route =
oneOf
[ map Topic (s "topic" </> string)
, map Blog (s "blog" </> int)
, map User (s "user" </> string)
, map Comment (s "user" </> string </> s "comment" </> int)
]
-- /topic/wolf ==> Just (Topic "wolf")
-- /topic/ ==> Nothing
-- /blog/42 ==> Just (Blog 42)
-- /blog/wolf ==> Nothing
-- /user/sam/ ==> Just (User "sam")
-- /user/bob/comment/42 ==> Just (Comment "PI:NAME:<NAME>END_PI" 42)
-- /user/tom/comment/35 ==> Just (Comment "PI:NAME:<NAME>END_PI" 35)
-- /user/ ==> Nothing
If there are multiple parsers that could succeed, the first one wins.
-}
oneOf : List (Parser a b) -> Parser a b
oneOf parsers =
Parser <| \state ->
List.concatMap (\(Parser parser) -> parser state) parsers
{-| A parser that does not consume any path segments.
type Route = Overview | Post Int
blog : Parser (BlogRoute -> a) a
blog =
s "blog" </>
oneOf
[ map Overview top
, map Post (s "post" </> int)
]
-- /blog/ ==> Just Overview
-- /blog/post/42 ==> Just (Post 42)
-}
top : Parser a a
top =
Parser <| \state -> [state]
-- QUERY
{-| The [`Url.Parser.Query`](Url-Parser-Query) module defines its own
[`Parser`](Url-Parser-Query#Parser) type. This function helps you use those
with normal parsers. For example, maybe you want to add a search feature to
your blog website:
import Url.Parser.Query as Query
type Route
= Overview (Maybe String)
| Post Int
blog : Parser (Route -> a) a
blog =
oneOf
[ map Overview (s "blog" <?> Query.string "q")
, map Post (s "blog" </> int)
]
-- /blog/ ==> Just (Overview Nothing)
-- /blog/?q=wolf ==> Just (Overview (Just "wolf"))
-- /blog/wolf ==> Nothing
-- /blog/42 ==> Just (Post 42)
-- /blog/42?q=wolf ==> Just (Post 42)
-- /blog/42/wolf ==> Nothing
-}
questionMark : Parser a (query -> b) -> Query.Parser query -> Parser a b
questionMark parser queryParser =
slash parser (query queryParser)
{-| The [`Url.Parser.Query`](Url-Parser-Query) module defines its own
[`Parser`](Url-Parser-Query#Parser) type. This function is a helper to convert
those into normal parsers.
import Url.Parser.Query as Query
-- the following expressions are both the same!
--
-- s "blog" <?> Query.string "search"
-- s "blog" </> query (Query.string "search")
This may be handy if you need query parameters but are not parsing any path
segments.
-}
query : Query.Parser query -> Parser (query -> a) a
query (Q.Parser queryParser) =
Parser <| \{ visited, unvisited, params, frag, value } ->
[ State visited unvisited params frag (value (queryParser params))
]
-- FRAGMENT
{-| Create a parser for the URL fragment, the stuff after the `#`. This can
be handy for handling links to DOM elements within a page. Pages like this one!
type alias Docs =
(String, Maybe String)
docs : Parser (Docs -> a) a
docs =
map Tuple.pair (string </> fragment identity)
-- /List/map ==> Nothing
-- /List/#map ==> Just ("List", Just "map")
-- /List#map ==> Just ("List", Just "map")
-- /List# ==> Just ("List", Just "")
-- /List ==> Just ("List", Nothing)
-- / ==> Nothing
-}
fragment : (Maybe String -> fragment) -> Parser (fragment -> a) a
fragment toFrag =
Parser <| \{ visited, unvisited, params, frag, value } ->
[ State visited unvisited params frag (value (toFrag frag))
]
-- PARSE
{-| Actually run a parser! You provide some [`Url`](Url#Url) that
represent a valid URL. From there `parse` runs your parser on the path, query
parameters, and fragment.
import Url
import Url.Parser exposing (Parser, parse, int, map, oneOf, s, top)
type Route = Home | Blog Int | NotFound
route : Parser (Route -> a) a
route =
oneOf
[ map Home top
, map Blog (s "blog" </> int)
]
toRoute : String -> Route
toRoute string =
case Url.fromString string of
Nothing ->
NotFound
Just url ->
Maybe.withDefault NotFound (parse route url)
-- toRoute "/blog/42" == NotFound
-- toRoute "https://example.com/" == Home
-- toRoute "https://example.com/blog" == NotFound
-- toRoute "https://example.com/blog/42" == Blog 42
-- toRoute "https://example.com/blog/42/" == Blog 42
-- toRoute "https://example.com/blog/42#wolf" == Blog 42
-- toRoute "https://example.com/blog/42?q=wolf" == Blog 42
-- toRoute "https://example.com/settings" == NotFound
Functions like `toRoute` are useful when creating single-page apps with
[`Browser.fullscreen`][fs]. I use them in `init` and `onNavigation` to handle
the initial URL and any changes.
[fs]: /packages/elm/browser/latest/Browser#fullscreen
-}
parse : Parser (a -> a) a -> Url -> Maybe a
parse (Parser parser) url =
getFirstMatch <| parser <|
State [] (preparePath url.path) (prepareQuery url.query) url.fragment identity
getFirstMatch : List (State a) -> Maybe a
getFirstMatch states =
case states of
[] ->
Nothing
state :: rest ->
case state.unvisited of
[] ->
Just state.value
[""] ->
Just state.value
_ ->
getFirstMatch rest
-- PREPARE PATH
preparePath : String -> List String
preparePath path =
case String.split "/" path of
"" :: segments ->
removeFinalEmpty segments
segments ->
removeFinalEmpty segments
removeFinalEmpty : List String -> List String
removeFinalEmpty segments =
case segments of
[] ->
[]
"" :: [] ->
[]
segment :: rest ->
segment :: removeFinalEmpty rest
-- PREPARE QUERY
prepareQuery : Maybe String -> Dict String (List String)
prepareQuery maybeQuery =
case maybeQuery of
Nothing ->
Dict.empty
Just qry ->
List.foldr addParam Dict.empty (String.split "&" qry)
addParam : String -> Dict String (List String) -> Dict String (List String)
addParam segment dict =
case String.split "=" segment of
[rawKey, rawValue] ->
case Url.percentDecode rawKey of
Nothing ->
dict
Just key ->
case Url.percentDecode rawValue of
Nothing ->
dict
Just value ->
Dict.update key (addToParametersHelp value) dict
_ ->
dict
addToParametersHelp : a -> Maybe (List a) -> Maybe (List a)
addToParametersHelp value maybeList =
case maybeList of
Nothing ->
Just [value]
Just list ->
Just (value :: list)
| elm |
[
{
"context": " comments = [ \"good\", \"great\" ]\n\n [ ( \"name\", \"John\" |> Part.string )\n , ( \"age\", 30 |> Part.",
"end": 235,
"score": 0.9977895021,
"start": 231,
"tag": "NAME",
"value": "John"
}
] | src/Getto/Http/Part.elm | getto-systems/elm-http-part | 0 | module Getto.Http.Part exposing
( Value
, string
, int
, file
, bytes
, list
, object
, toBody
)
{-| build http parts
roles = [ "admin" ] |> Set.fromList
comments = [ "good", "great" ]
[ ( "name", "John" |> Part.string )
, ( "age", 30 |> Part.int )
, ( "file", file |> Part.file )
, ( "roles", roles |> Part.set Part.string )
, ( "comments", comments |> Part.list Part.string )
] |> Part.object
# Definition
@docs Value
# Encoder
@docs string, int, file, bytes, list, object
# Encode
@docs toBody
-}
import Getto.Url.Query.Encode as QueryEncode
import File exposing ( File )
import Bytes exposing ( Bytes )
import Http
{-| part value
-}
type Value
= StringValue String
| FileValue File
| BytesValue String Bytes
| ListValue (List Value)
| ObjectValue (List ( String, Value ))
type Part
= StringPart String
| FilePart File
| BytesPart String Bytes
{-| string part
-}
string : String -> Value
string = StringValue
{-| int part
-}
int : Int -> Value
int = String.fromInt >> string
{-| file part
-}
file : File -> Value
file = FileValue
{-| bytes part
-}
bytes : String -> Bytes -> Value
bytes = BytesValue
{-| list part
-}
list : (a -> Value) -> List a -> Value
list f = List.map f >> ListValue
{-| object part
-}
object : List ( String, Value ) -> Value
object = ObjectValue
{-| convert value to http part
-}
toBody : Value -> Http.Body
toBody =
flatten []
>> List.map toPart
>> Http.multipartBody
flatten : List String -> Value -> List ( List String, Part )
flatten current part =
case part of
StringValue value -> [ ( current, value |> StringPart ) ]
FileValue value -> [ ( current, value |> FilePart ) ]
BytesValue contentType value -> [ ( current, value |> BytesPart contentType ) ]
ListValue parts -> parts |> List.concatMap (flatten (current ++ [""]))
ObjectValue parts -> parts |> List.concatMap (\(name,p) -> p |> flatten (current ++ [name]))
toPart : ( List String, Part ) -> Http.Part
toPart (names,part) =
let
name = names |> QueryEncode.toName
in
case part of
StringPart value -> value |> Http.stringPart name
FilePart value -> value |> Http.filePart name
BytesPart contentType value -> value |> Http.bytesPart name contentType
| 52435 | module Getto.Http.Part exposing
( Value
, string
, int
, file
, bytes
, list
, object
, toBody
)
{-| build http parts
roles = [ "admin" ] |> Set.fromList
comments = [ "good", "great" ]
[ ( "name", "<NAME>" |> Part.string )
, ( "age", 30 |> Part.int )
, ( "file", file |> Part.file )
, ( "roles", roles |> Part.set Part.string )
, ( "comments", comments |> Part.list Part.string )
] |> Part.object
# Definition
@docs Value
# Encoder
@docs string, int, file, bytes, list, object
# Encode
@docs toBody
-}
import Getto.Url.Query.Encode as QueryEncode
import File exposing ( File )
import Bytes exposing ( Bytes )
import Http
{-| part value
-}
type Value
= StringValue String
| FileValue File
| BytesValue String Bytes
| ListValue (List Value)
| ObjectValue (List ( String, Value ))
type Part
= StringPart String
| FilePart File
| BytesPart String Bytes
{-| string part
-}
string : String -> Value
string = StringValue
{-| int part
-}
int : Int -> Value
int = String.fromInt >> string
{-| file part
-}
file : File -> Value
file = FileValue
{-| bytes part
-}
bytes : String -> Bytes -> Value
bytes = BytesValue
{-| list part
-}
list : (a -> Value) -> List a -> Value
list f = List.map f >> ListValue
{-| object part
-}
object : List ( String, Value ) -> Value
object = ObjectValue
{-| convert value to http part
-}
toBody : Value -> Http.Body
toBody =
flatten []
>> List.map toPart
>> Http.multipartBody
flatten : List String -> Value -> List ( List String, Part )
flatten current part =
case part of
StringValue value -> [ ( current, value |> StringPart ) ]
FileValue value -> [ ( current, value |> FilePart ) ]
BytesValue contentType value -> [ ( current, value |> BytesPart contentType ) ]
ListValue parts -> parts |> List.concatMap (flatten (current ++ [""]))
ObjectValue parts -> parts |> List.concatMap (\(name,p) -> p |> flatten (current ++ [name]))
toPart : ( List String, Part ) -> Http.Part
toPart (names,part) =
let
name = names |> QueryEncode.toName
in
case part of
StringPart value -> value |> Http.stringPart name
FilePart value -> value |> Http.filePart name
BytesPart contentType value -> value |> Http.bytesPart name contentType
| true | module Getto.Http.Part exposing
( Value
, string
, int
, file
, bytes
, list
, object
, toBody
)
{-| build http parts
roles = [ "admin" ] |> Set.fromList
comments = [ "good", "great" ]
[ ( "name", "PI:NAME:<NAME>END_PI" |> Part.string )
, ( "age", 30 |> Part.int )
, ( "file", file |> Part.file )
, ( "roles", roles |> Part.set Part.string )
, ( "comments", comments |> Part.list Part.string )
] |> Part.object
# Definition
@docs Value
# Encoder
@docs string, int, file, bytes, list, object
# Encode
@docs toBody
-}
import Getto.Url.Query.Encode as QueryEncode
import File exposing ( File )
import Bytes exposing ( Bytes )
import Http
{-| part value
-}
type Value
= StringValue String
| FileValue File
| BytesValue String Bytes
| ListValue (List Value)
| ObjectValue (List ( String, Value ))
type Part
= StringPart String
| FilePart File
| BytesPart String Bytes
{-| string part
-}
string : String -> Value
string = StringValue
{-| int part
-}
int : Int -> Value
int = String.fromInt >> string
{-| file part
-}
file : File -> Value
file = FileValue
{-| bytes part
-}
bytes : String -> Bytes -> Value
bytes = BytesValue
{-| list part
-}
list : (a -> Value) -> List a -> Value
list f = List.map f >> ListValue
{-| object part
-}
object : List ( String, Value ) -> Value
object = ObjectValue
{-| convert value to http part
-}
toBody : Value -> Http.Body
toBody =
flatten []
>> List.map toPart
>> Http.multipartBody
flatten : List String -> Value -> List ( List String, Part )
flatten current part =
case part of
StringValue value -> [ ( current, value |> StringPart ) ]
FileValue value -> [ ( current, value |> FilePart ) ]
BytesValue contentType value -> [ ( current, value |> BytesPart contentType ) ]
ListValue parts -> parts |> List.concatMap (flatten (current ++ [""]))
ObjectValue parts -> parts |> List.concatMap (\(name,p) -> p |> flatten (current ++ [name]))
toPart : ( List String, Part ) -> Http.Part
toPart (names,part) =
let
name = names |> QueryEncode.toName
in
case part of
StringPart value -> value |> Http.stringPart name
FilePart value -> value |> Http.filePart name
BytesPart contentType value -> value |> Http.bytesPart name contentType
| elm |
[
{
"context": " { authUrl = authUrl\n , token = authToken\n , projectsAvailable = RemoteData.Load",
"end": 100354,
"score": 0.7533665895,
"start": 100345,
"tag": "PASSWORD",
"value": "authToken"
}
] | src/State/State.elm | exosphere-project/exosphere | 15 | module State.State exposing (update)
import Browser
import Browser.Navigation
import Helpers.ExoSetupStatus
import Helpers.GetterSetters as GetterSetters
import Helpers.Helpers as Helpers
import Helpers.RemoteDataPlusPlus as RDPP
import Helpers.ServerResourceUsage
import Http
import LocalStorage.LocalStorage as LocalStorage
import Maybe
import OpenStack.ServerPassword as OSServerPassword
import OpenStack.ServerTags as OSServerTags
import OpenStack.ServerVolumes as OSSvrVols
import OpenStack.Types as OSTypes
import OpenStack.Volumes as OSVolumes
import Orchestration.Orchestration as Orchestration
import Page.AllResourcesList
import Page.FloatingIpAssign
import Page.FloatingIpList
import Page.GetSupport
import Page.Home
import Page.InstanceSourcePicker
import Page.KeypairCreate
import Page.KeypairList
import Page.LoginJetstream
import Page.LoginOpenstack
import Page.LoginPicker
import Page.MessageLog
import Page.SelectProjects
import Page.ServerCreate
import Page.ServerCreateImage
import Page.ServerDetail
import Page.ServerList
import Page.Settings
import Page.VolumeAttach
import Page.VolumeCreate
import Page.VolumeDetail
import Page.VolumeList
import Ports
import RemoteData
import Rest.ApiModelHelpers as ApiModelHelpers
import Rest.Glance
import Rest.Keystone
import Rest.Neutron
import Rest.Nova
import Route
import State.Auth
import State.Error
import State.ViewState as ViewStateHelpers
import Style.Toast
import Style.Widgets.NumericTextInput.NumericTextInput
import Task
import Time
import Toasty
import Types.Error as Error exposing (AppError, ErrorContext, ErrorLevel(..))
import Types.Guacamole as GuacTypes
import Types.HelperTypes as HelperTypes exposing (HttpRequestMethod(..), UnscopedProviderProject)
import Types.OuterModel exposing (OuterModel)
import Types.OuterMsg exposing (OuterMsg(..))
import Types.Project exposing (Endpoints, Project, ProjectSecret(..))
import Types.Server exposing (ExoSetupStatus(..), NewServerNetworkOptions(..), Server, ServerFromExoProps, ServerOrigin(..), currentExoServerVersion)
import Types.ServerResourceUsage
import Types.SharedModel exposing (SharedModel)
import Types.SharedMsg exposing (ProjectSpecificMsgConstructor(..), ServerSpecificMsgConstructor(..), SharedMsg(..), TickInterval)
import Types.View
exposing
( LoginView(..)
, NonProjectViewConstructor(..)
, ProjectViewConstructor(..)
, ViewState(..)
)
import Types.Workflow
exposing
( CustomWorkflow
, CustomWorkflowTokenRDPP
, ServerCustomWorkflowStatus(..)
)
import Url
import View.Helpers exposing (toExoPalette)
update : OuterMsg -> Result AppError OuterModel -> ( Result AppError OuterModel, Cmd OuterMsg )
update msg result =
case result of
Err appError ->
( Err appError, Cmd.none )
Ok model ->
case updateValid msg model of
( newModel, nextMsg ) ->
( Ok newModel, nextMsg )
updateValid : OuterMsg -> OuterModel -> ( OuterModel, Cmd OuterMsg )
updateValid msg outerModel =
{- We want to `setStorage` on every update. This function adds the setStorage
command for every step of the update function.
-}
let
( newOuterModel, cmds ) =
updateUnderlying msg outerModel
orchestrationTimeCmd =
-- Each trip through the runtime, we get the time and feed it to orchestration module
case msg of
SharedMsg (DoOrchestration _) ->
Cmd.none
SharedMsg (Tick _ _) ->
Cmd.none
_ ->
Task.perform (\posix -> SharedMsg <| DoOrchestration posix) Time.now
in
( newOuterModel
, Cmd.batch
[ Ports.setStorage (LocalStorage.generateStoredState newOuterModel.sharedModel)
, orchestrationTimeCmd
, cmds
]
)
-- There may be a better approach than these mapping functions, I'm not sure yet.
mapToOuterMsg : ( a, Cmd SharedMsg ) -> ( a, Cmd OuterMsg )
mapToOuterMsg ( model, cmdSharedMsg ) =
( model, Cmd.map SharedMsg cmdSharedMsg )
mapToOuterModel : OuterModel -> ( SharedModel, Cmd a ) -> ( OuterModel, Cmd a )
mapToOuterModel outerModel ( newSharedModel, cmd ) =
( { outerModel | sharedModel = newSharedModel }, cmd )
pipelineCmdOuterModelMsg : (OuterModel -> ( OuterModel, Cmd OuterMsg )) -> ( OuterModel, Cmd OuterMsg ) -> ( OuterModel, Cmd OuterMsg )
pipelineCmdOuterModelMsg fn ( outerModel, outerCmd ) =
let
( newModel, newCmd ) =
fn outerModel
in
( newModel, Cmd.batch [ outerCmd, newCmd ] )
updateUnderlying : OuterMsg -> OuterModel -> ( OuterModel, Cmd OuterMsg )
updateUnderlying outerMsg outerModel =
let
sharedModel =
outerModel.sharedModel
in
case ( outerMsg, outerModel.viewState ) of
( SharedMsg sharedMsg, _ ) ->
processSharedMsg sharedMsg outerModel
-- TODO exact same structure for each page-specific case here. Is there a way to deduplicate or factor out?
( GetSupportMsg pageMsg, NonProjectView (GetSupport pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.GetSupport.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| GetSupport newPageModel
}
, Cmd.map GetSupportMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( HomeMsg pageMsg, NonProjectView (Home pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.Home.update pageMsg pageModel
in
( { outerModel
| viewState = NonProjectView <| Home newPageModel
}
, Cmd.map HomeMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( LoginJetstreamMsg pageMsg, NonProjectView (Login (LoginJetstream pageModel)) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.LoginJetstream.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| Login <| LoginJetstream newPageModel
}
, Cmd.map LoginJetstreamMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( LoginOpenstackMsg pageMsg, NonProjectView (Login (LoginOpenstack pageModel)) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.LoginOpenstack.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| Login <| LoginOpenstack newPageModel
}
, Cmd.map LoginOpenstackMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( LoginPickerMsg pageMsg, NonProjectView LoginPicker ) ->
let
( _, cmd, sharedMsg ) =
Page.LoginPicker.update pageMsg
in
( { outerModel
| viewState = NonProjectView <| LoginPicker
}
, Cmd.map LoginPickerMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( MessageLogMsg pageMsg, NonProjectView (MessageLog pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.MessageLog.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| MessageLog newPageModel
}
, Cmd.map MessageLogMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( SelectProjectsMsg pageMsg, NonProjectView (SelectProjects pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.SelectProjects.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| SelectProjects newPageModel
}
, Cmd.map SelectProjectsMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( SettingsMsg pageMsg, NonProjectView (Settings pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.Settings.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| Settings newPageModel
}
, Cmd.map SettingsMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( pageSpecificMsg, ProjectView projectId projectViewModel projectViewConstructor ) ->
case GetterSetters.projectLookup sharedModel projectId of
Just project ->
case ( pageSpecificMsg, projectViewConstructor ) of
-- This is the repetitive dispatch code that people warn you about when you use the nested Elm architecture.
-- Maybe there is a way to make it less repetitive (or at least more compact) in the future.
( AllResourcesListMsg pageMsg, AllResourcesList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.AllResourcesList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
AllResourcesList newSharedModel
}
, Cmd.map AllResourcesListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( FloatingIpAssignMsg pageMsg, FloatingIpAssign pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.FloatingIpAssign.update pageMsg sharedModel project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
FloatingIpAssign newSharedModel
}
, Cmd.map FloatingIpAssignMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( FloatingIpListMsg pageMsg, FloatingIpList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.FloatingIpList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
FloatingIpList newSharedModel
}
, Cmd.map FloatingIpListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( InstanceSourcePickerMsg pageMsg, InstanceSourcePicker pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.InstanceSourcePicker.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
InstanceSourcePicker newSharedModel
}
, Cmd.map InstanceSourcePickerMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( KeypairCreateMsg pageMsg, KeypairCreate pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.KeypairCreate.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
KeypairCreate newSharedModel
}
, Cmd.map KeypairCreateMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( KeypairListMsg pageMsg, KeypairList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.KeypairList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
KeypairList newSharedModel
}
, Cmd.map KeypairListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerCreateMsg pageMsg, ServerCreate pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerCreate.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerCreate newSharedModel
}
, Cmd.map ServerCreateMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerCreateImageMsg pageMsg, ServerCreateImage pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerCreateImage.update pageMsg sharedModel project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerCreateImage newSharedModel
}
, Cmd.map ServerCreateImageMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerDetailMsg pageMsg, ServerDetail pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerDetail.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerDetail newSharedModel
}
, Cmd.map ServerDetailMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerListMsg pageMsg, ServerList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerList newSharedModel
}
, Cmd.map ServerListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeAttachMsg pageMsg, VolumeAttach pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeAttach.update pageMsg sharedModel project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeAttach newSharedModel
}
, Cmd.map VolumeAttachMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeCreateMsg pageMsg, VolumeCreate pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeCreate.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeCreate newSharedModel
}
, Cmd.map VolumeCreateMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeDetailMsg pageMsg, VolumeDetail pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeDetail.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeDetail newSharedModel
}
, Cmd.map VolumeDetailMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeListMsg pageMsg, VolumeList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeList newSharedModel
}
, Cmd.map VolumeListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
_ ->
-- This is not great because it allows us to forget to write a case statement above, but I don't know of a nicer way to write a catchall case for when a page-specific Msg is received for an inapplicable page.
( outerModel, Cmd.none )
Nothing ->
( outerModel, Cmd.none )
( _, _ ) ->
-- This is not great because it allows us to forget to write a case statement above, but I don't know of a nicer way to write a catchall case for when a page-specific Msg is received for an inapplicable page.
( outerModel, Cmd.none )
processSharedMsg : SharedMsg -> OuterModel -> ( OuterModel, Cmd OuterMsg )
processSharedMsg sharedMsg outerModel =
let
{ sharedModel } =
outerModel
{ viewContext } =
sharedModel
in
case sharedMsg of
ChangeSystemThemePreference preference ->
let
{ style } =
sharedModel
{ styleMode } =
style
newStyleMode =
{ styleMode | systemPreference = Just preference }
newStyle =
{ style | styleMode = newStyleMode }
newPalette =
toExoPalette newStyle
newViewContext =
{ viewContext | palette = newPalette }
in
mapToOuterModel outerModel
( { sharedModel
| style = newStyle
, viewContext = newViewContext
}
, Cmd.none
)
Logout ->
( outerModel, Ports.logout () )
ToastyMsg subMsg ->
Toasty.update Style.Toast.toastConfig ToastyMsg subMsg outerModel.sharedModel
|> mapToOuterMsg
|> mapToOuterModel outerModel
MsgChangeWindowSize x y ->
( { sharedModel
| viewContext =
{ viewContext
| windowSize = { width = x, height = y }
}
}
, Cmd.none
)
|> mapToOuterModel outerModel
Tick interval time ->
processTick outerModel interval time
|> mapToOuterModel outerModel
DoOrchestration posixTime ->
Orchestration.orchModel sharedModel posixTime
|> mapToOuterMsg
|> mapToOuterModel outerModel
HandleApiErrorWithBody errorContext error ->
State.Error.processSynchronousApiError sharedModel errorContext error
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestUnscopedToken openstackLoginUnscoped ->
let
creds =
-- Ensure auth URL includes port number and version
{ openstackLoginUnscoped
| authUrl =
State.Auth.authUrlWithPortAndVersion openstackLoginUnscoped.authUrl
}
in
( outerModel, Rest.Keystone.requestUnscopedAuthToken sharedModel.cloudCorsProxyUrl creds )
|> mapToOuterMsg
JetstreamLogin jetstreamCreds ->
let
openstackCredsList =
State.Auth.jetstreamToOpenstackCreds jetstreamCreds
cmds =
List.map
(\creds -> Rest.Keystone.requestUnscopedAuthToken sharedModel.cloudCorsProxyUrl creds)
openstackCredsList
in
( outerModel, Cmd.batch cmds )
|> mapToOuterMsg
ReceiveScopedAuthToken projectDescription ( metadata, response ) ->
case Rest.Keystone.decodeScopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
sharedModel
(ErrorContext
"decode scoped auth token"
ErrorCrit
Nothing
)
error
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok authToken ->
case Helpers.serviceCatalogToEndpoints authToken.catalog of
Err e ->
State.Error.processStringError
sharedModel
(ErrorContext
"Decode project endpoints"
ErrorCrit
(Just "Please check with your cloud administrator or the Exosphere developers.")
)
e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok endpoints ->
let
projectId =
authToken.project.uuid
in
-- If we don't have a project with same name + authUrl then create one, if we do then update its OSTypes.AuthToken
-- This code ensures we don't end up with duplicate projects on the same provider in our model.
case
GetterSetters.projectLookup sharedModel <| projectId
of
Nothing ->
createProject outerModel projectDescription authToken endpoints
Just project ->
-- If we don't have an application credential for this project yet, then get one
let
appCredCmd =
case project.secret of
ApplicationCredential _ ->
Cmd.none
_ ->
Rest.Keystone.requestAppCredential
sharedModel.clientUuid
sharedModel.clientCurrentTime
project
( newOuterModel, updateTokenCmd ) =
State.Auth.projectUpdateAuthToken outerModel project authToken
in
( newOuterModel, Cmd.batch [ appCredCmd, updateTokenCmd ] )
|> mapToOuterMsg
ReceiveUnscopedAuthToken keystoneUrl ( metadata, response ) ->
case Rest.Keystone.decodeUnscopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
sharedModel
(ErrorContext
"decode unscoped auth token"
ErrorCrit
Nothing
)
error
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok authToken ->
case
GetterSetters.providerLookup sharedModel keystoneUrl
of
Just unscopedProvider ->
-- We already have an unscoped provider in the model with the same auth URL, update its token
State.Auth.unscopedProviderUpdateAuthToken
sharedModel
unscopedProvider
authToken
|> mapToOuterMsg
|> mapToOuterModel outerModel
Nothing ->
-- We don't have an unscoped provider with the same auth URL, create it
createUnscopedProvider sharedModel authToken keystoneUrl
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveUnscopedProjects keystoneUrl unscopedProjects ->
case
GetterSetters.providerLookup sharedModel keystoneUrl
of
Just provider ->
let
newProvider =
{ provider | projectsAvailable = RemoteData.Success unscopedProjects }
newSharedModel =
GetterSetters.modelUpdateUnscopedProvider sharedModel newProvider
newOuterModel =
{ outerModel | sharedModel = newSharedModel }
in
-- If we are not already on a SelectProjects view, then go there
case outerModel.viewState of
NonProjectView (SelectProjects _) ->
( newOuterModel, Cmd.none )
_ ->
( newOuterModel
, Route.pushUrl viewContext (Route.SelectProjects keystoneUrl)
)
Nothing ->
-- Provider not found, may have been removed, nothing to do
( outerModel, Cmd.none )
RequestProjectLoginFromProvider keystoneUrl unscopedProjects ->
case GetterSetters.providerLookup sharedModel keystoneUrl of
Just provider ->
let
buildLoginRequest : UnscopedProviderProject -> Cmd SharedMsg
buildLoginRequest project =
Rest.Keystone.requestScopedAuthToken
sharedModel.cloudCorsProxyUrl
project.description
<|
OSTypes.TokenCreds
keystoneUrl
provider.token
project.project.uuid
loginRequests =
List.map buildLoginRequest unscopedProjects
|> Cmd.batch
-- Remove unscoped provider from model now that we have selected projects from it
newUnscopedProviders =
List.filter
(\p -> p.authUrl /= keystoneUrl)
sharedModel.unscopedProviders
-- If we still have at least one unscoped provider in the model then ask the user to choose projects from it
newViewStateCmd =
case List.head newUnscopedProviders of
Just unscopedProvider ->
Route.pushUrl viewContext (Route.SelectProjects unscopedProvider.authUrl)
Nothing ->
-- If we have at least one project then show it, else show the login page
case List.head sharedModel.projects of
Just project ->
Route.pushUrl viewContext <|
Route.ProjectRoute project.auth.project.uuid <|
Route.AllResourcesList
Nothing ->
Route.pushUrl viewContext Route.LoginPicker
sharedModelUpdatedUnscopedProviders =
{ sharedModel | unscopedProviders = newUnscopedProviders }
in
( { outerModel | sharedModel = sharedModelUpdatedUnscopedProviders }
, Cmd.batch [ Cmd.map SharedMsg loginRequests, newViewStateCmd ]
)
Nothing ->
State.Error.processStringError
sharedModel
(ErrorContext
("look for OpenStack provider with Keystone URL " ++ keystoneUrl)
ErrorCrit
Nothing
)
"Provider could not found in Exosphere's list of Providers."
|> mapToOuterMsg
|> mapToOuterModel outerModel
ProjectMsg projectIdentifier innerMsg ->
case GetterSetters.projectLookup sharedModel projectIdentifier of
Nothing ->
-- Project not found, may have been removed, nothing to do
( outerModel, Cmd.none )
Just project ->
processProjectSpecificMsg outerModel project innerMsg
OpenNewWindow url ->
( outerModel, Ports.openNewWindow url )
LinkClicked urlRequest ->
case urlRequest of
Browser.Internal url ->
( outerModel, Browser.Navigation.pushUrl viewContext.navigationKey (Url.toString url) )
Browser.External url ->
( outerModel, Browser.Navigation.load url )
UrlChanged url ->
ViewStateHelpers.navigateToPage url outerModel
SelectTheme themeChoice ->
let
oldStyle =
sharedModel.style
oldStyleMode =
oldStyle.styleMode
newStyleMode =
{ oldStyleMode | theme = themeChoice }
newStyle =
{ oldStyle | styleMode = newStyleMode }
in
( { sharedModel
| style = newStyle
, viewContext = { viewContext | palette = toExoPalette newStyle }
}
, Cmd.none
)
|> mapToOuterModel outerModel
NoOp ->
( outerModel, Cmd.none )
SetExperimentalFeaturesEnabled choice ->
( { sharedModel | viewContext = { viewContext | experimentalFeaturesEnabled = choice } }, Cmd.none )
|> mapToOuterModel outerModel
processTick : OuterModel -> TickInterval -> Time.Posix -> ( SharedModel, Cmd OuterMsg )
processTick outerModel interval time =
let
serverVolsNeedFrequentPoll : Project -> Server -> Bool
serverVolsNeedFrequentPoll project server =
GetterSetters.getVolsAttachedToServer project server
|> List.any volNeedsFrequentPoll
volNeedsFrequentPoll volume =
not <|
List.member
volume.status
[ OSTypes.Available
, OSTypes.Maintenance
, OSTypes.InUse
, OSTypes.Error
, OSTypes.ErrorDeleting
, OSTypes.ErrorBackingUp
, OSTypes.ErrorRestoring
, OSTypes.ErrorExtending
]
viewIndependentCmd =
if interval == 5 then
Task.perform DoOrchestration Time.now
else
Cmd.none
( viewDependentModel, viewDependentCmd ) =
{- TODO move some of this to Orchestration? -}
case outerModel.viewState of
NonProjectView _ ->
( outerModel.sharedModel, Cmd.none )
ProjectView projectName _ projectViewState ->
case GetterSetters.projectLookup outerModel.sharedModel projectName of
Nothing ->
{- Should this throw an error? -}
( outerModel.sharedModel, Cmd.none )
Just project ->
let
pollVolumes : ( SharedModel, Cmd SharedMsg )
pollVolumes =
( outerModel.sharedModel
, case interval of
5 ->
if List.any volNeedsFrequentPoll (RemoteData.withDefault [] project.volumes) then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
in
case projectViewState of
AllResourcesList _ ->
pollVolumes
ServerDetail model ->
let
volCmd =
OSVolumes.requestVolumes project
in
case interval of
5 ->
case GetterSetters.serverLookup project model.serverUuid of
Just server ->
( outerModel.sharedModel
, if serverVolsNeedFrequentPoll project server then
volCmd
else
Cmd.none
)
Nothing ->
( outerModel.sharedModel, Cmd.none )
300 ->
( outerModel.sharedModel, volCmd )
_ ->
( outerModel.sharedModel, Cmd.none )
VolumeDetail pageModel ->
( outerModel.sharedModel
, case interval of
5 ->
case GetterSetters.volumeLookup project pageModel.volumeUuid of
Nothing ->
Cmd.none
Just volume ->
if volNeedsFrequentPoll volume then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
VolumeList _ ->
pollVolumes
_ ->
( outerModel.sharedModel, Cmd.none )
in
( { viewDependentModel | clientCurrentTime = time }
, Cmd.batch
[ viewDependentCmd
, viewIndependentCmd
]
|> Cmd.map SharedMsg
)
processProjectSpecificMsg : OuterModel -> Project -> ProjectSpecificMsgConstructor -> ( OuterModel, Cmd OuterMsg )
processProjectSpecificMsg outerModel project msg =
let
sharedModel =
outerModel.sharedModel
in
case msg of
PrepareCredentialedRequest requestProto posixTime ->
let
-- Add proxy URL
requestNeedingToken =
requestProto sharedModel.cloudCorsProxyUrl
currentTimeMillis =
posixTime |> Time.posixToMillis
tokenExpireTimeMillis =
project.auth.expiresAt |> Time.posixToMillis
tokenExpired =
-- Token expiring within 5 minutes
tokenExpireTimeMillis < currentTimeMillis + 300000
in
if not tokenExpired then
-- Token still valid, fire the request with current token
( sharedModel, requestNeedingToken project.auth.tokenValue )
|> mapToOuterMsg
|> mapToOuterModel outerModel
else
-- Token is expired (or nearly expired) so we add request to list of pending requests and refresh that token
let
newPQRs =
( project.auth.project.uuid, requestNeedingToken ) :: outerModel.pendingCredentialedRequests
cmdResult =
State.Auth.requestAuthToken sharedModel project
newOuterModel =
{ outerModel | pendingCredentialedRequests = newPQRs }
in
case cmdResult of
Err e ->
let
errorContext =
ErrorContext
("Refresh authentication token for project " ++ project.auth.project.name)
ErrorCrit
(Just "Please remove this project from Exosphere and add it again.")
in
State.Error.processStringError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel newOuterModel
Ok cmd ->
( sharedModel, cmd )
|> mapToOuterMsg
|> mapToOuterModel newOuterModel
ToggleCreatePopup ->
case outerModel.viewState of
ProjectView projectId projectViewModel viewConstructor ->
let
newViewState =
ProjectView
projectId
{ projectViewModel
| createPopup = not projectViewModel.createPopup
}
viewConstructor
in
( { outerModel | viewState = newViewState }, Cmd.none )
_ ->
( outerModel, Cmd.none )
RemoveProject ->
let
newProjects =
List.filter (\p -> p.auth.project.uuid /= project.auth.project.uuid) sharedModel.projects
newOuterModel =
{ outerModel | sharedModel = { sharedModel | projects = newProjects } }
cmd =
-- if we are in a view specific to this project then navigate to the home page
case outerModel.viewState of
ProjectView projectId _ _ ->
if projectId == project.auth.project.uuid then
Route.pushUrl sharedModel.viewContext Route.Home
else
Cmd.none
_ ->
Cmd.none
in
( newOuterModel, cmd )
ServerMsg serverUuid serverMsgConstructor ->
case GetterSetters.serverLookup project serverUuid of
Nothing ->
let
errorContext =
ErrorContext
"receive results of API call for a specific server"
ErrorDebug
Nothing
in
State.Error.processStringError
sharedModel
errorContext
(String.join " "
[ "Instance"
, serverUuid
, "does not exist in the model, it may have been deleted."
]
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
Just server ->
processServerSpecificMsg outerModel project server serverMsgConstructor
RequestServers ->
ApiModelHelpers.requestServers project.auth.project.uuid sharedModel
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestCreateServer pageModel networkUuid ->
let
customWorkFlowSource =
if pageModel.includeWorkflow && Maybe.withDefault False pageModel.workflowInputIsValid then
Just
{ repository = pageModel.workflowInputRepository
, reference = pageModel.workflowInputReference
, path = pageModel.workflowInputPath
}
else
Nothing
createServerRequest =
{ name = pageModel.serverName
, count = pageModel.count
, imageUuid = pageModel.imageUuid
, flavorUuid = pageModel.flavorUuid
, volBackedSizeGb =
pageModel.volSizeTextInput
|> Maybe.andThen Style.Widgets.NumericTextInput.NumericTextInput.toMaybe
, networkUuid = networkUuid
, keypairName = pageModel.keypairName
, userData =
Helpers.renderUserDataTemplate
project
pageModel.userDataTemplate
pageModel.keypairName
(pageModel.deployGuacamole |> Maybe.withDefault False)
pageModel.deployDesktopEnvironment
customWorkFlowSource
pageModel.installOperatingSystemUpdates
sharedModel.instanceConfigMgtRepoUrl
sharedModel.instanceConfigMgtRepoCheckout
, metadata =
Helpers.newServerMetadata
currentExoServerVersion
sharedModel.clientUuid
(pageModel.deployGuacamole |> Maybe.withDefault False)
pageModel.deployDesktopEnvironment
project.auth.user.name
pageModel.floatingIpCreationOption
customWorkFlowSource
}
in
( outerModel, Rest.Nova.requestCreateServer project createServerRequest )
|> mapToOuterMsg
RequestCreateVolume name size ->
let
createVolumeRequest =
{ name = name
, size = size
}
in
( outerModel, OSVolumes.requestCreateVolume project createVolumeRequest )
|> mapToOuterMsg
RequestDeleteVolume volumeUuid ->
( outerModel, OSVolumes.requestDeleteVolume project volumeUuid )
|> mapToOuterMsg
RequestDetachVolume volumeUuid ->
let
maybeVolume =
OSVolumes.volumeLookup project volumeUuid
maybeServerUuid =
maybeVolume
|> Maybe.map (GetterSetters.getServersWithVolAttached project)
|> Maybe.andThen List.head
in
case maybeServerUuid of
Just serverUuid ->
( outerModel, OSSvrVols.requestDetachVolume project serverUuid volumeUuid )
|> mapToOuterMsg
Nothing ->
State.Error.processStringError
sharedModel
(ErrorContext
("look for server UUID with attached volume " ++ volumeUuid)
ErrorCrit
Nothing
)
"Could not determine server attached to this volume."
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestDeleteFloatingIp floatingIpAddress ->
( outerModel, Rest.Neutron.requestDeleteFloatingIp project floatingIpAddress )
|> mapToOuterMsg
RequestAssignFloatingIp port_ floatingIpUuid ->
let
setViewCmd =
Route.pushUrl sharedModel.viewContext
(Route.ProjectRoute project.auth.project.uuid <| Route.FloatingIpList)
in
( outerModel
, Cmd.batch
[ setViewCmd
, Cmd.map SharedMsg <| Rest.Neutron.requestAssignFloatingIp project port_ floatingIpUuid
]
)
RequestUnassignFloatingIp floatingIpUuid ->
( outerModel, Rest.Neutron.requestUnassignFloatingIp project floatingIpUuid )
|> mapToOuterMsg
ReceiveImages images ->
Rest.Glance.receiveImages sharedModel project images
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestDeleteServers serverUuidsToDelete ->
let
applyDelete : OSTypes.ServerUuid -> ( Project, Cmd SharedMsg ) -> ( Project, Cmd SharedMsg )
applyDelete serverUuid projCmdTuple =
let
( delServerProj, delServerCmd ) =
requestDeleteServer (Tuple.first projCmdTuple) serverUuid False
in
( delServerProj, Cmd.batch [ Tuple.second projCmdTuple, delServerCmd ] )
( newProject, cmd ) =
List.foldl
applyDelete
( project, Cmd.none )
serverUuidsToDelete
in
( GetterSetters.modelUpdateProject sharedModel newProject
, cmd
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveServers errorContext result ->
case result of
Ok servers ->
Rest.Nova.receiveServers sharedModel project servers
|> mapToOuterMsg
|> mapToOuterModel outerModel
Err e ->
let
oldServersData =
project.servers.data
newProject =
{ project
| servers =
RDPP.RemoteDataPlusPlus
oldServersData
(RDPP.NotLoading (Just ( e, sharedModel.clientCurrentTime )))
}
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newSharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveServer serverUuid errorContext result ->
case result of
Ok server ->
Rest.Nova.receiveServer sharedModel project server
|> mapToOuterMsg
|> mapToOuterModel outerModel
Err httpErrorWithBody ->
let
httpError =
httpErrorWithBody.error
non404 =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server not in project, may have been deleted, ignoring this error
( outerModel, Cmd.none )
Just server ->
-- Reset receivedTime and loadingSeparately
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps
| receivedTime = Nothing
, loadingSeparately = False
}
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newSharedModel errorContext httpErrorWithBody
|> mapToOuterMsg
|> mapToOuterModel outerModel
in
case httpError of
Http.BadStatus code ->
if code == 404 then
let
newErrorContext =
{ errorContext
| level = Error.ErrorDebug
, actionContext =
errorContext.actionContext
++ " -- 404 means server may have been deleted"
}
newProject =
GetterSetters.projectDeleteServer project serverUuid
newModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newModel newErrorContext httpErrorWithBody
|> mapToOuterMsg
|> mapToOuterModel outerModel
else
non404
_ ->
non404
ReceiveFlavors flavors ->
let
-- If we are creating a server and no flavor is selected, select the smallest flavor
maybeSmallestFlavor =
GetterSetters.sortedFlavors flavors |> List.head
( newOuterModel, newCmd ) =
Rest.Nova.receiveFlavors sharedModel project flavors
|> mapToOuterMsg
|> mapToOuterModel outerModel
in
case maybeSmallestFlavor of
Just smallestFlavor ->
( newOuterModel, newCmd )
|> pipelineCmdOuterModelMsg
(updateUnderlying (ServerCreateMsg <| Page.ServerCreate.GotDefaultFlavor smallestFlavor.uuid))
Nothing ->
( newOuterModel, newCmd )
RequestKeypairs ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success _ ->
project.keypairs
_ ->
RemoteData.Loading
newProject =
{ project | keypairs = newKeypairs }
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel
, Rest.Nova.requestKeypairs newProject
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveKeypairs keypairs ->
Rest.Nova.receiveKeypairs sharedModel project keypairs
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestCreateKeypair keypairName publicKey ->
( outerModel, Rest.Nova.requestCreateKeypair project keypairName publicKey )
|> mapToOuterMsg
ReceiveCreateKeypair keypair ->
let
newProject =
GetterSetters.projectUpdateKeypair project keypair
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( { outerModel | sharedModel = newSharedModel }
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute newProject.auth.project.uuid Route.KeypairList)
)
RequestDeleteKeypair keypairId ->
( outerModel, Rest.Nova.requestDeleteKeypair project keypairId )
|> mapToOuterMsg
ReceiveDeleteKeypair errorContext keypairName result ->
case result of
Err httpError ->
State.Error.processStringError sharedModel errorContext (Helpers.httpErrorToString httpError)
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok () ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success keypairs ->
keypairs
|> List.filter (\k -> k.name /= keypairName)
|> RemoteData.Success
_ ->
project.keypairs
newProject =
{ project | keypairs = newKeypairs }
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterModel outerModel
ReceiveCreateServer _ ->
let
newRoute =
Route.ProjectRoute
project.auth.project.uuid
Route.AllResourcesList
( newSharedModel, newCmd ) =
( sharedModel, Cmd.none )
|> Helpers.pipelineCmd
(ApiModelHelpers.requestServers project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestNetworks project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts project.auth.project.uuid)
in
( { outerModel | sharedModel = newSharedModel }
, Cmd.batch
[ Cmd.map SharedMsg newCmd
, Route.pushUrl sharedModel.viewContext newRoute
]
)
ReceiveNetworks errorContext result ->
case result of
Ok networks ->
let
newProject =
Rest.Neutron.receiveNetworks sharedModel project networks
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterMsg
|> mapToOuterModel outerModel
|> pipelineCmdOuterModelMsg (updateUnderlying (ServerCreateMsg <| Page.ServerCreate.GotNetworks))
Err httpError ->
let
oldNetworksData =
project.networks.data
newProject =
{ project
| networks =
RDPP.RemoteDataPlusPlus
oldNetworksData
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newModel errorContext httpError
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveAutoAllocatedNetwork errorContext result ->
let
newProject =
case result of
Ok netUuid ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave netUuid sharedModel.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
Err httpError ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
project.autoAllocatedNetworkUuid.data
(RDPP.NotLoading
(Just
( httpError
, sharedModel.clientCurrentTime
)
)
)
}
newSharedModel =
GetterSetters.modelUpdateProject
sharedModel
newProject
( newNewSharedModel, newCmd ) =
case result of
Ok _ ->
ApiModelHelpers.requestNetworks project.auth.project.uuid newSharedModel
Err httpError ->
State.Error.processSynchronousApiError newSharedModel errorContext httpError
|> Helpers.pipelineCmd (ApiModelHelpers.requestNetworks project.auth.project.uuid)
( newOuterModel, underlyingCmd ) =
case Helpers.newServerNetworkOptions newProject of
AutoSelectedNetwork netUuid ->
updateUnderlying
(ServerCreateMsg <| Page.ServerCreate.GotAutoAllocatedNetwork netUuid)
{ outerModel | sharedModel = newNewSharedModel }
_ ->
( { outerModel | sharedModel = newNewSharedModel }, Cmd.none )
in
( newOuterModel, Cmd.batch [ Cmd.map SharedMsg newCmd, underlyingCmd ] )
ReceiveFloatingIps ips ->
Rest.Neutron.receiveFloatingIps sharedModel project ips
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceivePorts errorContext result ->
case result of
Ok ports ->
let
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave ports sharedModel.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
Err httpError ->
let
oldPortsData =
project.ports.data
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
oldPortsData
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
}
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newSharedModel errorContext httpError
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteFloatingIp uuid ->
Rest.Neutron.receiveDeleteFloatingIp sharedModel project uuid
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveAssignFloatingIp floatingIp ->
-- TODO update servers so that new assignment is reflected in the UI
let
newProject =
processNewFloatingIp sharedModel.clientCurrentTime project floatingIp
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterModel outerModel
ReceiveUnassignFloatingIp floatingIp ->
-- TODO update servers so that unassignment is reflected in the UI
let
newProject =
processNewFloatingIp sharedModel.clientCurrentTime project floatingIp
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveSecurityGroups groups ->
Rest.Neutron.receiveSecurityGroupsAndEnsureExoGroup sharedModel project groups
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveCreateExoSecurityGroup group ->
Rest.Neutron.receiveCreateExoSecurityGroupAndRequestCreateRules sharedModel project group
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveCreateVolume ->
{- Should we add new volume to model now? -}
( outerModel
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute project.auth.project.uuid Route.VolumeList)
)
ReceiveVolumes volumes ->
let
-- Look for any server backing volumes that were created with no name, and give them a reasonable name
updateVolNameCmds : List (Cmd SharedMsg)
updateVolNameCmds =
RDPP.withDefault [] project.servers
-- List of tuples containing server and Maybe boot vol
|> List.map
(\s ->
( s
, Helpers.getBootVol
(RemoteData.withDefault
[]
project.volumes
)
s.osProps.uuid
)
)
-- We only care about servers created by exosphere
|> List.filter
(\t ->
case Tuple.first t |> .exoProps |> .serverOrigin of
ServerFromExo _ ->
True
ServerNotFromExo ->
False
)
-- We only care about servers created as current OpenStack user
|> List.filter
(\t ->
(Tuple.first t).osProps.details.userUuid
== project.auth.user.uuid
)
-- We only care about servers with a non-empty name
|> List.filter
(\t ->
Tuple.first t
|> .osProps
|> .name
|> String.isEmpty
|> not
)
-- We only care about volume-backed servers
|> List.filterMap
(\t ->
case t of
( server, Just vol ) ->
-- Flatten second part of tuple
Just ( server, vol )
_ ->
Nothing
)
-- We only care about unnamed backing volumes
|> List.filter
(\t ->
Tuple.second t
|> .name
|> String.isEmpty
)
|> List.map
(\t ->
OSVolumes.requestUpdateVolumeName
project
(t |> Tuple.second |> .uuid)
("boot-vol-"
++ (t |> Tuple.first |> .osProps |> .name)
)
)
newProject =
{ project | volumes = RemoteData.succeed volumes }
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.batch updateVolNameCmds )
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteVolume ->
( outerModel, OSVolumes.requestVolumes project )
|> mapToOuterMsg
ReceiveUpdateVolumeName ->
( outerModel, OSVolumes.requestVolumes project )
|> mapToOuterMsg
ReceiveAttachVolume attachment ->
( outerModel
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute project.auth.project.uuid <| Route.VolumeMountInstructions attachment)
)
ReceiveDetachVolume ->
( outerModel
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute project.auth.project.uuid Route.VolumeList)
)
ReceiveAppCredential appCredential ->
let
newProject =
{ project | secret = ApplicationCredential appCredential }
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveComputeQuota quota ->
let
newProject =
{ project | computeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveVolumeQuota quota ->
let
newProject =
{ project | volumeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveRandomServerName serverName ->
updateUnderlying (ServerCreateMsg <| Page.ServerCreate.GotServerName serverName) outerModel
processServerSpecificMsg : OuterModel -> Project -> Server -> ServerSpecificMsgConstructor -> ( OuterModel, Cmd OuterMsg )
processServerSpecificMsg outerModel project server serverMsgConstructor =
let
sharedModel =
outerModel.sharedModel
in
case serverMsgConstructor of
RequestServer ->
ApiModelHelpers.requestServer project.auth.project.uuid server.osProps.uuid sharedModel
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestDeleteServer retainFloatingIps ->
let
( newProject, cmd ) =
requestDeleteServer project server.osProps.uuid retainFloatingIps
in
( GetterSetters.modelUpdateProject sharedModel newProject, cmd )
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestAttachVolume volumeUuid ->
( outerModel, OSSvrVols.requestAttachVolume project server.osProps.uuid volumeUuid )
|> mapToOuterMsg
RequestCreateServerImage imageName ->
let
newRoute =
Route.ProjectRoute
project.auth.project.uuid
Route.AllResourcesList
createImageCmd =
Rest.Nova.requestCreateServerImage project server.osProps.uuid imageName
in
( outerModel
, Cmd.batch
[ Cmd.map SharedMsg createImageCmd
, Route.pushUrl sharedModel.viewContext newRoute
]
)
RequestSetServerName newServerName ->
( outerModel, Rest.Nova.requestSetServerName project server.osProps.uuid newServerName )
|> mapToOuterMsg
ReceiveServerEvents _ result ->
case result of
Ok serverEvents ->
let
newServer =
{ server | events = RemoteData.Success serverEvents }
newProject =
GetterSetters.projectUpdateServer project newServer
in
( GetterSetters.modelUpdateProject sharedModel newProject
, Cmd.none
)
|> mapToOuterModel outerModel
Err _ ->
-- Dropping this on the floor for now, someday we may want to do something different
( outerModel, Cmd.none )
ReceiveConsoleUrl url ->
Rest.Nova.receiveConsoleUrl sharedModel project server url
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteServer ->
let
newProject =
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | deletionAttempted = True }
newServer =
{ server | exoProps = newExoProps }
in
GetterSetters.projectUpdateServer project newServer
newOuterModel =
{ outerModel | sharedModel = GetterSetters.modelUpdateProject sharedModel newProject }
in
( newOuterModel
, case outerModel.viewState of
ProjectView projectId _ (ServerDetail pageModel) ->
if pageModel.serverUuid == server.osProps.uuid then
Route.pushUrl sharedModel.viewContext (Route.ProjectRoute projectId Route.AllResourcesList)
else
Cmd.none
_ ->
Cmd.none
)
ReceiveCreateFloatingIp errorContext result ->
case result of
Ok ip ->
Rest.Neutron.receiveCreateFloatingIp sharedModel project server ip
|> mapToOuterMsg
|> mapToOuterModel outerModel
Err httpErrorWithBody ->
let
newErrorContext =
if GetterSetters.serverPresentNotDeleting sharedModel server.osProps.uuid then
errorContext
else
{ errorContext | level = ErrorDebug }
in
State.Error.processSynchronousApiError sharedModel newErrorContext httpErrorWithBody
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveServerPassword password ->
if String.isEmpty password then
( outerModel, Cmd.none )
else
let
tag =
"exoPw:" ++ password
cmd =
case server.exoProps.serverOrigin of
ServerNotFromExo ->
Cmd.none
ServerFromExo serverFromExoProps ->
if serverFromExoProps.exoServerVersion >= 1 then
Cmd.batch
[ OSServerTags.requestCreateServerTag project server.osProps.uuid tag
, OSServerPassword.requestClearServerPassword project server.osProps.uuid
]
else
Cmd.none
in
( outerModel, cmd )
|> mapToOuterMsg
ReceiveSetServerName _ errorContext result ->
case result of
Err e ->
State.Error.processSynchronousApiError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok actualNewServerName ->
let
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | name = actualNewServerName }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newOuterModel =
{ outerModel | sharedModel = GetterSetters.modelUpdateProject sharedModel newProject }
-- Later, maybe: Check that newServerName == actualNewServerName
in
updateUnderlying (ServerDetailMsg <| Page.ServerDetail.GotServerNamePendingConfirmation Nothing)
newOuterModel
ReceiveSetServerMetadata intendedMetadataItem errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok newServerMetadata ->
-- Update the model after ensuring the intended metadata item was actually added
if List.member intendedMetadataItem newServerMetadata then
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = newServerMetadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterMsg
|> mapToOuterModel outerModel
else
-- This is bonkers, throw an error
State.Error.processStringError
sharedModel
errorContext
"The metadata items returned by OpenStack did not include the metadata item that we tried to set."
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteServerMetadata metadataKey errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok _ ->
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = List.filter (\i -> i.key /= metadataKey) oldServerDetails.metadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterModel outerModel
ReceiveGuacamoleAuthToken result ->
let
errorContext =
ErrorContext
"Receive a response from Guacamole auth token API"
ErrorDebug
Nothing
sharedModelUpdateGuacProps : ServerFromExoProps -> GuacTypes.LaunchedWithGuacProps -> SharedModel
sharedModelUpdateGuacProps exoOriginProps guacProps =
let
newOriginProps =
{ exoOriginProps | guacamoleStatus = GuacTypes.LaunchedWithGuacamole guacProps }
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
newSharedModel
in
case server.exoProps.serverOrigin of
ServerFromExo exoOriginProps ->
case exoOriginProps.guacamoleStatus of
GuacTypes.LaunchedWithGuacamole oldGuacProps ->
let
newGuacProps =
case result of
Ok tokenValue ->
if server.osProps.details.openstackStatus == OSTypes.ServerActive then
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
tokenValue
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
}
else
-- Server is not active, this token won't work, so we don't store it
{ oldGuacProps
| authToken =
RDPP.empty
}
Err e ->
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
oldGuacProps.authToken.data
(RDPP.NotLoading (Just ( e, sharedModel.clientCurrentTime )))
}
in
( sharedModelUpdateGuacProps
exoOriginProps
newGuacProps
, Cmd.none
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
GuacTypes.NotLaunchedWithGuacamole ->
State.Error.processStringError
sharedModel
errorContext
"Server does not appear to have been launched with Guacamole support"
|> mapToOuterMsg
|> mapToOuterModel outerModel
ServerNotFromExo ->
State.Error.processStringError
sharedModel
errorContext
"Server does not appear to have been launched from Exosphere"
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestServerAction func targetStatuses ->
let
oldExoProps =
server.exoProps
newServer =
Server server.osProps { oldExoProps | targetOpenstackStatus = targetStatuses } server.events
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, func newProject.endpoints.nova )
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveConsoleLog errorContext result ->
case server.exoProps.serverOrigin of
ServerNotFromExo ->
( outerModel, Cmd.none )
ServerFromExo exoOriginProps ->
let
oldExoSetupStatus =
case exoOriginProps.exoSetupStatus.data of
RDPP.DontHave ->
ExoSetupUnknown
RDPP.DoHave s _ ->
s
( newExoSetupStatusRDPP, exoSetupStatusMetadataCmd ) =
case result of
Err httpError ->
( RDPP.RemoteDataPlusPlus
exoOriginProps.exoSetupStatus.data
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
, Cmd.none
)
Ok consoleLog ->
let
newExoSetupStatus =
Helpers.ExoSetupStatus.parseConsoleLogExoSetupStatus
oldExoSetupStatus
consoleLog
server.osProps.details.created
sharedModel.clientCurrentTime
cmd =
if newExoSetupStatus == oldExoSetupStatus then
Cmd.none
else
let
value =
Helpers.ExoSetupStatus.exoSetupStatusToStr newExoSetupStatus
metadataItem =
OSTypes.MetadataItem
"exoSetup"
value
in
Rest.Nova.requestSetServerMetadata project server.osProps.uuid metadataItem
in
( RDPP.RemoteDataPlusPlus
(RDPP.DoHave
newExoSetupStatus
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
, cmd
)
newResourceUsage =
case result of
Err httpError ->
RDPP.RemoteDataPlusPlus
exoOriginProps.resourceUsage.data
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
Ok consoleLog ->
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
(Helpers.ServerResourceUsage.parseConsoleLog
consoleLog
(RDPP.withDefault
Types.ServerResourceUsage.emptyResourceUsageHistory
exoOriginProps.resourceUsage
)
)
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
newWorkflowToken : CustomWorkflow -> CustomWorkflowTokenRDPP
newWorkflowToken currentWorkflow =
case result of
Err httpError ->
RDPP.RemoteDataPlusPlus
RDPP.DontHave
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
Ok consoleLog ->
let
maybeParsedToken =
Helpers.parseConsoleLogForWorkflowToken consoleLog
in
case maybeParsedToken of
Just parsedToken ->
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
parsedToken
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
Nothing ->
currentWorkflow.authToken
newWorkflowStatus : ServerCustomWorkflowStatus
newWorkflowStatus =
case exoOriginProps.customWorkflowStatus of
NotLaunchedWithCustomWorkflow ->
exoOriginProps.customWorkflowStatus
LaunchedWithCustomWorkflow customWorkflow ->
LaunchedWithCustomWorkflow { customWorkflow | authToken = newWorkflowToken customWorkflow }
newOriginProps =
{ exoOriginProps
| resourceUsage = newResourceUsage
, exoSetupStatus = newExoSetupStatusRDPP
, customWorkflowStatus = newWorkflowStatus
}
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
case result of
Err httpError ->
State.Error.processSynchronousApiError newSharedModel errorContext httpError
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok _ ->
( newSharedModel, exoSetupStatusMetadataCmd )
|> mapToOuterMsg
|> mapToOuterModel outerModel
processNewFloatingIp : Time.Posix -> Project -> OSTypes.FloatingIp -> Project
processNewFloatingIp time project floatingIp =
let
otherIps =
project.floatingIps
|> RDPP.withDefault []
|> List.filter (\i -> i.uuid /= floatingIp.uuid)
newIps =
floatingIp :: otherIps
in
{ project
| floatingIps =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave newIps time)
(RDPP.NotLoading Nothing)
}
createProject : OuterModel -> Maybe OSTypes.ProjectDescription -> OSTypes.ScopedAuthToken -> Endpoints -> ( OuterModel, Cmd OuterMsg )
createProject outerModel description authToken endpoints =
let
sharedModel =
outerModel.sharedModel
newProject =
{ secret = NoProjectSecret
, auth = authToken
-- Maybe todo, eliminate parallel data structures in auth and endpoints?
, endpoints = endpoints
, description = description
, images = []
, servers = RDPP.RemoteDataPlusPlus RDPP.DontHave RDPP.Loading
, flavors = []
, keypairs = RemoteData.NotAsked
, volumes = RemoteData.NotAsked
, networks = RDPP.empty
, autoAllocatedNetworkUuid = RDPP.empty
, floatingIps = RDPP.empty
, ports = RDPP.empty
, securityGroups = []
, computeQuota = RemoteData.NotAsked
, volumeQuota = RemoteData.NotAsked
}
newProjects =
newProject :: outerModel.sharedModel.projects
newViewStateCmd =
-- If the user is selecting projects from an unscoped provider then don't interrupt them
case outerModel.viewState of
NonProjectView (SelectProjects _) ->
Cmd.none
-- Otherwise take them to home page
_ ->
Route.pushUrl sharedModel.viewContext <|
Route.Home
( newSharedModel, newCmd ) =
( { sharedModel
| projects = newProjects
}
, [ Rest.Nova.requestServers
, Rest.Neutron.requestSecurityGroups
, Rest.Keystone.requestAppCredential sharedModel.clientUuid sharedModel.clientCurrentTime
]
|> List.map (\x -> x newProject)
|> Cmd.batch
)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestVolumes newProject.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestFloatingIps newProject.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts newProject.auth.project.uuid)
in
( { outerModel | sharedModel = newSharedModel }
, Cmd.batch [ newViewStateCmd, Cmd.map SharedMsg newCmd ]
)
createUnscopedProvider : SharedModel -> OSTypes.UnscopedAuthToken -> HelperTypes.Url -> ( SharedModel, Cmd SharedMsg )
createUnscopedProvider model authToken authUrl =
let
newProvider =
{ authUrl = authUrl
, token = authToken
, projectsAvailable = RemoteData.Loading
}
newProviders =
newProvider :: model.unscopedProviders
in
( { model | unscopedProviders = newProviders }
, Rest.Keystone.requestUnscopedProjects newProvider model.cloudCorsProxyUrl
)
requestDeleteServer : Project -> OSTypes.ServerUuid -> Bool -> ( Project, Cmd SharedMsg )
requestDeleteServer project serverUuid retainFloatingIps =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server likely deleted already, do nothing
( project, Cmd.none )
Just server ->
let
oldExoProps =
server.exoProps
newServer =
{ server | exoProps = { oldExoProps | deletionAttempted = True } }
deleteFloatingIpCmds =
if retainFloatingIps then
[]
else
GetterSetters.getServerFloatingIps project server.osProps.uuid
|> List.map .uuid
|> List.map (Rest.Neutron.requestDeleteFloatingIp project)
newProject =
GetterSetters.projectUpdateServer project newServer
in
( newProject
, Cmd.batch
[ Rest.Nova.requestDeleteServer
newProject.auth.project.uuid
newProject.endpoints.nova
newServer.osProps.uuid
, Cmd.batch deleteFloatingIpCmds
]
)
| 61621 | module State.State exposing (update)
import Browser
import Browser.Navigation
import Helpers.ExoSetupStatus
import Helpers.GetterSetters as GetterSetters
import Helpers.Helpers as Helpers
import Helpers.RemoteDataPlusPlus as RDPP
import Helpers.ServerResourceUsage
import Http
import LocalStorage.LocalStorage as LocalStorage
import Maybe
import OpenStack.ServerPassword as OSServerPassword
import OpenStack.ServerTags as OSServerTags
import OpenStack.ServerVolumes as OSSvrVols
import OpenStack.Types as OSTypes
import OpenStack.Volumes as OSVolumes
import Orchestration.Orchestration as Orchestration
import Page.AllResourcesList
import Page.FloatingIpAssign
import Page.FloatingIpList
import Page.GetSupport
import Page.Home
import Page.InstanceSourcePicker
import Page.KeypairCreate
import Page.KeypairList
import Page.LoginJetstream
import Page.LoginOpenstack
import Page.LoginPicker
import Page.MessageLog
import Page.SelectProjects
import Page.ServerCreate
import Page.ServerCreateImage
import Page.ServerDetail
import Page.ServerList
import Page.Settings
import Page.VolumeAttach
import Page.VolumeCreate
import Page.VolumeDetail
import Page.VolumeList
import Ports
import RemoteData
import Rest.ApiModelHelpers as ApiModelHelpers
import Rest.Glance
import Rest.Keystone
import Rest.Neutron
import Rest.Nova
import Route
import State.Auth
import State.Error
import State.ViewState as ViewStateHelpers
import Style.Toast
import Style.Widgets.NumericTextInput.NumericTextInput
import Task
import Time
import Toasty
import Types.Error as Error exposing (AppError, ErrorContext, ErrorLevel(..))
import Types.Guacamole as GuacTypes
import Types.HelperTypes as HelperTypes exposing (HttpRequestMethod(..), UnscopedProviderProject)
import Types.OuterModel exposing (OuterModel)
import Types.OuterMsg exposing (OuterMsg(..))
import Types.Project exposing (Endpoints, Project, ProjectSecret(..))
import Types.Server exposing (ExoSetupStatus(..), NewServerNetworkOptions(..), Server, ServerFromExoProps, ServerOrigin(..), currentExoServerVersion)
import Types.ServerResourceUsage
import Types.SharedModel exposing (SharedModel)
import Types.SharedMsg exposing (ProjectSpecificMsgConstructor(..), ServerSpecificMsgConstructor(..), SharedMsg(..), TickInterval)
import Types.View
exposing
( LoginView(..)
, NonProjectViewConstructor(..)
, ProjectViewConstructor(..)
, ViewState(..)
)
import Types.Workflow
exposing
( CustomWorkflow
, CustomWorkflowTokenRDPP
, ServerCustomWorkflowStatus(..)
)
import Url
import View.Helpers exposing (toExoPalette)
update : OuterMsg -> Result AppError OuterModel -> ( Result AppError OuterModel, Cmd OuterMsg )
update msg result =
case result of
Err appError ->
( Err appError, Cmd.none )
Ok model ->
case updateValid msg model of
( newModel, nextMsg ) ->
( Ok newModel, nextMsg )
updateValid : OuterMsg -> OuterModel -> ( OuterModel, Cmd OuterMsg )
updateValid msg outerModel =
{- We want to `setStorage` on every update. This function adds the setStorage
command for every step of the update function.
-}
let
( newOuterModel, cmds ) =
updateUnderlying msg outerModel
orchestrationTimeCmd =
-- Each trip through the runtime, we get the time and feed it to orchestration module
case msg of
SharedMsg (DoOrchestration _) ->
Cmd.none
SharedMsg (Tick _ _) ->
Cmd.none
_ ->
Task.perform (\posix -> SharedMsg <| DoOrchestration posix) Time.now
in
( newOuterModel
, Cmd.batch
[ Ports.setStorage (LocalStorage.generateStoredState newOuterModel.sharedModel)
, orchestrationTimeCmd
, cmds
]
)
-- There may be a better approach than these mapping functions, I'm not sure yet.
mapToOuterMsg : ( a, Cmd SharedMsg ) -> ( a, Cmd OuterMsg )
mapToOuterMsg ( model, cmdSharedMsg ) =
( model, Cmd.map SharedMsg cmdSharedMsg )
mapToOuterModel : OuterModel -> ( SharedModel, Cmd a ) -> ( OuterModel, Cmd a )
mapToOuterModel outerModel ( newSharedModel, cmd ) =
( { outerModel | sharedModel = newSharedModel }, cmd )
pipelineCmdOuterModelMsg : (OuterModel -> ( OuterModel, Cmd OuterMsg )) -> ( OuterModel, Cmd OuterMsg ) -> ( OuterModel, Cmd OuterMsg )
pipelineCmdOuterModelMsg fn ( outerModel, outerCmd ) =
let
( newModel, newCmd ) =
fn outerModel
in
( newModel, Cmd.batch [ outerCmd, newCmd ] )
updateUnderlying : OuterMsg -> OuterModel -> ( OuterModel, Cmd OuterMsg )
updateUnderlying outerMsg outerModel =
let
sharedModel =
outerModel.sharedModel
in
case ( outerMsg, outerModel.viewState ) of
( SharedMsg sharedMsg, _ ) ->
processSharedMsg sharedMsg outerModel
-- TODO exact same structure for each page-specific case here. Is there a way to deduplicate or factor out?
( GetSupportMsg pageMsg, NonProjectView (GetSupport pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.GetSupport.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| GetSupport newPageModel
}
, Cmd.map GetSupportMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( HomeMsg pageMsg, NonProjectView (Home pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.Home.update pageMsg pageModel
in
( { outerModel
| viewState = NonProjectView <| Home newPageModel
}
, Cmd.map HomeMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( LoginJetstreamMsg pageMsg, NonProjectView (Login (LoginJetstream pageModel)) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.LoginJetstream.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| Login <| LoginJetstream newPageModel
}
, Cmd.map LoginJetstreamMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( LoginOpenstackMsg pageMsg, NonProjectView (Login (LoginOpenstack pageModel)) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.LoginOpenstack.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| Login <| LoginOpenstack newPageModel
}
, Cmd.map LoginOpenstackMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( LoginPickerMsg pageMsg, NonProjectView LoginPicker ) ->
let
( _, cmd, sharedMsg ) =
Page.LoginPicker.update pageMsg
in
( { outerModel
| viewState = NonProjectView <| LoginPicker
}
, Cmd.map LoginPickerMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( MessageLogMsg pageMsg, NonProjectView (MessageLog pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.MessageLog.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| MessageLog newPageModel
}
, Cmd.map MessageLogMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( SelectProjectsMsg pageMsg, NonProjectView (SelectProjects pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.SelectProjects.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| SelectProjects newPageModel
}
, Cmd.map SelectProjectsMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( SettingsMsg pageMsg, NonProjectView (Settings pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.Settings.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| Settings newPageModel
}
, Cmd.map SettingsMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( pageSpecificMsg, ProjectView projectId projectViewModel projectViewConstructor ) ->
case GetterSetters.projectLookup sharedModel projectId of
Just project ->
case ( pageSpecificMsg, projectViewConstructor ) of
-- This is the repetitive dispatch code that people warn you about when you use the nested Elm architecture.
-- Maybe there is a way to make it less repetitive (or at least more compact) in the future.
( AllResourcesListMsg pageMsg, AllResourcesList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.AllResourcesList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
AllResourcesList newSharedModel
}
, Cmd.map AllResourcesListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( FloatingIpAssignMsg pageMsg, FloatingIpAssign pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.FloatingIpAssign.update pageMsg sharedModel project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
FloatingIpAssign newSharedModel
}
, Cmd.map FloatingIpAssignMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( FloatingIpListMsg pageMsg, FloatingIpList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.FloatingIpList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
FloatingIpList newSharedModel
}
, Cmd.map FloatingIpListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( InstanceSourcePickerMsg pageMsg, InstanceSourcePicker pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.InstanceSourcePicker.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
InstanceSourcePicker newSharedModel
}
, Cmd.map InstanceSourcePickerMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( KeypairCreateMsg pageMsg, KeypairCreate pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.KeypairCreate.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
KeypairCreate newSharedModel
}
, Cmd.map KeypairCreateMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( KeypairListMsg pageMsg, KeypairList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.KeypairList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
KeypairList newSharedModel
}
, Cmd.map KeypairListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerCreateMsg pageMsg, ServerCreate pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerCreate.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerCreate newSharedModel
}
, Cmd.map ServerCreateMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerCreateImageMsg pageMsg, ServerCreateImage pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerCreateImage.update pageMsg sharedModel project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerCreateImage newSharedModel
}
, Cmd.map ServerCreateImageMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerDetailMsg pageMsg, ServerDetail pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerDetail.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerDetail newSharedModel
}
, Cmd.map ServerDetailMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerListMsg pageMsg, ServerList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerList newSharedModel
}
, Cmd.map ServerListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeAttachMsg pageMsg, VolumeAttach pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeAttach.update pageMsg sharedModel project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeAttach newSharedModel
}
, Cmd.map VolumeAttachMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeCreateMsg pageMsg, VolumeCreate pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeCreate.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeCreate newSharedModel
}
, Cmd.map VolumeCreateMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeDetailMsg pageMsg, VolumeDetail pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeDetail.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeDetail newSharedModel
}
, Cmd.map VolumeDetailMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeListMsg pageMsg, VolumeList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeList newSharedModel
}
, Cmd.map VolumeListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
_ ->
-- This is not great because it allows us to forget to write a case statement above, but I don't know of a nicer way to write a catchall case for when a page-specific Msg is received for an inapplicable page.
( outerModel, Cmd.none )
Nothing ->
( outerModel, Cmd.none )
( _, _ ) ->
-- This is not great because it allows us to forget to write a case statement above, but I don't know of a nicer way to write a catchall case for when a page-specific Msg is received for an inapplicable page.
( outerModel, Cmd.none )
processSharedMsg : SharedMsg -> OuterModel -> ( OuterModel, Cmd OuterMsg )
processSharedMsg sharedMsg outerModel =
let
{ sharedModel } =
outerModel
{ viewContext } =
sharedModel
in
case sharedMsg of
ChangeSystemThemePreference preference ->
let
{ style } =
sharedModel
{ styleMode } =
style
newStyleMode =
{ styleMode | systemPreference = Just preference }
newStyle =
{ style | styleMode = newStyleMode }
newPalette =
toExoPalette newStyle
newViewContext =
{ viewContext | palette = newPalette }
in
mapToOuterModel outerModel
( { sharedModel
| style = newStyle
, viewContext = newViewContext
}
, Cmd.none
)
Logout ->
( outerModel, Ports.logout () )
ToastyMsg subMsg ->
Toasty.update Style.Toast.toastConfig ToastyMsg subMsg outerModel.sharedModel
|> mapToOuterMsg
|> mapToOuterModel outerModel
MsgChangeWindowSize x y ->
( { sharedModel
| viewContext =
{ viewContext
| windowSize = { width = x, height = y }
}
}
, Cmd.none
)
|> mapToOuterModel outerModel
Tick interval time ->
processTick outerModel interval time
|> mapToOuterModel outerModel
DoOrchestration posixTime ->
Orchestration.orchModel sharedModel posixTime
|> mapToOuterMsg
|> mapToOuterModel outerModel
HandleApiErrorWithBody errorContext error ->
State.Error.processSynchronousApiError sharedModel errorContext error
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestUnscopedToken openstackLoginUnscoped ->
let
creds =
-- Ensure auth URL includes port number and version
{ openstackLoginUnscoped
| authUrl =
State.Auth.authUrlWithPortAndVersion openstackLoginUnscoped.authUrl
}
in
( outerModel, Rest.Keystone.requestUnscopedAuthToken sharedModel.cloudCorsProxyUrl creds )
|> mapToOuterMsg
JetstreamLogin jetstreamCreds ->
let
openstackCredsList =
State.Auth.jetstreamToOpenstackCreds jetstreamCreds
cmds =
List.map
(\creds -> Rest.Keystone.requestUnscopedAuthToken sharedModel.cloudCorsProxyUrl creds)
openstackCredsList
in
( outerModel, Cmd.batch cmds )
|> mapToOuterMsg
ReceiveScopedAuthToken projectDescription ( metadata, response ) ->
case Rest.Keystone.decodeScopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
sharedModel
(ErrorContext
"decode scoped auth token"
ErrorCrit
Nothing
)
error
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok authToken ->
case Helpers.serviceCatalogToEndpoints authToken.catalog of
Err e ->
State.Error.processStringError
sharedModel
(ErrorContext
"Decode project endpoints"
ErrorCrit
(Just "Please check with your cloud administrator or the Exosphere developers.")
)
e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok endpoints ->
let
projectId =
authToken.project.uuid
in
-- If we don't have a project with same name + authUrl then create one, if we do then update its OSTypes.AuthToken
-- This code ensures we don't end up with duplicate projects on the same provider in our model.
case
GetterSetters.projectLookup sharedModel <| projectId
of
Nothing ->
createProject outerModel projectDescription authToken endpoints
Just project ->
-- If we don't have an application credential for this project yet, then get one
let
appCredCmd =
case project.secret of
ApplicationCredential _ ->
Cmd.none
_ ->
Rest.Keystone.requestAppCredential
sharedModel.clientUuid
sharedModel.clientCurrentTime
project
( newOuterModel, updateTokenCmd ) =
State.Auth.projectUpdateAuthToken outerModel project authToken
in
( newOuterModel, Cmd.batch [ appCredCmd, updateTokenCmd ] )
|> mapToOuterMsg
ReceiveUnscopedAuthToken keystoneUrl ( metadata, response ) ->
case Rest.Keystone.decodeUnscopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
sharedModel
(ErrorContext
"decode unscoped auth token"
ErrorCrit
Nothing
)
error
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok authToken ->
case
GetterSetters.providerLookup sharedModel keystoneUrl
of
Just unscopedProvider ->
-- We already have an unscoped provider in the model with the same auth URL, update its token
State.Auth.unscopedProviderUpdateAuthToken
sharedModel
unscopedProvider
authToken
|> mapToOuterMsg
|> mapToOuterModel outerModel
Nothing ->
-- We don't have an unscoped provider with the same auth URL, create it
createUnscopedProvider sharedModel authToken keystoneUrl
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveUnscopedProjects keystoneUrl unscopedProjects ->
case
GetterSetters.providerLookup sharedModel keystoneUrl
of
Just provider ->
let
newProvider =
{ provider | projectsAvailable = RemoteData.Success unscopedProjects }
newSharedModel =
GetterSetters.modelUpdateUnscopedProvider sharedModel newProvider
newOuterModel =
{ outerModel | sharedModel = newSharedModel }
in
-- If we are not already on a SelectProjects view, then go there
case outerModel.viewState of
NonProjectView (SelectProjects _) ->
( newOuterModel, Cmd.none )
_ ->
( newOuterModel
, Route.pushUrl viewContext (Route.SelectProjects keystoneUrl)
)
Nothing ->
-- Provider not found, may have been removed, nothing to do
( outerModel, Cmd.none )
RequestProjectLoginFromProvider keystoneUrl unscopedProjects ->
case GetterSetters.providerLookup sharedModel keystoneUrl of
Just provider ->
let
buildLoginRequest : UnscopedProviderProject -> Cmd SharedMsg
buildLoginRequest project =
Rest.Keystone.requestScopedAuthToken
sharedModel.cloudCorsProxyUrl
project.description
<|
OSTypes.TokenCreds
keystoneUrl
provider.token
project.project.uuid
loginRequests =
List.map buildLoginRequest unscopedProjects
|> Cmd.batch
-- Remove unscoped provider from model now that we have selected projects from it
newUnscopedProviders =
List.filter
(\p -> p.authUrl /= keystoneUrl)
sharedModel.unscopedProviders
-- If we still have at least one unscoped provider in the model then ask the user to choose projects from it
newViewStateCmd =
case List.head newUnscopedProviders of
Just unscopedProvider ->
Route.pushUrl viewContext (Route.SelectProjects unscopedProvider.authUrl)
Nothing ->
-- If we have at least one project then show it, else show the login page
case List.head sharedModel.projects of
Just project ->
Route.pushUrl viewContext <|
Route.ProjectRoute project.auth.project.uuid <|
Route.AllResourcesList
Nothing ->
Route.pushUrl viewContext Route.LoginPicker
sharedModelUpdatedUnscopedProviders =
{ sharedModel | unscopedProviders = newUnscopedProviders }
in
( { outerModel | sharedModel = sharedModelUpdatedUnscopedProviders }
, Cmd.batch [ Cmd.map SharedMsg loginRequests, newViewStateCmd ]
)
Nothing ->
State.Error.processStringError
sharedModel
(ErrorContext
("look for OpenStack provider with Keystone URL " ++ keystoneUrl)
ErrorCrit
Nothing
)
"Provider could not found in Exosphere's list of Providers."
|> mapToOuterMsg
|> mapToOuterModel outerModel
ProjectMsg projectIdentifier innerMsg ->
case GetterSetters.projectLookup sharedModel projectIdentifier of
Nothing ->
-- Project not found, may have been removed, nothing to do
( outerModel, Cmd.none )
Just project ->
processProjectSpecificMsg outerModel project innerMsg
OpenNewWindow url ->
( outerModel, Ports.openNewWindow url )
LinkClicked urlRequest ->
case urlRequest of
Browser.Internal url ->
( outerModel, Browser.Navigation.pushUrl viewContext.navigationKey (Url.toString url) )
Browser.External url ->
( outerModel, Browser.Navigation.load url )
UrlChanged url ->
ViewStateHelpers.navigateToPage url outerModel
SelectTheme themeChoice ->
let
oldStyle =
sharedModel.style
oldStyleMode =
oldStyle.styleMode
newStyleMode =
{ oldStyleMode | theme = themeChoice }
newStyle =
{ oldStyle | styleMode = newStyleMode }
in
( { sharedModel
| style = newStyle
, viewContext = { viewContext | palette = toExoPalette newStyle }
}
, Cmd.none
)
|> mapToOuterModel outerModel
NoOp ->
( outerModel, Cmd.none )
SetExperimentalFeaturesEnabled choice ->
( { sharedModel | viewContext = { viewContext | experimentalFeaturesEnabled = choice } }, Cmd.none )
|> mapToOuterModel outerModel
processTick : OuterModel -> TickInterval -> Time.Posix -> ( SharedModel, Cmd OuterMsg )
processTick outerModel interval time =
let
serverVolsNeedFrequentPoll : Project -> Server -> Bool
serverVolsNeedFrequentPoll project server =
GetterSetters.getVolsAttachedToServer project server
|> List.any volNeedsFrequentPoll
volNeedsFrequentPoll volume =
not <|
List.member
volume.status
[ OSTypes.Available
, OSTypes.Maintenance
, OSTypes.InUse
, OSTypes.Error
, OSTypes.ErrorDeleting
, OSTypes.ErrorBackingUp
, OSTypes.ErrorRestoring
, OSTypes.ErrorExtending
]
viewIndependentCmd =
if interval == 5 then
Task.perform DoOrchestration Time.now
else
Cmd.none
( viewDependentModel, viewDependentCmd ) =
{- TODO move some of this to Orchestration? -}
case outerModel.viewState of
NonProjectView _ ->
( outerModel.sharedModel, Cmd.none )
ProjectView projectName _ projectViewState ->
case GetterSetters.projectLookup outerModel.sharedModel projectName of
Nothing ->
{- Should this throw an error? -}
( outerModel.sharedModel, Cmd.none )
Just project ->
let
pollVolumes : ( SharedModel, Cmd SharedMsg )
pollVolumes =
( outerModel.sharedModel
, case interval of
5 ->
if List.any volNeedsFrequentPoll (RemoteData.withDefault [] project.volumes) then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
in
case projectViewState of
AllResourcesList _ ->
pollVolumes
ServerDetail model ->
let
volCmd =
OSVolumes.requestVolumes project
in
case interval of
5 ->
case GetterSetters.serverLookup project model.serverUuid of
Just server ->
( outerModel.sharedModel
, if serverVolsNeedFrequentPoll project server then
volCmd
else
Cmd.none
)
Nothing ->
( outerModel.sharedModel, Cmd.none )
300 ->
( outerModel.sharedModel, volCmd )
_ ->
( outerModel.sharedModel, Cmd.none )
VolumeDetail pageModel ->
( outerModel.sharedModel
, case interval of
5 ->
case GetterSetters.volumeLookup project pageModel.volumeUuid of
Nothing ->
Cmd.none
Just volume ->
if volNeedsFrequentPoll volume then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
VolumeList _ ->
pollVolumes
_ ->
( outerModel.sharedModel, Cmd.none )
in
( { viewDependentModel | clientCurrentTime = time }
, Cmd.batch
[ viewDependentCmd
, viewIndependentCmd
]
|> Cmd.map SharedMsg
)
processProjectSpecificMsg : OuterModel -> Project -> ProjectSpecificMsgConstructor -> ( OuterModel, Cmd OuterMsg )
processProjectSpecificMsg outerModel project msg =
let
sharedModel =
outerModel.sharedModel
in
case msg of
PrepareCredentialedRequest requestProto posixTime ->
let
-- Add proxy URL
requestNeedingToken =
requestProto sharedModel.cloudCorsProxyUrl
currentTimeMillis =
posixTime |> Time.posixToMillis
tokenExpireTimeMillis =
project.auth.expiresAt |> Time.posixToMillis
tokenExpired =
-- Token expiring within 5 minutes
tokenExpireTimeMillis < currentTimeMillis + 300000
in
if not tokenExpired then
-- Token still valid, fire the request with current token
( sharedModel, requestNeedingToken project.auth.tokenValue )
|> mapToOuterMsg
|> mapToOuterModel outerModel
else
-- Token is expired (or nearly expired) so we add request to list of pending requests and refresh that token
let
newPQRs =
( project.auth.project.uuid, requestNeedingToken ) :: outerModel.pendingCredentialedRequests
cmdResult =
State.Auth.requestAuthToken sharedModel project
newOuterModel =
{ outerModel | pendingCredentialedRequests = newPQRs }
in
case cmdResult of
Err e ->
let
errorContext =
ErrorContext
("Refresh authentication token for project " ++ project.auth.project.name)
ErrorCrit
(Just "Please remove this project from Exosphere and add it again.")
in
State.Error.processStringError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel newOuterModel
Ok cmd ->
( sharedModel, cmd )
|> mapToOuterMsg
|> mapToOuterModel newOuterModel
ToggleCreatePopup ->
case outerModel.viewState of
ProjectView projectId projectViewModel viewConstructor ->
let
newViewState =
ProjectView
projectId
{ projectViewModel
| createPopup = not projectViewModel.createPopup
}
viewConstructor
in
( { outerModel | viewState = newViewState }, Cmd.none )
_ ->
( outerModel, Cmd.none )
RemoveProject ->
let
newProjects =
List.filter (\p -> p.auth.project.uuid /= project.auth.project.uuid) sharedModel.projects
newOuterModel =
{ outerModel | sharedModel = { sharedModel | projects = newProjects } }
cmd =
-- if we are in a view specific to this project then navigate to the home page
case outerModel.viewState of
ProjectView projectId _ _ ->
if projectId == project.auth.project.uuid then
Route.pushUrl sharedModel.viewContext Route.Home
else
Cmd.none
_ ->
Cmd.none
in
( newOuterModel, cmd )
ServerMsg serverUuid serverMsgConstructor ->
case GetterSetters.serverLookup project serverUuid of
Nothing ->
let
errorContext =
ErrorContext
"receive results of API call for a specific server"
ErrorDebug
Nothing
in
State.Error.processStringError
sharedModel
errorContext
(String.join " "
[ "Instance"
, serverUuid
, "does not exist in the model, it may have been deleted."
]
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
Just server ->
processServerSpecificMsg outerModel project server serverMsgConstructor
RequestServers ->
ApiModelHelpers.requestServers project.auth.project.uuid sharedModel
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestCreateServer pageModel networkUuid ->
let
customWorkFlowSource =
if pageModel.includeWorkflow && Maybe.withDefault False pageModel.workflowInputIsValid then
Just
{ repository = pageModel.workflowInputRepository
, reference = pageModel.workflowInputReference
, path = pageModel.workflowInputPath
}
else
Nothing
createServerRequest =
{ name = pageModel.serverName
, count = pageModel.count
, imageUuid = pageModel.imageUuid
, flavorUuid = pageModel.flavorUuid
, volBackedSizeGb =
pageModel.volSizeTextInput
|> Maybe.andThen Style.Widgets.NumericTextInput.NumericTextInput.toMaybe
, networkUuid = networkUuid
, keypairName = pageModel.keypairName
, userData =
Helpers.renderUserDataTemplate
project
pageModel.userDataTemplate
pageModel.keypairName
(pageModel.deployGuacamole |> Maybe.withDefault False)
pageModel.deployDesktopEnvironment
customWorkFlowSource
pageModel.installOperatingSystemUpdates
sharedModel.instanceConfigMgtRepoUrl
sharedModel.instanceConfigMgtRepoCheckout
, metadata =
Helpers.newServerMetadata
currentExoServerVersion
sharedModel.clientUuid
(pageModel.deployGuacamole |> Maybe.withDefault False)
pageModel.deployDesktopEnvironment
project.auth.user.name
pageModel.floatingIpCreationOption
customWorkFlowSource
}
in
( outerModel, Rest.Nova.requestCreateServer project createServerRequest )
|> mapToOuterMsg
RequestCreateVolume name size ->
let
createVolumeRequest =
{ name = name
, size = size
}
in
( outerModel, OSVolumes.requestCreateVolume project createVolumeRequest )
|> mapToOuterMsg
RequestDeleteVolume volumeUuid ->
( outerModel, OSVolumes.requestDeleteVolume project volumeUuid )
|> mapToOuterMsg
RequestDetachVolume volumeUuid ->
let
maybeVolume =
OSVolumes.volumeLookup project volumeUuid
maybeServerUuid =
maybeVolume
|> Maybe.map (GetterSetters.getServersWithVolAttached project)
|> Maybe.andThen List.head
in
case maybeServerUuid of
Just serverUuid ->
( outerModel, OSSvrVols.requestDetachVolume project serverUuid volumeUuid )
|> mapToOuterMsg
Nothing ->
State.Error.processStringError
sharedModel
(ErrorContext
("look for server UUID with attached volume " ++ volumeUuid)
ErrorCrit
Nothing
)
"Could not determine server attached to this volume."
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestDeleteFloatingIp floatingIpAddress ->
( outerModel, Rest.Neutron.requestDeleteFloatingIp project floatingIpAddress )
|> mapToOuterMsg
RequestAssignFloatingIp port_ floatingIpUuid ->
let
setViewCmd =
Route.pushUrl sharedModel.viewContext
(Route.ProjectRoute project.auth.project.uuid <| Route.FloatingIpList)
in
( outerModel
, Cmd.batch
[ setViewCmd
, Cmd.map SharedMsg <| Rest.Neutron.requestAssignFloatingIp project port_ floatingIpUuid
]
)
RequestUnassignFloatingIp floatingIpUuid ->
( outerModel, Rest.Neutron.requestUnassignFloatingIp project floatingIpUuid )
|> mapToOuterMsg
ReceiveImages images ->
Rest.Glance.receiveImages sharedModel project images
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestDeleteServers serverUuidsToDelete ->
let
applyDelete : OSTypes.ServerUuid -> ( Project, Cmd SharedMsg ) -> ( Project, Cmd SharedMsg )
applyDelete serverUuid projCmdTuple =
let
( delServerProj, delServerCmd ) =
requestDeleteServer (Tuple.first projCmdTuple) serverUuid False
in
( delServerProj, Cmd.batch [ Tuple.second projCmdTuple, delServerCmd ] )
( newProject, cmd ) =
List.foldl
applyDelete
( project, Cmd.none )
serverUuidsToDelete
in
( GetterSetters.modelUpdateProject sharedModel newProject
, cmd
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveServers errorContext result ->
case result of
Ok servers ->
Rest.Nova.receiveServers sharedModel project servers
|> mapToOuterMsg
|> mapToOuterModel outerModel
Err e ->
let
oldServersData =
project.servers.data
newProject =
{ project
| servers =
RDPP.RemoteDataPlusPlus
oldServersData
(RDPP.NotLoading (Just ( e, sharedModel.clientCurrentTime )))
}
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newSharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveServer serverUuid errorContext result ->
case result of
Ok server ->
Rest.Nova.receiveServer sharedModel project server
|> mapToOuterMsg
|> mapToOuterModel outerModel
Err httpErrorWithBody ->
let
httpError =
httpErrorWithBody.error
non404 =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server not in project, may have been deleted, ignoring this error
( outerModel, Cmd.none )
Just server ->
-- Reset receivedTime and loadingSeparately
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps
| receivedTime = Nothing
, loadingSeparately = False
}
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newSharedModel errorContext httpErrorWithBody
|> mapToOuterMsg
|> mapToOuterModel outerModel
in
case httpError of
Http.BadStatus code ->
if code == 404 then
let
newErrorContext =
{ errorContext
| level = Error.ErrorDebug
, actionContext =
errorContext.actionContext
++ " -- 404 means server may have been deleted"
}
newProject =
GetterSetters.projectDeleteServer project serverUuid
newModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newModel newErrorContext httpErrorWithBody
|> mapToOuterMsg
|> mapToOuterModel outerModel
else
non404
_ ->
non404
ReceiveFlavors flavors ->
let
-- If we are creating a server and no flavor is selected, select the smallest flavor
maybeSmallestFlavor =
GetterSetters.sortedFlavors flavors |> List.head
( newOuterModel, newCmd ) =
Rest.Nova.receiveFlavors sharedModel project flavors
|> mapToOuterMsg
|> mapToOuterModel outerModel
in
case maybeSmallestFlavor of
Just smallestFlavor ->
( newOuterModel, newCmd )
|> pipelineCmdOuterModelMsg
(updateUnderlying (ServerCreateMsg <| Page.ServerCreate.GotDefaultFlavor smallestFlavor.uuid))
Nothing ->
( newOuterModel, newCmd )
RequestKeypairs ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success _ ->
project.keypairs
_ ->
RemoteData.Loading
newProject =
{ project | keypairs = newKeypairs }
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel
, Rest.Nova.requestKeypairs newProject
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveKeypairs keypairs ->
Rest.Nova.receiveKeypairs sharedModel project keypairs
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestCreateKeypair keypairName publicKey ->
( outerModel, Rest.Nova.requestCreateKeypair project keypairName publicKey )
|> mapToOuterMsg
ReceiveCreateKeypair keypair ->
let
newProject =
GetterSetters.projectUpdateKeypair project keypair
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( { outerModel | sharedModel = newSharedModel }
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute newProject.auth.project.uuid Route.KeypairList)
)
RequestDeleteKeypair keypairId ->
( outerModel, Rest.Nova.requestDeleteKeypair project keypairId )
|> mapToOuterMsg
ReceiveDeleteKeypair errorContext keypairName result ->
case result of
Err httpError ->
State.Error.processStringError sharedModel errorContext (Helpers.httpErrorToString httpError)
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok () ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success keypairs ->
keypairs
|> List.filter (\k -> k.name /= keypairName)
|> RemoteData.Success
_ ->
project.keypairs
newProject =
{ project | keypairs = newKeypairs }
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterModel outerModel
ReceiveCreateServer _ ->
let
newRoute =
Route.ProjectRoute
project.auth.project.uuid
Route.AllResourcesList
( newSharedModel, newCmd ) =
( sharedModel, Cmd.none )
|> Helpers.pipelineCmd
(ApiModelHelpers.requestServers project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestNetworks project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts project.auth.project.uuid)
in
( { outerModel | sharedModel = newSharedModel }
, Cmd.batch
[ Cmd.map SharedMsg newCmd
, Route.pushUrl sharedModel.viewContext newRoute
]
)
ReceiveNetworks errorContext result ->
case result of
Ok networks ->
let
newProject =
Rest.Neutron.receiveNetworks sharedModel project networks
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterMsg
|> mapToOuterModel outerModel
|> pipelineCmdOuterModelMsg (updateUnderlying (ServerCreateMsg <| Page.ServerCreate.GotNetworks))
Err httpError ->
let
oldNetworksData =
project.networks.data
newProject =
{ project
| networks =
RDPP.RemoteDataPlusPlus
oldNetworksData
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newModel errorContext httpError
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveAutoAllocatedNetwork errorContext result ->
let
newProject =
case result of
Ok netUuid ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave netUuid sharedModel.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
Err httpError ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
project.autoAllocatedNetworkUuid.data
(RDPP.NotLoading
(Just
( httpError
, sharedModel.clientCurrentTime
)
)
)
}
newSharedModel =
GetterSetters.modelUpdateProject
sharedModel
newProject
( newNewSharedModel, newCmd ) =
case result of
Ok _ ->
ApiModelHelpers.requestNetworks project.auth.project.uuid newSharedModel
Err httpError ->
State.Error.processSynchronousApiError newSharedModel errorContext httpError
|> Helpers.pipelineCmd (ApiModelHelpers.requestNetworks project.auth.project.uuid)
( newOuterModel, underlyingCmd ) =
case Helpers.newServerNetworkOptions newProject of
AutoSelectedNetwork netUuid ->
updateUnderlying
(ServerCreateMsg <| Page.ServerCreate.GotAutoAllocatedNetwork netUuid)
{ outerModel | sharedModel = newNewSharedModel }
_ ->
( { outerModel | sharedModel = newNewSharedModel }, Cmd.none )
in
( newOuterModel, Cmd.batch [ Cmd.map SharedMsg newCmd, underlyingCmd ] )
ReceiveFloatingIps ips ->
Rest.Neutron.receiveFloatingIps sharedModel project ips
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceivePorts errorContext result ->
case result of
Ok ports ->
let
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave ports sharedModel.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
Err httpError ->
let
oldPortsData =
project.ports.data
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
oldPortsData
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
}
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newSharedModel errorContext httpError
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteFloatingIp uuid ->
Rest.Neutron.receiveDeleteFloatingIp sharedModel project uuid
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveAssignFloatingIp floatingIp ->
-- TODO update servers so that new assignment is reflected in the UI
let
newProject =
processNewFloatingIp sharedModel.clientCurrentTime project floatingIp
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterModel outerModel
ReceiveUnassignFloatingIp floatingIp ->
-- TODO update servers so that unassignment is reflected in the UI
let
newProject =
processNewFloatingIp sharedModel.clientCurrentTime project floatingIp
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveSecurityGroups groups ->
Rest.Neutron.receiveSecurityGroupsAndEnsureExoGroup sharedModel project groups
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveCreateExoSecurityGroup group ->
Rest.Neutron.receiveCreateExoSecurityGroupAndRequestCreateRules sharedModel project group
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveCreateVolume ->
{- Should we add new volume to model now? -}
( outerModel
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute project.auth.project.uuid Route.VolumeList)
)
ReceiveVolumes volumes ->
let
-- Look for any server backing volumes that were created with no name, and give them a reasonable name
updateVolNameCmds : List (Cmd SharedMsg)
updateVolNameCmds =
RDPP.withDefault [] project.servers
-- List of tuples containing server and Maybe boot vol
|> List.map
(\s ->
( s
, Helpers.getBootVol
(RemoteData.withDefault
[]
project.volumes
)
s.osProps.uuid
)
)
-- We only care about servers created by exosphere
|> List.filter
(\t ->
case Tuple.first t |> .exoProps |> .serverOrigin of
ServerFromExo _ ->
True
ServerNotFromExo ->
False
)
-- We only care about servers created as current OpenStack user
|> List.filter
(\t ->
(Tuple.first t).osProps.details.userUuid
== project.auth.user.uuid
)
-- We only care about servers with a non-empty name
|> List.filter
(\t ->
Tuple.first t
|> .osProps
|> .name
|> String.isEmpty
|> not
)
-- We only care about volume-backed servers
|> List.filterMap
(\t ->
case t of
( server, Just vol ) ->
-- Flatten second part of tuple
Just ( server, vol )
_ ->
Nothing
)
-- We only care about unnamed backing volumes
|> List.filter
(\t ->
Tuple.second t
|> .name
|> String.isEmpty
)
|> List.map
(\t ->
OSVolumes.requestUpdateVolumeName
project
(t |> Tuple.second |> .uuid)
("boot-vol-"
++ (t |> Tuple.first |> .osProps |> .name)
)
)
newProject =
{ project | volumes = RemoteData.succeed volumes }
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.batch updateVolNameCmds )
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteVolume ->
( outerModel, OSVolumes.requestVolumes project )
|> mapToOuterMsg
ReceiveUpdateVolumeName ->
( outerModel, OSVolumes.requestVolumes project )
|> mapToOuterMsg
ReceiveAttachVolume attachment ->
( outerModel
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute project.auth.project.uuid <| Route.VolumeMountInstructions attachment)
)
ReceiveDetachVolume ->
( outerModel
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute project.auth.project.uuid Route.VolumeList)
)
ReceiveAppCredential appCredential ->
let
newProject =
{ project | secret = ApplicationCredential appCredential }
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveComputeQuota quota ->
let
newProject =
{ project | computeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveVolumeQuota quota ->
let
newProject =
{ project | volumeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveRandomServerName serverName ->
updateUnderlying (ServerCreateMsg <| Page.ServerCreate.GotServerName serverName) outerModel
processServerSpecificMsg : OuterModel -> Project -> Server -> ServerSpecificMsgConstructor -> ( OuterModel, Cmd OuterMsg )
processServerSpecificMsg outerModel project server serverMsgConstructor =
let
sharedModel =
outerModel.sharedModel
in
case serverMsgConstructor of
RequestServer ->
ApiModelHelpers.requestServer project.auth.project.uuid server.osProps.uuid sharedModel
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestDeleteServer retainFloatingIps ->
let
( newProject, cmd ) =
requestDeleteServer project server.osProps.uuid retainFloatingIps
in
( GetterSetters.modelUpdateProject sharedModel newProject, cmd )
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestAttachVolume volumeUuid ->
( outerModel, OSSvrVols.requestAttachVolume project server.osProps.uuid volumeUuid )
|> mapToOuterMsg
RequestCreateServerImage imageName ->
let
newRoute =
Route.ProjectRoute
project.auth.project.uuid
Route.AllResourcesList
createImageCmd =
Rest.Nova.requestCreateServerImage project server.osProps.uuid imageName
in
( outerModel
, Cmd.batch
[ Cmd.map SharedMsg createImageCmd
, Route.pushUrl sharedModel.viewContext newRoute
]
)
RequestSetServerName newServerName ->
( outerModel, Rest.Nova.requestSetServerName project server.osProps.uuid newServerName )
|> mapToOuterMsg
ReceiveServerEvents _ result ->
case result of
Ok serverEvents ->
let
newServer =
{ server | events = RemoteData.Success serverEvents }
newProject =
GetterSetters.projectUpdateServer project newServer
in
( GetterSetters.modelUpdateProject sharedModel newProject
, Cmd.none
)
|> mapToOuterModel outerModel
Err _ ->
-- Dropping this on the floor for now, someday we may want to do something different
( outerModel, Cmd.none )
ReceiveConsoleUrl url ->
Rest.Nova.receiveConsoleUrl sharedModel project server url
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteServer ->
let
newProject =
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | deletionAttempted = True }
newServer =
{ server | exoProps = newExoProps }
in
GetterSetters.projectUpdateServer project newServer
newOuterModel =
{ outerModel | sharedModel = GetterSetters.modelUpdateProject sharedModel newProject }
in
( newOuterModel
, case outerModel.viewState of
ProjectView projectId _ (ServerDetail pageModel) ->
if pageModel.serverUuid == server.osProps.uuid then
Route.pushUrl sharedModel.viewContext (Route.ProjectRoute projectId Route.AllResourcesList)
else
Cmd.none
_ ->
Cmd.none
)
ReceiveCreateFloatingIp errorContext result ->
case result of
Ok ip ->
Rest.Neutron.receiveCreateFloatingIp sharedModel project server ip
|> mapToOuterMsg
|> mapToOuterModel outerModel
Err httpErrorWithBody ->
let
newErrorContext =
if GetterSetters.serverPresentNotDeleting sharedModel server.osProps.uuid then
errorContext
else
{ errorContext | level = ErrorDebug }
in
State.Error.processSynchronousApiError sharedModel newErrorContext httpErrorWithBody
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveServerPassword password ->
if String.isEmpty password then
( outerModel, Cmd.none )
else
let
tag =
"exoPw:" ++ password
cmd =
case server.exoProps.serverOrigin of
ServerNotFromExo ->
Cmd.none
ServerFromExo serverFromExoProps ->
if serverFromExoProps.exoServerVersion >= 1 then
Cmd.batch
[ OSServerTags.requestCreateServerTag project server.osProps.uuid tag
, OSServerPassword.requestClearServerPassword project server.osProps.uuid
]
else
Cmd.none
in
( outerModel, cmd )
|> mapToOuterMsg
ReceiveSetServerName _ errorContext result ->
case result of
Err e ->
State.Error.processSynchronousApiError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok actualNewServerName ->
let
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | name = actualNewServerName }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newOuterModel =
{ outerModel | sharedModel = GetterSetters.modelUpdateProject sharedModel newProject }
-- Later, maybe: Check that newServerName == actualNewServerName
in
updateUnderlying (ServerDetailMsg <| Page.ServerDetail.GotServerNamePendingConfirmation Nothing)
newOuterModel
ReceiveSetServerMetadata intendedMetadataItem errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok newServerMetadata ->
-- Update the model after ensuring the intended metadata item was actually added
if List.member intendedMetadataItem newServerMetadata then
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = newServerMetadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterMsg
|> mapToOuterModel outerModel
else
-- This is bonkers, throw an error
State.Error.processStringError
sharedModel
errorContext
"The metadata items returned by OpenStack did not include the metadata item that we tried to set."
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteServerMetadata metadataKey errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok _ ->
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = List.filter (\i -> i.key /= metadataKey) oldServerDetails.metadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterModel outerModel
ReceiveGuacamoleAuthToken result ->
let
errorContext =
ErrorContext
"Receive a response from Guacamole auth token API"
ErrorDebug
Nothing
sharedModelUpdateGuacProps : ServerFromExoProps -> GuacTypes.LaunchedWithGuacProps -> SharedModel
sharedModelUpdateGuacProps exoOriginProps guacProps =
let
newOriginProps =
{ exoOriginProps | guacamoleStatus = GuacTypes.LaunchedWithGuacamole guacProps }
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
newSharedModel
in
case server.exoProps.serverOrigin of
ServerFromExo exoOriginProps ->
case exoOriginProps.guacamoleStatus of
GuacTypes.LaunchedWithGuacamole oldGuacProps ->
let
newGuacProps =
case result of
Ok tokenValue ->
if server.osProps.details.openstackStatus == OSTypes.ServerActive then
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
tokenValue
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
}
else
-- Server is not active, this token won't work, so we don't store it
{ oldGuacProps
| authToken =
RDPP.empty
}
Err e ->
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
oldGuacProps.authToken.data
(RDPP.NotLoading (Just ( e, sharedModel.clientCurrentTime )))
}
in
( sharedModelUpdateGuacProps
exoOriginProps
newGuacProps
, Cmd.none
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
GuacTypes.NotLaunchedWithGuacamole ->
State.Error.processStringError
sharedModel
errorContext
"Server does not appear to have been launched with Guacamole support"
|> mapToOuterMsg
|> mapToOuterModel outerModel
ServerNotFromExo ->
State.Error.processStringError
sharedModel
errorContext
"Server does not appear to have been launched from Exosphere"
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestServerAction func targetStatuses ->
let
oldExoProps =
server.exoProps
newServer =
Server server.osProps { oldExoProps | targetOpenstackStatus = targetStatuses } server.events
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, func newProject.endpoints.nova )
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveConsoleLog errorContext result ->
case server.exoProps.serverOrigin of
ServerNotFromExo ->
( outerModel, Cmd.none )
ServerFromExo exoOriginProps ->
let
oldExoSetupStatus =
case exoOriginProps.exoSetupStatus.data of
RDPP.DontHave ->
ExoSetupUnknown
RDPP.DoHave s _ ->
s
( newExoSetupStatusRDPP, exoSetupStatusMetadataCmd ) =
case result of
Err httpError ->
( RDPP.RemoteDataPlusPlus
exoOriginProps.exoSetupStatus.data
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
, Cmd.none
)
Ok consoleLog ->
let
newExoSetupStatus =
Helpers.ExoSetupStatus.parseConsoleLogExoSetupStatus
oldExoSetupStatus
consoleLog
server.osProps.details.created
sharedModel.clientCurrentTime
cmd =
if newExoSetupStatus == oldExoSetupStatus then
Cmd.none
else
let
value =
Helpers.ExoSetupStatus.exoSetupStatusToStr newExoSetupStatus
metadataItem =
OSTypes.MetadataItem
"exoSetup"
value
in
Rest.Nova.requestSetServerMetadata project server.osProps.uuid metadataItem
in
( RDPP.RemoteDataPlusPlus
(RDPP.DoHave
newExoSetupStatus
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
, cmd
)
newResourceUsage =
case result of
Err httpError ->
RDPP.RemoteDataPlusPlus
exoOriginProps.resourceUsage.data
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
Ok consoleLog ->
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
(Helpers.ServerResourceUsage.parseConsoleLog
consoleLog
(RDPP.withDefault
Types.ServerResourceUsage.emptyResourceUsageHistory
exoOriginProps.resourceUsage
)
)
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
newWorkflowToken : CustomWorkflow -> CustomWorkflowTokenRDPP
newWorkflowToken currentWorkflow =
case result of
Err httpError ->
RDPP.RemoteDataPlusPlus
RDPP.DontHave
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
Ok consoleLog ->
let
maybeParsedToken =
Helpers.parseConsoleLogForWorkflowToken consoleLog
in
case maybeParsedToken of
Just parsedToken ->
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
parsedToken
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
Nothing ->
currentWorkflow.authToken
newWorkflowStatus : ServerCustomWorkflowStatus
newWorkflowStatus =
case exoOriginProps.customWorkflowStatus of
NotLaunchedWithCustomWorkflow ->
exoOriginProps.customWorkflowStatus
LaunchedWithCustomWorkflow customWorkflow ->
LaunchedWithCustomWorkflow { customWorkflow | authToken = newWorkflowToken customWorkflow }
newOriginProps =
{ exoOriginProps
| resourceUsage = newResourceUsage
, exoSetupStatus = newExoSetupStatusRDPP
, customWorkflowStatus = newWorkflowStatus
}
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
case result of
Err httpError ->
State.Error.processSynchronousApiError newSharedModel errorContext httpError
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok _ ->
( newSharedModel, exoSetupStatusMetadataCmd )
|> mapToOuterMsg
|> mapToOuterModel outerModel
processNewFloatingIp : Time.Posix -> Project -> OSTypes.FloatingIp -> Project
processNewFloatingIp time project floatingIp =
let
otherIps =
project.floatingIps
|> RDPP.withDefault []
|> List.filter (\i -> i.uuid /= floatingIp.uuid)
newIps =
floatingIp :: otherIps
in
{ project
| floatingIps =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave newIps time)
(RDPP.NotLoading Nothing)
}
createProject : OuterModel -> Maybe OSTypes.ProjectDescription -> OSTypes.ScopedAuthToken -> Endpoints -> ( OuterModel, Cmd OuterMsg )
createProject outerModel description authToken endpoints =
let
sharedModel =
outerModel.sharedModel
newProject =
{ secret = NoProjectSecret
, auth = authToken
-- Maybe todo, eliminate parallel data structures in auth and endpoints?
, endpoints = endpoints
, description = description
, images = []
, servers = RDPP.RemoteDataPlusPlus RDPP.DontHave RDPP.Loading
, flavors = []
, keypairs = RemoteData.NotAsked
, volumes = RemoteData.NotAsked
, networks = RDPP.empty
, autoAllocatedNetworkUuid = RDPP.empty
, floatingIps = RDPP.empty
, ports = RDPP.empty
, securityGroups = []
, computeQuota = RemoteData.NotAsked
, volumeQuota = RemoteData.NotAsked
}
newProjects =
newProject :: outerModel.sharedModel.projects
newViewStateCmd =
-- If the user is selecting projects from an unscoped provider then don't interrupt them
case outerModel.viewState of
NonProjectView (SelectProjects _) ->
Cmd.none
-- Otherwise take them to home page
_ ->
Route.pushUrl sharedModel.viewContext <|
Route.Home
( newSharedModel, newCmd ) =
( { sharedModel
| projects = newProjects
}
, [ Rest.Nova.requestServers
, Rest.Neutron.requestSecurityGroups
, Rest.Keystone.requestAppCredential sharedModel.clientUuid sharedModel.clientCurrentTime
]
|> List.map (\x -> x newProject)
|> Cmd.batch
)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestVolumes newProject.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestFloatingIps newProject.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts newProject.auth.project.uuid)
in
( { outerModel | sharedModel = newSharedModel }
, Cmd.batch [ newViewStateCmd, Cmd.map SharedMsg newCmd ]
)
createUnscopedProvider : SharedModel -> OSTypes.UnscopedAuthToken -> HelperTypes.Url -> ( SharedModel, Cmd SharedMsg )
createUnscopedProvider model authToken authUrl =
let
newProvider =
{ authUrl = authUrl
, token = <PASSWORD>
, projectsAvailable = RemoteData.Loading
}
newProviders =
newProvider :: model.unscopedProviders
in
( { model | unscopedProviders = newProviders }
, Rest.Keystone.requestUnscopedProjects newProvider model.cloudCorsProxyUrl
)
requestDeleteServer : Project -> OSTypes.ServerUuid -> Bool -> ( Project, Cmd SharedMsg )
requestDeleteServer project serverUuid retainFloatingIps =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server likely deleted already, do nothing
( project, Cmd.none )
Just server ->
let
oldExoProps =
server.exoProps
newServer =
{ server | exoProps = { oldExoProps | deletionAttempted = True } }
deleteFloatingIpCmds =
if retainFloatingIps then
[]
else
GetterSetters.getServerFloatingIps project server.osProps.uuid
|> List.map .uuid
|> List.map (Rest.Neutron.requestDeleteFloatingIp project)
newProject =
GetterSetters.projectUpdateServer project newServer
in
( newProject
, Cmd.batch
[ Rest.Nova.requestDeleteServer
newProject.auth.project.uuid
newProject.endpoints.nova
newServer.osProps.uuid
, Cmd.batch deleteFloatingIpCmds
]
)
| true | module State.State exposing (update)
import Browser
import Browser.Navigation
import Helpers.ExoSetupStatus
import Helpers.GetterSetters as GetterSetters
import Helpers.Helpers as Helpers
import Helpers.RemoteDataPlusPlus as RDPP
import Helpers.ServerResourceUsage
import Http
import LocalStorage.LocalStorage as LocalStorage
import Maybe
import OpenStack.ServerPassword as OSServerPassword
import OpenStack.ServerTags as OSServerTags
import OpenStack.ServerVolumes as OSSvrVols
import OpenStack.Types as OSTypes
import OpenStack.Volumes as OSVolumes
import Orchestration.Orchestration as Orchestration
import Page.AllResourcesList
import Page.FloatingIpAssign
import Page.FloatingIpList
import Page.GetSupport
import Page.Home
import Page.InstanceSourcePicker
import Page.KeypairCreate
import Page.KeypairList
import Page.LoginJetstream
import Page.LoginOpenstack
import Page.LoginPicker
import Page.MessageLog
import Page.SelectProjects
import Page.ServerCreate
import Page.ServerCreateImage
import Page.ServerDetail
import Page.ServerList
import Page.Settings
import Page.VolumeAttach
import Page.VolumeCreate
import Page.VolumeDetail
import Page.VolumeList
import Ports
import RemoteData
import Rest.ApiModelHelpers as ApiModelHelpers
import Rest.Glance
import Rest.Keystone
import Rest.Neutron
import Rest.Nova
import Route
import State.Auth
import State.Error
import State.ViewState as ViewStateHelpers
import Style.Toast
import Style.Widgets.NumericTextInput.NumericTextInput
import Task
import Time
import Toasty
import Types.Error as Error exposing (AppError, ErrorContext, ErrorLevel(..))
import Types.Guacamole as GuacTypes
import Types.HelperTypes as HelperTypes exposing (HttpRequestMethod(..), UnscopedProviderProject)
import Types.OuterModel exposing (OuterModel)
import Types.OuterMsg exposing (OuterMsg(..))
import Types.Project exposing (Endpoints, Project, ProjectSecret(..))
import Types.Server exposing (ExoSetupStatus(..), NewServerNetworkOptions(..), Server, ServerFromExoProps, ServerOrigin(..), currentExoServerVersion)
import Types.ServerResourceUsage
import Types.SharedModel exposing (SharedModel)
import Types.SharedMsg exposing (ProjectSpecificMsgConstructor(..), ServerSpecificMsgConstructor(..), SharedMsg(..), TickInterval)
import Types.View
exposing
( LoginView(..)
, NonProjectViewConstructor(..)
, ProjectViewConstructor(..)
, ViewState(..)
)
import Types.Workflow
exposing
( CustomWorkflow
, CustomWorkflowTokenRDPP
, ServerCustomWorkflowStatus(..)
)
import Url
import View.Helpers exposing (toExoPalette)
update : OuterMsg -> Result AppError OuterModel -> ( Result AppError OuterModel, Cmd OuterMsg )
update msg result =
case result of
Err appError ->
( Err appError, Cmd.none )
Ok model ->
case updateValid msg model of
( newModel, nextMsg ) ->
( Ok newModel, nextMsg )
updateValid : OuterMsg -> OuterModel -> ( OuterModel, Cmd OuterMsg )
updateValid msg outerModel =
{- We want to `setStorage` on every update. This function adds the setStorage
command for every step of the update function.
-}
let
( newOuterModel, cmds ) =
updateUnderlying msg outerModel
orchestrationTimeCmd =
-- Each trip through the runtime, we get the time and feed it to orchestration module
case msg of
SharedMsg (DoOrchestration _) ->
Cmd.none
SharedMsg (Tick _ _) ->
Cmd.none
_ ->
Task.perform (\posix -> SharedMsg <| DoOrchestration posix) Time.now
in
( newOuterModel
, Cmd.batch
[ Ports.setStorage (LocalStorage.generateStoredState newOuterModel.sharedModel)
, orchestrationTimeCmd
, cmds
]
)
-- There may be a better approach than these mapping functions, I'm not sure yet.
mapToOuterMsg : ( a, Cmd SharedMsg ) -> ( a, Cmd OuterMsg )
mapToOuterMsg ( model, cmdSharedMsg ) =
( model, Cmd.map SharedMsg cmdSharedMsg )
mapToOuterModel : OuterModel -> ( SharedModel, Cmd a ) -> ( OuterModel, Cmd a )
mapToOuterModel outerModel ( newSharedModel, cmd ) =
( { outerModel | sharedModel = newSharedModel }, cmd )
pipelineCmdOuterModelMsg : (OuterModel -> ( OuterModel, Cmd OuterMsg )) -> ( OuterModel, Cmd OuterMsg ) -> ( OuterModel, Cmd OuterMsg )
pipelineCmdOuterModelMsg fn ( outerModel, outerCmd ) =
let
( newModel, newCmd ) =
fn outerModel
in
( newModel, Cmd.batch [ outerCmd, newCmd ] )
updateUnderlying : OuterMsg -> OuterModel -> ( OuterModel, Cmd OuterMsg )
updateUnderlying outerMsg outerModel =
let
sharedModel =
outerModel.sharedModel
in
case ( outerMsg, outerModel.viewState ) of
( SharedMsg sharedMsg, _ ) ->
processSharedMsg sharedMsg outerModel
-- TODO exact same structure for each page-specific case here. Is there a way to deduplicate or factor out?
( GetSupportMsg pageMsg, NonProjectView (GetSupport pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.GetSupport.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| GetSupport newPageModel
}
, Cmd.map GetSupportMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( HomeMsg pageMsg, NonProjectView (Home pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.Home.update pageMsg pageModel
in
( { outerModel
| viewState = NonProjectView <| Home newPageModel
}
, Cmd.map HomeMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( LoginJetstreamMsg pageMsg, NonProjectView (Login (LoginJetstream pageModel)) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.LoginJetstream.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| Login <| LoginJetstream newPageModel
}
, Cmd.map LoginJetstreamMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( LoginOpenstackMsg pageMsg, NonProjectView (Login (LoginOpenstack pageModel)) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.LoginOpenstack.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| Login <| LoginOpenstack newPageModel
}
, Cmd.map LoginOpenstackMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( LoginPickerMsg pageMsg, NonProjectView LoginPicker ) ->
let
( _, cmd, sharedMsg ) =
Page.LoginPicker.update pageMsg
in
( { outerModel
| viewState = NonProjectView <| LoginPicker
}
, Cmd.map LoginPickerMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( MessageLogMsg pageMsg, NonProjectView (MessageLog pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.MessageLog.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| MessageLog newPageModel
}
, Cmd.map MessageLogMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( SelectProjectsMsg pageMsg, NonProjectView (SelectProjects pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.SelectProjects.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| SelectProjects newPageModel
}
, Cmd.map SelectProjectsMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( SettingsMsg pageMsg, NonProjectView (Settings pageModel) ) ->
let
( newPageModel, cmd, sharedMsg ) =
Page.Settings.update pageMsg sharedModel pageModel
in
( { outerModel
| viewState = NonProjectView <| Settings newPageModel
}
, Cmd.map SettingsMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( pageSpecificMsg, ProjectView projectId projectViewModel projectViewConstructor ) ->
case GetterSetters.projectLookup sharedModel projectId of
Just project ->
case ( pageSpecificMsg, projectViewConstructor ) of
-- This is the repetitive dispatch code that people warn you about when you use the nested Elm architecture.
-- Maybe there is a way to make it less repetitive (or at least more compact) in the future.
( AllResourcesListMsg pageMsg, AllResourcesList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.AllResourcesList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
AllResourcesList newSharedModel
}
, Cmd.map AllResourcesListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( FloatingIpAssignMsg pageMsg, FloatingIpAssign pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.FloatingIpAssign.update pageMsg sharedModel project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
FloatingIpAssign newSharedModel
}
, Cmd.map FloatingIpAssignMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( FloatingIpListMsg pageMsg, FloatingIpList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.FloatingIpList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
FloatingIpList newSharedModel
}
, Cmd.map FloatingIpListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( InstanceSourcePickerMsg pageMsg, InstanceSourcePicker pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.InstanceSourcePicker.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
InstanceSourcePicker newSharedModel
}
, Cmd.map InstanceSourcePickerMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( KeypairCreateMsg pageMsg, KeypairCreate pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.KeypairCreate.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
KeypairCreate newSharedModel
}
, Cmd.map KeypairCreateMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( KeypairListMsg pageMsg, KeypairList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.KeypairList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
KeypairList newSharedModel
}
, Cmd.map KeypairListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerCreateMsg pageMsg, ServerCreate pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerCreate.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerCreate newSharedModel
}
, Cmd.map ServerCreateMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerCreateImageMsg pageMsg, ServerCreateImage pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerCreateImage.update pageMsg sharedModel project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerCreateImage newSharedModel
}
, Cmd.map ServerCreateImageMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerDetailMsg pageMsg, ServerDetail pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerDetail.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerDetail newSharedModel
}
, Cmd.map ServerDetailMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( ServerListMsg pageMsg, ServerList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.ServerList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
ServerList newSharedModel
}
, Cmd.map ServerListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeAttachMsg pageMsg, VolumeAttach pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeAttach.update pageMsg sharedModel project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeAttach newSharedModel
}
, Cmd.map VolumeAttachMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeCreateMsg pageMsg, VolumeCreate pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeCreate.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeCreate newSharedModel
}
, Cmd.map VolumeCreateMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeDetailMsg pageMsg, VolumeDetail pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeDetail.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeDetail newSharedModel
}
, Cmd.map VolumeDetailMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
( VolumeListMsg pageMsg, VolumeList pageModel ) ->
let
( newSharedModel, cmd, sharedMsg ) =
Page.VolumeList.update pageMsg project pageModel
in
( { outerModel
| viewState =
ProjectView projectId projectViewModel <|
VolumeList newSharedModel
}
, Cmd.map VolumeListMsg cmd
)
|> pipelineCmdOuterModelMsg
(processSharedMsg sharedMsg)
_ ->
-- This is not great because it allows us to forget to write a case statement above, but I don't know of a nicer way to write a catchall case for when a page-specific Msg is received for an inapplicable page.
( outerModel, Cmd.none )
Nothing ->
( outerModel, Cmd.none )
( _, _ ) ->
-- This is not great because it allows us to forget to write a case statement above, but I don't know of a nicer way to write a catchall case for when a page-specific Msg is received for an inapplicable page.
( outerModel, Cmd.none )
processSharedMsg : SharedMsg -> OuterModel -> ( OuterModel, Cmd OuterMsg )
processSharedMsg sharedMsg outerModel =
let
{ sharedModel } =
outerModel
{ viewContext } =
sharedModel
in
case sharedMsg of
ChangeSystemThemePreference preference ->
let
{ style } =
sharedModel
{ styleMode } =
style
newStyleMode =
{ styleMode | systemPreference = Just preference }
newStyle =
{ style | styleMode = newStyleMode }
newPalette =
toExoPalette newStyle
newViewContext =
{ viewContext | palette = newPalette }
in
mapToOuterModel outerModel
( { sharedModel
| style = newStyle
, viewContext = newViewContext
}
, Cmd.none
)
Logout ->
( outerModel, Ports.logout () )
ToastyMsg subMsg ->
Toasty.update Style.Toast.toastConfig ToastyMsg subMsg outerModel.sharedModel
|> mapToOuterMsg
|> mapToOuterModel outerModel
MsgChangeWindowSize x y ->
( { sharedModel
| viewContext =
{ viewContext
| windowSize = { width = x, height = y }
}
}
, Cmd.none
)
|> mapToOuterModel outerModel
Tick interval time ->
processTick outerModel interval time
|> mapToOuterModel outerModel
DoOrchestration posixTime ->
Orchestration.orchModel sharedModel posixTime
|> mapToOuterMsg
|> mapToOuterModel outerModel
HandleApiErrorWithBody errorContext error ->
State.Error.processSynchronousApiError sharedModel errorContext error
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestUnscopedToken openstackLoginUnscoped ->
let
creds =
-- Ensure auth URL includes port number and version
{ openstackLoginUnscoped
| authUrl =
State.Auth.authUrlWithPortAndVersion openstackLoginUnscoped.authUrl
}
in
( outerModel, Rest.Keystone.requestUnscopedAuthToken sharedModel.cloudCorsProxyUrl creds )
|> mapToOuterMsg
JetstreamLogin jetstreamCreds ->
let
openstackCredsList =
State.Auth.jetstreamToOpenstackCreds jetstreamCreds
cmds =
List.map
(\creds -> Rest.Keystone.requestUnscopedAuthToken sharedModel.cloudCorsProxyUrl creds)
openstackCredsList
in
( outerModel, Cmd.batch cmds )
|> mapToOuterMsg
ReceiveScopedAuthToken projectDescription ( metadata, response ) ->
case Rest.Keystone.decodeScopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
sharedModel
(ErrorContext
"decode scoped auth token"
ErrorCrit
Nothing
)
error
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok authToken ->
case Helpers.serviceCatalogToEndpoints authToken.catalog of
Err e ->
State.Error.processStringError
sharedModel
(ErrorContext
"Decode project endpoints"
ErrorCrit
(Just "Please check with your cloud administrator or the Exosphere developers.")
)
e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok endpoints ->
let
projectId =
authToken.project.uuid
in
-- If we don't have a project with same name + authUrl then create one, if we do then update its OSTypes.AuthToken
-- This code ensures we don't end up with duplicate projects on the same provider in our model.
case
GetterSetters.projectLookup sharedModel <| projectId
of
Nothing ->
createProject outerModel projectDescription authToken endpoints
Just project ->
-- If we don't have an application credential for this project yet, then get one
let
appCredCmd =
case project.secret of
ApplicationCredential _ ->
Cmd.none
_ ->
Rest.Keystone.requestAppCredential
sharedModel.clientUuid
sharedModel.clientCurrentTime
project
( newOuterModel, updateTokenCmd ) =
State.Auth.projectUpdateAuthToken outerModel project authToken
in
( newOuterModel, Cmd.batch [ appCredCmd, updateTokenCmd ] )
|> mapToOuterMsg
ReceiveUnscopedAuthToken keystoneUrl ( metadata, response ) ->
case Rest.Keystone.decodeUnscopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
sharedModel
(ErrorContext
"decode unscoped auth token"
ErrorCrit
Nothing
)
error
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok authToken ->
case
GetterSetters.providerLookup sharedModel keystoneUrl
of
Just unscopedProvider ->
-- We already have an unscoped provider in the model with the same auth URL, update its token
State.Auth.unscopedProviderUpdateAuthToken
sharedModel
unscopedProvider
authToken
|> mapToOuterMsg
|> mapToOuterModel outerModel
Nothing ->
-- We don't have an unscoped provider with the same auth URL, create it
createUnscopedProvider sharedModel authToken keystoneUrl
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveUnscopedProjects keystoneUrl unscopedProjects ->
case
GetterSetters.providerLookup sharedModel keystoneUrl
of
Just provider ->
let
newProvider =
{ provider | projectsAvailable = RemoteData.Success unscopedProjects }
newSharedModel =
GetterSetters.modelUpdateUnscopedProvider sharedModel newProvider
newOuterModel =
{ outerModel | sharedModel = newSharedModel }
in
-- If we are not already on a SelectProjects view, then go there
case outerModel.viewState of
NonProjectView (SelectProjects _) ->
( newOuterModel, Cmd.none )
_ ->
( newOuterModel
, Route.pushUrl viewContext (Route.SelectProjects keystoneUrl)
)
Nothing ->
-- Provider not found, may have been removed, nothing to do
( outerModel, Cmd.none )
RequestProjectLoginFromProvider keystoneUrl unscopedProjects ->
case GetterSetters.providerLookup sharedModel keystoneUrl of
Just provider ->
let
buildLoginRequest : UnscopedProviderProject -> Cmd SharedMsg
buildLoginRequest project =
Rest.Keystone.requestScopedAuthToken
sharedModel.cloudCorsProxyUrl
project.description
<|
OSTypes.TokenCreds
keystoneUrl
provider.token
project.project.uuid
loginRequests =
List.map buildLoginRequest unscopedProjects
|> Cmd.batch
-- Remove unscoped provider from model now that we have selected projects from it
newUnscopedProviders =
List.filter
(\p -> p.authUrl /= keystoneUrl)
sharedModel.unscopedProviders
-- If we still have at least one unscoped provider in the model then ask the user to choose projects from it
newViewStateCmd =
case List.head newUnscopedProviders of
Just unscopedProvider ->
Route.pushUrl viewContext (Route.SelectProjects unscopedProvider.authUrl)
Nothing ->
-- If we have at least one project then show it, else show the login page
case List.head sharedModel.projects of
Just project ->
Route.pushUrl viewContext <|
Route.ProjectRoute project.auth.project.uuid <|
Route.AllResourcesList
Nothing ->
Route.pushUrl viewContext Route.LoginPicker
sharedModelUpdatedUnscopedProviders =
{ sharedModel | unscopedProviders = newUnscopedProviders }
in
( { outerModel | sharedModel = sharedModelUpdatedUnscopedProviders }
, Cmd.batch [ Cmd.map SharedMsg loginRequests, newViewStateCmd ]
)
Nothing ->
State.Error.processStringError
sharedModel
(ErrorContext
("look for OpenStack provider with Keystone URL " ++ keystoneUrl)
ErrorCrit
Nothing
)
"Provider could not found in Exosphere's list of Providers."
|> mapToOuterMsg
|> mapToOuterModel outerModel
ProjectMsg projectIdentifier innerMsg ->
case GetterSetters.projectLookup sharedModel projectIdentifier of
Nothing ->
-- Project not found, may have been removed, nothing to do
( outerModel, Cmd.none )
Just project ->
processProjectSpecificMsg outerModel project innerMsg
OpenNewWindow url ->
( outerModel, Ports.openNewWindow url )
LinkClicked urlRequest ->
case urlRequest of
Browser.Internal url ->
( outerModel, Browser.Navigation.pushUrl viewContext.navigationKey (Url.toString url) )
Browser.External url ->
( outerModel, Browser.Navigation.load url )
UrlChanged url ->
ViewStateHelpers.navigateToPage url outerModel
SelectTheme themeChoice ->
let
oldStyle =
sharedModel.style
oldStyleMode =
oldStyle.styleMode
newStyleMode =
{ oldStyleMode | theme = themeChoice }
newStyle =
{ oldStyle | styleMode = newStyleMode }
in
( { sharedModel
| style = newStyle
, viewContext = { viewContext | palette = toExoPalette newStyle }
}
, Cmd.none
)
|> mapToOuterModel outerModel
NoOp ->
( outerModel, Cmd.none )
SetExperimentalFeaturesEnabled choice ->
( { sharedModel | viewContext = { viewContext | experimentalFeaturesEnabled = choice } }, Cmd.none )
|> mapToOuterModel outerModel
processTick : OuterModel -> TickInterval -> Time.Posix -> ( SharedModel, Cmd OuterMsg )
processTick outerModel interval time =
let
serverVolsNeedFrequentPoll : Project -> Server -> Bool
serverVolsNeedFrequentPoll project server =
GetterSetters.getVolsAttachedToServer project server
|> List.any volNeedsFrequentPoll
volNeedsFrequentPoll volume =
not <|
List.member
volume.status
[ OSTypes.Available
, OSTypes.Maintenance
, OSTypes.InUse
, OSTypes.Error
, OSTypes.ErrorDeleting
, OSTypes.ErrorBackingUp
, OSTypes.ErrorRestoring
, OSTypes.ErrorExtending
]
viewIndependentCmd =
if interval == 5 then
Task.perform DoOrchestration Time.now
else
Cmd.none
( viewDependentModel, viewDependentCmd ) =
{- TODO move some of this to Orchestration? -}
case outerModel.viewState of
NonProjectView _ ->
( outerModel.sharedModel, Cmd.none )
ProjectView projectName _ projectViewState ->
case GetterSetters.projectLookup outerModel.sharedModel projectName of
Nothing ->
{- Should this throw an error? -}
( outerModel.sharedModel, Cmd.none )
Just project ->
let
pollVolumes : ( SharedModel, Cmd SharedMsg )
pollVolumes =
( outerModel.sharedModel
, case interval of
5 ->
if List.any volNeedsFrequentPoll (RemoteData.withDefault [] project.volumes) then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
in
case projectViewState of
AllResourcesList _ ->
pollVolumes
ServerDetail model ->
let
volCmd =
OSVolumes.requestVolumes project
in
case interval of
5 ->
case GetterSetters.serverLookup project model.serverUuid of
Just server ->
( outerModel.sharedModel
, if serverVolsNeedFrequentPoll project server then
volCmd
else
Cmd.none
)
Nothing ->
( outerModel.sharedModel, Cmd.none )
300 ->
( outerModel.sharedModel, volCmd )
_ ->
( outerModel.sharedModel, Cmd.none )
VolumeDetail pageModel ->
( outerModel.sharedModel
, case interval of
5 ->
case GetterSetters.volumeLookup project pageModel.volumeUuid of
Nothing ->
Cmd.none
Just volume ->
if volNeedsFrequentPoll volume then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
VolumeList _ ->
pollVolumes
_ ->
( outerModel.sharedModel, Cmd.none )
in
( { viewDependentModel | clientCurrentTime = time }
, Cmd.batch
[ viewDependentCmd
, viewIndependentCmd
]
|> Cmd.map SharedMsg
)
processProjectSpecificMsg : OuterModel -> Project -> ProjectSpecificMsgConstructor -> ( OuterModel, Cmd OuterMsg )
processProjectSpecificMsg outerModel project msg =
let
sharedModel =
outerModel.sharedModel
in
case msg of
PrepareCredentialedRequest requestProto posixTime ->
let
-- Add proxy URL
requestNeedingToken =
requestProto sharedModel.cloudCorsProxyUrl
currentTimeMillis =
posixTime |> Time.posixToMillis
tokenExpireTimeMillis =
project.auth.expiresAt |> Time.posixToMillis
tokenExpired =
-- Token expiring within 5 minutes
tokenExpireTimeMillis < currentTimeMillis + 300000
in
if not tokenExpired then
-- Token still valid, fire the request with current token
( sharedModel, requestNeedingToken project.auth.tokenValue )
|> mapToOuterMsg
|> mapToOuterModel outerModel
else
-- Token is expired (or nearly expired) so we add request to list of pending requests and refresh that token
let
newPQRs =
( project.auth.project.uuid, requestNeedingToken ) :: outerModel.pendingCredentialedRequests
cmdResult =
State.Auth.requestAuthToken sharedModel project
newOuterModel =
{ outerModel | pendingCredentialedRequests = newPQRs }
in
case cmdResult of
Err e ->
let
errorContext =
ErrorContext
("Refresh authentication token for project " ++ project.auth.project.name)
ErrorCrit
(Just "Please remove this project from Exosphere and add it again.")
in
State.Error.processStringError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel newOuterModel
Ok cmd ->
( sharedModel, cmd )
|> mapToOuterMsg
|> mapToOuterModel newOuterModel
ToggleCreatePopup ->
case outerModel.viewState of
ProjectView projectId projectViewModel viewConstructor ->
let
newViewState =
ProjectView
projectId
{ projectViewModel
| createPopup = not projectViewModel.createPopup
}
viewConstructor
in
( { outerModel | viewState = newViewState }, Cmd.none )
_ ->
( outerModel, Cmd.none )
RemoveProject ->
let
newProjects =
List.filter (\p -> p.auth.project.uuid /= project.auth.project.uuid) sharedModel.projects
newOuterModel =
{ outerModel | sharedModel = { sharedModel | projects = newProjects } }
cmd =
-- if we are in a view specific to this project then navigate to the home page
case outerModel.viewState of
ProjectView projectId _ _ ->
if projectId == project.auth.project.uuid then
Route.pushUrl sharedModel.viewContext Route.Home
else
Cmd.none
_ ->
Cmd.none
in
( newOuterModel, cmd )
ServerMsg serverUuid serverMsgConstructor ->
case GetterSetters.serverLookup project serverUuid of
Nothing ->
let
errorContext =
ErrorContext
"receive results of API call for a specific server"
ErrorDebug
Nothing
in
State.Error.processStringError
sharedModel
errorContext
(String.join " "
[ "Instance"
, serverUuid
, "does not exist in the model, it may have been deleted."
]
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
Just server ->
processServerSpecificMsg outerModel project server serverMsgConstructor
RequestServers ->
ApiModelHelpers.requestServers project.auth.project.uuid sharedModel
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestCreateServer pageModel networkUuid ->
let
customWorkFlowSource =
if pageModel.includeWorkflow && Maybe.withDefault False pageModel.workflowInputIsValid then
Just
{ repository = pageModel.workflowInputRepository
, reference = pageModel.workflowInputReference
, path = pageModel.workflowInputPath
}
else
Nothing
createServerRequest =
{ name = pageModel.serverName
, count = pageModel.count
, imageUuid = pageModel.imageUuid
, flavorUuid = pageModel.flavorUuid
, volBackedSizeGb =
pageModel.volSizeTextInput
|> Maybe.andThen Style.Widgets.NumericTextInput.NumericTextInput.toMaybe
, networkUuid = networkUuid
, keypairName = pageModel.keypairName
, userData =
Helpers.renderUserDataTemplate
project
pageModel.userDataTemplate
pageModel.keypairName
(pageModel.deployGuacamole |> Maybe.withDefault False)
pageModel.deployDesktopEnvironment
customWorkFlowSource
pageModel.installOperatingSystemUpdates
sharedModel.instanceConfigMgtRepoUrl
sharedModel.instanceConfigMgtRepoCheckout
, metadata =
Helpers.newServerMetadata
currentExoServerVersion
sharedModel.clientUuid
(pageModel.deployGuacamole |> Maybe.withDefault False)
pageModel.deployDesktopEnvironment
project.auth.user.name
pageModel.floatingIpCreationOption
customWorkFlowSource
}
in
( outerModel, Rest.Nova.requestCreateServer project createServerRequest )
|> mapToOuterMsg
RequestCreateVolume name size ->
let
createVolumeRequest =
{ name = name
, size = size
}
in
( outerModel, OSVolumes.requestCreateVolume project createVolumeRequest )
|> mapToOuterMsg
RequestDeleteVolume volumeUuid ->
( outerModel, OSVolumes.requestDeleteVolume project volumeUuid )
|> mapToOuterMsg
RequestDetachVolume volumeUuid ->
let
maybeVolume =
OSVolumes.volumeLookup project volumeUuid
maybeServerUuid =
maybeVolume
|> Maybe.map (GetterSetters.getServersWithVolAttached project)
|> Maybe.andThen List.head
in
case maybeServerUuid of
Just serverUuid ->
( outerModel, OSSvrVols.requestDetachVolume project serverUuid volumeUuid )
|> mapToOuterMsg
Nothing ->
State.Error.processStringError
sharedModel
(ErrorContext
("look for server UUID with attached volume " ++ volumeUuid)
ErrorCrit
Nothing
)
"Could not determine server attached to this volume."
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestDeleteFloatingIp floatingIpAddress ->
( outerModel, Rest.Neutron.requestDeleteFloatingIp project floatingIpAddress )
|> mapToOuterMsg
RequestAssignFloatingIp port_ floatingIpUuid ->
let
setViewCmd =
Route.pushUrl sharedModel.viewContext
(Route.ProjectRoute project.auth.project.uuid <| Route.FloatingIpList)
in
( outerModel
, Cmd.batch
[ setViewCmd
, Cmd.map SharedMsg <| Rest.Neutron.requestAssignFloatingIp project port_ floatingIpUuid
]
)
RequestUnassignFloatingIp floatingIpUuid ->
( outerModel, Rest.Neutron.requestUnassignFloatingIp project floatingIpUuid )
|> mapToOuterMsg
ReceiveImages images ->
Rest.Glance.receiveImages sharedModel project images
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestDeleteServers serverUuidsToDelete ->
let
applyDelete : OSTypes.ServerUuid -> ( Project, Cmd SharedMsg ) -> ( Project, Cmd SharedMsg )
applyDelete serverUuid projCmdTuple =
let
( delServerProj, delServerCmd ) =
requestDeleteServer (Tuple.first projCmdTuple) serverUuid False
in
( delServerProj, Cmd.batch [ Tuple.second projCmdTuple, delServerCmd ] )
( newProject, cmd ) =
List.foldl
applyDelete
( project, Cmd.none )
serverUuidsToDelete
in
( GetterSetters.modelUpdateProject sharedModel newProject
, cmd
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveServers errorContext result ->
case result of
Ok servers ->
Rest.Nova.receiveServers sharedModel project servers
|> mapToOuterMsg
|> mapToOuterModel outerModel
Err e ->
let
oldServersData =
project.servers.data
newProject =
{ project
| servers =
RDPP.RemoteDataPlusPlus
oldServersData
(RDPP.NotLoading (Just ( e, sharedModel.clientCurrentTime )))
}
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newSharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveServer serverUuid errorContext result ->
case result of
Ok server ->
Rest.Nova.receiveServer sharedModel project server
|> mapToOuterMsg
|> mapToOuterModel outerModel
Err httpErrorWithBody ->
let
httpError =
httpErrorWithBody.error
non404 =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server not in project, may have been deleted, ignoring this error
( outerModel, Cmd.none )
Just server ->
-- Reset receivedTime and loadingSeparately
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps
| receivedTime = Nothing
, loadingSeparately = False
}
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newSharedModel errorContext httpErrorWithBody
|> mapToOuterMsg
|> mapToOuterModel outerModel
in
case httpError of
Http.BadStatus code ->
if code == 404 then
let
newErrorContext =
{ errorContext
| level = Error.ErrorDebug
, actionContext =
errorContext.actionContext
++ " -- 404 means server may have been deleted"
}
newProject =
GetterSetters.projectDeleteServer project serverUuid
newModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newModel newErrorContext httpErrorWithBody
|> mapToOuterMsg
|> mapToOuterModel outerModel
else
non404
_ ->
non404
ReceiveFlavors flavors ->
let
-- If we are creating a server and no flavor is selected, select the smallest flavor
maybeSmallestFlavor =
GetterSetters.sortedFlavors flavors |> List.head
( newOuterModel, newCmd ) =
Rest.Nova.receiveFlavors sharedModel project flavors
|> mapToOuterMsg
|> mapToOuterModel outerModel
in
case maybeSmallestFlavor of
Just smallestFlavor ->
( newOuterModel, newCmd )
|> pipelineCmdOuterModelMsg
(updateUnderlying (ServerCreateMsg <| Page.ServerCreate.GotDefaultFlavor smallestFlavor.uuid))
Nothing ->
( newOuterModel, newCmd )
RequestKeypairs ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success _ ->
project.keypairs
_ ->
RemoteData.Loading
newProject =
{ project | keypairs = newKeypairs }
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel
, Rest.Nova.requestKeypairs newProject
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveKeypairs keypairs ->
Rest.Nova.receiveKeypairs sharedModel project keypairs
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestCreateKeypair keypairName publicKey ->
( outerModel, Rest.Nova.requestCreateKeypair project keypairName publicKey )
|> mapToOuterMsg
ReceiveCreateKeypair keypair ->
let
newProject =
GetterSetters.projectUpdateKeypair project keypair
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( { outerModel | sharedModel = newSharedModel }
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute newProject.auth.project.uuid Route.KeypairList)
)
RequestDeleteKeypair keypairId ->
( outerModel, Rest.Nova.requestDeleteKeypair project keypairId )
|> mapToOuterMsg
ReceiveDeleteKeypair errorContext keypairName result ->
case result of
Err httpError ->
State.Error.processStringError sharedModel errorContext (Helpers.httpErrorToString httpError)
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok () ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success keypairs ->
keypairs
|> List.filter (\k -> k.name /= keypairName)
|> RemoteData.Success
_ ->
project.keypairs
newProject =
{ project | keypairs = newKeypairs }
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterModel outerModel
ReceiveCreateServer _ ->
let
newRoute =
Route.ProjectRoute
project.auth.project.uuid
Route.AllResourcesList
( newSharedModel, newCmd ) =
( sharedModel, Cmd.none )
|> Helpers.pipelineCmd
(ApiModelHelpers.requestServers project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestNetworks project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts project.auth.project.uuid)
in
( { outerModel | sharedModel = newSharedModel }
, Cmd.batch
[ Cmd.map SharedMsg newCmd
, Route.pushUrl sharedModel.viewContext newRoute
]
)
ReceiveNetworks errorContext result ->
case result of
Ok networks ->
let
newProject =
Rest.Neutron.receiveNetworks sharedModel project networks
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterMsg
|> mapToOuterModel outerModel
|> pipelineCmdOuterModelMsg (updateUnderlying (ServerCreateMsg <| Page.ServerCreate.GotNetworks))
Err httpError ->
let
oldNetworksData =
project.networks.data
newProject =
{ project
| networks =
RDPP.RemoteDataPlusPlus
oldNetworksData
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newModel errorContext httpError
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveAutoAllocatedNetwork errorContext result ->
let
newProject =
case result of
Ok netUuid ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave netUuid sharedModel.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
Err httpError ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
project.autoAllocatedNetworkUuid.data
(RDPP.NotLoading
(Just
( httpError
, sharedModel.clientCurrentTime
)
)
)
}
newSharedModel =
GetterSetters.modelUpdateProject
sharedModel
newProject
( newNewSharedModel, newCmd ) =
case result of
Ok _ ->
ApiModelHelpers.requestNetworks project.auth.project.uuid newSharedModel
Err httpError ->
State.Error.processSynchronousApiError newSharedModel errorContext httpError
|> Helpers.pipelineCmd (ApiModelHelpers.requestNetworks project.auth.project.uuid)
( newOuterModel, underlyingCmd ) =
case Helpers.newServerNetworkOptions newProject of
AutoSelectedNetwork netUuid ->
updateUnderlying
(ServerCreateMsg <| Page.ServerCreate.GotAutoAllocatedNetwork netUuid)
{ outerModel | sharedModel = newNewSharedModel }
_ ->
( { outerModel | sharedModel = newNewSharedModel }, Cmd.none )
in
( newOuterModel, Cmd.batch [ Cmd.map SharedMsg newCmd, underlyingCmd ] )
ReceiveFloatingIps ips ->
Rest.Neutron.receiveFloatingIps sharedModel project ips
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceivePorts errorContext result ->
case result of
Ok ports ->
let
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave ports sharedModel.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
Err httpError ->
let
oldPortsData =
project.ports.data
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
oldPortsData
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
}
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
State.Error.processSynchronousApiError newSharedModel errorContext httpError
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteFloatingIp uuid ->
Rest.Neutron.receiveDeleteFloatingIp sharedModel project uuid
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveAssignFloatingIp floatingIp ->
-- TODO update servers so that new assignment is reflected in the UI
let
newProject =
processNewFloatingIp sharedModel.clientCurrentTime project floatingIp
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterModel outerModel
ReceiveUnassignFloatingIp floatingIp ->
-- TODO update servers so that unassignment is reflected in the UI
let
newProject =
processNewFloatingIp sharedModel.clientCurrentTime project floatingIp
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveSecurityGroups groups ->
Rest.Neutron.receiveSecurityGroupsAndEnsureExoGroup sharedModel project groups
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveCreateExoSecurityGroup group ->
Rest.Neutron.receiveCreateExoSecurityGroupAndRequestCreateRules sharedModel project group
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveCreateVolume ->
{- Should we add new volume to model now? -}
( outerModel
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute project.auth.project.uuid Route.VolumeList)
)
ReceiveVolumes volumes ->
let
-- Look for any server backing volumes that were created with no name, and give them a reasonable name
updateVolNameCmds : List (Cmd SharedMsg)
updateVolNameCmds =
RDPP.withDefault [] project.servers
-- List of tuples containing server and Maybe boot vol
|> List.map
(\s ->
( s
, Helpers.getBootVol
(RemoteData.withDefault
[]
project.volumes
)
s.osProps.uuid
)
)
-- We only care about servers created by exosphere
|> List.filter
(\t ->
case Tuple.first t |> .exoProps |> .serverOrigin of
ServerFromExo _ ->
True
ServerNotFromExo ->
False
)
-- We only care about servers created as current OpenStack user
|> List.filter
(\t ->
(Tuple.first t).osProps.details.userUuid
== project.auth.user.uuid
)
-- We only care about servers with a non-empty name
|> List.filter
(\t ->
Tuple.first t
|> .osProps
|> .name
|> String.isEmpty
|> not
)
-- We only care about volume-backed servers
|> List.filterMap
(\t ->
case t of
( server, Just vol ) ->
-- Flatten second part of tuple
Just ( server, vol )
_ ->
Nothing
)
-- We only care about unnamed backing volumes
|> List.filter
(\t ->
Tuple.second t
|> .name
|> String.isEmpty
)
|> List.map
(\t ->
OSVolumes.requestUpdateVolumeName
project
(t |> Tuple.second |> .uuid)
("boot-vol-"
++ (t |> Tuple.first |> .osProps |> .name)
)
)
newProject =
{ project | volumes = RemoteData.succeed volumes }
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.batch updateVolNameCmds )
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteVolume ->
( outerModel, OSVolumes.requestVolumes project )
|> mapToOuterMsg
ReceiveUpdateVolumeName ->
( outerModel, OSVolumes.requestVolumes project )
|> mapToOuterMsg
ReceiveAttachVolume attachment ->
( outerModel
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute project.auth.project.uuid <| Route.VolumeMountInstructions attachment)
)
ReceiveDetachVolume ->
( outerModel
, Route.pushUrl sharedModel.viewContext (Route.ProjectRoute project.auth.project.uuid Route.VolumeList)
)
ReceiveAppCredential appCredential ->
let
newProject =
{ project | secret = ApplicationCredential appCredential }
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveComputeQuota quota ->
let
newProject =
{ project | computeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveVolumeQuota quota ->
let
newProject =
{ project | volumeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject sharedModel newProject, Cmd.none )
|> mapToOuterModel outerModel
ReceiveRandomServerName serverName ->
updateUnderlying (ServerCreateMsg <| Page.ServerCreate.GotServerName serverName) outerModel
processServerSpecificMsg : OuterModel -> Project -> Server -> ServerSpecificMsgConstructor -> ( OuterModel, Cmd OuterMsg )
processServerSpecificMsg outerModel project server serverMsgConstructor =
let
sharedModel =
outerModel.sharedModel
in
case serverMsgConstructor of
RequestServer ->
ApiModelHelpers.requestServer project.auth.project.uuid server.osProps.uuid sharedModel
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestDeleteServer retainFloatingIps ->
let
( newProject, cmd ) =
requestDeleteServer project server.osProps.uuid retainFloatingIps
in
( GetterSetters.modelUpdateProject sharedModel newProject, cmd )
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestAttachVolume volumeUuid ->
( outerModel, OSSvrVols.requestAttachVolume project server.osProps.uuid volumeUuid )
|> mapToOuterMsg
RequestCreateServerImage imageName ->
let
newRoute =
Route.ProjectRoute
project.auth.project.uuid
Route.AllResourcesList
createImageCmd =
Rest.Nova.requestCreateServerImage project server.osProps.uuid imageName
in
( outerModel
, Cmd.batch
[ Cmd.map SharedMsg createImageCmd
, Route.pushUrl sharedModel.viewContext newRoute
]
)
RequestSetServerName newServerName ->
( outerModel, Rest.Nova.requestSetServerName project server.osProps.uuid newServerName )
|> mapToOuterMsg
ReceiveServerEvents _ result ->
case result of
Ok serverEvents ->
let
newServer =
{ server | events = RemoteData.Success serverEvents }
newProject =
GetterSetters.projectUpdateServer project newServer
in
( GetterSetters.modelUpdateProject sharedModel newProject
, Cmd.none
)
|> mapToOuterModel outerModel
Err _ ->
-- Dropping this on the floor for now, someday we may want to do something different
( outerModel, Cmd.none )
ReceiveConsoleUrl url ->
Rest.Nova.receiveConsoleUrl sharedModel project server url
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteServer ->
let
newProject =
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | deletionAttempted = True }
newServer =
{ server | exoProps = newExoProps }
in
GetterSetters.projectUpdateServer project newServer
newOuterModel =
{ outerModel | sharedModel = GetterSetters.modelUpdateProject sharedModel newProject }
in
( newOuterModel
, case outerModel.viewState of
ProjectView projectId _ (ServerDetail pageModel) ->
if pageModel.serverUuid == server.osProps.uuid then
Route.pushUrl sharedModel.viewContext (Route.ProjectRoute projectId Route.AllResourcesList)
else
Cmd.none
_ ->
Cmd.none
)
ReceiveCreateFloatingIp errorContext result ->
case result of
Ok ip ->
Rest.Neutron.receiveCreateFloatingIp sharedModel project server ip
|> mapToOuterMsg
|> mapToOuterModel outerModel
Err httpErrorWithBody ->
let
newErrorContext =
if GetterSetters.serverPresentNotDeleting sharedModel server.osProps.uuid then
errorContext
else
{ errorContext | level = ErrorDebug }
in
State.Error.processSynchronousApiError sharedModel newErrorContext httpErrorWithBody
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveServerPassword password ->
if String.isEmpty password then
( outerModel, Cmd.none )
else
let
tag =
"exoPw:" ++ password
cmd =
case server.exoProps.serverOrigin of
ServerNotFromExo ->
Cmd.none
ServerFromExo serverFromExoProps ->
if serverFromExoProps.exoServerVersion >= 1 then
Cmd.batch
[ OSServerTags.requestCreateServerTag project server.osProps.uuid tag
, OSServerPassword.requestClearServerPassword project server.osProps.uuid
]
else
Cmd.none
in
( outerModel, cmd )
|> mapToOuterMsg
ReceiveSetServerName _ errorContext result ->
case result of
Err e ->
State.Error.processSynchronousApiError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok actualNewServerName ->
let
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | name = actualNewServerName }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newOuterModel =
{ outerModel | sharedModel = GetterSetters.modelUpdateProject sharedModel newProject }
-- Later, maybe: Check that newServerName == actualNewServerName
in
updateUnderlying (ServerDetailMsg <| Page.ServerDetail.GotServerNamePendingConfirmation Nothing)
newOuterModel
ReceiveSetServerMetadata intendedMetadataItem errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok newServerMetadata ->
-- Update the model after ensuring the intended metadata item was actually added
if List.member intendedMetadataItem newServerMetadata then
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = newServerMetadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterMsg
|> mapToOuterModel outerModel
else
-- This is bonkers, throw an error
State.Error.processStringError
sharedModel
errorContext
"The metadata items returned by OpenStack did not include the metadata item that we tried to set."
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveDeleteServerMetadata metadataKey errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError sharedModel errorContext e
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok _ ->
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = List.filter (\i -> i.key /= metadataKey) oldServerDetails.metadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, Cmd.none )
|> mapToOuterModel outerModel
ReceiveGuacamoleAuthToken result ->
let
errorContext =
ErrorContext
"Receive a response from Guacamole auth token API"
ErrorDebug
Nothing
sharedModelUpdateGuacProps : ServerFromExoProps -> GuacTypes.LaunchedWithGuacProps -> SharedModel
sharedModelUpdateGuacProps exoOriginProps guacProps =
let
newOriginProps =
{ exoOriginProps | guacamoleStatus = GuacTypes.LaunchedWithGuacamole guacProps }
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
newSharedModel
in
case server.exoProps.serverOrigin of
ServerFromExo exoOriginProps ->
case exoOriginProps.guacamoleStatus of
GuacTypes.LaunchedWithGuacamole oldGuacProps ->
let
newGuacProps =
case result of
Ok tokenValue ->
if server.osProps.details.openstackStatus == OSTypes.ServerActive then
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
tokenValue
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
}
else
-- Server is not active, this token won't work, so we don't store it
{ oldGuacProps
| authToken =
RDPP.empty
}
Err e ->
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
oldGuacProps.authToken.data
(RDPP.NotLoading (Just ( e, sharedModel.clientCurrentTime )))
}
in
( sharedModelUpdateGuacProps
exoOriginProps
newGuacProps
, Cmd.none
)
|> mapToOuterMsg
|> mapToOuterModel outerModel
GuacTypes.NotLaunchedWithGuacamole ->
State.Error.processStringError
sharedModel
errorContext
"Server does not appear to have been launched with Guacamole support"
|> mapToOuterMsg
|> mapToOuterModel outerModel
ServerNotFromExo ->
State.Error.processStringError
sharedModel
errorContext
"Server does not appear to have been launched from Exosphere"
|> mapToOuterMsg
|> mapToOuterModel outerModel
RequestServerAction func targetStatuses ->
let
oldExoProps =
server.exoProps
newServer =
Server server.osProps { oldExoProps | targetOpenstackStatus = targetStatuses } server.events
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
( newSharedModel, func newProject.endpoints.nova )
|> mapToOuterMsg
|> mapToOuterModel outerModel
ReceiveConsoleLog errorContext result ->
case server.exoProps.serverOrigin of
ServerNotFromExo ->
( outerModel, Cmd.none )
ServerFromExo exoOriginProps ->
let
oldExoSetupStatus =
case exoOriginProps.exoSetupStatus.data of
RDPP.DontHave ->
ExoSetupUnknown
RDPP.DoHave s _ ->
s
( newExoSetupStatusRDPP, exoSetupStatusMetadataCmd ) =
case result of
Err httpError ->
( RDPP.RemoteDataPlusPlus
exoOriginProps.exoSetupStatus.data
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
, Cmd.none
)
Ok consoleLog ->
let
newExoSetupStatus =
Helpers.ExoSetupStatus.parseConsoleLogExoSetupStatus
oldExoSetupStatus
consoleLog
server.osProps.details.created
sharedModel.clientCurrentTime
cmd =
if newExoSetupStatus == oldExoSetupStatus then
Cmd.none
else
let
value =
Helpers.ExoSetupStatus.exoSetupStatusToStr newExoSetupStatus
metadataItem =
OSTypes.MetadataItem
"exoSetup"
value
in
Rest.Nova.requestSetServerMetadata project server.osProps.uuid metadataItem
in
( RDPP.RemoteDataPlusPlus
(RDPP.DoHave
newExoSetupStatus
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
, cmd
)
newResourceUsage =
case result of
Err httpError ->
RDPP.RemoteDataPlusPlus
exoOriginProps.resourceUsage.data
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
Ok consoleLog ->
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
(Helpers.ServerResourceUsage.parseConsoleLog
consoleLog
(RDPP.withDefault
Types.ServerResourceUsage.emptyResourceUsageHistory
exoOriginProps.resourceUsage
)
)
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
newWorkflowToken : CustomWorkflow -> CustomWorkflowTokenRDPP
newWorkflowToken currentWorkflow =
case result of
Err httpError ->
RDPP.RemoteDataPlusPlus
RDPP.DontHave
(RDPP.NotLoading (Just ( httpError, sharedModel.clientCurrentTime )))
Ok consoleLog ->
let
maybeParsedToken =
Helpers.parseConsoleLogForWorkflowToken consoleLog
in
case maybeParsedToken of
Just parsedToken ->
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
parsedToken
sharedModel.clientCurrentTime
)
(RDPP.NotLoading Nothing)
Nothing ->
currentWorkflow.authToken
newWorkflowStatus : ServerCustomWorkflowStatus
newWorkflowStatus =
case exoOriginProps.customWorkflowStatus of
NotLaunchedWithCustomWorkflow ->
exoOriginProps.customWorkflowStatus
LaunchedWithCustomWorkflow customWorkflow ->
LaunchedWithCustomWorkflow { customWorkflow | authToken = newWorkflowToken customWorkflow }
newOriginProps =
{ exoOriginProps
| resourceUsage = newResourceUsage
, exoSetupStatus = newExoSetupStatusRDPP
, customWorkflowStatus = newWorkflowStatus
}
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newSharedModel =
GetterSetters.modelUpdateProject sharedModel newProject
in
case result of
Err httpError ->
State.Error.processSynchronousApiError newSharedModel errorContext httpError
|> mapToOuterMsg
|> mapToOuterModel outerModel
Ok _ ->
( newSharedModel, exoSetupStatusMetadataCmd )
|> mapToOuterMsg
|> mapToOuterModel outerModel
processNewFloatingIp : Time.Posix -> Project -> OSTypes.FloatingIp -> Project
processNewFloatingIp time project floatingIp =
let
otherIps =
project.floatingIps
|> RDPP.withDefault []
|> List.filter (\i -> i.uuid /= floatingIp.uuid)
newIps =
floatingIp :: otherIps
in
{ project
| floatingIps =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave newIps time)
(RDPP.NotLoading Nothing)
}
createProject : OuterModel -> Maybe OSTypes.ProjectDescription -> OSTypes.ScopedAuthToken -> Endpoints -> ( OuterModel, Cmd OuterMsg )
createProject outerModel description authToken endpoints =
let
sharedModel =
outerModel.sharedModel
newProject =
{ secret = NoProjectSecret
, auth = authToken
-- Maybe todo, eliminate parallel data structures in auth and endpoints?
, endpoints = endpoints
, description = description
, images = []
, servers = RDPP.RemoteDataPlusPlus RDPP.DontHave RDPP.Loading
, flavors = []
, keypairs = RemoteData.NotAsked
, volumes = RemoteData.NotAsked
, networks = RDPP.empty
, autoAllocatedNetworkUuid = RDPP.empty
, floatingIps = RDPP.empty
, ports = RDPP.empty
, securityGroups = []
, computeQuota = RemoteData.NotAsked
, volumeQuota = RemoteData.NotAsked
}
newProjects =
newProject :: outerModel.sharedModel.projects
newViewStateCmd =
-- If the user is selecting projects from an unscoped provider then don't interrupt them
case outerModel.viewState of
NonProjectView (SelectProjects _) ->
Cmd.none
-- Otherwise take them to home page
_ ->
Route.pushUrl sharedModel.viewContext <|
Route.Home
( newSharedModel, newCmd ) =
( { sharedModel
| projects = newProjects
}
, [ Rest.Nova.requestServers
, Rest.Neutron.requestSecurityGroups
, Rest.Keystone.requestAppCredential sharedModel.clientUuid sharedModel.clientCurrentTime
]
|> List.map (\x -> x newProject)
|> Cmd.batch
)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestVolumes newProject.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestFloatingIps newProject.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts newProject.auth.project.uuid)
in
( { outerModel | sharedModel = newSharedModel }
, Cmd.batch [ newViewStateCmd, Cmd.map SharedMsg newCmd ]
)
createUnscopedProvider : SharedModel -> OSTypes.UnscopedAuthToken -> HelperTypes.Url -> ( SharedModel, Cmd SharedMsg )
createUnscopedProvider model authToken authUrl =
let
newProvider =
{ authUrl = authUrl
, token = PI:PASSWORD:<PASSWORD>END_PI
, projectsAvailable = RemoteData.Loading
}
newProviders =
newProvider :: model.unscopedProviders
in
( { model | unscopedProviders = newProviders }
, Rest.Keystone.requestUnscopedProjects newProvider model.cloudCorsProxyUrl
)
requestDeleteServer : Project -> OSTypes.ServerUuid -> Bool -> ( Project, Cmd SharedMsg )
requestDeleteServer project serverUuid retainFloatingIps =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server likely deleted already, do nothing
( project, Cmd.none )
Just server ->
let
oldExoProps =
server.exoProps
newServer =
{ server | exoProps = { oldExoProps | deletionAttempted = True } }
deleteFloatingIpCmds =
if retainFloatingIps then
[]
else
GetterSetters.getServerFloatingIps project server.osProps.uuid
|> List.map .uuid
|> List.map (Rest.Neutron.requestDeleteFloatingIp project)
newProject =
GetterSetters.projectUpdateServer project newServer
in
( newProject
, Cmd.batch
[ Rest.Nova.requestDeleteServer
newProject.auth.project.uuid
newProject.endpoints.nova
newServer.osProps.uuid
, Cmd.batch deleteFloatingIpCmds
]
)
| elm |
[
{
"context": "il\n testEmail =\n case Email.fromString \"some.email@domain.com\" of\n Just email ->\n ema",
"end": 904,
"score": 0.9996318817,
"start": 883,
"tag": "EMAIL",
"value": "some.email@domain.com"
}
] | tests/NoDebug/TodoOrToString.elm | bebbs/elm-review | 0 | module NoDebug.TodoOrToString exposing (rule)
{-|
@docs rule
-}
import Elm.Syntax.Exposing as Exposing
import Elm.Syntax.Expression as Expression exposing (Expression)
import Elm.Syntax.Import exposing (Import)
import Elm.Syntax.Node as Node exposing (Node)
import Review.Rule as Rule exposing (Error, Rule)
{-| Forbid the use of [`Debug.todo`] and [`Debug.toString`].
config =
[ NoDebug.TodoOrToString.rule
]
The reason why there is a is separate rule for handling [`Debug.log`] and one for
handling [`Debug.todo`] and [`Debug.toString`], is because these two functions
are reasonable and useful to have in tests.
You can for instance create test data without having to handle the error case
everywhere. If you do enter the error case in the following example, then tests
will fail.
testEmail : Email
testEmail =
case Email.fromString "some.email@domain.com" of
Just email ->
email
Nothing ->
Debug.todo "Supplied an invalid email in tests"
If you want to allow these functions in tests but not in production code, you
can configure the rule like this.
import Review.Rule as Rule exposing (Rule)
config =
[ NoDebug.TodoOrToString.rule
|> Rule.ignoreErrorsForDirectories [ "tests/" ]
]
## Fail
_ =
if condition then
a
else
Debug.todo ""
_ =
Debug.toString data
## Success
if condition then
a
else
b
## Try it out
You can try this rule out by running the following command:
```bash
elm-review --template jfmengels/elm-review-debug/example --rules NoDebug.TodoOrToString
```
[`Debug.log`]: https://package.elm-lang.org/packages/elm/core/latest/Debug#log
[`Debug.todo`]: https://package.elm-lang.org/packages/elm/core/latest/Debug#todo
[`Debug.toString`]: https://package.elm-lang.org/packages/elm/core/latest/Debug#toString
-}
rule : Rule
rule =
Rule.newModuleRuleSchema "NoDebug.TodoOrToString" init
|> Rule.withImportVisitor importVisitor
|> Rule.withExpressionVisitor expressionVisitor
|> Rule.fromModuleRuleSchema
type alias Context =
{ hasTodoBeenImported : Bool
, hasToStringBeenImported : Bool
}
init : Context
init =
{ hasTodoBeenImported = False
, hasToStringBeenImported = False
}
error : Node a -> String -> Error {}
error node name =
Rule.error
{ message = "Remove the use of `Debug." ++ name ++ "` before shipping to production"
, details =
[ "`Debug." ++ name ++ "` can be useful when developing, but is not meant to be shipped to production or published in a package. I suggest removing its use before committing and attempting to push to production."
]
}
(Node.range node)
importVisitor : Node Import -> Context -> ( List nothing, Context )
importVisitor node context =
let
moduleName : List String
moduleName =
node
|> Node.value
|> .moduleName
|> Node.value
in
if moduleName == [ "Debug" ] then
case node |> Node.value |> .exposingList |> Maybe.map Node.value of
Just (Exposing.All _) ->
( [], { hasTodoBeenImported = True, hasToStringBeenImported = True } )
Just (Exposing.Explicit importedNames) ->
( []
, { context
| hasTodoBeenImported = List.any (is "todo") importedNames
, hasToStringBeenImported = List.any (is "toString") importedNames
}
)
Nothing ->
( [], context )
else
( [], context )
is : String -> Node Exposing.TopLevelExpose -> Bool
is name node =
case Node.value node of
Exposing.FunctionExpose functionName ->
name == functionName
_ ->
False
expressionVisitor : Node Expression -> Rule.Direction -> Context -> ( List (Error {}), Context )
expressionVisitor node direction context =
case ( direction, Node.value node ) of
( Rule.OnEnter, Expression.FunctionOrValue [ "Debug" ] name ) ->
if name == "todo" then
( [ error node name ], context )
else if name == "toString" then
( [ error node name ], context )
else
( [], context )
( Rule.OnEnter, Expression.FunctionOrValue [] name ) ->
if name == "todo" && context.hasTodoBeenImported then
( [ error node name ], context )
else if name == "toString" && context.hasToStringBeenImported then
( [ error node name ], context )
else
( [], context )
_ ->
( [], context )
| 57233 | module NoDebug.TodoOrToString exposing (rule)
{-|
@docs rule
-}
import Elm.Syntax.Exposing as Exposing
import Elm.Syntax.Expression as Expression exposing (Expression)
import Elm.Syntax.Import exposing (Import)
import Elm.Syntax.Node as Node exposing (Node)
import Review.Rule as Rule exposing (Error, Rule)
{-| Forbid the use of [`Debug.todo`] and [`Debug.toString`].
config =
[ NoDebug.TodoOrToString.rule
]
The reason why there is a is separate rule for handling [`Debug.log`] and one for
handling [`Debug.todo`] and [`Debug.toString`], is because these two functions
are reasonable and useful to have in tests.
You can for instance create test data without having to handle the error case
everywhere. If you do enter the error case in the following example, then tests
will fail.
testEmail : Email
testEmail =
case Email.fromString "<EMAIL>" of
Just email ->
email
Nothing ->
Debug.todo "Supplied an invalid email in tests"
If you want to allow these functions in tests but not in production code, you
can configure the rule like this.
import Review.Rule as Rule exposing (Rule)
config =
[ NoDebug.TodoOrToString.rule
|> Rule.ignoreErrorsForDirectories [ "tests/" ]
]
## Fail
_ =
if condition then
a
else
Debug.todo ""
_ =
Debug.toString data
## Success
if condition then
a
else
b
## Try it out
You can try this rule out by running the following command:
```bash
elm-review --template jfmengels/elm-review-debug/example --rules NoDebug.TodoOrToString
```
[`Debug.log`]: https://package.elm-lang.org/packages/elm/core/latest/Debug#log
[`Debug.todo`]: https://package.elm-lang.org/packages/elm/core/latest/Debug#todo
[`Debug.toString`]: https://package.elm-lang.org/packages/elm/core/latest/Debug#toString
-}
rule : Rule
rule =
Rule.newModuleRuleSchema "NoDebug.TodoOrToString" init
|> Rule.withImportVisitor importVisitor
|> Rule.withExpressionVisitor expressionVisitor
|> Rule.fromModuleRuleSchema
type alias Context =
{ hasTodoBeenImported : Bool
, hasToStringBeenImported : Bool
}
init : Context
init =
{ hasTodoBeenImported = False
, hasToStringBeenImported = False
}
error : Node a -> String -> Error {}
error node name =
Rule.error
{ message = "Remove the use of `Debug." ++ name ++ "` before shipping to production"
, details =
[ "`Debug." ++ name ++ "` can be useful when developing, but is not meant to be shipped to production or published in a package. I suggest removing its use before committing and attempting to push to production."
]
}
(Node.range node)
importVisitor : Node Import -> Context -> ( List nothing, Context )
importVisitor node context =
let
moduleName : List String
moduleName =
node
|> Node.value
|> .moduleName
|> Node.value
in
if moduleName == [ "Debug" ] then
case node |> Node.value |> .exposingList |> Maybe.map Node.value of
Just (Exposing.All _) ->
( [], { hasTodoBeenImported = True, hasToStringBeenImported = True } )
Just (Exposing.Explicit importedNames) ->
( []
, { context
| hasTodoBeenImported = List.any (is "todo") importedNames
, hasToStringBeenImported = List.any (is "toString") importedNames
}
)
Nothing ->
( [], context )
else
( [], context )
is : String -> Node Exposing.TopLevelExpose -> Bool
is name node =
case Node.value node of
Exposing.FunctionExpose functionName ->
name == functionName
_ ->
False
expressionVisitor : Node Expression -> Rule.Direction -> Context -> ( List (Error {}), Context )
expressionVisitor node direction context =
case ( direction, Node.value node ) of
( Rule.OnEnter, Expression.FunctionOrValue [ "Debug" ] name ) ->
if name == "todo" then
( [ error node name ], context )
else if name == "toString" then
( [ error node name ], context )
else
( [], context )
( Rule.OnEnter, Expression.FunctionOrValue [] name ) ->
if name == "todo" && context.hasTodoBeenImported then
( [ error node name ], context )
else if name == "toString" && context.hasToStringBeenImported then
( [ error node name ], context )
else
( [], context )
_ ->
( [], context )
| true | module NoDebug.TodoOrToString exposing (rule)
{-|
@docs rule
-}
import Elm.Syntax.Exposing as Exposing
import Elm.Syntax.Expression as Expression exposing (Expression)
import Elm.Syntax.Import exposing (Import)
import Elm.Syntax.Node as Node exposing (Node)
import Review.Rule as Rule exposing (Error, Rule)
{-| Forbid the use of [`Debug.todo`] and [`Debug.toString`].
config =
[ NoDebug.TodoOrToString.rule
]
The reason why there is a is separate rule for handling [`Debug.log`] and one for
handling [`Debug.todo`] and [`Debug.toString`], is because these two functions
are reasonable and useful to have in tests.
You can for instance create test data without having to handle the error case
everywhere. If you do enter the error case in the following example, then tests
will fail.
testEmail : Email
testEmail =
case Email.fromString "PI:EMAIL:<EMAIL>END_PI" of
Just email ->
email
Nothing ->
Debug.todo "Supplied an invalid email in tests"
If you want to allow these functions in tests but not in production code, you
can configure the rule like this.
import Review.Rule as Rule exposing (Rule)
config =
[ NoDebug.TodoOrToString.rule
|> Rule.ignoreErrorsForDirectories [ "tests/" ]
]
## Fail
_ =
if condition then
a
else
Debug.todo ""
_ =
Debug.toString data
## Success
if condition then
a
else
b
## Try it out
You can try this rule out by running the following command:
```bash
elm-review --template jfmengels/elm-review-debug/example --rules NoDebug.TodoOrToString
```
[`Debug.log`]: https://package.elm-lang.org/packages/elm/core/latest/Debug#log
[`Debug.todo`]: https://package.elm-lang.org/packages/elm/core/latest/Debug#todo
[`Debug.toString`]: https://package.elm-lang.org/packages/elm/core/latest/Debug#toString
-}
rule : Rule
rule =
Rule.newModuleRuleSchema "NoDebug.TodoOrToString" init
|> Rule.withImportVisitor importVisitor
|> Rule.withExpressionVisitor expressionVisitor
|> Rule.fromModuleRuleSchema
type alias Context =
{ hasTodoBeenImported : Bool
, hasToStringBeenImported : Bool
}
init : Context
init =
{ hasTodoBeenImported = False
, hasToStringBeenImported = False
}
error : Node a -> String -> Error {}
error node name =
Rule.error
{ message = "Remove the use of `Debug." ++ name ++ "` before shipping to production"
, details =
[ "`Debug." ++ name ++ "` can be useful when developing, but is not meant to be shipped to production or published in a package. I suggest removing its use before committing and attempting to push to production."
]
}
(Node.range node)
importVisitor : Node Import -> Context -> ( List nothing, Context )
importVisitor node context =
let
moduleName : List String
moduleName =
node
|> Node.value
|> .moduleName
|> Node.value
in
if moduleName == [ "Debug" ] then
case node |> Node.value |> .exposingList |> Maybe.map Node.value of
Just (Exposing.All _) ->
( [], { hasTodoBeenImported = True, hasToStringBeenImported = True } )
Just (Exposing.Explicit importedNames) ->
( []
, { context
| hasTodoBeenImported = List.any (is "todo") importedNames
, hasToStringBeenImported = List.any (is "toString") importedNames
}
)
Nothing ->
( [], context )
else
( [], context )
is : String -> Node Exposing.TopLevelExpose -> Bool
is name node =
case Node.value node of
Exposing.FunctionExpose functionName ->
name == functionName
_ ->
False
expressionVisitor : Node Expression -> Rule.Direction -> Context -> ( List (Error {}), Context )
expressionVisitor node direction context =
case ( direction, Node.value node ) of
( Rule.OnEnter, Expression.FunctionOrValue [ "Debug" ] name ) ->
if name == "todo" then
( [ error node name ], context )
else if name == "toString" then
( [ error node name ], context )
else
( [], context )
( Rule.OnEnter, Expression.FunctionOrValue [] name ) ->
if name == "todo" && context.hasTodoBeenImported then
( [ error node name ], context )
else if name == "toString" && context.hasToStringBeenImported then
( [ error node name ], context )
else
( [], context )
_ ->
( [], context )
| elm |
[
{
"context": "onBody <| Encode.object [ (\"name\", Encode.string \"Cool Dude\"), ( \"count\", Encode.int 27) ]\n , expect ",
"end": 4602,
"score": 0.7470307946,
"start": 4598,
"tag": "NAME",
"value": "Cool"
},
{
"context": "Http.multipartBody\n [ Http.stringPart \"username\" \"someone-cool\"\n , Http.filePart \"fun-",
"end": 5370,
"score": 0.9993534684,
"start": 5362,
"tag": "USERNAME",
"value": "username"
},
{
"context": "artBody\n [ Http.stringPart \"username\" \"someone-cool\"\n , Http.filePart \"fun-image\" file\n ",
"end": 5385,
"score": 0.9993927479,
"start": 5373,
"tag": "USERNAME",
"value": "someone-cool"
}
] | tests/src/Specs/HttpLogSpec.elm | jhack32/elm-spec | 24 | module Specs.HttpLogSpec exposing (main)
import Spec exposing (..)
import Spec.Setup as Setup
import Spec.Markup as Markup
import Spec.Markup.Selector exposing (..)
import Spec.Markup.Event as Event
import Spec.Claim exposing (..)
import Spec.Http
import Spec.Http.Route exposing (..)
import Spec.File
import Html exposing (Html)
import Html.Attributes as Attr
import Html.Events as Events
import Http
import Bytes.Encode as Bytes
import File exposing (File)
import File.Select
import Json.Encode as Encode
import Runner
httpRequestLogSpec : Spec Model Msg
httpRequestLogSpec =
Spec.describe "logRequests"
[ scenario "there are requests" (
given (
testSubject
[ getRequest "http://fun.com/fun/1" [ Http.header "Content-Type" "text/plain;charset=utf-8", Http.header "X-Fun-Header" "my-header" ]
, getRequest "http://awesome.com/awesome?name=cool" [ Http.header "Content-Type" "text/plain;charset=utf-8" ]
, postRequest "http://super.com/super"
]
)
|> when "requests are sent"
[ Spec.Http.logRequests
, Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
, Event.click
, Spec.Http.logRequests
, Event.click
, Spec.Http.logRequests
]
|> observeThat
[ it "makes the GET requests" (
Spec.Http.observeRequests (route "GET" <| Matching ".+")
|> expect (isListWithLength 2)
)
, it "makes the POST requests" (
Spec.Http.observeRequests (route "POST" <| Matching ".+")
|> expect (isListWithLength 1)
)
]
)
]
logBytesRequestSpec : Spec Model Msg
logBytesRequestSpec =
describe "log an HTTP request with bytes body"
[ scenario "the request is logged" (
given (
testSubject
[ bytesRequest "http://fun.com/bytes" <| Bytes.encode <| Bytes.string "This is binary stuff!"
]
)
|> when "requests are sent"
[ Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
]
|> it "makes the POST requests" (
Spec.Http.observeRequests (route "POST" <| Matching ".+")
|> expect (isListWithLength 1)
)
)
]
logFileRequestSpec : Spec Model Msg
logFileRequestSpec =
describe "log an HTTP request with file body"
[ scenario "the request is logged" (
given (
testSubject
[ fileRequest "http://fun.com/files"
]
)
|> when "a file is selected"
[ Markup.target << by [ id "select-file" ]
, Event.click
, Spec.File.select
[ Spec.File.withText "/some/path/to/my-test-file.txt" "some super cool content"
|> Spec.File.withMimeType "text/plain"
]
]
|> when "requests are sent"
[ Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
]
|> it "makes the POST requests" (
Spec.Http.observeRequests (route "POST" <| Matching ".+")
|> expect (isListWithLength 1)
)
)
]
logMultipartRequestSpec : Spec Model Msg
logMultipartRequestSpec =
describe "log a multipart HTTP request"
[ scenario "a multipart request" (
given (
testSubject [ multipartRequest "http://place.com/api/request" ]
)
|> when "a file is selected"
[ Markup.target << by [ id "select-file" ]
, Event.click
, Spec.File.select
[ Spec.File.withText "/some/path/to/my-awesome-image.png" "some image data"
|> Spec.File.withMimeType "image/png"
]
]
|> when "requests are sent"
[ Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
]
|> it "makes the POST request" (
Spec.Http.observeRequests (post "http://place.com/api/request")
|> expect (isListWithLength 1)
)
)
]
getRequest url headers _ =
Http.request
{ method = "GET"
, headers = headers
, url = url
, body = Http.emptyBody
, expect = Http.expectString ReceivedRequest
, timeout = Nothing
, tracker = Nothing
}
postRequest url _ =
Http.request
{ method = "POST"
, headers =
[ Http.header "Content-Type" "text/plain;charset=utf-8"
, Http.header "X-Fun-Header" "my-header"
, Http.header "X-Super-Header" "super"
]
, url = url
, body = Http.jsonBody <| Encode.object [ ("name", Encode.string "Cool Dude"), ( "count", Encode.int 27) ]
, expect = Http.expectString ReceivedRequest
, timeout = Nothing
, tracker = Nothing
}
bytesRequest url bytes _ =
Http.post
{ url = url
, body = Http.bytesBody "application/octet-stream" bytes
, expect = Http.expectString ReceivedRequest
}
fileRequest url (Model model) =
model.selectedFile
|> Maybe.map (\file ->
Http.post
{ url = url
, body = Http.fileBody file
, expect = Http.expectString ReceivedRequest
}
)
|> Maybe.withDefault Cmd.none
multipartRequest url (Model model) =
model.selectedFile
|> Maybe.map (\file ->
Http.post
{ url = url
, body = Http.multipartBody
[ Http.stringPart "username" "someone-cool"
, Http.filePart "fun-image" file
, Http.bytesPart "fun-bytes" "image/png" <| Bytes.encode <| Bytes.string "This is binary stuff!"
]
, expect = Http.expectString ReceivedRequest
}
)
|> Maybe.withDefault Cmd.none
testSubject requests =
Setup.initWithModel (defaultModel requests)
|> Setup.withView testView
|> Setup.withUpdate testUpdate
type Model =
Model
{ requests: List (Model -> Cmd Msg)
, selectedFile: Maybe File
}
defaultModel requests =
Model
{ requests = requests
, selectedFile = Nothing
}
type Msg
= SendRequest
| SelectFile
| GotFile File
| ReceivedRequest (Result Http.Error String)
testUpdate : Msg -> Model -> (Model, Cmd Msg)
testUpdate msg (Model model) =
case msg of
SelectFile ->
( Model model, File.Select.file [] GotFile )
GotFile file ->
( Model { model | selectedFile = Just file }, Cmd.none )
SendRequest ->
case model.requests of
[] ->
( Model model, Cmd.none )
next :: requests ->
( Model { model | requests = requests }
, next <| Model model
)
ReceivedRequest _ ->
( Model model, Cmd.none )
testView : Model -> Html Msg
testView model =
Html.div []
[ Html.button [ Attr.id "request-button", Events.onClick SendRequest ] [ Html.text "Send Next Request!" ]
, Html.button [ Attr.id "select-file", Events.onClick SelectFile ] [ Html.text "Select file!" ]
]
selectSpec : String -> Maybe (Spec Model Msg)
selectSpec name =
case name of
"logRequests" -> Just httpRequestLogSpec
"logBytesRequest" -> Just logBytesRequestSpec
"logFileRequest" -> Just logFileRequestSpec
"logMultipartRequest" -> Just logMultipartRequestSpec
_ -> Nothing
main =
Runner.browserProgram selectSpec | 15802 | module Specs.HttpLogSpec exposing (main)
import Spec exposing (..)
import Spec.Setup as Setup
import Spec.Markup as Markup
import Spec.Markup.Selector exposing (..)
import Spec.Markup.Event as Event
import Spec.Claim exposing (..)
import Spec.Http
import Spec.Http.Route exposing (..)
import Spec.File
import Html exposing (Html)
import Html.Attributes as Attr
import Html.Events as Events
import Http
import Bytes.Encode as Bytes
import File exposing (File)
import File.Select
import Json.Encode as Encode
import Runner
httpRequestLogSpec : Spec Model Msg
httpRequestLogSpec =
Spec.describe "logRequests"
[ scenario "there are requests" (
given (
testSubject
[ getRequest "http://fun.com/fun/1" [ Http.header "Content-Type" "text/plain;charset=utf-8", Http.header "X-Fun-Header" "my-header" ]
, getRequest "http://awesome.com/awesome?name=cool" [ Http.header "Content-Type" "text/plain;charset=utf-8" ]
, postRequest "http://super.com/super"
]
)
|> when "requests are sent"
[ Spec.Http.logRequests
, Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
, Event.click
, Spec.Http.logRequests
, Event.click
, Spec.Http.logRequests
]
|> observeThat
[ it "makes the GET requests" (
Spec.Http.observeRequests (route "GET" <| Matching ".+")
|> expect (isListWithLength 2)
)
, it "makes the POST requests" (
Spec.Http.observeRequests (route "POST" <| Matching ".+")
|> expect (isListWithLength 1)
)
]
)
]
logBytesRequestSpec : Spec Model Msg
logBytesRequestSpec =
describe "log an HTTP request with bytes body"
[ scenario "the request is logged" (
given (
testSubject
[ bytesRequest "http://fun.com/bytes" <| Bytes.encode <| Bytes.string "This is binary stuff!"
]
)
|> when "requests are sent"
[ Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
]
|> it "makes the POST requests" (
Spec.Http.observeRequests (route "POST" <| Matching ".+")
|> expect (isListWithLength 1)
)
)
]
logFileRequestSpec : Spec Model Msg
logFileRequestSpec =
describe "log an HTTP request with file body"
[ scenario "the request is logged" (
given (
testSubject
[ fileRequest "http://fun.com/files"
]
)
|> when "a file is selected"
[ Markup.target << by [ id "select-file" ]
, Event.click
, Spec.File.select
[ Spec.File.withText "/some/path/to/my-test-file.txt" "some super cool content"
|> Spec.File.withMimeType "text/plain"
]
]
|> when "requests are sent"
[ Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
]
|> it "makes the POST requests" (
Spec.Http.observeRequests (route "POST" <| Matching ".+")
|> expect (isListWithLength 1)
)
)
]
logMultipartRequestSpec : Spec Model Msg
logMultipartRequestSpec =
describe "log a multipart HTTP request"
[ scenario "a multipart request" (
given (
testSubject [ multipartRequest "http://place.com/api/request" ]
)
|> when "a file is selected"
[ Markup.target << by [ id "select-file" ]
, Event.click
, Spec.File.select
[ Spec.File.withText "/some/path/to/my-awesome-image.png" "some image data"
|> Spec.File.withMimeType "image/png"
]
]
|> when "requests are sent"
[ Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
]
|> it "makes the POST request" (
Spec.Http.observeRequests (post "http://place.com/api/request")
|> expect (isListWithLength 1)
)
)
]
getRequest url headers _ =
Http.request
{ method = "GET"
, headers = headers
, url = url
, body = Http.emptyBody
, expect = Http.expectString ReceivedRequest
, timeout = Nothing
, tracker = Nothing
}
postRequest url _ =
Http.request
{ method = "POST"
, headers =
[ Http.header "Content-Type" "text/plain;charset=utf-8"
, Http.header "X-Fun-Header" "my-header"
, Http.header "X-Super-Header" "super"
]
, url = url
, body = Http.jsonBody <| Encode.object [ ("name", Encode.string "<NAME> Dude"), ( "count", Encode.int 27) ]
, expect = Http.expectString ReceivedRequest
, timeout = Nothing
, tracker = Nothing
}
bytesRequest url bytes _ =
Http.post
{ url = url
, body = Http.bytesBody "application/octet-stream" bytes
, expect = Http.expectString ReceivedRequest
}
fileRequest url (Model model) =
model.selectedFile
|> Maybe.map (\file ->
Http.post
{ url = url
, body = Http.fileBody file
, expect = Http.expectString ReceivedRequest
}
)
|> Maybe.withDefault Cmd.none
multipartRequest url (Model model) =
model.selectedFile
|> Maybe.map (\file ->
Http.post
{ url = url
, body = Http.multipartBody
[ Http.stringPart "username" "someone-cool"
, Http.filePart "fun-image" file
, Http.bytesPart "fun-bytes" "image/png" <| Bytes.encode <| Bytes.string "This is binary stuff!"
]
, expect = Http.expectString ReceivedRequest
}
)
|> Maybe.withDefault Cmd.none
testSubject requests =
Setup.initWithModel (defaultModel requests)
|> Setup.withView testView
|> Setup.withUpdate testUpdate
type Model =
Model
{ requests: List (Model -> Cmd Msg)
, selectedFile: Maybe File
}
defaultModel requests =
Model
{ requests = requests
, selectedFile = Nothing
}
type Msg
= SendRequest
| SelectFile
| GotFile File
| ReceivedRequest (Result Http.Error String)
testUpdate : Msg -> Model -> (Model, Cmd Msg)
testUpdate msg (Model model) =
case msg of
SelectFile ->
( Model model, File.Select.file [] GotFile )
GotFile file ->
( Model { model | selectedFile = Just file }, Cmd.none )
SendRequest ->
case model.requests of
[] ->
( Model model, Cmd.none )
next :: requests ->
( Model { model | requests = requests }
, next <| Model model
)
ReceivedRequest _ ->
( Model model, Cmd.none )
testView : Model -> Html Msg
testView model =
Html.div []
[ Html.button [ Attr.id "request-button", Events.onClick SendRequest ] [ Html.text "Send Next Request!" ]
, Html.button [ Attr.id "select-file", Events.onClick SelectFile ] [ Html.text "Select file!" ]
]
selectSpec : String -> Maybe (Spec Model Msg)
selectSpec name =
case name of
"logRequests" -> Just httpRequestLogSpec
"logBytesRequest" -> Just logBytesRequestSpec
"logFileRequest" -> Just logFileRequestSpec
"logMultipartRequest" -> Just logMultipartRequestSpec
_ -> Nothing
main =
Runner.browserProgram selectSpec | true | module Specs.HttpLogSpec exposing (main)
import Spec exposing (..)
import Spec.Setup as Setup
import Spec.Markup as Markup
import Spec.Markup.Selector exposing (..)
import Spec.Markup.Event as Event
import Spec.Claim exposing (..)
import Spec.Http
import Spec.Http.Route exposing (..)
import Spec.File
import Html exposing (Html)
import Html.Attributes as Attr
import Html.Events as Events
import Http
import Bytes.Encode as Bytes
import File exposing (File)
import File.Select
import Json.Encode as Encode
import Runner
httpRequestLogSpec : Spec Model Msg
httpRequestLogSpec =
Spec.describe "logRequests"
[ scenario "there are requests" (
given (
testSubject
[ getRequest "http://fun.com/fun/1" [ Http.header "Content-Type" "text/plain;charset=utf-8", Http.header "X-Fun-Header" "my-header" ]
, getRequest "http://awesome.com/awesome?name=cool" [ Http.header "Content-Type" "text/plain;charset=utf-8" ]
, postRequest "http://super.com/super"
]
)
|> when "requests are sent"
[ Spec.Http.logRequests
, Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
, Event.click
, Spec.Http.logRequests
, Event.click
, Spec.Http.logRequests
]
|> observeThat
[ it "makes the GET requests" (
Spec.Http.observeRequests (route "GET" <| Matching ".+")
|> expect (isListWithLength 2)
)
, it "makes the POST requests" (
Spec.Http.observeRequests (route "POST" <| Matching ".+")
|> expect (isListWithLength 1)
)
]
)
]
logBytesRequestSpec : Spec Model Msg
logBytesRequestSpec =
describe "log an HTTP request with bytes body"
[ scenario "the request is logged" (
given (
testSubject
[ bytesRequest "http://fun.com/bytes" <| Bytes.encode <| Bytes.string "This is binary stuff!"
]
)
|> when "requests are sent"
[ Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
]
|> it "makes the POST requests" (
Spec.Http.observeRequests (route "POST" <| Matching ".+")
|> expect (isListWithLength 1)
)
)
]
logFileRequestSpec : Spec Model Msg
logFileRequestSpec =
describe "log an HTTP request with file body"
[ scenario "the request is logged" (
given (
testSubject
[ fileRequest "http://fun.com/files"
]
)
|> when "a file is selected"
[ Markup.target << by [ id "select-file" ]
, Event.click
, Spec.File.select
[ Spec.File.withText "/some/path/to/my-test-file.txt" "some super cool content"
|> Spec.File.withMimeType "text/plain"
]
]
|> when "requests are sent"
[ Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
]
|> it "makes the POST requests" (
Spec.Http.observeRequests (route "POST" <| Matching ".+")
|> expect (isListWithLength 1)
)
)
]
logMultipartRequestSpec : Spec Model Msg
logMultipartRequestSpec =
describe "log a multipart HTTP request"
[ scenario "a multipart request" (
given (
testSubject [ multipartRequest "http://place.com/api/request" ]
)
|> when "a file is selected"
[ Markup.target << by [ id "select-file" ]
, Event.click
, Spec.File.select
[ Spec.File.withText "/some/path/to/my-awesome-image.png" "some image data"
|> Spec.File.withMimeType "image/png"
]
]
|> when "requests are sent"
[ Markup.target << by [ id "request-button" ]
, Event.click
, Spec.Http.logRequests
]
|> it "makes the POST request" (
Spec.Http.observeRequests (post "http://place.com/api/request")
|> expect (isListWithLength 1)
)
)
]
getRequest url headers _ =
Http.request
{ method = "GET"
, headers = headers
, url = url
, body = Http.emptyBody
, expect = Http.expectString ReceivedRequest
, timeout = Nothing
, tracker = Nothing
}
postRequest url _ =
Http.request
{ method = "POST"
, headers =
[ Http.header "Content-Type" "text/plain;charset=utf-8"
, Http.header "X-Fun-Header" "my-header"
, Http.header "X-Super-Header" "super"
]
, url = url
, body = Http.jsonBody <| Encode.object [ ("name", Encode.string "PI:NAME:<NAME>END_PI Dude"), ( "count", Encode.int 27) ]
, expect = Http.expectString ReceivedRequest
, timeout = Nothing
, tracker = Nothing
}
bytesRequest url bytes _ =
Http.post
{ url = url
, body = Http.bytesBody "application/octet-stream" bytes
, expect = Http.expectString ReceivedRequest
}
fileRequest url (Model model) =
model.selectedFile
|> Maybe.map (\file ->
Http.post
{ url = url
, body = Http.fileBody file
, expect = Http.expectString ReceivedRequest
}
)
|> Maybe.withDefault Cmd.none
multipartRequest url (Model model) =
model.selectedFile
|> Maybe.map (\file ->
Http.post
{ url = url
, body = Http.multipartBody
[ Http.stringPart "username" "someone-cool"
, Http.filePart "fun-image" file
, Http.bytesPart "fun-bytes" "image/png" <| Bytes.encode <| Bytes.string "This is binary stuff!"
]
, expect = Http.expectString ReceivedRequest
}
)
|> Maybe.withDefault Cmd.none
testSubject requests =
Setup.initWithModel (defaultModel requests)
|> Setup.withView testView
|> Setup.withUpdate testUpdate
type Model =
Model
{ requests: List (Model -> Cmd Msg)
, selectedFile: Maybe File
}
defaultModel requests =
Model
{ requests = requests
, selectedFile = Nothing
}
type Msg
= SendRequest
| SelectFile
| GotFile File
| ReceivedRequest (Result Http.Error String)
testUpdate : Msg -> Model -> (Model, Cmd Msg)
testUpdate msg (Model model) =
case msg of
SelectFile ->
( Model model, File.Select.file [] GotFile )
GotFile file ->
( Model { model | selectedFile = Just file }, Cmd.none )
SendRequest ->
case model.requests of
[] ->
( Model model, Cmd.none )
next :: requests ->
( Model { model | requests = requests }
, next <| Model model
)
ReceivedRequest _ ->
( Model model, Cmd.none )
testView : Model -> Html Msg
testView model =
Html.div []
[ Html.button [ Attr.id "request-button", Events.onClick SendRequest ] [ Html.text "Send Next Request!" ]
, Html.button [ Attr.id "select-file", Events.onClick SelectFile ] [ Html.text "Select file!" ]
]
selectSpec : String -> Maybe (Spec Model Msg)
selectSpec name =
case name of
"logRequests" -> Just httpRequestLogSpec
"logBytesRequest" -> Just logBytesRequestSpec
"logFileRequest" -> Just logFileRequestSpec
"logMultipartRequest" -> Just logMultipartRequestSpec
_ -> Nothing
main =
Runner.browserProgram selectSpec | elm |
[
{
"context": "icksADay\n@docs ticksAWeek\n\nCopyright (c) 2016-2018 Robin Luiten\n\n-}\n\nimport Date exposing (Date, Day(..), Month(.",
"end": 1437,
"score": 0.9998526573,
"start": 1425,
"tag": "NAME",
"value": "Robin Luiten"
}
] | src/Date/Extra/Core.elm | AdrianRibao/elm-date-extra | 81 | module Date.Extra.Core
exposing
( daysInMonth
, daysInNextMonth
, daysInPrevMonth
, daysInMonthDate
, daysBackToStartOfWeek
, epochDateStr
, firstOfNextMonthDate
, fromTime
, intToMonth
, isLeapYear
, isLeapYearDate
, isoDayOfWeek
, lastOfMonthDate
, lastOfPrevMonthDate
, monthList
, monthToInt
, nextDay
, nextMonth
, prevDay
, prevMonth
, ticksAnHour
, ticksADay
, ticksAMillisecond
, ticksAMinute
, ticksASecond
, ticksAWeek
, toFirstOfMonth
, toTime
, yearToDayLength
)
{-| Date core.
## Info
@docs monthToInt
@docs intToMonth
@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-2018 Robin Luiten
-}
import Date exposing (Date, Day(..), Month(..))
import Time
import Date.Extra.Internal as Internal
import Date.Extra.Internal2 as Internal2
import Date.Extra.Period as Period
{-| Return days in month for year month.
-}
daysInMonth : Int -> Month -> Int
daysInMonth =
Internal2.daysInMonth
{-| Return days in next calendar month.
-}
daysInNextMonth : Date -> Int
daysInNextMonth =
Internal2.daysInNextMonth
{-| Return days in next calendar month.
-}
daysInPrevMonth : Date -> Int
daysInPrevMonth =
Internal2.daysInPrevMonth
{-| Days in month for given date.
-}
daysInMonthDate : Date -> Int
daysInMonthDate =
Internal2.daysInMonthDate
{-| Epoch starting point for tick 0.
-}
epochDateStr : String
epochDateStr =
Internal2.epochDateStr
{-| Convenience fromTime as time ticks are Elm Ints in this library.
-}
fromTime : Int -> Date
fromTime =
Internal2.fromTime
{-| Return integer as month. Jan <= 1 Feb == 2 up to Dec > 11.
-}
intToMonth : Int -> Month
intToMonth =
Internal2.intToMonth
{-| Return True if Year is a leap year.
-}
isLeapYear : Int -> Bool
isLeapYear =
Internal2.isLeapYear
{-| Return True if Year of Date is a leap year.
-}
isLeapYearDate : Date -> Bool
isLeapYearDate =
Internal2.isLeapYearDate
{-| Return the Iso DayOfWeek Monday 1, to Sunday 7.
-}
isoDayOfWeek : Date.Day -> Int
isoDayOfWeek =
Internal2.isoDayOfWeek
{-| List of months in order from Jan to Dec.
-}
monthList : List Month
monthList =
Internal2.monthList
{-| Return month as integer. Jan = 1 to Dec = 12.
-}
monthToInt : Month -> Int
monthToInt =
Internal2.monthToInt
{-| Return next day in calendar sequence.
-}
nextDay : Day -> Day
nextDay =
Internal2.nextDay
{-| Return next month in calendar sequence.
-}
nextMonth : Month -> Month
nextMonth =
Internal2.nextMonth
{-| Return previous day in calendar sequence.
-}
prevDay : Day -> Day
prevDay =
Internal2.prevDay
{-| Return previous month in calendar sequence.
-}
prevMonth : Month -> Month
prevMonth =
Internal2.prevMonth
{-| Ticks in an hour.
-}
ticksAnHour : Int
ticksAnHour =
Internal2.ticksAnHour
{-| Ticks in a day.
-}
ticksADay : Int
ticksADay =
Internal2.ticksADay
{-| Ticks in a millisecond. (this is 1 on Win 7 in Chrome)
-}
ticksAMillisecond : Int
ticksAMillisecond =
Internal2.ticksAMillisecond
{-| Ticks in a minute.
-}
ticksAMinute : Int
ticksAMinute =
Internal2.ticksAMinute
{-| Ticks in a second.
-}
ticksASecond : Int
ticksASecond =
Internal2.ticksASecond
{-| Ticks in a week.
-}
ticksAWeek : Int
ticksAWeek =
Internal2.ticksAWeek
{-| Convenience toTime as time ticks are Elm Ints in this library.
-}
toTime : Date -> Int
toTime =
Internal2.toTime
{-| Return number of days in a year.
-}
yearToDayLength : Int -> Int
yearToDayLength =
Internal2.yearToDayLength
{-| Return first of next month date.
-}
firstOfNextMonthDate : Date -> Date
firstOfNextMonthDate date =
compensateZoneOffset
date
(Internal2.firstOfNextMonthDate date)
{-| Return last of previous month date.
-}
lastOfPrevMonthDate : Date -> Date
lastOfPrevMonthDate date =
compensateZoneOffset
date
(Internal2.lastOfPrevMonthDate date)
{-| Return date of first day of month.
-}
toFirstOfMonth : Date -> Date
toFirstOfMonth date =
compensateZoneOffset
date
(Internal2.fromTime (Internal2.firstOfMonthTicks date))
{-| Return date of last day of month.
-}
lastOfMonthDate : Date -> Date
lastOfMonthDate date =
compensateZoneOffset
date
(Internal2.fromTime (Internal2.lastOfMonthTicks date))
{-| Adjust value of date2 compensating for a time zone offset difference
between date1 and date2. This is used for cases where date2 is created based
on date1 but crosses day light saving boundary.
-}
compensateZoneOffset date1 date2 =
Period.add
Period.Minute
((Internal.getTimezoneOffset date2)
- (Internal.getTimezoneOffset date1)
)
date2
{-| Return number of days back to start of week day.
First parameter Date.day - is current day of week.
Second parameter Date.day - is start day of week.
-}
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
| 2804 | module Date.Extra.Core
exposing
( daysInMonth
, daysInNextMonth
, daysInPrevMonth
, daysInMonthDate
, daysBackToStartOfWeek
, epochDateStr
, firstOfNextMonthDate
, fromTime
, intToMonth
, isLeapYear
, isLeapYearDate
, isoDayOfWeek
, lastOfMonthDate
, lastOfPrevMonthDate
, monthList
, monthToInt
, nextDay
, nextMonth
, prevDay
, prevMonth
, ticksAnHour
, ticksADay
, ticksAMillisecond
, ticksAMinute
, ticksASecond
, ticksAWeek
, toFirstOfMonth
, toTime
, yearToDayLength
)
{-| Date core.
## Info
@docs monthToInt
@docs intToMonth
@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-2018 <NAME>
-}
import Date exposing (Date, Day(..), Month(..))
import Time
import Date.Extra.Internal as Internal
import Date.Extra.Internal2 as Internal2
import Date.Extra.Period as Period
{-| Return days in month for year month.
-}
daysInMonth : Int -> Month -> Int
daysInMonth =
Internal2.daysInMonth
{-| Return days in next calendar month.
-}
daysInNextMonth : Date -> Int
daysInNextMonth =
Internal2.daysInNextMonth
{-| Return days in next calendar month.
-}
daysInPrevMonth : Date -> Int
daysInPrevMonth =
Internal2.daysInPrevMonth
{-| Days in month for given date.
-}
daysInMonthDate : Date -> Int
daysInMonthDate =
Internal2.daysInMonthDate
{-| Epoch starting point for tick 0.
-}
epochDateStr : String
epochDateStr =
Internal2.epochDateStr
{-| Convenience fromTime as time ticks are Elm Ints in this library.
-}
fromTime : Int -> Date
fromTime =
Internal2.fromTime
{-| Return integer as month. Jan <= 1 Feb == 2 up to Dec > 11.
-}
intToMonth : Int -> Month
intToMonth =
Internal2.intToMonth
{-| Return True if Year is a leap year.
-}
isLeapYear : Int -> Bool
isLeapYear =
Internal2.isLeapYear
{-| Return True if Year of Date is a leap year.
-}
isLeapYearDate : Date -> Bool
isLeapYearDate =
Internal2.isLeapYearDate
{-| Return the Iso DayOfWeek Monday 1, to Sunday 7.
-}
isoDayOfWeek : Date.Day -> Int
isoDayOfWeek =
Internal2.isoDayOfWeek
{-| List of months in order from Jan to Dec.
-}
monthList : List Month
monthList =
Internal2.monthList
{-| Return month as integer. Jan = 1 to Dec = 12.
-}
monthToInt : Month -> Int
monthToInt =
Internal2.monthToInt
{-| Return next day in calendar sequence.
-}
nextDay : Day -> Day
nextDay =
Internal2.nextDay
{-| Return next month in calendar sequence.
-}
nextMonth : Month -> Month
nextMonth =
Internal2.nextMonth
{-| Return previous day in calendar sequence.
-}
prevDay : Day -> Day
prevDay =
Internal2.prevDay
{-| Return previous month in calendar sequence.
-}
prevMonth : Month -> Month
prevMonth =
Internal2.prevMonth
{-| Ticks in an hour.
-}
ticksAnHour : Int
ticksAnHour =
Internal2.ticksAnHour
{-| Ticks in a day.
-}
ticksADay : Int
ticksADay =
Internal2.ticksADay
{-| Ticks in a millisecond. (this is 1 on Win 7 in Chrome)
-}
ticksAMillisecond : Int
ticksAMillisecond =
Internal2.ticksAMillisecond
{-| Ticks in a minute.
-}
ticksAMinute : Int
ticksAMinute =
Internal2.ticksAMinute
{-| Ticks in a second.
-}
ticksASecond : Int
ticksASecond =
Internal2.ticksASecond
{-| Ticks in a week.
-}
ticksAWeek : Int
ticksAWeek =
Internal2.ticksAWeek
{-| Convenience toTime as time ticks are Elm Ints in this library.
-}
toTime : Date -> Int
toTime =
Internal2.toTime
{-| Return number of days in a year.
-}
yearToDayLength : Int -> Int
yearToDayLength =
Internal2.yearToDayLength
{-| Return first of next month date.
-}
firstOfNextMonthDate : Date -> Date
firstOfNextMonthDate date =
compensateZoneOffset
date
(Internal2.firstOfNextMonthDate date)
{-| Return last of previous month date.
-}
lastOfPrevMonthDate : Date -> Date
lastOfPrevMonthDate date =
compensateZoneOffset
date
(Internal2.lastOfPrevMonthDate date)
{-| Return date of first day of month.
-}
toFirstOfMonth : Date -> Date
toFirstOfMonth date =
compensateZoneOffset
date
(Internal2.fromTime (Internal2.firstOfMonthTicks date))
{-| Return date of last day of month.
-}
lastOfMonthDate : Date -> Date
lastOfMonthDate date =
compensateZoneOffset
date
(Internal2.fromTime (Internal2.lastOfMonthTicks date))
{-| Adjust value of date2 compensating for a time zone offset difference
between date1 and date2. This is used for cases where date2 is created based
on date1 but crosses day light saving boundary.
-}
compensateZoneOffset date1 date2 =
Period.add
Period.Minute
((Internal.getTimezoneOffset date2)
- (Internal.getTimezoneOffset date1)
)
date2
{-| Return number of days back to start of week day.
First parameter Date.day - is current day of week.
Second parameter Date.day - is start day of week.
-}
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.Extra.Core
exposing
( daysInMonth
, daysInNextMonth
, daysInPrevMonth
, daysInMonthDate
, daysBackToStartOfWeek
, epochDateStr
, firstOfNextMonthDate
, fromTime
, intToMonth
, isLeapYear
, isLeapYearDate
, isoDayOfWeek
, lastOfMonthDate
, lastOfPrevMonthDate
, monthList
, monthToInt
, nextDay
, nextMonth
, prevDay
, prevMonth
, ticksAnHour
, ticksADay
, ticksAMillisecond
, ticksAMinute
, ticksASecond
, ticksAWeek
, toFirstOfMonth
, toTime
, yearToDayLength
)
{-| Date core.
## Info
@docs monthToInt
@docs intToMonth
@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-2018 PI:NAME:<NAME>END_PI
-}
import Date exposing (Date, Day(..), Month(..))
import Time
import Date.Extra.Internal as Internal
import Date.Extra.Internal2 as Internal2
import Date.Extra.Period as Period
{-| Return days in month for year month.
-}
daysInMonth : Int -> Month -> Int
daysInMonth =
Internal2.daysInMonth
{-| Return days in next calendar month.
-}
daysInNextMonth : Date -> Int
daysInNextMonth =
Internal2.daysInNextMonth
{-| Return days in next calendar month.
-}
daysInPrevMonth : Date -> Int
daysInPrevMonth =
Internal2.daysInPrevMonth
{-| Days in month for given date.
-}
daysInMonthDate : Date -> Int
daysInMonthDate =
Internal2.daysInMonthDate
{-| Epoch starting point for tick 0.
-}
epochDateStr : String
epochDateStr =
Internal2.epochDateStr
{-| Convenience fromTime as time ticks are Elm Ints in this library.
-}
fromTime : Int -> Date
fromTime =
Internal2.fromTime
{-| Return integer as month. Jan <= 1 Feb == 2 up to Dec > 11.
-}
intToMonth : Int -> Month
intToMonth =
Internal2.intToMonth
{-| Return True if Year is a leap year.
-}
isLeapYear : Int -> Bool
isLeapYear =
Internal2.isLeapYear
{-| Return True if Year of Date is a leap year.
-}
isLeapYearDate : Date -> Bool
isLeapYearDate =
Internal2.isLeapYearDate
{-| Return the Iso DayOfWeek Monday 1, to Sunday 7.
-}
isoDayOfWeek : Date.Day -> Int
isoDayOfWeek =
Internal2.isoDayOfWeek
{-| List of months in order from Jan to Dec.
-}
monthList : List Month
monthList =
Internal2.monthList
{-| Return month as integer. Jan = 1 to Dec = 12.
-}
monthToInt : Month -> Int
monthToInt =
Internal2.monthToInt
{-| Return next day in calendar sequence.
-}
nextDay : Day -> Day
nextDay =
Internal2.nextDay
{-| Return next month in calendar sequence.
-}
nextMonth : Month -> Month
nextMonth =
Internal2.nextMonth
{-| Return previous day in calendar sequence.
-}
prevDay : Day -> Day
prevDay =
Internal2.prevDay
{-| Return previous month in calendar sequence.
-}
prevMonth : Month -> Month
prevMonth =
Internal2.prevMonth
{-| Ticks in an hour.
-}
ticksAnHour : Int
ticksAnHour =
Internal2.ticksAnHour
{-| Ticks in a day.
-}
ticksADay : Int
ticksADay =
Internal2.ticksADay
{-| Ticks in a millisecond. (this is 1 on Win 7 in Chrome)
-}
ticksAMillisecond : Int
ticksAMillisecond =
Internal2.ticksAMillisecond
{-| Ticks in a minute.
-}
ticksAMinute : Int
ticksAMinute =
Internal2.ticksAMinute
{-| Ticks in a second.
-}
ticksASecond : Int
ticksASecond =
Internal2.ticksASecond
{-| Ticks in a week.
-}
ticksAWeek : Int
ticksAWeek =
Internal2.ticksAWeek
{-| Convenience toTime as time ticks are Elm Ints in this library.
-}
toTime : Date -> Int
toTime =
Internal2.toTime
{-| Return number of days in a year.
-}
yearToDayLength : Int -> Int
yearToDayLength =
Internal2.yearToDayLength
{-| Return first of next month date.
-}
firstOfNextMonthDate : Date -> Date
firstOfNextMonthDate date =
compensateZoneOffset
date
(Internal2.firstOfNextMonthDate date)
{-| Return last of previous month date.
-}
lastOfPrevMonthDate : Date -> Date
lastOfPrevMonthDate date =
compensateZoneOffset
date
(Internal2.lastOfPrevMonthDate date)
{-| Return date of first day of month.
-}
toFirstOfMonth : Date -> Date
toFirstOfMonth date =
compensateZoneOffset
date
(Internal2.fromTime (Internal2.firstOfMonthTicks date))
{-| Return date of last day of month.
-}
lastOfMonthDate : Date -> Date
lastOfMonthDate date =
compensateZoneOffset
date
(Internal2.fromTime (Internal2.lastOfMonthTicks date))
{-| Adjust value of date2 compensating for a time zone offset difference
between date1 and date2. This is used for cases where date2 is created based
on date1 but crosses day light saving boundary.
-}
compensateZoneOffset date1 date2 =
Period.add
Period.Minute
((Internal.getTimezoneOffset date2)
- (Internal.getTimezoneOffset date1)
)
date2
{-| Return number of days back to start of week day.
First parameter Date.day - is current day of week.
Second parameter Date.day - is start day of week.
-}
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": "{- Copyright (C) 2018 Mark D. Blackwell.\n All rights reserved.\n This program is distr",
"end": 39,
"score": 0.9998527765,
"start": 22,
"tag": "NAME",
"value": "Mark D. Blackwell"
}
] | src/front-end/update/LogUpdate.elm | MarkDBlackwell/qplaylist-remember | 0 | {- Copyright (C) 2018 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 LogUpdate exposing
( cmdLogDecoding
, cmdLogRequest
, cmdLogResponse
)
import Debug
import ElmCycle
import RequestUpdateType
exposing
( Action(..)
)
-- UPDATE
cmdLogAction : Action -> Maybe String -> Cmd ElmCycle.Msg
cmdLogAction action textMaybe =
let
keepForConsoleLogging : String
keepForConsoleLogging =
let
actionString : String
actionString =
case action of
ActionDecoding ->
"Decoding"
ActionRequest ->
"Request"
ActionResponse ->
"Response"
text : String
text =
textMaybe
|> Maybe.withDefault "Ok"
in
--Use Debug.log during development:
--text
-- |> Debug.log actionString
text
in
Cmd.none
cmdLogDecoding : Maybe String -> Cmd ElmCycle.Msg
cmdLogDecoding textMaybe =
textMaybe
|> cmdLogAction ActionDecoding
cmdLogRequest : String -> Cmd ElmCycle.Msg
cmdLogRequest text =
Just text
|> cmdLogAction ActionRequest
cmdLogResponse : Maybe String -> Cmd ElmCycle.Msg
cmdLogResponse textMaybe =
textMaybe
|> cmdLogAction ActionResponse
| 50901 | {- Copyright (C) 2018 <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 LogUpdate exposing
( cmdLogDecoding
, cmdLogRequest
, cmdLogResponse
)
import Debug
import ElmCycle
import RequestUpdateType
exposing
( Action(..)
)
-- UPDATE
cmdLogAction : Action -> Maybe String -> Cmd ElmCycle.Msg
cmdLogAction action textMaybe =
let
keepForConsoleLogging : String
keepForConsoleLogging =
let
actionString : String
actionString =
case action of
ActionDecoding ->
"Decoding"
ActionRequest ->
"Request"
ActionResponse ->
"Response"
text : String
text =
textMaybe
|> Maybe.withDefault "Ok"
in
--Use Debug.log during development:
--text
-- |> Debug.log actionString
text
in
Cmd.none
cmdLogDecoding : Maybe String -> Cmd ElmCycle.Msg
cmdLogDecoding textMaybe =
textMaybe
|> cmdLogAction ActionDecoding
cmdLogRequest : String -> Cmd ElmCycle.Msg
cmdLogRequest text =
Just text
|> cmdLogAction ActionRequest
cmdLogResponse : Maybe String -> Cmd ElmCycle.Msg
cmdLogResponse textMaybe =
textMaybe
|> cmdLogAction ActionResponse
| true | {- Copyright (C) 2018 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 LogUpdate exposing
( cmdLogDecoding
, cmdLogRequest
, cmdLogResponse
)
import Debug
import ElmCycle
import RequestUpdateType
exposing
( Action(..)
)
-- UPDATE
cmdLogAction : Action -> Maybe String -> Cmd ElmCycle.Msg
cmdLogAction action textMaybe =
let
keepForConsoleLogging : String
keepForConsoleLogging =
let
actionString : String
actionString =
case action of
ActionDecoding ->
"Decoding"
ActionRequest ->
"Request"
ActionResponse ->
"Response"
text : String
text =
textMaybe
|> Maybe.withDefault "Ok"
in
--Use Debug.log during development:
--text
-- |> Debug.log actionString
text
in
Cmd.none
cmdLogDecoding : Maybe String -> Cmd ElmCycle.Msg
cmdLogDecoding textMaybe =
textMaybe
|> cmdLogAction ActionDecoding
cmdLogRequest : String -> Cmd ElmCycle.Msg
cmdLogRequest text =
Just text
|> cmdLogAction ActionRequest
cmdLogResponse : Maybe String -> Cmd ElmCycle.Msg
cmdLogResponse textMaybe =
textMaybe
|> cmdLogAction ActionResponse
| elm |
[
{
"context": "\"\n |> withBearerToken \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYSJ9.MvhYYpYBuN1rUaV0GGnQGvr889zY0xSc20Lnt8nMTfE\"\n |> withHeader \"Test\"",
"end": 1294,
"score": 0.9997428656,
"start": 1201,
"tag": "KEY",
"value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYSJ9.MvhYYpYBuN1rUaV0GGnQGvr889zY0xSc20Lnt8nMTfE"
},
{
"context": " , Http.header \"Authorization\" \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYSJ9",
"end": 2458,
"score": 0.9982279539,
"start": 2452,
"tag": "KEY",
"value": "Bearer"
},
{
"context": " , Http.header \"Authorization\" \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYSJ9.MvhYYpYBuN1rUaV0GGnQGvr889zY0xSc20Lnt8nMTfE\"\n ]\n ",
"end": 2552,
"score": 0.9945585728,
"start": 2459,
"tag": "KEY",
"value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYSJ9.MvhYYpYBuN1rUaV0GGnQGvr889zY0xSc20Lnt8nMTfE"
}
] | part10/elm-stuff/packages/lukewestby/elm-http-builder/5.2.0/tests/Tests.elm | rtfeldman/elm-0.18-workshop | 11 | module Tests exposing (..)
import Time
import Http exposing (Request)
import Json.Decode as Decode
import Json.Encode as Encode
import Test exposing (Test, test, describe)
import Expect
import HttpBuilder exposing (..)
import Native.Polyfills
polyfillsEnabled : Bool
polyfillsEnabled =
Native.Polyfills.enabled
testDecoder : Decode.Decoder String
testDecoder =
Decode.at [ "hello" ] Decode.string
alwaysEmptyOk : a -> Result x ()
alwaysEmptyOk _ =
Ok ()
expectNothing : Http.Expect ()
expectNothing =
Http.expectStringResponse alwaysEmptyOk
defaultBuilder : RequestBuilder ()
defaultBuilder =
{ method = "POST"
, url = "example.com"
, expect = expectNothing
, timeout = Nothing
, withCredentials = False
, headers = []
, body = Http.emptyBody
, queryParams = []
, cacheBuster = Nothing
}
all : Test
all =
describe "HttpBuilder"
[ test "polyfills are set up" <|
\() -> polyfillsEnabled |> Expect.equal True
, test "Request Building" <|
\() ->
let
actual =
get "http://example.com"
|> withBearerToken "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYSJ9.MvhYYpYBuN1rUaV0GGnQGvr889zY0xSc20Lnt8nMTfE"
|> withHeader "Test" "Header"
|> withHeaders [ ( "OtherTest", "Header" ) ]
|> withStringBody "text/plain" """{ "test": "body" }"""
|> withTimeout (10 * Time.second)
|> withCredentials
|> withQueryParams [ ( "hello", "world" ) ]
|> withCacheBuster "cb"
|> withExpect expectNothing
expected =
{ method = "GET"
, url = "http://example.com"
, queryParams = [ ( "hello", "world" ) ]
, body = Http.stringBody "text/plain" """{ "test": "body" }"""
, timeout = Just (10 * Time.second)
, expect = expectNothing
, withCredentials = True
, headers =
[ Http.header "OtherTest" "Header"
, Http.header "Test" "Header"
, Http.header "Authorization" "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYSJ9.MvhYYpYBuN1rUaV0GGnQGvr889zY0xSc20Lnt8nMTfE"
]
, cacheBuster = Just "cb"
}
in
Expect.equal expected actual
, describe "with*Body functions"
[ test "withStringBody applies string directly" <|
\() ->
post "example.com"
|> withStringBody "text/plain" "hello"
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.stringBody "text/plain" "hello" }
, test "withJsonBody applies a Json.Value as a string" <|
\() ->
post "example.com"
|> withJsonBody (Encode.string "hello")
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.jsonBody (Encode.string "hello") }
, test "withUrlEncodedBody encodes pairs as url components" <|
\() ->
post "example.com"
|> withUrlEncodedBody [ ( "hello", "w orld" ) ]
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.stringBody "application/x-www-form-urlencoded" "hello=w+orld" }
, test "withMultipartStringBody passes through to Http.multipart" <|
\() ->
post "example.com"
|> withMultipartStringBody [ ( "hello", "world" ) ]
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.multipartBody [ Http.stringPart "hello" "world" ] }
]
]
| 1975 | module Tests exposing (..)
import Time
import Http exposing (Request)
import Json.Decode as Decode
import Json.Encode as Encode
import Test exposing (Test, test, describe)
import Expect
import HttpBuilder exposing (..)
import Native.Polyfills
polyfillsEnabled : Bool
polyfillsEnabled =
Native.Polyfills.enabled
testDecoder : Decode.Decoder String
testDecoder =
Decode.at [ "hello" ] Decode.string
alwaysEmptyOk : a -> Result x ()
alwaysEmptyOk _ =
Ok ()
expectNothing : Http.Expect ()
expectNothing =
Http.expectStringResponse alwaysEmptyOk
defaultBuilder : RequestBuilder ()
defaultBuilder =
{ method = "POST"
, url = "example.com"
, expect = expectNothing
, timeout = Nothing
, withCredentials = False
, headers = []
, body = Http.emptyBody
, queryParams = []
, cacheBuster = Nothing
}
all : Test
all =
describe "HttpBuilder"
[ test "polyfills are set up" <|
\() -> polyfillsEnabled |> Expect.equal True
, test "Request Building" <|
\() ->
let
actual =
get "http://example.com"
|> withBearerToken "<KEY>"
|> withHeader "Test" "Header"
|> withHeaders [ ( "OtherTest", "Header" ) ]
|> withStringBody "text/plain" """{ "test": "body" }"""
|> withTimeout (10 * Time.second)
|> withCredentials
|> withQueryParams [ ( "hello", "world" ) ]
|> withCacheBuster "cb"
|> withExpect expectNothing
expected =
{ method = "GET"
, url = "http://example.com"
, queryParams = [ ( "hello", "world" ) ]
, body = Http.stringBody "text/plain" """{ "test": "body" }"""
, timeout = Just (10 * Time.second)
, expect = expectNothing
, withCredentials = True
, headers =
[ Http.header "OtherTest" "Header"
, Http.header "Test" "Header"
, Http.header "Authorization" "<KEY> <KEY>"
]
, cacheBuster = Just "cb"
}
in
Expect.equal expected actual
, describe "with*Body functions"
[ test "withStringBody applies string directly" <|
\() ->
post "example.com"
|> withStringBody "text/plain" "hello"
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.stringBody "text/plain" "hello" }
, test "withJsonBody applies a Json.Value as a string" <|
\() ->
post "example.com"
|> withJsonBody (Encode.string "hello")
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.jsonBody (Encode.string "hello") }
, test "withUrlEncodedBody encodes pairs as url components" <|
\() ->
post "example.com"
|> withUrlEncodedBody [ ( "hello", "w orld" ) ]
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.stringBody "application/x-www-form-urlencoded" "hello=w+orld" }
, test "withMultipartStringBody passes through to Http.multipart" <|
\() ->
post "example.com"
|> withMultipartStringBody [ ( "hello", "world" ) ]
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.multipartBody [ Http.stringPart "hello" "world" ] }
]
]
| true | module Tests exposing (..)
import Time
import Http exposing (Request)
import Json.Decode as Decode
import Json.Encode as Encode
import Test exposing (Test, test, describe)
import Expect
import HttpBuilder exposing (..)
import Native.Polyfills
polyfillsEnabled : Bool
polyfillsEnabled =
Native.Polyfills.enabled
testDecoder : Decode.Decoder String
testDecoder =
Decode.at [ "hello" ] Decode.string
alwaysEmptyOk : a -> Result x ()
alwaysEmptyOk _ =
Ok ()
expectNothing : Http.Expect ()
expectNothing =
Http.expectStringResponse alwaysEmptyOk
defaultBuilder : RequestBuilder ()
defaultBuilder =
{ method = "POST"
, url = "example.com"
, expect = expectNothing
, timeout = Nothing
, withCredentials = False
, headers = []
, body = Http.emptyBody
, queryParams = []
, cacheBuster = Nothing
}
all : Test
all =
describe "HttpBuilder"
[ test "polyfills are set up" <|
\() -> polyfillsEnabled |> Expect.equal True
, test "Request Building" <|
\() ->
let
actual =
get "http://example.com"
|> withBearerToken "PI:KEY:<KEY>END_PI"
|> withHeader "Test" "Header"
|> withHeaders [ ( "OtherTest", "Header" ) ]
|> withStringBody "text/plain" """{ "test": "body" }"""
|> withTimeout (10 * Time.second)
|> withCredentials
|> withQueryParams [ ( "hello", "world" ) ]
|> withCacheBuster "cb"
|> withExpect expectNothing
expected =
{ method = "GET"
, url = "http://example.com"
, queryParams = [ ( "hello", "world" ) ]
, body = Http.stringBody "text/plain" """{ "test": "body" }"""
, timeout = Just (10 * Time.second)
, expect = expectNothing
, withCredentials = True
, headers =
[ Http.header "OtherTest" "Header"
, Http.header "Test" "Header"
, Http.header "Authorization" "PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI"
]
, cacheBuster = Just "cb"
}
in
Expect.equal expected actual
, describe "with*Body functions"
[ test "withStringBody applies string directly" <|
\() ->
post "example.com"
|> withStringBody "text/plain" "hello"
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.stringBody "text/plain" "hello" }
, test "withJsonBody applies a Json.Value as a string" <|
\() ->
post "example.com"
|> withJsonBody (Encode.string "hello")
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.jsonBody (Encode.string "hello") }
, test "withUrlEncodedBody encodes pairs as url components" <|
\() ->
post "example.com"
|> withUrlEncodedBody [ ( "hello", "w orld" ) ]
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.stringBody "application/x-www-form-urlencoded" "hello=w+orld" }
, test "withMultipartStringBody passes through to Http.multipart" <|
\() ->
post "example.com"
|> withMultipartStringBody [ ( "hello", "world" ) ]
|> withExpect expectNothing
|> Expect.equal { defaultBuilder | body = Http.multipartBody [ Http.stringPart "hello" "world" ] }
]
]
| elm |
[
{
"context": "User\n , AnonymousUser\n , NamedUser \"AzureDiamond\"\n , NamedUser \"Mr. Boop\"\n , Anonymo",
"end": 1566,
"score": 0.9995701909,
"start": 1554,
"tag": "USERNAME",
"value": "AzureDiamond"
},
{
"context": " , NamedUser \"AzureDiamond\"\n , NamedUser \"Mr. Boop\"\n , AnonymousUser\n ]\n , count = ",
"end": 1597,
"score": 0.9409556985,
"start": 1589,
"tag": "NAME",
"value": "Mr. Boop"
},
{
"context": "d password ->\n { model | formPassword = password }\n\n FormChangePasswordConfirmation passwor",
"end": 2506,
"score": 0.933681488,
"start": 2498,
"tag": "PASSWORD",
"value": "password"
}
] | examples/00-kitchen-sink.elm | reergymerej/elm-architecture-tutorial | 0 | module Main exposing (..)
import Html
import Html.Attributes
import Html.Events
type alias Model =
{ todoItems : TaskList
, visiblity : Visibility
, users : UserList
, count : Int
, textReverseInput : String
, formName : String
, formPassword : String
, formPasswordConfirmation : String
}
type Msg
= SetVisibilityActive
| SetVisibilityAll
| SetVisibilityComplete
| IncreaseCount
| DecreaseCount
| ResetCount
| ChangeTextReverseInput String
| FormChangeName String
| FormChangePassword String
| FormChangePasswordConfirmation String
main : Program Never Model Msg
main =
Html.beginnerProgram
{ model = model
, view = view
, update = update
}
{-
> our view function is producing a Html Msg value. This means that it is a chunk of HTML that can produce Msg values.
https://guide.elm-lang.org/architecture/user_input/buttons.html
-}
type alias Markup =
Html.Html Msg
type alias Task =
{ task : String
, complete : Bool
}
type Visibility
= All
| Active
| Completed
type alias TaskList =
List Task
type User
= AnonymousUser
| NamedUser String
type alias UserList =
List User
model : Model
model =
{ todoItems =
[ { task = "Buy milk"
, complete = True
}
, { task = "Drink milk"
, complete = False
}
]
, visiblity = All
, users =
[ AnonymousUser
, AnonymousUser
, NamedUser "AzureDiamond"
, NamedUser "Mr. Boop"
, AnonymousUser
]
, count = 0
, textReverseInput = ""
, formName = ""
, formPassword = ""
, formPasswordConfirmation = ""
}
update : Msg -> Model -> Model
update msg model =
case msg of
SetVisibilityAll ->
{ model | visiblity = All }
SetVisibilityActive ->
{ model | visiblity = Active }
SetVisibilityComplete ->
{ model | visiblity = Completed }
IncreaseCount ->
{ model | count = model.count + 1 }
DecreaseCount ->
{ model | count = model.count - 1 }
ResetCount ->
{ model | count = 0 }
ChangeTextReverseInput value ->
{ model | textReverseInput = value }
FormChangeName name ->
{ model | formName = name }
FormChangePassword password ->
{ model | formPassword = password }
FormChangePasswordConfirmation password ->
{ model | formPasswordConfirmation = password }
renderTodoItems : TaskList -> Markup
renderTodoItems list =
Html.ul []
(List.map (\item -> Html.li [] [ Html.text item.task ]) list)
renderTodoVisibilityButton : String -> Msg -> Markup
renderTodoVisibilityButton text message =
Html.button
[ Html.Events.onClick message
]
[ Html.text text ]
renderTodoButtons : Markup
renderTodoButtons =
Html.div []
[ renderTodoVisibilityButton "Show All" SetVisibilityAll
, renderTodoVisibilityButton "Show Active" SetVisibilityActive
, renderTodoVisibilityButton "Show Completed" SetVisibilityComplete
]
filterTodoItems : TaskList -> Visibility -> TaskList
filterTodoItems taskList visibility =
case visibility of
All ->
taskList
Active ->
List.filter (\task -> task.complete == False) taskList
Completed ->
List.filter (\task -> task.complete == True) taskList
renderTodoStuff : Model -> Markup
renderTodoStuff model =
Html.div []
[ renderTodoItems (filterTodoItems model.todoItems model.visiblity)
, renderTodoButtons
]
renderUser : User -> Markup
renderUser user =
case user of
AnonymousUser ->
Html.div [] [ Html.text "Some Dude" ]
NamedUser name ->
Html.div [] [ Html.text name ]
renderUsers : UserList -> Markup
renderUsers users =
Html.div []
(List.map renderUser users)
renderAnonStuff : Model -> Markup
renderAnonStuff model =
Html.div []
[ renderUsers model.users
]
renderTitle : String -> Markup
renderTitle title =
Html.h3 [] [ Html.text title ]
renderClickableButton : Msg -> String -> Markup
renderClickableButton message label =
Html.button [ Html.Events.onClick message ] [ Html.text label ]
renderCounterStuff : Model -> Markup
renderCounterStuff model =
Html.div []
[ Html.div []
[ Html.span [] [ Html.text "count: " ]
, Html.span [] [ Html.text (toString model.count) ]
, Html.div []
[ renderClickableButton DecreaseCount "down"
, renderClickableButton IncreaseCount "up"
, renderClickableButton ResetCount "reset"
]
]
]
reverseString : String -> String
reverseString input =
String.reverse input
renderTextReverseStuff : Model -> Markup
renderTextReverseStuff model =
Html.div []
[ Html.input [ Html.Events.onInput ChangeTextReverseInput ] []
, Html.div [] [ Html.text (reverseString model.textReverseInput) ]
]
renderFormField placeholder onInputMessage =
Html.div []
[ Html.label [] [ Html.text placeholder ]
, Html.input
[ Html.Attributes.placeholder placeholder
, Html.Events.onInput onInputMessage
]
[]
]
passwordsAreOK : String -> String -> Bool
passwordsAreOK a b =
a == b
getPasswordValidationText : Bool -> String
getPasswordValidationText theyMatch =
if theyMatch then
"Good"
else
"Bad"
renderFormValidation : Model -> Markup
renderFormValidation model =
let
( color, message ) =
if passwordsAreOK model.formPassword model.formPasswordConfirmation then
( "green", getPasswordValidationText True )
else
( "red", getPasswordValidationText False )
in
Html.div
[ Html.Attributes.style [ ( "color", color ) ]
]
[ Html.text message ]
renderFormStuff : Model -> Markup
renderFormStuff model =
Html.div []
[ renderFormField "Name" FormChangeName
, renderFormField "Password" FormChangePassword
, renderFormField "Password Confirmation" FormChangePasswordConfirmation
, renderFormValidation model
]
view : Model -> Markup
view model =
Html.div []
[ Html.h1 [] [ Html.text "Kitchen Sink" ]
, Html.div []
[ Html.h2 [] [ Html.text "Union Types" ]
, Html.div []
[ renderTitle "todo list"
, renderTodoStuff model
, renderTitle "anonymous user"
, renderAnonStuff model
, renderTitle "A Simple Counter"
, renderCounterStuff model
, renderTitle "Text Reverse"
, renderTextReverseStuff model
, renderTitle "Form Section"
, renderFormStuff model
]
]
]
| 20472 | module Main exposing (..)
import Html
import Html.Attributes
import Html.Events
type alias Model =
{ todoItems : TaskList
, visiblity : Visibility
, users : UserList
, count : Int
, textReverseInput : String
, formName : String
, formPassword : String
, formPasswordConfirmation : String
}
type Msg
= SetVisibilityActive
| SetVisibilityAll
| SetVisibilityComplete
| IncreaseCount
| DecreaseCount
| ResetCount
| ChangeTextReverseInput String
| FormChangeName String
| FormChangePassword String
| FormChangePasswordConfirmation String
main : Program Never Model Msg
main =
Html.beginnerProgram
{ model = model
, view = view
, update = update
}
{-
> our view function is producing a Html Msg value. This means that it is a chunk of HTML that can produce Msg values.
https://guide.elm-lang.org/architecture/user_input/buttons.html
-}
type alias Markup =
Html.Html Msg
type alias Task =
{ task : String
, complete : Bool
}
type Visibility
= All
| Active
| Completed
type alias TaskList =
List Task
type User
= AnonymousUser
| NamedUser String
type alias UserList =
List User
model : Model
model =
{ todoItems =
[ { task = "Buy milk"
, complete = True
}
, { task = "Drink milk"
, complete = False
}
]
, visiblity = All
, users =
[ AnonymousUser
, AnonymousUser
, NamedUser "AzureDiamond"
, NamedUser "<NAME>"
, AnonymousUser
]
, count = 0
, textReverseInput = ""
, formName = ""
, formPassword = ""
, formPasswordConfirmation = ""
}
update : Msg -> Model -> Model
update msg model =
case msg of
SetVisibilityAll ->
{ model | visiblity = All }
SetVisibilityActive ->
{ model | visiblity = Active }
SetVisibilityComplete ->
{ model | visiblity = Completed }
IncreaseCount ->
{ model | count = model.count + 1 }
DecreaseCount ->
{ model | count = model.count - 1 }
ResetCount ->
{ model | count = 0 }
ChangeTextReverseInput value ->
{ model | textReverseInput = value }
FormChangeName name ->
{ model | formName = name }
FormChangePassword password ->
{ model | formPassword = <PASSWORD> }
FormChangePasswordConfirmation password ->
{ model | formPasswordConfirmation = password }
renderTodoItems : TaskList -> Markup
renderTodoItems list =
Html.ul []
(List.map (\item -> Html.li [] [ Html.text item.task ]) list)
renderTodoVisibilityButton : String -> Msg -> Markup
renderTodoVisibilityButton text message =
Html.button
[ Html.Events.onClick message
]
[ Html.text text ]
renderTodoButtons : Markup
renderTodoButtons =
Html.div []
[ renderTodoVisibilityButton "Show All" SetVisibilityAll
, renderTodoVisibilityButton "Show Active" SetVisibilityActive
, renderTodoVisibilityButton "Show Completed" SetVisibilityComplete
]
filterTodoItems : TaskList -> Visibility -> TaskList
filterTodoItems taskList visibility =
case visibility of
All ->
taskList
Active ->
List.filter (\task -> task.complete == False) taskList
Completed ->
List.filter (\task -> task.complete == True) taskList
renderTodoStuff : Model -> Markup
renderTodoStuff model =
Html.div []
[ renderTodoItems (filterTodoItems model.todoItems model.visiblity)
, renderTodoButtons
]
renderUser : User -> Markup
renderUser user =
case user of
AnonymousUser ->
Html.div [] [ Html.text "Some Dude" ]
NamedUser name ->
Html.div [] [ Html.text name ]
renderUsers : UserList -> Markup
renderUsers users =
Html.div []
(List.map renderUser users)
renderAnonStuff : Model -> Markup
renderAnonStuff model =
Html.div []
[ renderUsers model.users
]
renderTitle : String -> Markup
renderTitle title =
Html.h3 [] [ Html.text title ]
renderClickableButton : Msg -> String -> Markup
renderClickableButton message label =
Html.button [ Html.Events.onClick message ] [ Html.text label ]
renderCounterStuff : Model -> Markup
renderCounterStuff model =
Html.div []
[ Html.div []
[ Html.span [] [ Html.text "count: " ]
, Html.span [] [ Html.text (toString model.count) ]
, Html.div []
[ renderClickableButton DecreaseCount "down"
, renderClickableButton IncreaseCount "up"
, renderClickableButton ResetCount "reset"
]
]
]
reverseString : String -> String
reverseString input =
String.reverse input
renderTextReverseStuff : Model -> Markup
renderTextReverseStuff model =
Html.div []
[ Html.input [ Html.Events.onInput ChangeTextReverseInput ] []
, Html.div [] [ Html.text (reverseString model.textReverseInput) ]
]
renderFormField placeholder onInputMessage =
Html.div []
[ Html.label [] [ Html.text placeholder ]
, Html.input
[ Html.Attributes.placeholder placeholder
, Html.Events.onInput onInputMessage
]
[]
]
passwordsAreOK : String -> String -> Bool
passwordsAreOK a b =
a == b
getPasswordValidationText : Bool -> String
getPasswordValidationText theyMatch =
if theyMatch then
"Good"
else
"Bad"
renderFormValidation : Model -> Markup
renderFormValidation model =
let
( color, message ) =
if passwordsAreOK model.formPassword model.formPasswordConfirmation then
( "green", getPasswordValidationText True )
else
( "red", getPasswordValidationText False )
in
Html.div
[ Html.Attributes.style [ ( "color", color ) ]
]
[ Html.text message ]
renderFormStuff : Model -> Markup
renderFormStuff model =
Html.div []
[ renderFormField "Name" FormChangeName
, renderFormField "Password" FormChangePassword
, renderFormField "Password Confirmation" FormChangePasswordConfirmation
, renderFormValidation model
]
view : Model -> Markup
view model =
Html.div []
[ Html.h1 [] [ Html.text "Kitchen Sink" ]
, Html.div []
[ Html.h2 [] [ Html.text "Union Types" ]
, Html.div []
[ renderTitle "todo list"
, renderTodoStuff model
, renderTitle "anonymous user"
, renderAnonStuff model
, renderTitle "A Simple Counter"
, renderCounterStuff model
, renderTitle "Text Reverse"
, renderTextReverseStuff model
, renderTitle "Form Section"
, renderFormStuff model
]
]
]
| true | module Main exposing (..)
import Html
import Html.Attributes
import Html.Events
type alias Model =
{ todoItems : TaskList
, visiblity : Visibility
, users : UserList
, count : Int
, textReverseInput : String
, formName : String
, formPassword : String
, formPasswordConfirmation : String
}
type Msg
= SetVisibilityActive
| SetVisibilityAll
| SetVisibilityComplete
| IncreaseCount
| DecreaseCount
| ResetCount
| ChangeTextReverseInput String
| FormChangeName String
| FormChangePassword String
| FormChangePasswordConfirmation String
main : Program Never Model Msg
main =
Html.beginnerProgram
{ model = model
, view = view
, update = update
}
{-
> our view function is producing a Html Msg value. This means that it is a chunk of HTML that can produce Msg values.
https://guide.elm-lang.org/architecture/user_input/buttons.html
-}
type alias Markup =
Html.Html Msg
type alias Task =
{ task : String
, complete : Bool
}
type Visibility
= All
| Active
| Completed
type alias TaskList =
List Task
type User
= AnonymousUser
| NamedUser String
type alias UserList =
List User
model : Model
model =
{ todoItems =
[ { task = "Buy milk"
, complete = True
}
, { task = "Drink milk"
, complete = False
}
]
, visiblity = All
, users =
[ AnonymousUser
, AnonymousUser
, NamedUser "AzureDiamond"
, NamedUser "PI:NAME:<NAME>END_PI"
, AnonymousUser
]
, count = 0
, textReverseInput = ""
, formName = ""
, formPassword = ""
, formPasswordConfirmation = ""
}
update : Msg -> Model -> Model
update msg model =
case msg of
SetVisibilityAll ->
{ model | visiblity = All }
SetVisibilityActive ->
{ model | visiblity = Active }
SetVisibilityComplete ->
{ model | visiblity = Completed }
IncreaseCount ->
{ model | count = model.count + 1 }
DecreaseCount ->
{ model | count = model.count - 1 }
ResetCount ->
{ model | count = 0 }
ChangeTextReverseInput value ->
{ model | textReverseInput = value }
FormChangeName name ->
{ model | formName = name }
FormChangePassword password ->
{ model | formPassword = PI:PASSWORD:<PASSWORD>END_PI }
FormChangePasswordConfirmation password ->
{ model | formPasswordConfirmation = password }
renderTodoItems : TaskList -> Markup
renderTodoItems list =
Html.ul []
(List.map (\item -> Html.li [] [ Html.text item.task ]) list)
renderTodoVisibilityButton : String -> Msg -> Markup
renderTodoVisibilityButton text message =
Html.button
[ Html.Events.onClick message
]
[ Html.text text ]
renderTodoButtons : Markup
renderTodoButtons =
Html.div []
[ renderTodoVisibilityButton "Show All" SetVisibilityAll
, renderTodoVisibilityButton "Show Active" SetVisibilityActive
, renderTodoVisibilityButton "Show Completed" SetVisibilityComplete
]
filterTodoItems : TaskList -> Visibility -> TaskList
filterTodoItems taskList visibility =
case visibility of
All ->
taskList
Active ->
List.filter (\task -> task.complete == False) taskList
Completed ->
List.filter (\task -> task.complete == True) taskList
renderTodoStuff : Model -> Markup
renderTodoStuff model =
Html.div []
[ renderTodoItems (filterTodoItems model.todoItems model.visiblity)
, renderTodoButtons
]
renderUser : User -> Markup
renderUser user =
case user of
AnonymousUser ->
Html.div [] [ Html.text "Some Dude" ]
NamedUser name ->
Html.div [] [ Html.text name ]
renderUsers : UserList -> Markup
renderUsers users =
Html.div []
(List.map renderUser users)
renderAnonStuff : Model -> Markup
renderAnonStuff model =
Html.div []
[ renderUsers model.users
]
renderTitle : String -> Markup
renderTitle title =
Html.h3 [] [ Html.text title ]
renderClickableButton : Msg -> String -> Markup
renderClickableButton message label =
Html.button [ Html.Events.onClick message ] [ Html.text label ]
renderCounterStuff : Model -> Markup
renderCounterStuff model =
Html.div []
[ Html.div []
[ Html.span [] [ Html.text "count: " ]
, Html.span [] [ Html.text (toString model.count) ]
, Html.div []
[ renderClickableButton DecreaseCount "down"
, renderClickableButton IncreaseCount "up"
, renderClickableButton ResetCount "reset"
]
]
]
reverseString : String -> String
reverseString input =
String.reverse input
renderTextReverseStuff : Model -> Markup
renderTextReverseStuff model =
Html.div []
[ Html.input [ Html.Events.onInput ChangeTextReverseInput ] []
, Html.div [] [ Html.text (reverseString model.textReverseInput) ]
]
renderFormField placeholder onInputMessage =
Html.div []
[ Html.label [] [ Html.text placeholder ]
, Html.input
[ Html.Attributes.placeholder placeholder
, Html.Events.onInput onInputMessage
]
[]
]
passwordsAreOK : String -> String -> Bool
passwordsAreOK a b =
a == b
getPasswordValidationText : Bool -> String
getPasswordValidationText theyMatch =
if theyMatch then
"Good"
else
"Bad"
renderFormValidation : Model -> Markup
renderFormValidation model =
let
( color, message ) =
if passwordsAreOK model.formPassword model.formPasswordConfirmation then
( "green", getPasswordValidationText True )
else
( "red", getPasswordValidationText False )
in
Html.div
[ Html.Attributes.style [ ( "color", color ) ]
]
[ Html.text message ]
renderFormStuff : Model -> Markup
renderFormStuff model =
Html.div []
[ renderFormField "Name" FormChangeName
, renderFormField "Password" FormChangePassword
, renderFormField "Password Confirmation" FormChangePasswordConfirmation
, renderFormValidation model
]
view : Model -> Markup
view model =
Html.div []
[ Html.h1 [] [ Html.text "Kitchen Sink" ]
, Html.div []
[ Html.h2 [] [ Html.text "Union Types" ]
, Html.div []
[ renderTitle "todo list"
, renderTodoStuff model
, renderTitle "anonymous user"
, renderAnonStuff model
, renderTitle "A Simple Counter"
, renderCounterStuff model
, renderTitle "Text Reverse"
, renderTextReverseStuff model
, renderTitle "Form Section"
, renderFormStuff model
]
]
]
| elm |
[
{
"context": "5F56D9BC9,11616\"\n , \"AAdiscussions,203\"\n , \"AaronTracker,4\"\n , \"AbandonedPorn,300746\"\n , \"ABCDesis,4",
"end": 814,
"score": 0.8445467353,
"start": 802,
"tag": "USERNAME",
"value": "AaronTracker"
},
{
"context": "racies,12269\"\n , \"actuallesbians,50164\"\n , \"AdamCarolla,5185\"\n , \"Addons4Kodi,4778\"\n , \"Adelaide,64",
"end": 1362,
"score": 0.9982309341,
"start": 1351,
"tag": "NAME",
"value": "AdamCarolla"
},
{
"context": "ddits,2564\"\n , \"againstmensrights,8568\"\n , \"Agario,20815\"\n , \"agentcarter,8096\"\n , \"aggies,841",
"end": 1976,
"score": 0.8957502842,
"start": 1970,
"tag": "NAME",
"value": "Agario"
},
{
"context": "ainstmensrights,8568\"\n , \"Agario,20815\"\n , \"agentcarter,8096\"\n , \"aggies,8415\"\n , \"ainbow,39002\"\n ",
"end": 2002,
"score": 0.9798946381,
"start": 1991,
"tag": "USERNAME",
"value": "agentcarter"
},
{
"context": "22\"\n , \"aldub,251\"\n , \"Aleague,4828\"\n , \"alexandradaddario,11623\"\n , \"AlexisRen,10418\"\n ,",
"end": 2417,
"score": 0.594851315,
"start": 2413,
"tag": "USERNAME",
"value": "alex"
},
{
"context": " , \"aldub,251\"\n , \"Aleague,4828\"\n , \"alexandradaddario,11623\"\n , \"AlexisRen,10418\"\n , \"AlienBlue,2",
"end": 2430,
"score": 0.8796987534,
"start": 2417,
"tag": "NAME",
"value": "andradaddario"
},
{
"context": "ague,4828\"\n , \"alexandradaddario,11623\"\n , \"AlexisRen,10418\"\n , \"AlienBlue,205706\"\n , \"aliens,142",
"end": 2454,
"score": 0.9850382805,
"start": 2445,
"tag": "NAME",
"value": "AlexisRen"
},
{
"context": "ISexy,29827\"\n , \"AmItheAsshole,9068\"\n , \"amiugly,58738\"\n , \"Amsterdam,8891\"\n , \"AnaheimDuc",
"end": 3089,
"score": 0.5457838178,
"start": 3087,
"tag": "USERNAME",
"value": "ug"
},
{
"context": "uggest,33759\"\n , \"Animewallpaper,25418\"\n , \"Anna_Faith,3919\"\n , \"annakendrick,23257\"\n , \"AnnArbor,",
"end": 4294,
"score": 0.8907321692,
"start": 4284,
"tag": "NAME",
"value": "Anna_Faith"
},
{
"context": "nna_Faith,3919\"\n , \"annakendrick,23257\"\n , \"AnnArbor,6710\"\n , \"announcements,9800402\"\n , \"annual",
"end": 4343,
"score": 0.900506258,
"start": 4335,
"tag": "NAME",
"value": "AnnArbor"
},
{
"context": "arewerolling,5972\"\n , \"argentina,18793\"\n , \"ArianaGrande,18748\"\n , \"arielwinter,8131\"\n , \"arizona,91",
"end": 5373,
"score": 0.9162958264,
"start": 5361,
"tag": "NAME",
"value": "ArianaGrande"
},
{
"context": " , \"asmr,112789\"\n , \"asoiaf,244263\"\n , \"asoiafcirclejerk,4344\"\n , \"aspergers,15150\"\n , \"assassinscre",
"end": 7304,
"score": 0.6609541178,
"start": 7291,
"tag": "USERNAME",
"value": "iafcirclejerk"
},
{
"context": "oiaf,244263\"\n , \"asoiafcirclejerk,4344\"\n , \"aspergers,15150\"\n , \"assassinscreed,46238\"\n , \"assett",
"end": 7327,
"score": 0.7551537752,
"start": 7318,
"tag": "USERNAME",
"value": "aspergers"
},
{
"context": "ergers,15150\"\n , \"assassinscreed,46238\"\n , \"assettocorsa,6121\"\n , \"Assistance,29810\"\n , \"astr",
"end": 7376,
"score": 0.642067492,
"start": 7371,
"tag": "USERNAME",
"value": "asset"
},
{
"context": "in,49385\"\n , \"bapcsalescanada,10233\"\n , \"bapcsalesuk,4425\"\n , \"BarbaraPalvin,5677\"\n , \"Barca,130",
"end": 9818,
"score": 0.9782152772,
"start": 9810,
"tag": "NAME",
"value": "csalesuk"
},
{
"context": "alescanada,10233\"\n , \"bapcsalesuk,4425\"\n , \"BarbaraPalvin,5677\"\n , \"Barca,13022\"\n , \"Barcelona,3289\"\n",
"end": 9845,
"score": 0.999350667,
"start": 9832,
"tag": "NAME",
"value": "BarbaraPalvin"
},
{
"context": "pcsalesuk,4425\"\n , \"BarbaraPalvin,5677\"\n , \"Barca,13022\"\n , \"Barcelona,3289\"\n , \"bardmains,29",
"end": 9864,
"score": 0.9004435539,
"start": 9859,
"tag": "NAME",
"value": "Barca"
},
{
"context": " , \"bee_irl,4427\"\n , \"beer,175146\"\n , \"beercirclejerk,1519\"\n , \"beermoney,99255\"\n , \"beerporn,317",
"end": 10856,
"score": 0.9648215771,
"start": 10844,
"tag": "USERNAME",
"value": "ercirclejerk"
},
{
"context": "AfterAdoption,35617\"\n , \"belgium,24164\"\n , \"BellaThorne,6409\"\n , \"Bellingham,3929\"\n , \"bengals,7308",
"end": 11097,
"score": 0.9895160794,
"start": 11086,
"tag": "NAME",
"value": "BellaThorne"
},
{
"context": ", \"belgium,24164\"\n , \"BellaThorne,6409\"\n , \"Bellingham,3929\"\n , \"bengals,7308\"\n , \"benzodiazepi",
"end": 11118,
"score": 0.7402564287,
"start": 11111,
"tag": "NAME",
"value": "Belling"
},
{
"context": " , \"Bellingham,3929\"\n , \"bengals,7308\"\n , \"benzodiazepines,3782\"\n , \"berkeley,10041\"\n , \"berlin,9091\"\n",
"end": 11171,
"score": 0.9931344986,
"start": 11156,
"tag": "USERNAME",
"value": "benzodiazepines"
},
{
"context": "bengals,7308\"\n , \"benzodiazepines,3782\"\n , \"berkeley,10041\"\n , \"berlin,9091\"\n , \"Berserk,11710\"\n",
"end": 11193,
"score": 0.6467951536,
"start": 11185,
"tag": "USERNAME",
"value": "berkeley"
},
{
"context": "nzodiazepines,3782\"\n , \"berkeley,10041\"\n , \"berlin,9091\"\n , \"Berserk,11710\"\n , \"berserklejerk,",
"end": 11214,
"score": 0.5254083276,
"start": 11208,
"tag": "NAME",
"value": "berlin"
},
{
"context": " , \"berkeley,10041\"\n , \"berlin,9091\"\n , \"Berserk,11710\"\n , \"berserklejerk,378\"\n , \"bertstrip",
"end": 11235,
"score": 0.9825895429,
"start": 11228,
"tag": "NAME",
"value": "Berserk"
},
{
"context": "\n , \"berlin,9091\"\n , \"Berserk,11710\"\n , \"berserklejerk,378\"\n , \"bertstrips,73130\"\n , \"Besiege,2048",
"end": 11263,
"score": 0.9972465634,
"start": 11250,
"tag": "USERNAME",
"value": "berserklejerk"
},
{
"context": " \"Berserk,11710\"\n , \"berserklejerk,378\"\n , \"bertstrips,73130\"\n , \"Besiege,20487\"\n , \"Bestbuy,1252\"",
"end": 11286,
"score": 0.9947667718,
"start": 11276,
"tag": "USERNAME",
"value": "bertstrips"
},
{
"context": "erserklejerk,378\"\n , \"bertstrips,73130\"\n , \"Besiege,20487\"\n , \"Bestbuy,1252\"\n , \"bestof,48253",
"end": 11306,
"score": 0.6897485852,
"start": 11301,
"tag": "NAME",
"value": "Besie"
},
{
"context": "esgonewild,23533\"\n , \"bikewrench,15542\"\n , \"BillBurr,9891\"\n , \"billiards,7126\"\n , \"bindingofisaa",
"end": 11992,
"score": 0.8348031044,
"start": 11984,
"tag": "NAME",
"value": "BillBurr"
},
{
"context": "\"Blink182,11129\"\n , \"BlocParty,778\"\n , \"blogsnark,1030\"\n , \"bloodborne,51353\"\n , \"bloodbowl,3",
"end": 13172,
"score": 0.5764844418,
"start": 13167,
"tag": "USERNAME",
"value": "snark"
},
{
"context": "oodRealism,35697\"\n , \"Bombing,11698\"\n , \"bonnaroo,13215\"\n , \"Bonsai,28350\"\n , \"bookporn,429",
"end": 13723,
"score": 0.5612466335,
"start": 13720,
"tag": "USERNAME",
"value": "nar"
},
{
"context": "brasil,43923\"\n , \"bravefrontier,28337\"\n , \"Braveryjerk,18373\"\n , \"Braves,11507\"\n , \"Braves",
"end": 14446,
"score": 0.6033631563,
"start": 14444,
"tag": "NAME",
"value": "ra"
},
{
"context": "eManagement,20962\"\n , \"cableporn,58421\"\n , \"CadenMoranDiary,499\"\n , \"CafeRacers,10591\"\n , \"CAguns,1342\"",
"end": 15689,
"score": 0.8941244483,
"start": 15674,
"tag": "NAME",
"value": "CadenMoranDiary"
},
{
"context": "eas,5342\"\n , \"CalamariRaceTeam,8602\"\n , \"Calgary,18553\"\n , \"CalgaryFlames,3872\"\n , \"Calif",
"end": 15803,
"score": 0.5059497952,
"start": 15802,
"tag": "NAME",
"value": "g"
},
{
"context": "alligraphy,30726\"\n , \"CallOfDuty,18139\"\n , \"calvinandhobbes,109777\"\n , \"camaro,4841\"\n , \"camping,52059\"",
"end": 15973,
"score": 0.7710540891,
"start": 15958,
"tag": "USERNAME",
"value": "calvinandhobbes"
},
{
"context": "Duty,18139\"\n , \"calvinandhobbes,109777\"\n , \"camaro,4841\"\n , \"camping,52059\"\n , \"CampingandHiki",
"end": 15995,
"score": 0.7028347254,
"start": 15989,
"tag": "NAME",
"value": "camaro"
},
{
"context": ", \"capstone,1876\"\n , \"CaptchaArt,16528\"\n , \"CaraDelevingne,5521\"\n , \"CarAV,10821\"\n , \"carcrash,15916\"\n",
"end": 16491,
"score": 0.8328819275,
"start": 16477,
"tag": "NAME",
"value": "CaraDelevingne"
},
{
"context": "tchaArt,16528\"\n , \"CaraDelevingne,5521\"\n , \"CarAV,10821\"\n , \"carcrash,15916\"\n , \"Cardinals,10",
"end": 16510,
"score": 0.59084934,
"start": 16505,
"tag": "NAME",
"value": "CarAV"
},
{
"context": "rdistry,6647\"\n , \"careerguidance,14037\"\n , \"CarletonU,1893\"\n , \"carnivalclan,10\"\n , \"Caroli",
"end": 16627,
"score": 0.5600534678,
"start": 16624,
"tag": "NAME",
"value": "Car"
},
{
"context": ", \"CarletonU,1893\"\n , \"carnivalclan,10\"\n , \"CarolineVreeland,1513\"\n , \"carporn,130914\"\n , \"cars,181029\"\n",
"end": 16687,
"score": 0.9994986057,
"start": 16671,
"tag": "NAME",
"value": "CarolineVreeland"
},
{
"context": "erdrawing,11157\"\n , \"CharacterRant,719\"\n , \"Charcuterie,14267\"\n , \"Chargers,9499\"\n , \"Charleston,50",
"end": 17861,
"score": 0.6621034145,
"start": 17850,
"tag": "USERNAME",
"value": "Charcuterie"
},
{
"context": "ColorizedHistory,99105\"\n , \"Colts,8260\"\n , \"Columbus,15298\"\n , \"CombatFootage,77124\"\n , \"combine",
"end": 20582,
"score": 0.8621602058,
"start": 20574,
"tag": "NAME",
"value": "Columbus"
},
{
"context": "n,3306\"\n , \"dancegavindance,1821\"\n , \"danganronpa,2745\"\n , \"dankchristianmemes,13003\"\n , \"dan",
"end": 24452,
"score": 0.6127851605,
"start": 24447,
"tag": "USERNAME",
"value": "ronpa"
},
{
"context": "egavindance,1821\"\n , \"danganronpa,2745\"\n , \"dankchristianmemes,13003\"\n , \"dankmemes,11694\"\n , \"DankNation,",
"end": 24484,
"score": 0.9507595897,
"start": 24466,
"tag": "USERNAME",
"value": "dankchristianmemes"
},
{
"context": "pa,2745\"\n , \"dankchristianmemes,13003\"\n , \"dankmemes,11694\"\n , \"DankNation,1331\"\n , \"DANMAG,5078",
"end": 24508,
"score": 0.6758560538,
"start": 24500,
"tag": "USERNAME",
"value": "ankmemes"
},
{
"context": "darksouls3,13399\"\n , \"darksouls,82119\"\n , \"DarthJarJar,10433\"\n , \"Dashcam,6012\"\n , \"dashcamgifs,13",
"end": 24822,
"score": 0.6759914756,
"start": 24812,
"tag": "USERNAME",
"value": "arthJarJar"
},
{
"context": "ataisugly,11323\"\n , \"datascience,11962\"\n , \"DatGuyLirik,9885\"\n , \"dating,13296\"\n , \"dating_",
"end": 24996,
"score": 0.4400307834,
"start": 24993,
"tag": "USERNAME",
"value": "Dat"
},
{
"context": "isugly,11323\"\n , \"datascience,11962\"\n , \"DatGuyLirik,9885\"\n , \"dating,13296\"\n , \"dating_advice,3",
"end": 25004,
"score": 0.7736009359,
"start": 24996,
"tag": "NAME",
"value": "GuyLirik"
},
{
"context": "\"dating,13296\"\n , \"dating_advice,37281\"\n , \"DavidBowie,2792\"\n , \"davidtennant,5976\"\n , \"dawngate,6",
"end": 25077,
"score": 0.9973958731,
"start": 25067,
"tag": "NAME",
"value": "DavidBowie"
},
{
"context": "ting_advice,37281\"\n , \"DavidBowie,2792\"\n , \"davidtennant,5976\"\n , \"dawngate,6220\"\n , \"DaystromInstit",
"end": 25103,
"score": 0.9272243977,
"start": 25091,
"tag": "USERNAME",
"value": "davidtennant"
},
{
"context": "are,4180\"\n , \"Delightfullychubby,23120\"\n , \"Dell,1397\"\n , \"delusionalartists,77858\"\n , \"demo",
"end": 26066,
"score": 0.8918572664,
"start": 26062,
"tag": "NAME",
"value": "Dell"
},
{
"context": " , \"Denmark,37793\"\n , \"Dentistry,8266\"\n , \"Denton,4653\"\n , \"Denver,30830\"\n , \"DenverBroncos,1",
"end": 26216,
"score": 0.6507760882,
"start": 26210,
"tag": "NAME",
"value": "Denton"
},
{
"context": " , \"Dentistry,8266\"\n , \"Denton,4653\"\n , \"Denver,30830\"\n , \"DenverBroncos,14461\"\n , \"denvern",
"end": 26236,
"score": 0.8049509525,
"start": 26230,
"tag": "NAME",
"value": "Denver"
},
{
"context": "\"\n , \"Denton,4653\"\n , \"Denver,30830\"\n , \"DenverBroncos,14461\"\n , \"denvernuggets,2380\"\n , \"deOhneRe",
"end": 26264,
"score": 0.9770264626,
"start": 26251,
"tag": "NAME",
"value": "DenverBroncos"
},
{
"context": "nver,30830\"\n , \"DenverBroncos,14461\"\n , \"denvernuggets,2380\"\n , \"deOhneRegeln,251\"\n , \"depre",
"end": 26286,
"score": 0.5687682033,
"start": 26282,
"tag": "USERNAME",
"value": "vern"
},
{
"context": "ssion,124996\"\n , \"DepthHub,229662\"\n , \"DerekSmart,357\"\n , \"DescentIntoTyranny,6177\"\n , \"Desig",
"end": 26391,
"score": 0.3891458213,
"start": 26386,
"tag": "USERNAME",
"value": "Smart"
},
{
"context": "\"\n , \"devils,5355\"\n , \"devops,10947\"\n , \"Dexter,43453\"\n , \"DFO,5521\"\n , \"dfsports,10596\"\n ",
"end": 26851,
"score": 0.9113177061,
"start": 26845,
"tag": "NAME",
"value": "Dexter"
},
{
"context": "\"\n , \"DHMIS,707\"\n , \"diabetes,12708\"\n , \"Diablo,138207\"\n , \"diablo3,77581\"\n , \"Diablo3witch",
"end": 26971,
"score": 0.9721525311,
"start": 26965,
"tag": "NAME",
"value": "Diablo"
},
{
"context": "o3,77581\"\n , \"Diablo3witchdoctors,9364\"\n , \"DickButt,12541\"\n , \"Diesel,5248\"\n , \"digimon,12964\"\n",
"end": 27050,
"score": 0.9842422605,
"start": 27042,
"tag": "NAME",
"value": "DickButt"
},
{
"context": "3witchdoctors,9364\"\n , \"DickButt,12541\"\n , \"Diesel,5248\"\n , \"digimon,12964\"\n , \"digitalnomad,1",
"end": 27071,
"score": 0.7113156915,
"start": 27065,
"tag": "NAME",
"value": "Diesel"
},
{
"context": "scworld,14437\"\n , \"dishonored,10526\"\n , \"disney,60279\"\n , \"Disney_Infinity,3854\"\n , \"Disney",
"end": 27395,
"score": 0.5069233775,
"start": 27392,
"tag": "USERNAME",
"value": "ney"
},
{
"context": "duelyst,4587\"\n , \"DumpsterDiving,24676\"\n , \"duncantrussell,2897\"\n , \"DunderMifflin,91474\"\n , \"dune,781",
"end": 29158,
"score": 0.9241762161,
"start": 29144,
"tag": "USERNAME",
"value": "duncantrussell"
},
{
"context": " , \"EliteOne,3825\"\n , \"elonmusk,6205\"\n , \"ElsaHosk,2291\"\n , \"Elsanna,6510\"\n , \"ELTP,492\"\n ",
"end": 30634,
"score": 0.537011981,
"start": 30630,
"tag": "NAME",
"value": "Elsa"
},
{
"context": "liteOne,3825\"\n , \"elonmusk,6205\"\n , \"ElsaHosk,2291\"\n , \"Elsanna,6510\"\n , \"ELTP,492\"\n ,",
"end": 30638,
"score": 0.6560468674,
"start": 30637,
"tag": "NAME",
"value": "k"
},
{
"context": " , \"elonmusk,6205\"\n , \"ElsaHosk,2291\"\n , \"Elsanna,6510\"\n , \"ELTP,492\"\n , \"emacs,11891\"\n ",
"end": 30655,
"score": 0.7587116957,
"start": 30652,
"tag": "NAME",
"value": "Els"
},
{
"context": "rald_Council,1265\"\n , \"EmeraldPS2,2312\"\n , \"EmiliaClarke,15573\"\n , \"EmilyRatajkowski,14364\"\n , \"Emin",
"end": 30796,
"score": 0.9973748326,
"start": 30784,
"tag": "NAME",
"value": "EmiliaClarke"
},
{
"context": "meraldPS2,2312\"\n , \"EmiliaClarke,15573\"\n , \"EmilyRatajkowski,14364\"\n , \"Eminem,13876\"\n , \"Emma_Roberts,5",
"end": 30827,
"score": 0.9996349812,
"start": 30811,
"tag": "NAME",
"value": "EmilyRatajkowski"
},
{
"context": "ilyRatajkowski,14364\"\n , \"Eminem,13876\"\n , \"Emma_Roberts,5105\"\n , \"EmmaStone,26948\"\n , \"EmmaWatson,7",
"end": 30875,
"score": 0.9908028841,
"start": 30863,
"tag": "NAME",
"value": "Emma_Roberts"
},
{
"context": "Emma_Roberts,5105\"\n , \"EmmaStone,26948\"\n , \"EmmaWatson,78697\"\n , \"Emo,5639\"\n , \"emojipasta,2438\"\n ",
"end": 30923,
"score": 0.9516885877,
"start": 30913,
"tag": "NAME",
"value": "EmmaWatson"
},
{
"context": "alAttraction,9684\"\n , \"Equestrian,5357\"\n , \"ericprydz,1932\"\n , \"esports,11919\"\n , \"ethereum,6650\"",
"end": 31658,
"score": 0.9984838963,
"start": 31649,
"tag": "USERNAME",
"value": "ericprydz"
},
{
"context": " \"Fighters,10406\"\n , \"Filmmakers,71513\"\n , \"FilthyFrank,10673\"\n , \"FinalFantasy,50546\"\n , \"finance,",
"end": 34391,
"score": 0.8771770597,
"start": 34380,
"tag": "NAME",
"value": "FilthyFrank"
},
{
"context": "itler,5416\"\n , \"forwardsfromreddit,844\"\n , \"forza,14659\"\n , \"foshelter,20679\"\n , \"fountainpen",
"end": 36291,
"score": 0.9102759361,
"start": 36286,
"tag": "NAME",
"value": "forza"
},
{
"context": "orwardsfromreddit,844\"\n , \"forza,14659\"\n , \"foshelter,20679\"\n , \"fountainpens,27552\"\n , \"foxes,40",
"end": 36315,
"score": 0.6018176079,
"start": 36306,
"tag": "USERNAME",
"value": "foshelter"
},
{
"context": " , \"forza,14659\"\n , \"foshelter,20679\"\n , \"fountainpens,27552\"\n , \"foxes,40002\"\n , \"FoxStevenson,83",
"end": 36342,
"score": 0.6014814377,
"start": 36330,
"tag": "USERNAME",
"value": "fountainpens"
},
{
"context": " \"fountainpens,27552\"\n , \"foxes,40002\"\n , \"FoxStevenson,836\"\n , \"fpvracing,5746\"\n , \"fragrance,7844",
"end": 36389,
"score": 0.5210522413,
"start": 36378,
"tag": "NAME",
"value": "oxStevenson"
},
{
"context": " , \"FRC,4624\"\n , \"FreckledGirls,20055\"\n , \"fredericton,1494\"\n , \"FREE,16458\"\n , \"FreeAtheism,1890\"",
"end": 36592,
"score": 0.7748722434,
"start": 36581,
"tag": "USERNAME",
"value": "fredericton"
},
{
"context": " , \"gifs,7066012\"\n , \"GifSound,53551\"\n , \"gifsthatendtoosoon,1718\"\n , \"GiftofGames,30220\"\n , \"GifTournam",
"end": 40174,
"score": 0.8735204935,
"start": 40156,
"tag": "USERNAME",
"value": "gifsthatendtoosoon"
},
{
"context": "\"\n , \"gmod,11149\"\n , \"goats,7944\"\n , \"goddesses,22908\"\n , \"GODZILLA,12182\"\n , \"golang,18078",
"end": 40742,
"score": 0.7269078493,
"start": 40736,
"tag": "USERNAME",
"value": "desses"
},
{
"context": "GODZILLA,12182\"\n , \"golang,18078\"\n , \"goldenretrievers,16491\"\n , \"goldredditsays,9226\"\n , \"golf,61",
"end": 40817,
"score": 0.8091852665,
"start": 40807,
"tag": "USERNAME",
"value": "retrievers"
},
{
"context": "hardware,79340\"\n , \"hardwareswap,26206\"\n , \"Harley,10855\"\n , \"HarleyQuinn,5352\"\n , \"Harmontown",
"end": 43197,
"score": 0.6586944461,
"start": 43191,
"tag": "NAME",
"value": "Harley"
},
{
"context": " \"hardwareswap,26206\"\n , \"Harley,10855\"\n , \"HarleyQuinn,5352\"\n , \"Harmontown,10149\"\n , \"HaroldPo",
"end": 43220,
"score": 0.5455237031,
"start": 43212,
"tag": "NAME",
"value": "HarleyQu"
},
{
"context": "HarleyQuinn,5352\"\n , \"Harmontown,10149\"\n , \"HaroldPorn,1873\"\n , \"harrypotter,217025\"\n , \"Haruhi,23",
"end": 43272,
"score": 0.7330218554,
"start": 43262,
"tag": "NAME",
"value": "HaroldPorn"
},
{
"context": "th,10607\"\n , \"heroesofthestorm,118071\"\n , \"HeyCarl,28011\"\n , \"HFY,28174\"\n , \"hiddenwow,894",
"end": 43957,
"score": 0.5068085194,
"start": 43955,
"tag": "NAME",
"value": "ey"
},
{
"context": "\"HyruleWarriors,3185\"\n , \"IAmA,9726122\"\n , \"iamverysmart,159490\"\n , \"IASIP,96036\"\n , \"IBO,3428\"\n ",
"end": 46305,
"score": 0.9656710625,
"start": 46293,
"tag": "USERNAME",
"value": "iamverysmart"
},
{
"context": "7442\"\n , \"ifiwonthelottery,42974\"\n , \"ifyoulikeblank,52089\"\n , \"IgnorantImgur,16797\"\n , \"IHE,138",
"end": 46628,
"score": 0.5761685371,
"start": 46620,
"tag": "USERNAME",
"value": "ikeblank"
},
{
"context": "tToLearn,165699\"\n , \"iZombie,5513\"\n , \"JacksFilms,1171\"\n , \"jacksonville,4712\"\n , \"JacksonWri",
"end": 49917,
"score": 0.6083734035,
"start": 49912,
"tag": "USERNAME",
"value": "Films"
},
{
"context": "JacksFilms,1171\"\n , \"jacksonville,4712\"\n , \"JacksonWrites,9891\"\n , \"jag_ivl,802\"\n , \"Jaguars",
"end": 49961,
"score": 0.6140420437,
"start": 49957,
"tag": "NAME",
"value": "Jack"
},
{
"context": ", \"JacksonWrites,9891\"\n , \"jag_ivl,802\"\n , \"Jaguars,3980\"\n , \"jailbreak,105777\"\n , \"jakeandamir,",
"end": 50011,
"score": 0.9207860231,
"start": 50004,
"tag": "NAME",
"value": "Jaguars"
},
{
"context": "ailbreak,105777\"\n , \"jakeandamir,11311\"\n , \"JamesBond,14555\"\n , \"JaneTheVirginCW,865\"\n , \"japan,6",
"end": 50085,
"score": 0.5527516007,
"start": 50076,
"tag": "NAME",
"value": "JamesBond"
},
{
"context": " , \"Jazz,56782\"\n , \"jazzyhiphop,4709\"\n , \"Jeep,30392\"\n , \"jellybeantoes,12844\"\n , \"Jennife",
"end": 50500,
"score": 0.5030159354,
"start": 50497,
"tag": "NAME",
"value": "eep"
},
{
"context": ", \"Jeep,30392\"\n , \"jellybeantoes,12844\"\n , \"JenniferLawrence,44301\"\n , \"Jeopardy,6809\"\n , \"jerktalkdiamo",
"end": 50559,
"score": 0.997780025,
"start": 50543,
"tag": "NAME",
"value": "JenniferLawrence"
},
{
"context": "Jeopardy,6809\"\n , \"jerktalkdiamond,964\"\n , \"JessicaJones,4399\"\n , \"JessicaNigri,27798\"\n , \"JimSterli",
"end": 50636,
"score": 0.9978820682,
"start": 50624,
"tag": "NAME",
"value": "JessicaJones"
},
{
"context": "talkdiamond,964\"\n , \"JessicaJones,4399\"\n , \"JessicaNigri,27798\"\n , \"JimSterling,2762\"\n , \"Jobs4Bitco",
"end": 50662,
"score": 0.9772465825,
"start": 50650,
"tag": "NAME",
"value": "JessicaNigri"
},
{
"context": "sicaJones,4399\"\n , \"JessicaNigri,27798\"\n , \"JimSterling,2762\"\n , \"Jobs4Bitcoins,9211\"\n , \"jobs,7482",
"end": 50688,
"score": 0.9836799502,
"start": 50677,
"tag": "NAME",
"value": "JimSterling"
},
{
"context": "\n , \"jobs,74822\"\n , \"joerogan2,2010\"\n , \"JoeRogan,38103\"\n , \"JohnCena,6286\"\n , \"John_Fruscian",
"end": 50779,
"score": 0.9485213161,
"start": 50771,
"tag": "NAME",
"value": "JoeRogan"
},
{
"context": " , \"joerogan2,2010\"\n , \"JoeRogan,38103\"\n , \"JohnCena,6286\"\n , \"John_Frusciante,2685\"\n , \"joinsqu",
"end": 50802,
"score": 0.9739871025,
"start": 50794,
"tag": "NAME",
"value": "JohnCena"
},
{
"context": " , \"JoeRogan,38103\"\n , \"JohnCena,6286\"\n , \"John_Frusciante,2685\"\n , \"joinsquad,2495\"\n , \"Jokes,4760749",
"end": 50831,
"score": 0.8882805705,
"start": 50816,
"tag": "NAME",
"value": "John_Frusciante"
},
{
"context": " , \"joinsquad,2495\"\n , \"Jokes,4760749\"\n , \"JonTron,27893\"\n , \"Jordansw,28\"\n , \"Journalism,9987",
"end": 50897,
"score": 0.741977036,
"start": 50890,
"tag": "NAME",
"value": "JonTron"
},
{
"context": " , \"Jokes,4760749\"\n , \"JonTron,27893\"\n , \"Jordansw,28\"\n , \"Journalism,9987\"\n , \"JRPG,27567\"\n ",
"end": 50920,
"score": 0.9554725289,
"start": 50912,
"tag": "NAME",
"value": "Jordansw"
},
{
"context": " , \"Journalism,9987\"\n , \"JRPG,27567\"\n , \"Judaism,12546\"\n , \"judo,8048\"\n , \"JurassicPark,1748",
"end": 50982,
"score": 0.5507308245,
"start": 50976,
"tag": "NAME",
"value": "udaism"
},
{
"context": "7\"\n , \"Judaism,12546\"\n , \"judo,8048\"\n , \"JurassicPark,17482\"\n , \"JustCause,2668\"\n , \"J",
"end": 51016,
"score": 0.4331957102,
"start": 51015,
"tag": "USERNAME",
"value": "J"
},
{
"context": "\"\n , \"Judaism,12546\"\n , \"judo,8048\"\n , \"JurassicPark,17482\"\n , \"JustCause,2668\"\n , \"Jus",
"end": 51018,
"score": 0.4760164022,
"start": 51016,
"tag": "NAME",
"value": "ur"
},
{
"context": " , \"Judaism,12546\"\n , \"judo,8048\"\n , \"JurassicPark,17482\"\n , \"JustCause,2668\"\n , \"JustEngaged,",
"end": 51027,
"score": 0.6848688722,
"start": 51018,
"tag": "USERNAME",
"value": "assicPark"
},
{
"context": " \"JustCause,2668\"\n , \"JustEngaged,4663\"\n , \"Justfuckmyshitup,46142\"\n , \"JusticePorn,431434\"\n , \"JusticeS",
"end": 51106,
"score": 0.8914266229,
"start": 51090,
"tag": "USERNAME",
"value": "Justfuckmyshitup"
},
{
"context": "p,46142\"\n , \"JusticePorn,431434\"\n , \"JusticeServed,18354\"\n , \"justlegbeardthings,5629\"\n , \"",
"end": 51158,
"score": 0.528211832,
"start": 51155,
"tag": "USERNAME",
"value": "Ser"
},
{
"context": "cePorn,431434\"\n , \"JusticeServed,18354\"\n , \"justlegbeardthings,5629\"\n , \"justneckbeardthings,102908\"\n , \"J",
"end": 51194,
"score": 0.9244940877,
"start": 51176,
"tag": "USERNAME",
"value": "justlegbeardthings"
},
{
"context": "ved,18354\"\n , \"justlegbeardthings,5629\"\n , \"justneckbeardthings,102908\"\n , \"JUSTNOFAMILY,1205\"\n , \"JUSTNOMI",
"end": 51227,
"score": 0.9286962152,
"start": 51208,
"tag": "USERNAME",
"value": "justneckbeardthings"
},
{
"context": "s,5629\"\n , \"justneckbeardthings,102908\"\n , \"JUSTNOFAMILY,1205\"\n , \"JUSTNOMIL,7008\"\n , \"Justridingalo",
"end": 51255,
"score": 0.9327307343,
"start": 51243,
"tag": "USERNAME",
"value": "JUSTNOFAMILY"
},
{
"context": "rdthings,102908\"\n , \"JUSTNOFAMILY,1205\"\n , \"JUSTNOMIL,7008\"\n , \"Justridingalong,1353\"\n , \"Justrol",
"end": 51278,
"score": 0.9658320546,
"start": 51269,
"tag": "USERNAME",
"value": "JUSTNOMIL"
},
{
"context": "otheshop,137533\"\n , \"JustUnsubbed,4916\"\n , \"Juve,2494\"\n , \"juxtaposition,6873\"\n , \"jworg,9\"\n",
"end": 51388,
"score": 0.8103373051,
"start": 51384,
"tag": "NAME",
"value": "Juve"
},
{
"context": " , \"Juve,2494\"\n , \"juxtaposition,6873\"\n , \"jworg,9\"\n , \"kancolle,4119\"\n , \"kancolle_ja,315\"\n",
"end": 51434,
"score": 0.9150161743,
"start": 51429,
"tag": "USERNAME",
"value": "jworg"
},
{
"context": " , \"juxtaposition,6873\"\n , \"jworg,9\"\n , \"kancolle,4119\"\n , \"kancolle_ja,315\"\n , \"KanMusu,2360",
"end": 51453,
"score": 0.8600834012,
"start": 51445,
"tag": "USERNAME",
"value": "kancolle"
},
{
"context": "873\"\n , \"jworg,9\"\n , \"kancolle,4119\"\n , \"kancolle_ja,315\"\n , \"KanMusu,2360\"\n , \"kansascity,14383",
"end": 51478,
"score": 0.9503772855,
"start": 51467,
"tag": "USERNAME",
"value": "kancolle_ja"
},
{
"context": " , \"kancolle,4119\"\n , \"kancolle_ja,315\"\n , \"KanMusu,2360\"\n , \"kansascity,14383\"\n , \"KansasCityC",
"end": 51498,
"score": 0.84450984,
"start": 51491,
"tag": "NAME",
"value": "KanMusu"
},
{
"context": "KansasCityChiefs,7443\"\n , \"Kanye,16570\"\n , \"Kappa,21399\"\n , \"KarmaConspiracy,59451\"\n , \"Karma",
"end": 51592,
"score": 0.7317753434,
"start": 51587,
"tag": "NAME",
"value": "Kappa"
},
{
"context": "3\"\n , \"Kanye,16570\"\n , \"Kappa,21399\"\n , \"KarmaConspiracy,59451\"\n , \"KarmaCourt,38476\"\n , \"katawashou",
"end": 51622,
"score": 0.8031721115,
"start": 51607,
"tag": "NAME",
"value": "KarmaConspiracy"
},
{
"context": "Kappa,21399\"\n , \"KarmaConspiracy,59451\"\n , \"KarmaCourt,38476\"\n , \"katawashoujo,11914\"\n , \"katebeck",
"end": 51647,
"score": 0.7760531306,
"start": 51637,
"tag": "NAME",
"value": "KarmaCourt"
},
{
"context": "rmaCourt,38476\"\n , \"katawashoujo,11914\"\n , \"katebeckinsale,6904\"\n , \"kateupton,37670\"\n , \"KatherineMcN",
"end": 51703,
"score": 0.8411076069,
"start": 51689,
"tag": "USERNAME",
"value": "katebeckinsale"
},
{
"context": "shoujo,11914\"\n , \"katebeckinsale,6904\"\n , \"kateupton,37670\"\n , \"KatherineMcNamara,2116\"\n , ",
"end": 51721,
"score": 0.6138359308,
"start": 51718,
"tag": "USERNAME",
"value": "ate"
},
{
"context": "tebeckinsale,6904\"\n , \"kateupton,37670\"\n , \"KatherineMcNamara,2116\"\n , \"katyperry,28154\"\n , \"KCRoyals,717",
"end": 51758,
"score": 0.9863057733,
"start": 51741,
"tag": "NAME",
"value": "KatherineMcNamara"
},
{
"context": "pton,37670\"\n , \"KatherineMcNamara,2116\"\n , \"katyperry,28154\"\n , \"KCRoyals,7173\"\n , \"KDRAMA,7567\"\n",
"end": 51781,
"score": 0.9493214488,
"start": 51772,
"tag": "USERNAME",
"value": "katyperry"
},
{
"context": " , \"kemonomimi,6100\"\n , \"KenM,84239\"\n , \"Kerala,1052\"\n , \"KerbalAcademy,10830\"\n , \"Kerba",
"end": 51884,
"score": 0.8237100244,
"start": 51881,
"tag": "NAME",
"value": "Ker"
},
{
"context": "\"\n , \"kpics,18704\"\n , \"kpop,42729\"\n , \"kratom,6984\"\n , \"kreiswichs,3233\"\n , \"kurdistan,27",
"end": 52908,
"score": 0.5743788481,
"start": 52904,
"tag": "USERNAME",
"value": "atom"
},
{
"context": " \"labrats,7696\"\n , \"LAClippers,4318\"\n , \"lacrosse,9361\"\n , \"LadyBoners,164202\"\n , \"Ladyboners",
"end": 53087,
"score": 0.6487367749,
"start": 53082,
"tag": "USERNAME",
"value": "rosse"
},
{
"context": ", \"LAClippers,4318\"\n , \"lacrosse,9361\"\n , \"LadyBoners,164202\"\n , \"Ladybonersgonecuddly,31680\"\n",
"end": 53105,
"score": 0.5257310867,
"start": 53102,
"tag": "NAME",
"value": "ady"
},
{
"context": "lippers,4318\"\n , \"lacrosse,9361\"\n , \"LadyBoners,164202\"\n , \"Ladybonersgonecuddly,31680\"\n , ",
"end": 53111,
"score": 0.5055550337,
"start": 53108,
"tag": "NAME",
"value": "ers"
},
{
"context": "164202\"\n , \"Ladybonersgonecuddly,31680\"\n , \"ladyladyboners,24988\"\n , \"lag_irl,135\"\n , \"lakers,18289\"\n ",
"end": 53176,
"score": 0.8879038095,
"start": 53162,
"tag": "USERNAME",
"value": "ladyladyboners"
},
{
"context": "st,7127\"\n , \"languagelearning,60392\"\n , \"lapfoxtrax,1947\"\n , \"LARP,4653\"\n , \"lastimages,31487\"\n",
"end": 53293,
"score": 0.7940117717,
"start": 53286,
"tag": "USERNAME",
"value": "foxtrax"
},
{
"context": "3432\"\n , \"lgg4,7273\"\n , \"lgv10,1098\"\n , \"LiaMarieJohnson,8477\"\n , \"Liberal,25497\"\n , \"liberta,614",
"end": 54790,
"score": 0.7727198601,
"start": 54778,
"tag": "USERNAME",
"value": "LiaMarieJohn"
},
{
"context": "\"lgg4,7273\"\n , \"lgv10,1098\"\n , \"LiaMarieJohnson,8477\"\n , \"Liberal,25497\"\n , \"liberta,614\"\n ",
"end": 54793,
"score": 0.4969414771,
"start": 54790,
"tag": "NAME",
"value": "son"
},
{
"context": "85\"\n , \"LSD,46263\"\n , \"Lubbock,2370\"\n , \"LucidDreaming,145245\"\n , \"Luna_Lovewell,19160\"\n , \"LV426,",
"end": 56737,
"score": 0.9357525706,
"start": 56724,
"tag": "USERNAME",
"value": "LucidDreaming"
},
{
"context": "ubbock,2370\"\n , \"LucidDreaming,145245\"\n , \"Luna_Lovewell,19160\"\n , \"LV426,17086\"\n , \"Lyft,2093\"\n ",
"end": 56766,
"score": 0.8454196453,
"start": 56754,
"tag": "USERNAME",
"value": "una_Lovewell"
},
{
"context": "timateTeam,7095\"\n , \"MadeMeSmile,82836\"\n , \"madisonwi,10112\"\n , \"MadMax,7903\"\n , \"madmen,41301\"\n ",
"end": 57140,
"score": 0.8694908023,
"start": 57131,
"tag": "USERNAME",
"value": "madisonwi"
},
{
"context": "adokaMagica,3756\"\n , \"Magic,16256\"\n , \"magicduels,4012\"\n , \"magicskyfairy,14873\"\n , \"magicT",
"end": 57250,
"score": 0.5994575024,
"start": 57247,
"tag": "USERNAME",
"value": "due"
},
{
"context": ", \"Magic,16256\"\n , \"magicduels,4012\"\n , \"magicskyfairy,14873\"\n , \"magicTCG,148320\"\n , \"Maine,7790\"",
"end": 57279,
"score": 0.7674828768,
"start": 57269,
"tag": "USERNAME",
"value": "icskyfairy"
},
{
"context": " , \"magicTCG,148320\"\n , \"Maine,7790\"\n , \"maisiewilliams,5556\"\n , \"makemychoice,22507\"\n , \"MakeNewFr",
"end": 57351,
"score": 0.8200457692,
"start": 57337,
"tag": "USERNAME",
"value": "maisiewilliams"
},
{
"context": ", \"Maine,7790\"\n , \"maisiewilliams,5556\"\n , \"makemychoice,22507\"\n , \"MakeNewFriendsHere,15706\"\n , \"Ma",
"end": 57377,
"score": 0.9777351022,
"start": 57365,
"tag": "USERNAME",
"value": "makemychoice"
},
{
"context": " , \"Mariners,8905\"\n , \"mariokart,9416\"\n , \"MarioMaker,17040\"\n , \"marketing,46823\"\n , \"Markip",
"end": 58232,
"score": 0.6746081114,
"start": 58227,
"tag": "NAME",
"value": "Mario"
},
{
"context": "\"MarioMaker,17040\"\n , \"marketing,46823\"\n , \"Markiplier,7966\"\n , \"MarkMyWords,20219\"\n , \"Marria",
"end": 58282,
"score": 0.5192016363,
"start": 58276,
"tag": "NAME",
"value": "Markip"
},
{
"context": "Marriage,4794\"\n , \"marriedredpill,6000\"\n , \"Mars,7017\"\n , \"martialarts,24258\"\n , \"maru,5669\"",
"end": 58380,
"score": 0.8649917841,
"start": 58376,
"tag": "NAME",
"value": "Mars"
},
{
"context": "Installation,3496\"\n , \"maximumfun,3798\"\n , \"maybemaybemaybe,4849\"\n , \"MaymayZone,6883\"\n , \"mazda,8207\"\n",
"end": 58849,
"score": 0.8050573468,
"start": 58834,
"tag": "USERNAME",
"value": "maybemaybemaybe"
},
{
"context": "mfun,3798\"\n , \"maybemaybemaybe,4849\"\n , \"MaymayZone,6883\"\n , \"mazda,8207\"\n , \"mbti,8408\"\n , ",
"end": 58873,
"score": 0.8590051532,
"start": 58866,
"tag": "USERNAME",
"value": "mayZone"
},
{
"context": "lhealth,14177\"\n , \"MEOW_IRL,25889\"\n , \"mercedes_benz,5538\"\n , \"MerylRearSolid,175\"\n , \"metacanad",
"end": 59788,
"score": 0.5828598142,
"start": 59780,
"tag": "USERNAME",
"value": "des_benz"
},
{
"context": "8676\"\n , \"MHOC,2463\"\n , \"Miami,9203\"\n , \"miamidolphins,8462\"\n , \"MiamiHurricanes,1377\"\n , \"Miat",
"end": 60309,
"score": 0.5801500678,
"start": 60299,
"tag": "USERNAME",
"value": "miamidolph"
},
{
"context": ", \"Miami,9203\"\n , \"miamidolphins,8462\"\n , \"MiamiHurricanes,1377\"\n , \"Miata,9770\"\n , \"michael",
"end": 60331,
"score": 0.5187741518,
"start": 60327,
"tag": "NAME",
"value": "iami"
},
{
"context": "ami,9203\"\n , \"miamidolphins,8462\"\n , \"MiamiHurricanes,1377\"\n , \"Miata,9770\"\n , \"michaelbaygif",
"end": 60337,
"score": 0.7331511974,
"start": 60332,
"tag": "NAME",
"value": "urric"
},
{
"context": "3\"\n , \"miamidolphins,8462\"\n , \"MiamiHurricanes,1377\"\n , \"Miata,9770\"\n , \"michaelbaygifs,54",
"end": 60341,
"score": 0.6141648293,
"start": 60339,
"tag": "NAME",
"value": "es"
},
{
"context": " \"MiamiHurricanes,1377\"\n , \"Miata,9770\"\n , \"michaelbaygifs,54261\"\n , \"Michigan,23179\"\n , \"MichiganWolv",
"end": 60388,
"score": 0.9946978688,
"start": 60374,
"tag": "USERNAME",
"value": "michaelbaygifs"
},
{
"context": "\n , \"Monero,2561\"\n , \"Monitors,9649\"\n , \"monkslookingatbeer,21422\"\n , \"monsteraday,2839\"\n , \"Monstercat",
"end": 62218,
"score": 0.9260779619,
"start": 62200,
"tag": "USERNAME",
"value": "monkslookingatbeer"
},
{
"context": "y,28804\"\n , \"myfriendwantstoknow,25670\"\n , \"mylittleandysonic1,1981\"\n , \"mylittlepony,66489\"\n , \"myp",
"end": 63711,
"score": 0.6799522042,
"start": 63699,
"tag": "USERNAME",
"value": "mylittleandy"
},
{
"context": "w,25670\"\n , \"mylittleandysonic1,1981\"\n , \"mylittlepony,66489\"\n , \"mypartneristrans,3779\"\n , \"MyPeo",
"end": 63743,
"score": 0.5840257406,
"start": 63733,
"tag": "USERNAME",
"value": "littlepony"
},
{
"context": " , \"mythbusters,16717\"\n , \"n64,9489\"\n , \"Nagato,382\"\n , \"namenerds,6336\"\n , \"NamFlashbac",
"end": 63891,
"score": 0.6337813139,
"start": 63889,
"tag": "NAME",
"value": "ag"
},
{
"context": "16717\"\n , \"n64,9489\"\n , \"Nagato,382\"\n , \"namenerds,6336\"\n , \"NamFlashbacks,3190\"\n , \"Nanny,892",
"end": 63916,
"score": 0.8344337344,
"start": 63907,
"tag": "USERNAME",
"value": "namenerds"
},
{
"context": "namenerds,6336\"\n , \"NamFlashbacks,3190\"\n , \"Nanny,892\"\n , \"nanowrimo,10847\"\n , \"narcos,5824\"\n",
"end": 63962,
"score": 0.8187506199,
"start": 63957,
"tag": "NAME",
"value": "Nanny"
},
{
"context": " , \"NamFlashbacks,3190\"\n , \"Nanny,892\"\n , \"nanowrimo,10847\"\n , \"narcos,5824\"\n , \"Naruto,66976\"\n ",
"end": 63984,
"score": 0.7528369427,
"start": 63975,
"tag": "USERNAME",
"value": "nanowrimo"
},
{
"context": "\n , \"Nanny,892\"\n , \"nanowrimo,10847\"\n , \"narcos,5824\"\n , \"Naruto,66976\"\n , \"nasa,40516\"\n ",
"end": 64005,
"score": 0.610722065,
"start": 63999,
"tag": "USERNAME",
"value": "narcos"
},
{
"context": " , \"nanowrimo,10847\"\n , \"narcos,5824\"\n , \"Naruto,66976\"\n , \"nasa,40516\"\n , \"NASCAR,20166\"\n ",
"end": 64025,
"score": 0.9975254536,
"start": 64019,
"tag": "NAME",
"value": "Naruto"
},
{
"context": " \"nashville,11165\"\n , \"NASLSoccer,2026\"\n , \"NatalieDormer,14878\"\n , \"nathanforyou,4854\"\n , \"NationalP",
"end": 64141,
"score": 0.9367156029,
"start": 64128,
"tag": "NAME",
"value": "NatalieDormer"
},
{
"context": "SLSoccer,2026\"\n , \"NatalieDormer,14878\"\n , \"nathanforyou,4854\"\n , \"NationalPark,6253\"\n , \"natty",
"end": 64163,
"score": 0.6780557632,
"start": 64156,
"tag": "USERNAME",
"value": "nathanf"
},
{
"context": "natureismetal,35697\"\n , \"navy,12037\"\n , \"NavyBlazer,2546\"\n , \"navyseals,1318\"\n , \"NBA2k,2",
"end": 64331,
"score": 0.5124057531,
"start": 64330,
"tag": "NAME",
"value": "y"
},
{
"context": "\"ottawa,18694\"\n , \"OttawaSenators,4489\"\n , \"Otters,15182\"\n , \"Outlander,4640\"\n , \"OutlandishAl",
"end": 69402,
"score": 0.9755766392,
"start": 69396,
"tag": "NAME",
"value": "Otters"
},
{
"context": "ofexile,55470\"\n , \"patientgamers,66432\"\n , \"Patriots,35985\"\n , \"Pauper,3510\"\n , \"paydaycirclejer",
"end": 70347,
"score": 0.8838160038,
"start": 70339,
"tag": "NAME",
"value": "Patriots"
},
{
"context": "atientgamers,66432\"\n , \"Patriots,35985\"\n , \"Pauper,3510\"\n , \"paydaycirclejerk,750\"\n , \"pay",
"end": 70364,
"score": 0.8224229217,
"start": 70362,
"tag": "NAME",
"value": "Pa"
},
{
"context": " \"peloton,12939\"\n , \"penguins,10697\"\n , \"PenmanshipPorn,120944\"\n , \"Pennsylvania,6406\"\n , \"penspinn",
"end": 70609,
"score": 0.7205007076,
"start": 70598,
"tag": "NAME",
"value": "manshipPorn"
},
{
"context": "pPorn,120944\"\n , \"Pennsylvania,6406\"\n , \"penspinning,13838\"\n , \"PeopleBeingJerks,31276\"\n , \"",
"end": 70658,
"score": 0.6438601613,
"start": 70654,
"tag": "USERNAME",
"value": "spin"
},
{
"context": "\"PeopleBeingJerks,31276\"\n , \"pepe,3873\"\n , \"pepethefrog,5498\"\n , \"Perfectfit,58195\"\n , \"perfectloop",
"end": 70737,
"score": 0.7638072968,
"start": 70726,
"tag": "USERNAME",
"value": "pepethefrog"
},
{
"context": "2\"\n , \"r4r,87824\"\n , \"Rabbits,28734\"\n , \"RachelCook,2362\"\n , \"racism,7995\"\n , \"radiocontrol,123",
"end": 75625,
"score": 0.7461217642,
"start": 75615,
"tag": "NAME",
"value": "RachelCook"
},
{
"context": " , \"rage,122716\"\n , \"ragecomics,41862\"\n , \"RagenChastain,1722\"\n , \"rails,16064\"\n , \"Rainbow6,9496\"\n ",
"end": 75791,
"score": 0.8717549443,
"start": 75778,
"tag": "NAME",
"value": "RagenChastain"
},
{
"context": "dness,37441\"\n , \"randomsuperpowers,580\"\n , \"randpaul,5063\"\n , \"rangers,9997\"\n , \"rant,18677\"",
"end": 76512,
"score": 0.6062157154,
"start": 76508,
"tag": "USERNAME",
"value": "rand"
},
{
"context": "8\"\n , \"RATS,15845\"\n , \"ravens,11730\"\n , \"rawdenim,25719\"\n , \"razorbacks,1594\"\n , \"RBI,29",
"end": 76793,
"score": 0.6140938997,
"start": 76790,
"tag": "USERNAME",
"value": "raw"
},
{
"context": " , \"RATS,15845\"\n , \"ravens,11730\"\n , \"rawdenim,25719\"\n , \"razorbacks,1594\"\n , \"RBI,29738\"\n",
"end": 76798,
"score": 0.5069779158,
"start": 76796,
"tag": "USERNAME",
"value": "im"
},
{
"context": " , \"reversegif,22540\"\n , \"reynad,1543\"\n , \"rickandmorty,191060\"\n , \"rickygervais,9435\"\n , \"riddles,",
"end": 78496,
"score": 0.9486088753,
"start": 78484,
"tag": "USERNAME",
"value": "rickandmorty"
},
{
"context": " \"reynad,1543\"\n , \"rickandmorty,191060\"\n , \"rickygervais,9435\"\n , \"riddles,30867\"\n , \"Rift,9693\"\n ",
"end": 78524,
"score": 0.9854860306,
"start": 78512,
"tag": "USERNAME",
"value": "rickygervais"
},
{
"context": "ockhounds,9937\"\n , \"rocksmith,13141\"\n , \"roguelikes,19191\"\n , \"Roguetroll,10\"\n , \"rojava,1",
"end": 78992,
"score": 0.5604999661,
"start": 78990,
"tag": "USERNAME",
"value": "ue"
},
{
"context": " , \"rolltide,3441\"\n , \"Romania,23826\"\n , \"ronandfez,3299\"\n , \"ronpaul,25443\"\n , \"RoomPorn,29070",
"end": 79180,
"score": 0.9870320559,
"start": 79171,
"tag": "USERNAME",
"value": "ronandfez"
},
{
"context": " , \"Romania,23826\"\n , \"ronandfez,3299\"\n , \"ronpaul,25443\"\n , \"RoomPorn,290703\"\n , \"roosterteet",
"end": 79201,
"score": 0.9867681265,
"start": 79194,
"tag": "USERNAME",
"value": "ronpaul"
},
{
"context": " \"ronpaul,25443\"\n , \"RoomPorn,290703\"\n , \"roosterteeth,129872\"\n , \"ROTC,1388\"\n , \"RotMG,6409\"",
"end": 79247,
"score": 0.5220088959,
"start": 79242,
"tag": "USERNAME",
"value": "oster"
},
{
"context": " , \"sales,9397\"\n , \"SaltLakeCity,10883\"\n , \"samharris,1730\"\n , \"samoyeds,4826\"\n , \"SampleSi",
"end": 80193,
"score": 0.4875885546,
"start": 80190,
"tag": "USERNAME",
"value": "sam"
},
{
"context": "nfrancisco,48702\"\n , \"SanJose,8772\"\n , \"SanJoseSharks,8349\"\n , \"santashelpers,5881\"\n , \"SantasLit",
"end": 80456,
"score": 0.6579579115,
"start": 80447,
"tag": "NAME",
"value": "oseSharks"
},
{
"context": "LittleHelpers,1775\"\n , \"saplings,22583\"\n , \"SarahHyland,7700\"\n , \"SargonofAkkad,2866\"\n , \"saskatche",
"end": 80564,
"score": 0.9875253439,
"start": 80553,
"tag": "NAME",
"value": "SarahHyland"
},
{
"context": "ms,7972\"\n , \"ScandinavianInterior,5242\"\n , \"ScarlettJohansson,23948\"\n , \"Scarrapics,7688\"\n , \"ScenesFromA",
"end": 80858,
"score": 0.9421234131,
"start": 80841,
"tag": "NAME",
"value": "ScarlettJohansson"
},
{
"context": "seinfeld,44057\"\n , \"seinfeldgifs,16169\"\n , \"SelenaGomez,17076\"\n , \"self,148033\"\n , \"SelfDrivingCars",
"end": 81644,
"score": 0.9666784406,
"start": 81633,
"tag": "NAME",
"value": "SelenaGomez"
},
{
"context": "sneakermarket,7491\"\n , \"Sneakers,62627\"\n , \"snek_irl,6224\"\n , \"Sneks,16810\"\n , \"snes,12996\"\n ",
"end": 85217,
"score": 0.8981999159,
"start": 85209,
"tag": "USERNAME",
"value": "snek_irl"
},
{
"context": "otify,32797\"\n , \"spotted,14019\"\n , \"springerspaniel,1026\"\n , \"springfieldMO,2589\"\n , \"Sprint",
"end": 87014,
"score": 0.5378608704,
"start": 87010,
"tag": "USERNAME",
"value": "span"
},
{
"context": " , \"Stims,4400\"\n , \"StLouis,16670\"\n , \"stlouisblues,5825\"\n , \"StLouisRams,4558\"\n , \"sto,82",
"end": 88517,
"score": 0.5148767829,
"start": 88514,
"tag": "USERNAME",
"value": "uis"
},
{
"context": "cculents,11380\"\n , \"SuddenlyGay,10271\"\n , \"sugarfreemua,8232\"\n , \"SuggestALaptop,21902\"\n , \"sugge",
"end": 89606,
"score": 0.590559423,
"start": 89597,
"tag": "USERNAME",
"value": "ugarfreem"
},
{
"context": "Teachers,29837\"\n , \"teaching,16431\"\n , \"TeamSolomid,14820\"\n , \"tech,82935\"\n , \"technews,1769",
"end": 91982,
"score": 0.5848081112,
"start": 91978,
"tag": "USERNAME",
"value": "Solo"
},
{
"context": "tmacgyver,56393\"\n , \"techtheatre,7690\"\n , \"TedCruz,988\"\n , \"teefies,4007\"\n , \"teenagers,105234",
"end": 92266,
"score": 0.6729363203,
"start": 92260,
"tag": "NAME",
"value": "edCruz"
},
{
"context": "eraOnline,18715\"\n , \"Terraria,78686\"\n , \"terriblefacebookmemes,33514\"\n , \"tesdcares,3954\"\n , \"teslamotors,",
"end": 92638,
"score": 0.7681119442,
"start": 92620,
"tag": "USERNAME",
"value": "riblefacebookmemes"
},
{
"context": ", \"TILinIndia,360\"\n , \"tiltshift,26505\"\n , \"TimAndEric,22437\"\n , \"timbers,3840\"\n , \"timberwolves,5",
"end": 94969,
"score": 0.761975646,
"start": 94959,
"tag": "USERNAME",
"value": "TimAndEric"
},
{
"context": "\"tiltshift,26505\"\n , \"TimAndEric,22437\"\n , \"timbers,3840\"\n , \"timberwolves,5029\"\n , \"timetolega",
"end": 94991,
"score": 0.8326393366,
"start": 94984,
"tag": "USERNAME",
"value": "timbers"
},
{
"context": " , \"TimAndEric,22437\"\n , \"timbers,3840\"\n , \"timberwolves,5029\"\n , \"timetolegalize,10058\"\n , \"tinabel",
"end": 95017,
"score": 0.9669313431,
"start": 95005,
"tag": "USERNAME",
"value": "timberwolves"
},
{
"context": "rwolves,5029\"\n , \"timetolegalize,10058\"\n , \"tinabelcher,14568\"\n , \"Tinder,178148\"\n , \"TinyHouses,67",
"end": 95071,
"score": 0.8677408695,
"start": 95060,
"tag": "USERNAME",
"value": "tinabelcher"
},
{
"context": "\"Tokyo,8491\"\n , \"TokyoGhoul,10479\"\n , \"tolkienfans,32828\"\n , \"TombRaider,4408\"\n , \"tomwait",
"end": 95434,
"score": 0.5382260084,
"start": 95432,
"tag": "USERNAME",
"value": "en"
},
{
"context": "erloss,605\"\n , \"tuckedinkitties,14781\"\n , \"Tucson,6725\"\n , \"Tulpas,9496\"\n , \"tulsa,4869\"\n ",
"end": 97881,
"score": 0.8336427212,
"start": 97876,
"tag": "NAME",
"value": "ucson"
},
{
"context": " \"xxfitness,89703\"\n , \"xxketo,23640\"\n , \"YanetGarcia,8212\"\n , \"yarntrolls,2171\"\n , \"YasuoMa",
"end": 105760,
"score": 0.5697921515,
"start": 105757,
"tag": "USERNAME",
"value": "etG"
},
{
"context": " , \"xxketo,23640\"\n , \"YanetGarcia,8212\"\n , \"yarntrolls,2171\"\n , \"YasuoMains,963\"\n , \"yee,4661\"\n ",
"end": 105789,
"score": 0.9577472806,
"start": 105779,
"tag": "USERNAME",
"value": "yarntrolls"
},
{
"context": "ments,18579\"\n , \"youtubehaiku,194879\"\n , \"yoyhammer,1854\"\n , \"yugioh,30391\"\n , \"yuruyuri,",
"end": 106192,
"score": 0.5841126442,
"start": 106191,
"tag": "USERNAME",
"value": "y"
},
{
"context": "\n , \"yugioh,30391\"\n , \"yuruyuri,856\"\n , \"yvonnestrahovski,9131\"\n , \"Zappa,5521\"\n , \"zelda,140888\"\n ",
"end": 106270,
"score": 0.9174100161,
"start": 106254,
"tag": "USERNAME",
"value": "yvonnestrahovski"
}
] | src/elm/Sfw.elm | Dobiasd/RedditTimeMachine | 21 | module Sfw (..) where
sfwRaw : List String
sfwRaw =
[ "100yearsago,32345"
, "1200isplenty,40968"
, "12thMan,946"
, "1911,6937"
, "195,10030"
, "2007scape,45053"
, "240sx,3708"
, "30ROCK,20200"
, "336RS,5"
, "3amjokes,48060"
, "3Dmodeling,8997"
, "3Dprinting,45402"
, "3DS,105660"
, "3DSdeals,13270"
, "3dshacks,4549"
, "40kLore,2901"
, "49ers,23227"
, "4ChanMeta,8778"
, "4PanelCringe,17496"
, "4Runner,3143"
, "4x4,18457"
, "4Xgaming,6475"
, "52weeksofcooking,21831"
, "7daystodie,8453"
, "7kglobal,586"
, "80smusic,6852"
, "8chan,9806"
, "90sAlternative,7895"
, "90smusic,6374"
, "911truth,9696"
, "9gag,4223"
, "A858DE45F56D9BC9,11616"
, "AAdiscussions,203"
, "AaronTracker,4"
, "AbandonedPorn,300746"
, "ABCDesis,4339"
, "ableton,18019"
, "ABraThatFits,43569"
, "AcademicBiblical,8561"
, "Acadiana,2074"
, "AccidentalComedy,34518"
, "AccidentalRenaissance,7883"
, "Accounting,29020"
, "AceAttorney,6444"
, "acecombat,1946"
, "AceOfAngels8,1547"
, "ACMilan,3076"
, "ACON_Support,455"
, "acting,13840"
, "ActionFigures,7067"
, "ActLikeYouBelong,20574"
, "ACTrade,10624"
, "actualconspiracies,12269"
, "actuallesbians,50164"
, "AdamCarolla,5185"
, "Addons4Kodi,4778"
, "Adelaide,6433"
, "ADHD,43331"
, "AdorableDragons,5874"
, "AdrenalinePorn,67900"
, "ads,7112"
, "adultery,4964"
, "adultswim,15055"
, "AdvancedRunning,8663"
, "AdventureCapitalist,2034"
, "adventurerlogkiraigen,3"
, "adventuretime,154732"
, "advertising,22881"
, "Advice,28313"
, "AdviceAnimals,4280324"
, "AdviceAtheists,15199"
, "AdvLog,6"
, "afinil,6147"
, "AFL,12831"
, "AfterEffects,13537"
, "AgainstGamerGate,1828"
, "AgainstHateSubreddits,2564"
, "againstmensrights,8568"
, "Agario,20815"
, "agentcarter,8096"
, "aggies,8415"
, "ainbow,39002"
, "AirBnB,3030"
, "AirForce,16643"
, "airsoft,24091"
, "A_irsoft,531"
, "airsoftmarket,3989"
, "ak47,7742"
, "AkameGaKILL,4701"
, "alaska,8188"
, "Albany,4057"
, "alberta,7316"
, "albiononline,2721"
, "AlbumArtPorn,38777"
, "Albuquerque,5171"
, "alcohol,19222"
, "aldub,251"
, "Aleague,4828"
, "alexandradaddario,11623"
, "AlexisRen,10418"
, "AlienBlue,205706"
, "aliens,14241"
, "AliensAmongUs,7610"
, "AlisonBrie,39875"
, "allthingsprotoss,8880"
, "AllThingsTerran,9039"
, "allthingszerg,9941"
, "alternativeart,50896"
, "altnewz,6882"
, "AMA,110503"
, "amateurradio,18510"
, "amazon,12531"
, "amazonecho,4205"
, "AmazonTopRated,31361"
, "Amd,15312"
, "americandad,10454"
, "AmericanHorrorStory,41385"
, "AmericanPolitics,7383"
, "amibeingdetained,28268"
, "AmIFreeToGo,18446"
, "amiibo,40041"
, "AmiiboCanada,2665"
, "AmISexy,29827"
, "AmItheAsshole,9068"
, "amiugly,58738"
, "Amsterdam,8891"
, "AnaheimDucks,4120"
, "analog,25027"
, "analogygifs,15193"
, "Anarchism,61152"
, "Anarcho_Capitalism,24470"
, "anarchomemes,2235"
, "Anarchy101,8342"
, "Android,619379"
, "androidapps,71654"
, "androidcirclejerk,10091"
, "androiddev,45103"
, "AndroidGaming,60786"
, "AndroidMasterRace,17075"
, "AndroidQuestions,21961"
, "androidthemes,43273"
, "AndroidTV,2073"
, "AndroidWear,22250"
, "ANGEL,3818"
, "angelsbaseball,4015"
, "AngieVarona,7416"
, "AngieVaronaLegal,14860"
, "angularjs,14290"
, "AnimalCollective,3999"
, "AnimalCrossing,52738"
, "AnimalPorn,58298"
, "Animals,16669"
, "AnimalsBeingBros,155109"
, "AnimalsBeingDerps,68440"
, "AnimalsBeingGeniuses,11587"
, "AnimalsBeingJerks,260301"
, "AnimalTextGifs,16525"
, "animation,30036"
, "anime,329033"
, "AnimeFigures,9580"
, "animegifs,23635"
, "animegifsound,2956"
, "anime_irl,21733"
, "animelegs,1158"
, "animenocontext,17583"
, "animeponytails,1120"
, "AnimeSketch,7131"
, "Animesuggest,33759"
, "Animewallpaper,25418"
, "Anna_Faith,3919"
, "annakendrick,23257"
, "AnnArbor,6710"
, "announcements,9800402"
, "annualkpopawards,63"
, "ANormalDayInRussia,107448"
, "answers,90064"
, "Anthropology,42357"
, "AntiAntiJokes,19258"
, "Anticonsumption,36517"
, "AntiJokes,67527"
, "antinatalism,1278"
, "ANTM,2152"
, "Anxiety,72471"
, "AnythingGoesNews,18624"
, "AnythingGoesPics,24342"
, "aoe2,15746"
, "aphextwin,3243"
, "apink,2849"
, "ApocalypseRising,1312"
, "AppalachianTrail,13382"
, "AppHookup,54908"
, "apple,303477"
, "applehelp,18550"
, "appletv,11595"
, "AppleWatch,17573"
, "ApplyingToCollege,3909"
, "AquamarineVI,258"
, "Aquariums,55476"
, "ar15,25099"
, "arabs,6346"
, "araragi,6637"
, "Archaeology,29159"
, "archeage,18222"
, "ArcherFX,114190"
, "Archery,23167"
, "architecture,66636"
, "ArchitecturePorn,67248"
, "archlinux,26220"
, "arcticmonkeys,7984"
, "arduino,54938"
, "arewerolling,5972"
, "argentina,18793"
, "ArianaGrande,18748"
, "arielwinter,8131"
, "arizona,9188"
, "ARK,9688"
, "Arkansas,5084"
, "arkfactions,352"
, "arma,27814"
, "armenia,1578"
, "ArmoredWarfare,4370"
, "army,17100"
, "arresteddevelopment,114120"
, "arrow,54555"
, "Art,4418320"
, "ArtefactPorn,52941"
, "artificial,20563"
, "ArtisanVideos,150438"
, "ArtistLounge,4904"
, "ArtPorn,47635"
, "AsABlackMan,5445"
, "asatru,5196"
, "asexuality,9774"
, "Ashens,9899"
, "asheville,5954"
, "AshVsEvilDead,2799"
, "asianamerican,9586"
, "AsianBeauty,33062"
, "AsianCuties,30944"
, "AsianHottiesGIFS,14792"
, "AsianLadyboners,6093"
, "AsianMasculinity,6203"
, "AsianParentStories,9823"
, "AskAcademia,22049"
, "askaconservative,1957"
, "AskAnAmerican,5448"
, "AskAnthropology,26531"
, "askashittydoctor,11900"
, "askcarsales,11328"
, "AskCulinary,91322"
, "AskDocs,11072"
, "AskDoctorSmeeee,6793"
, "askdrugs,11213"
, "AskElectronics,20673"
, "AskEngineers,47497"
, "AskEurope,4997"
, "AskFeminists,8567"
, "AskGames,8898"
, "askgaybros,20243"
, "AskHistorians,462271"
, "AskHistory,10196"
, "AskHR,2694"
, "AskLE,1681"
, "AskMen,220171"
, "AskMenOver30,13031"
, "askMRP,689"
, "AskNetsec,14828"
, "AskNYC,9909"
, "askphilosophy,35904"
, "AskPhysics,8632"
, "Ask_Politics,19137"
, "askportland,2530"
, "AskReddit,10155641"
, "askscience,6895111"
, "AskScienceDiscussion,12244"
, "AskScienceFiction,55288"
, "askseddit,17700"
, "AskSF,3748"
, "AskSocialScience,57653"
, "asktransgender,23115"
, "AskTrollX,8560"
, "asktrp,23896"
, "AskUK,12080"
, "AskVet,8103"
, "AskWomen,225556"
, "askwomenadvice,6981"
, "AskWomenOver30,6563"
, "asmr,112789"
, "asoiaf,244263"
, "asoiafcirclejerk,4344"
, "aspergers,15150"
, "assassinscreed,46238"
, "assettocorsa,6121"
, "Assistance,29810"
, "astrology,8515"
, "Astronomy,141457"
, "astrophotography,57121"
, "Astros,4952"
, "ASU,4409"
, "atheism,2099225"
, "atheistvids,7627"
, "Atlanta,32975"
, "AtlantaHawks,4422"
, "atlbeer,3517"
, "atletico,1135"
, "atmidnight,3523"
, "AubreyPlaza,14920"
, "auckland,5226"
, "Audi,14219"
, "audiobooks,13601"
, "audioengineering,51568"
, "Audiomemes,4680"
, "audiophile,54275"
, "AusFinance,7694"
, "auslaw,4139"
, "Austin,50816"
, "australia,106489"
, "AustralianCattleDog,4919"
, "AustralianMakeup,4210"
, "AustralianPolitics,6610"
, "Austria,17901"
, "Authentic_Vaping,733"
, "autism,10224"
, "AutoDetailing,28181"
, "Automate,16572"
, "Autos,72116"
, "aves,21455"
, "avfc,1877"
, "aviation,65472"
, "awakened,6010"
, "awardtravel,3823"
, "awesome,63586"
, "AwesomeCarMods,14282"
, "Awesomenauts,6926"
, "awfuleverything,8550"
, "awfuleyebrows,16927"
, "aws,7148"
, "aww,8383516"
, "Awwducational,105958"
, "awwnime,43090"
, "awwnverts,13808"
, "awwtf,5978"
, "Awww,30169"
, "awwwtf,52204"
, "ayylmao,12334"
, "AyyMD,2243"
, "AZCardinals,4375"
, "BabyBumps,30685"
, "BabyCorgis,3817"
, "babyelephantgifs,78348"
, "BABYMETAL,4337"
, "backpacking,66411"
, "BacktotheFuture,8217"
, "BackYardChickens,13125"
, "Bacon,23353"
, "baconreader,286837"
, "badcode,11582"
, "Bad_Cop_Follow_Up,383"
, "Bad_Cop_No_Donut,83168"
, "badeconomics,7137"
, "BadguyWolfies,2"
, "badhistory,53746"
, "badlegaladvice,6941"
, "badlinguistics,12134"
, "badmathematics,2022"
, "badMovies,17298"
, "badphilosophy,12828"
, "badpolitics,4844"
, "bad_religion,3771"
, "badroommates,7389"
, "badscience,7812"
, "BadSocialScience,4476"
, "badtattoos,46256"
, "baduk,7264"
, "badukpolitics,345"
, "badwomensanatomy,5426"
, "bagelheads,52"
, "BakaNewsJP,3604"
, "bakchodi,4281"
, "Baking,76381"
, "balisong,2263"
, "baltimore,17454"
, "Bandnames,20585"
, "bangalore,2431"
, "bangtan,716"
, "Banished,21413"
, "BanjoKazooie,2109"
, "banned,779"
, "BannedFrom4chan,10945"
, "bannedfromclubpenguin,49385"
, "bapcsalescanada,10233"
, "bapcsalesuk,4425"
, "BarbaraPalvin,5677"
, "Barca,13022"
, "Barcelona,3289"
, "bardmains,2928"
, "barstoolsports,3779"
, "bartenders,11404"
, "baseball,155176"
, "baseballcirclejerk,2681"
, "BasicIncome,31039"
, "Bass,39616"
, "bassnectar,4105"
, "BatFacts,7222"
, "batman,135188"
, "BatmanArkham,9761"
, "batonrouge,3672"
, "Battlecars,3906"
, "battlecats,2008"
, "Battlefield,28894"
, "battlefield3,51573"
, "battlefield_4,87684"
, "Battlefield_4_CTE,4335"
, "battlefront,8845"
, "battlestations,181457"
, "battlewagon,8473"
, "bayarea,37443"
, "baylor,1774"
, "BBQ,36931"
, "beadsprites,12708"
, "beagle,7016"
, "BeAmazed,49884"
, "BeardedDragons,6346"
, "BeardPorn,19798"
, "beards,107205"
, "beatles,26412"
, "Beatmatch,12427"
, "BeautifulFemales,6427"
, "BeautyBoxes,12831"
, "BeautyGuruChat,2738"
, "BeavisAndButthead,6556"
, "bee_irl,4427"
, "beer,175146"
, "beercirclejerk,1519"
, "beermoney,99255"
, "beerporn,31777"
, "beertrade,12564"
, "beerwithaview,18068"
, "beetlejuicing,11675"
, "beforeandafteredit,8036"
, "BeforeNAfterAdoption,35617"
, "belgium,24164"
, "BellaThorne,6409"
, "Bellingham,3929"
, "bengals,7308"
, "benzodiazepines,3782"
, "berkeley,10041"
, "berlin,9091"
, "Berserk,11710"
, "berserklejerk,378"
, "bertstrips,73130"
, "Besiege,20487"
, "Bestbuy,1252"
, "bestof,4825375"
, "bestoflegaladvice,24410"
, "BestOfLiveleak,23546"
, "bestofnetflix,47255"
, "BestOfOutrageCulture,8893"
, "BestOfReports,11937"
, "BestOfStreamingVideo,39169"
, "bettafish,8565"
, "BetterEveryLoop,1992"
, "betternews,1997"
, "BetterSubredditdrama,273"
, "beyondthebump,16392"
, "BF_Hardline,12243"
, "bicycletouring,18700"
, "bicycling,167014"
, "bigbangtheory,26548"
, "BigBrother,21975"
, "bigdickproblems,32160"
, "biggestproblem,424"
, "bikecommuting,18540"
, "Bikeporn,20438"
, "bikesgonewild,23533"
, "bikewrench,15542"
, "BillBurr,9891"
, "billiards,7126"
, "bindingofisaac,72273"
, "bioinformatics,9586"
, "biology,75423"
, "bioniclelego,4119"
, "Bioshock,41261"
, "bipolar,15450"
, "BipolarReddit,13766"
, "Birbs,12097"
, "birdpics,14683"
, "BirdsBeingDicks,29020"
, "birdsofprey,3160"
, "birdswitharms,82881"
, "Birmingham,5808"
, "birthcontrol,7624"
, "bisexual,35587"
, "bitchimabus,46877"
, "Bitcoin,176233"
, "BitcoinMarkets,21106"
, "bitcoinxt,13339"
, "bjj,33502"
, "blackberry,6943"
, "blackbookgraffiti,8555"
, "blackcats,3176"
, "blackdesertonline,8926"
, "Blackfellas,4072"
, "blackfriday,13730"
, "blackladies,9569"
, "BlackLivesMatter,564"
, "BlackMetal,11198"
, "blackmirror,5271"
, "blackops3,37209"
, "Blackout2015,32993"
, "blackpeoplegifs,93773"
, "BlackPeopleTwitter,536812"
, "BlackSails,3569"
, "Blacksmith,25543"
, "BlackwellAcademy,472"
, "bladeandsoul,6677"
, "blakelively,4838"
, "bleach,23050"
, "blender,24603"
, "Blep,44001"
, "blindspot,851"
, "Blink182,11129"
, "BlocParty,778"
, "blogsnark,1030"
, "bloodborne,51353"
, "bloodbowl,3653"
, "BloodGulchRP,177"
, "bloomington,3454"
, "blop,8423"
, "BlueJackets,3055"
, "blues,16528"
, "bluesguitarist,4297"
, "blunderyears,90372"
, "BMW,30818"
, "Boardgamedeals,5984"
, "boardgames,117122"
, "BobsBurgers,37735"
, "bodybuilding,117061"
, "bodymods,10743"
, "bodyweightfitness,187214"
, "Boise,4406"
, "BoJackHorseman,22545"
, "BokuNoHeroAcademia,4307"
, "BollywoodRealism,35697"
, "Bombing,11698"
, "bonnaroo,13215"
, "Bonsai,28350"
, "bookporn,42999"
, "books,6272500"
, "booksuggestions,53715"
, "BoomBeach,10288"
, "boop,34592"
, "BorderCollie,5289"
, "Borderlands2,42577"
, "Borderlands,66180"
, "borrow,4287"
, "borussiadortmund,6204"
, "boston,53540"
, "BostonBruins,13916"
, "bostonceltics,11780"
, "BostonTerrier,6458"
, "botsrights,8562"
, "boulder,8485"
, "bouldering,16196"
, "bourbon,27782"
, "Boxer,7302"
, "Boxing,34148"
, "boxoffice,12419"
, "BPD,9526"
, "BPDlovedones,1652"
, "braces,1244"
, "Brampton,1399"
, "brandnew,8326"
, "brasil2,376"
, "brasil,43923"
, "bravefrontier,28337"
, "Braveryjerk,18373"
, "Braves,11507"
, "BravestWarriors,9697"
, "BravoRealHousewives,3609"
, "Brawlhalla,3280"
, "Breadit,38587"
, "breakingbad,226518"
, "breakingmom,12082"
, "breastfeeding,11418"
, "Briggs,1412"
, "brisbane,15228"
, "bristol,5743"
, "BritishPolitics,3226"
, "britishproblems,112238"
, "BritishSuccess,17782"
, "BritishTV,25517"
, "britpics,17149"
, "Brogress,22861"
, "brokehugs,930"
, "brokengifs,39373"
, "Brooklyn,14035"
, "brooklynninenine,13368"
, "Browns,12674"
, "brum,2583"
, "BSG,17676"
, "btc,5936"
, "buccaneers,4970"
, "buccos,5494"
, "Buddhism,91326"
, "budgetfood,89715"
, "Buffalo,7561"
, "buffalobills,9056"
, "BuffaloWizards,4412"
, "buffy,18868"
, "bugout,11582"
, "buildapc,332244"
, "buildapcforme,36022"
, "buildapcsales,118479"
, "Bulldogs,9916"
, "Bullshitfacts,100"
, "BurningMan,16533"
, "Bushcraft,22441"
, "business,201584"
, "Buttcoin,6712"
, "BuyItForLife,187865"
, "ByTheMods,178"
, "c137,8148"
, "C25K,45786"
, "cablefail,18510"
, "CableManagement,20962"
, "cableporn,58421"
, "CadenMoranDiary,499"
, "CafeRacers,10591"
, "CAguns,1342"
, "cahideas,5342"
, "CalamariRaceTeam,8602"
, "Calgary,18553"
, "CalgaryFlames,3872"
, "California,28005"
, "CaliforniaForSanders,2977"
, "Calligraphy,30726"
, "CallOfDuty,18139"
, "calvinandhobbes,109777"
, "camaro,4841"
, "camping,52059"
, "CampingandHiking,106021"
, "canada,202444"
, "canadaguns,5588"
, "CanadaPolitics,24321"
, "Canadian_ecigarette,3086"
, "CanadianForces,5094"
, "canberra,3324"
, "cancer,6940"
, "candiceswanepoel,6678"
, "canes,1853"
, "CanineCosplay,2041"
, "cannabis,29817"
, "CannabisExtracts,23362"
, "canon,4748"
, "canucks,12026"
, "caps,7537"
, "capstone,1876"
, "CaptchaArt,16528"
, "CaraDelevingne,5521"
, "CarAV,10821"
, "carcrash,15916"
, "Cardinals,10645"
, "cardistry,6647"
, "careerguidance,14037"
, "CarletonU,1893"
, "carnivalclan,10"
, "CarolineVreeland,1513"
, "carporn,130914"
, "cars,181029"
, "Cartalk,25622"
, "caseyneistat,4144"
, "cassetteculture,5086"
, "castiron,13780"
, "CastleClash,1702"
, "castles,29368"
, "CastleTV,7685"
, "CasualConversation,105758"
, "casualiama,90386"
, "casualminecrafting,782"
, "casualnintendo,6267"
, "cataclysmdda,2095"
, "CatastrophicFailure,25039"
, "catbellies,8016"
, "CatGifs,27205"
, "CatHighFive,12747"
, "Catholicism,21215"
, "Catloaf,17258"
, "catpictures,55448"
, "cats,312768"
, "CatsAreAssholes,9683"
, "CatsInSinks,8154"
, "CatSlaps,10293"
, "catssittingdown,2902"
, "CatsStandingUp,56499"
, "CautiousBB,2491"
, "CCJ2,992"
, "CCW,26379"
, "CelebGfys,11641"
, "celeb_redheads,5133"
, "CelebrityArmpits,2054"
, "CelebrityFeet,5430"
, "Celebs,174806"
, "Cello,3627"
, "CFB,154117"
, "cfbball,2270"
, "cfbcirclejerk,1170"
, "CFBOffTopic,1829"
, "CFL,4825"
, "CGPGrey,43053"
, "changemyview,214363"
, "charactercrossovers,8297"
, "characterdrawing,11157"
, "CharacterRant,719"
, "Charcuterie,14267"
, "Chargers,9499"
, "Charleston,5065"
, "Charlotte,9223"
, "CharlotteHornets,3203"
, "Chattanooga,4290"
, "Cheese,10036"
, "chelseafc,22362"
, "ChemicalEngineering,5494"
, "chemicalreactiongifs,150902"
, "chemistry,63462"
, "CherokeeXJ,3482"
, "chess,43056"
, "CHIBears,20971"
, "chicago,75767"
, "chicagobulls,18884"
, "chickyboo,66"
, "CHICubs,7236"
, "ChiefKeef,2026"
, "Chihuahua,5681"
, "childfree,91356"
, "ChildrenFallingOver,69583"
, "chile,10669"
, "chiliadmystery,18929"
, "chillmusic,27584"
, "chillstep,11022"
, "China,26200"
, "ChineseLanguage,13675"
, "Chipotle,3245"
, "ChivalryGame,9331"
, "chloegracemoretz,12169"
, "chomsky,4922"
, "Christianity,107140"
, "christmas,10728"
, "chrome,32514"
, "Chromecast,51459"
, "chromeos,19097"
, "ChronicPain,6516"
, "chronotrigger,3598"
, "chuck,8789"
, "churning,32003"
, "cider,5157"
, "Cigarettes,4701"
, "cigars,33349"
, "cincinnati,13085"
, "Cinema4D,6713"
, "Cinemagraphs,112881"
, "CinemaSins,9200"
, "cinematography,15325"
, "CineShots,14842"
, "circlebroke2,6744"
, "circlebroke,34885"
, "circlejerk,271122"
, "circlejerkaustralia,2226"
, "cirkeltrek,2867"
, "CitiesSkylines,98594"
, "CityPorn,151648"
, "civ,133370"
, "civbattleroyale,7742"
, "civbeyondearth,10605"
, "civcirclejerk,3223"
, "Civcraft,7401"
, "civilengineering,4274"
, "CivilizatonExperiment,1265"
, "CivPolitics,21726"
, "CK2GameOfthrones,6724"
, "cky,496"
, "Clannad,3381"
, "ClashOfClans,81525"
, "classic4chan,85772"
, "classicalmusic,64714"
, "classiccars,17450"
, "ClassicRock,10769"
, "ClassyPornstars,15318"
, "cleanjokes,14002"
, "cleganebowl,5624"
, "Cleveland,11225"
, "clevelandcavs,9808"
, "CleverEdits,5346"
, "CLG,13686"
, "ClickerHeroes,15511"
, "climate,12966"
, "climateskeptics,6888"
, "climbing,72122"
, "Cloud9,4537"
, "Coachella,10822"
, "coaxedintoasnafu,17506"
, "cockatiel,2267"
, "cocktails,33081"
, "CodAW,24135"
, "CoDCompetitive,20874"
, "coding,66960"
, "CODZombies,13852"
, "COents,6279"
, "Coffee,110879"
, "Coilporn,13994"
, "coins,10866"
, "Coldplay,5509"
, "collapse,41520"
, "college,28864"
, "CollegeBasketball,61219"
, "collegehockey,3666"
, "Colorado,19638"
, "ColoradoAvalanche,4951"
, "ColoradoSprings,3994"
, "ColorBlind,4621"
, "Colorization,26156"
, "ColorizedHistory,99105"
, "Colts,8260"
, "Columbus,15298"
, "CombatFootage,77124"
, "combinedgifs,65130"
, "Comcast,2689"
, "comedy,28699"
, "comedybangbang,4013"
, "ComedyCemetery,10477"
, "comeonandslam,35693"
, "comicbookart,22250"
, "ComicBookCollabs,2817"
, "comicbookcollecting,1402"
, "comicbookmovies,17976"
, "comicbooks,160279"
, "comics,441001"
, "ComicWalls,11362"
, "commandline,22571"
, "CommercialCuts,30783"
, "communism101,6139"
, "communism,15299"
, "CommunismWorldwide,1627"
, "community,150790"
, "CompanyOfHeroes,6707"
, "CompetitiveEDH,3559"
, "CompetitiveHalo,3326"
, "CompetitiveHS,47685"
, "CompetitiveWoW,4515"
, "COMPLETEANARCHY,394"
, "compsci,94243"
, "computergraphics,12259"
, "computers,16264"
, "computertechs,15891"
, "confession,113513"
, "confessions,22184"
, "ConfusedTravolta,17331"
, "confusing_perspective,14521"
, "conlangs,8793"
, "Connecticut,10794"
, "Connery,1290"
, "Conservative,52253"
, "conservatives,3923"
, "consoledeals,18933"
, "consoles,5770"
, "conspiracy,345872"
, "conspiracyfact,2849"
, "ConspiracyGrumps,5407"
, "conspiratard,51165"
, "Constantine,4566"
, "Construction,6652"
, "consulting,12968"
, "ContagiousLaughter,132132"
, "contentawarescale,4899"
, "ContestOfChampions,3794"
, "Cooking,333643"
, "cookingvideos,17475"
, "coolgithubprojects,12806"
, "coolguides,94291"
, "copypasta,13476"
, "cordcutters,94372"
, "corgi,83554"
, "CorporateFacepalm,31639"
, "cosplay,137953"
, "cosplaygirls,134349"
, "Costco,3709"
, "counterstrike,22326"
, "counting,8140"
, "country,7503"
, "coupons,40863"
, "cowboybebop,11659"
, "cowboys,18201"
, "Coyotes,1832"
, "coys,13596"
, "CozyPlaces,32862"
, "cpp,33338"
, "C_Programming,18035"
, "Cr1TiKaL,2588"
, "CrackStatus,2292"
, "CraftBeer,10617"
, "crafts,55168"
, "CraftyTrolls,3403"
, "Crainn,1575"
, "CrappyDesign,237472"
, "crappymusic,18421"
, "crappyoffbrands,16576"
, "CrazyHand,9295"
, "CrazyIdeas,181705"
, "CredibleDefense,10878"
, "creepy,4398297"
, "creepygaming,24434"
, "creepyPMs,158516"
, "Cricket,26375"
, "cringe,385431"
, "CringeAnarchy,61496"
, "cringepics,583381"
, "cripplingalcoholism,21723"
, "criterion,4854"
, "criticalrole,2943"
, "CriticalTheory,10699"
, "croatia,11786"
, "crochet,35571"
, "CrohnsDisease,7483"
, "crossdressing,14590"
, "crossfit,36541"
, "CrossfitGirls,8882"
, "CrossStitch,13860"
, "CrossView,17811"
, "CruciblePlaybook,14983"
, "CrusaderKings,36885"
, "crusadersquest,3577"
, "crypto,29585"
, "CryptoCurrency,18837"
, "cscareerquestions,58581"
, "csgo,5317"
, "csgobetting,52532"
, "csgolounge,9997"
, "csgomarketforum,2979"
, "csharp,25499"
, "C_S_T,2115"
, "Cubers,13202"
, "CubeWorld,15976"
, "CucumbersScaringCats,20714"
, "curiosityrover,16986"
, "curlyhair,29461"
, "customhearthstone,4569"
, "custommagic,4485"
, "cute,11253"
, "cutegirlgifs,14393"
, "cuteguys,1369"
, "cutekorean,5063"
, "cutelittlefangs,1166"
, "cutouts,6122"
, "CyanideandHappiness,30836"
, "cyanogenmod,14028"
, "Cyberpunk,82363"
, "cycling,25596"
, "Cynicalbrit,55888"
, "DabArt,1043"
, "Dachshund,15446"
, "daddit,40075"
, "dadjokes,245586"
, "DadReflexes,52100"
, "DAE,17275"
, "DaftPunk,29431"
, "DailyShow,7881"
, "DailyTechNewsShow,5685"
, "DaisyRidley,1327"
, "Dallas,25779"
, "DallasStars,3831"
, "Damnthatsinteresting,146768"
, "dancarlin,3306"
, "dancegavindance,1821"
, "danganronpa,2745"
, "dankchristianmemes,13003"
, "dankmemes,11694"
, "DankNation,1331"
, "DANMAG,5078"
, "Daredevil,8712"
, "DarkEnlightenment,7829"
, "darkestdungeon,8726"
, "DarkFuturology,9937"
, "DarkNetMarketsNoobs,18225"
, "darknetplan,44075"
, "DarkSouls2,71753"
, "darksouls3,13399"
, "darksouls,82119"
, "DarthJarJar,10433"
, "Dashcam,6012"
, "dashcamgifs,13243"
, "DataHoarder,18525"
, "dataisbeautiful,4614966"
, "dataisugly,11323"
, "datascience,11962"
, "DatGuyLirik,9885"
, "dating,13296"
, "dating_advice,37281"
, "DavidBowie,2792"
, "davidtennant,5976"
, "dawngate,6220"
, "DaystromInstitute,17624"
, "dayz,112045"
, "dbz,62888"
, "DBZDokkanBattle,4102"
, "DC_Cinematic,6632"
, "DCcomics,69190"
, "dcss,2059"
, "de,25353"
, "DeadBedrooms,29380"
, "deadmau5,12463"
, "deadpool,29636"
, "DeadSpace,5586"
, "deals,25006"
, "DealsReddit,41886"
, "DealWin,80"
, "Deathcore,7633"
, "deathgrips,12664"
, "Debate,5177"
, "DebateAChristian,13626"
, "DebateaCommunist,6179"
, "DebateAnarchism,3414"
, "DebateAnAtheist,15404"
, "DebateCommunism,2942"
, "DebateFascism,1996"
, "DebateReligion,32207"
, "debian,12889"
, "DecidingToBeBetter,93400"
, "declutter,24903"
, "deepdream,20841"
, "deephouse,15805"
, "DeepIntoYouTube,142458"
, "deepweb,14568"
, "defaultgems,39649"
, "Defenders,15206"
, "de_IAmA,97400"
, "Delaware,4180"
, "Delightfullychubby,23120"
, "Dell,1397"
, "delusionalartists,77858"
, "democrats,17204"
, "Demotivational,96858"
, "Denmark,37793"
, "Dentistry,8266"
, "Denton,4653"
, "Denver,30830"
, "DenverBroncos,14461"
, "denvernuggets,2380"
, "deOhneRegeln,251"
, "depression,124996"
, "DepthHub,229662"
, "DerekSmart,357"
, "DescentIntoTyranny,6177"
, "Design,127308"
, "design_critiques,21406"
, "DesignPorn,99280"
, "DesirePath,37409"
, "DessertPorn,35858"
, "Destiny,12684"
, "DestinyTheGame,237300"
, "DestroyedTanks,4313"
, "DestructiveReaders,5756"
, "Detroit,14930"
, "detroitlions,12057"
, "DetroitPistons,3704"
, "DetroitRedWings,15784"
, "Deusex,9543"
, "devils,5355"
, "devops,10947"
, "Dexter,43453"
, "DFO,5521"
, "dfsports,10596"
, "dgu,10526"
, "DHMIS,707"
, "diabetes,12708"
, "Diablo,138207"
, "diablo3,77581"
, "Diablo3witchdoctors,9364"
, "DickButt,12541"
, "Diesel,5248"
, "digimon,12964"
, "digitalnomad,16439"
, "DigitalPainting,13354"
, "DimensionalJumping,5966"
, "Dinosaurs,31288"
, "DippingTobacco,6785"
, "dirtgame,3941"
, "Dirtybomb,9965"
, "discgolf,30366"
, "discordapp,1992"
, "discworld,14437"
, "dishonored,10526"
, "disney,60279"
, "Disney_Infinity,3854"
, "Disneyland,14792"
, "DivinityOriginalSin,9870"
, "Divorce,5435"
, "DiWHY,37561"
, "DIY,4962828"
, "DIY_eJuice,20583"
, "django,15141"
, "Djent,10102"
, "DJs,25214"
, "DMT,13018"
, "DnB,32667"
, "DnD,105398"
, "DnDBehindTheScreen,15534"
, "DnDGreentext,17156"
, "dndnext,21755"
, "docker,6166"
, "doctorwho,250183"
, "Documentaries,4580748"
, "Dodgers,10729"
, "DoesAnybodyElse,261602"
, "DoesNotTranslate,9940"
, "dogecoin,83697"
, "dogpictures,77382"
, "dogs,104862"
, "DogShowerThoughts,21093"
, "dogswearinghats,15014"
, "Dogtraining,39134"
, "donaldglover,20005"
, "dontdeadopeninside,3833"
, "DontPanic,11066"
, "dontstarve,19267"
, "doodles,17659"
, "Doom,5036"
, "doommetal,12216"
, "DotA2,258579"
, "dota2circlejerk,2798"
, "dota2dadjokes,3428"
, "Dota2Trade,12728"
, "dotamasterrace,6572"
, "dotnet,14555"
, "douglovesmovies,3111"
, "DowntonAbbey,11680"
, "Drag,5503"
, "dragonage,53735"
, "dragonblaze,1148"
, "dragons,3236"
, "Drama,17506"
, "drawing,75446"
, "Dreadfort,10290"
, "Dreadlocks,5904"
, "Dreamtheater,3460"
, "dresdenfiles,12027"
, "Drifting,13538"
, "DrugArt,8384"
, "DrugNerds,32064"
, "Drugs,228355"
, "drugscirclejerk,3598"
, "DrugStashes,8402"
, "drumcorps,5752"
, "drums,33872"
, "drunk,114115"
, "drunkenpeasants,1757"
, "DrunkOrAKid,65715"
, "drupal,6221"
, "Dualsport,9345"
, "dubai,4584"
, "DubbedGIFS,13450"
, "dubstep,89757"
, "ducks,3072"
, "duelyst,4587"
, "DumpsterDiving,24676"
, "duncantrussell,2897"
, "DunderMifflin,91474"
, "dune,7810"
, "dungeondefenders,5844"
, "DungeonsAndDragons,17802"
, "duolingo,29514"
, "dvdcollection,8984"
, "DvZ,1400"
, "dwarffortress,42783"
, "dxm,2143"
, "dyinglight,11424"
, "dykesgonemild,6450"
, "DynastyFF,3058"
, "E30,2265"
, "EAF,16034"
, "eagles,23209"
, "EA_NHL,11099"
, "earthbound,10060"
, "EarthPorn,6502343"
, "Earwolf,6522"
, "EatCheapAndHealthy,276512"
, "eatsandwiches,57048"
, "Ebay,8418"
, "EBEs,13932"
, "eCards,29022"
, "ECE,26731"
, "ecigclassifieds,11378"
, "ecig_vendors,8038"
, "Economics,236030"
, "economy,59749"
, "ecr_eu,3606"
, "EDC,85291"
, "EDH,21507"
, "Edinburgh,6329"
, "EditingAndLayout,24079"
, "editors,14771"
, "EDM,50366"
, "Edmonton,12765"
, "EdmontonOilers,4661"
, "edmprodcirclejerk,4782"
, "edmproduction,63802"
, "education,47548"
, "educationalgifs,115945"
, "Eesti,6153"
, "eFreebies,53414"
, "Egalitarianism,4904"
, "ElderScrolls,19349"
, "elderscrollsonline,67599"
, "eldertrees,48435"
, "ElectricForest,6570"
, "electricians,9406"
, "electricvehicles,4764"
, "electronic_cigarette,114500"
, "electronicmusic,138356"
, "electronics,53757"
, "EliteDangerous,55641"
, "EliteHudson,1081"
, "EliteLavigny,1954"
, "EliteOne,3825"
, "elonmusk,6205"
, "ElsaHosk,2291"
, "Elsanna,6510"
, "ELTP,492"
, "emacs,11891"
, "EmDrive,4569"
, "Emerald_Council,1265"
, "EmeraldPS2,2312"
, "EmiliaClarke,15573"
, "EmilyRatajkowski,14364"
, "Eminem,13876"
, "Emma_Roberts,5105"
, "EmmaStone,26948"
, "EmmaWatson,78697"
, "Emo,5639"
, "emojipasta,2438"
, "EmpireDidNothingWrong,5436"
, "ems,17159"
, "emulation,28880"
, "EndlessLegend,5083"
, "EndlessWar,11999"
, "energy,55095"
, "ENFP,7060"
, "engineering,104185"
, "EngineeringPorn,45885"
, "EngineeringStudents,51259"
, "engrish,11043"
, "Enhancement,75265"
, "enlightenedbirdmen,30500"
, "EnoughLibertarianSpam,9844"
, "enoughsandersspam,741"
, "entertainment,173904"
, "Entomology,8920"
, "entp,5604"
, "Entrepreneur,166649"
, "entwives,14075"
, "environment,146550"
, "EOOD,19281"
, "EpicMounts,5474"
, "EQNext,8756"
, "EqualAttraction,9684"
, "Equestrian,5357"
, "ericprydz,1932"
, "esports,11919"
, "ethereum,6650"
, "ethoslab,4633"
, "Etsy,16338"
, "eu4,32332"
, "europe,537859"
, "european,10269"
, "EuropeMeta,259"
, "europes,1507"
, "evangelion,17166"
, "Eve,56006"
, "evenwithcontext,31703"
, "eveological,25"
, "everquest,3755"
, "Everton,5136"
, "everymanshouldknow,242753"
, "EverythingScience,55621"
, "EVEX,12202"
, "EvilLeagueOfEvil,8410"
, "evolution,21123"
, "EvolveGame,9577"
, "excel,38541"
, "exchristian,8523"
, "exjw,8025"
, "exmormon,25885"
, "exmuslim,10826"
, "ExNoContact,3289"
, "exo,1394"
, "exoticspotting,8165"
, "ExpectationVsReality,100161"
, "explainlikedrcox,34458"
, "explainlikeIAmA,96385"
, "ExplainLikeImCalvin,47635"
, "explainlikeimfive,6846145"
, "ExplainLikeImPHD,11743"
, "ExposurePorn,68975"
, "Eyebleach,150127"
, "eyes,17399"
, "F1FeederSeries,1888"
, "f7u12_ham,6379"
, "FA30plus,538"
, "facebookdrama,7467"
, "facebookwins,53333"
, "facepalm,408876"
, "fairytail,18521"
, "fakealbumcovers,4364"
, "fakeid,10282"
, "falcons,8897"
, "Fallout,304961"
, "Fallout4,14098"
, "Fallout4Builds,3199"
, "Fallout4_ja,192"
, "FallOutBoy,5424"
, "falloutequestria,2519"
, "falloutlore,15668"
, "FalloutMods,9901"
, "falloutsettlements,13645"
, "falloutshelter,4096"
, "familyguy,25344"
, "FancyFollicles,77989"
, "fandomnatural,3460"
, "FanFiction,5293"
, "fantanoforever,4289"
, "Fantasy,87143"
, "fantasybaseball,17120"
, "fantasybball,14718"
, "fantasyfootball,160969"
, "Fantasy_Football,5605"
, "fantasyhockey,8947"
, "FantasyPL,17103"
, "FantasyWarTactics,386"
, "fantasywriters,15701"
, "FanTheories,163226"
, "FargoTV,14383"
, "farming,13773"
, "FashionReps,6721"
, "fasting,9539"
, "fatestaynight,6850"
, "fatlogic,116533"
, "fatpeoplestories,107408"
, "Favors,30877"
, "fcbayern,7483"
, "fcs,1613"
, "FearTheWalkingDead,16575"
, "feedthebeast,26505"
, "FeelsLikeTheFirstTime,37234"
, "FellowKids,69315"
, "femalefashionadvice,117403"
, "Feminism,54932"
, "feminisms,29926"
, "FemmeThoughts,7741"
, "FeMRADebates,4088"
, "Fencing,5323"
, "FenerbahceSK,421"
, "ferrets,11126"
, "festivals,17253"
, "Fez,1386"
, "fffffffuuuuuuuuuuuu,586149"
, "FFRecordKeeper,8706"
, "ffxi,4739"
, "ffxiv,84399"
, "FierceFlow,6322"
, "FIFA,56885"
, "FifaCareers,11352"
, "fifthworldproblems,57276"
, "Fighters,10406"
, "Filmmakers,71513"
, "FilthyFrank,10673"
, "FinalFantasy,50546"
, "finance,69808"
, "FinancialCareers,8026"
, "financialindependence,102734"
, "findapath,21112"
, "findareddit,40022"
, "Finland,9119"
, "Firearms,30216"
, "fireemblem,26359"
, "fireemblemcasual,1316"
, "firefall,4912"
, "Firefighting,9907"
, "firefly,76407"
, "firefox,23600"
, "Fireteams,51572"
, "fireTV,5788"
, "firstimpression,14369"
, "firstworldanarchists,281557"
, "FirstWorldConformists,11139"
, "firstworldproblems,157362"
, "Fishing,54308"
, "FitAndNatural,16547"
, "fitbit,13931"
, "fitmeals,125675"
, "Fitness,4850074"
, "fitnesscirclejerk,7865"
, "Fiveheads,8558"
, "FiveM,1791"
, "fivenightsatfreddys,17394"
, "FixedGearBicycle,23119"
, "Flagstaff,1493"
, "flashlight,12573"
, "FlashTV,47356"
, "flexibility,34107"
, "flicks,12974"
, "flightsim,12125"
, "Flipping,35830"
, "Floof,10597"
, "florida,12400"
, "FloridaGators,4319"
, "FloridaMan,122022"
, "Flyers,11064"
, "flyfishing,12324"
, "flying,30355"
, "fnafcringe,2614"
, "fnv,20981"
, "fo3,8039"
, "fo4,147215"
, "FO4mods,366"
, "FocusST,1754"
, "FoggyPics,10716"
, "folk,13476"
, "FolkPunk,15942"
, "food,4730209"
, "Foodforthought,157028"
, "foodhacks,95996"
, "FoodPorn,413543"
, "Foofighters,8927"
, "football,26489"
, "footballdownload,15273"
, "footballhighlights,27801"
, "footballmanagergames,23502"
, "footbaww,7007"
, "Ford,8074"
, "fordranger,1848"
, "forearmporn,11124"
, "ForeverAlone,42226"
, "ForeverAloneWomen,4718"
, "Forex,8666"
, "forhire,55995"
, "formula1,95331"
, "forsen,2524"
, "forwardsfromgrandma,70486"
, "forwardsfromhitler,5416"
, "forwardsfromreddit,844"
, "forza,14659"
, "foshelter,20679"
, "fountainpens,27552"
, "foxes,40002"
, "FoxStevenson,836"
, "fpvracing,5746"
, "fragrance,7844"
, "FragReddit,2859"
, "france,60157"
, "FranceLibre,763"
, "Frat,12810"
, "FRC,4624"
, "FreckledGirls,20055"
, "fredericton,1494"
, "FREE,16458"
, "FreeAtheism,1890"
, "freebies,351125"
, "FreeEBOOKS,45558"
, "FreeGameFindings,18033"
, "FreeGamesOnSteam,17645"
, "FreeKarma,13252"
, "freelance,27254"
, "freemasonry,6723"
, "FreeStuff,2104"
, "Freethought,43922"
, "French,27660"
, "FrenchForeignLegion,1126"
, "fresh_funny,2026"
, "fresno,2417"
, "Frisson,116693"
, "frogdogs,5541"
, "frogpants,924"
, "Frontend,14215"
, "FrontPage,5480"
, "Frozen,10432"
, "Frugal,516065"
, "FrugalFemaleFashion,23062"
, "Frugal_Jerk,30490"
, "frugalmalefashion,186054"
, "FrugalMaleFashionCDN,2892"
, "fsu,4512"
, "ft86,5081"
, "ftlgame,27565"
, "ftm,6808"
, "fuckingmanly,23970"
, "FuckingWithNature,26038"
, "fuckmusic,6714"
, "fuckolly,11440"
, "FuckTammy,2619"
, "Fuee,600"
, "FulfillmentByAmazon,7575"
, "FULLCOMMUNISM,12094"
, "fulllife,3927"
, "FullmetalAlchemist,14565"
, "fullmoviesongoogle,24619"
, "fullmoviesonyoutube,210823"
, "functionalprint,6624"
, "funhaus,49438"
, "funk,5940"
, "funkopop,8582"
, "funny,10101609"
, "FunnyandSad,29572"
, "funnysigns,13588"
, "furry,21671"
, "FurryHate,972"
, "FUTMobile,547"
, "futurama,141894"
, "futurebeats,60157"
, "FutureFight,3503"
, "futurefunk,4594"
, "futureporn,64894"
, "FutureWhatIf,17484"
, "Futurology,4595097"
, "gadgets,4642305"
, "gainit,79436"
, "GakiNoTsukai,19468"
, "galatasaray,1097"
, "galaxynote4,9060"
, "galaxynote5,2911"
, "galaxys5,8896"
, "GalaxyS6,9726"
, "gallifrey,50639"
, "Gameboy,7061"
, "gamecollecting,32836"
, "GameDeals,345705"
, "GameDealsMeta,5785"
, "gamedesign,23159"
, "gamedev,147807"
, "gameDevClassifieds,16322"
, "gamegrumps,82577"
, "gamemaker,9003"
, "gamemusic,44931"
, "gameofthrones,589306"
, "GamePhysics,134872"
, "GamerGhazi,9042"
, "gamernews,105654"
, "gamers,4586"
, "Games,669391"
, "GameSale,7647"
, "GameStop,2927"
, "gameswap,18094"
, "gametales,22621"
, "gamindustri,1854"
, "Gaming4Gamers,31124"
, "gaming,9188228"
, "Gamingcirclejerk,5930"
, "gaminggifs,6554"
, "gamingpc,42932"
, "gamingsuggestions,16755"
, "gangstaswithwaifus,10893"
, "gardening,123705"
, "GarlicBreadMemes,3860"
, "gatech,8121"
, "gats,10032"
, "gay,23383"
, "gaybros,56722"
, "gaybroscirclejerk,2539"
, "gaybrosgonemild,9501"
, "gaymers,43889"
, "GearsOfWar,9954"
, "GearVR,4157"
, "geek,312760"
, "geekboners,5302"
, "GeekPorn,35545"
, "geekygirls,5095"
, "GenderCritical,1916"
, "Gender_Critical,889"
, "GenderCynical,792"
, "genderqueer,9428"
, "gentlemanboners,360639"
, "gentlemanbonersgifs,28072"
, "gentlemangabers,4874"
, "geocaching,21065"
, "geography,19815"
, "geology,29271"
, "geometrydash,601"
, "geopolitics,30051"
, "German,15722"
, "germanshepherds,16158"
, "germany,28099"
, "getdisciplined,151245"
, "GetMotivated,4611698"
, "GetStudying,40202"
, "GettingDoug,1294"
, "GGdiscussion,763"
, "GGFreeForAll,95"
, "ggggg,16811"
, "ghettoglamourshots,38985"
, "ghibli,26297"
, "Ghostbc,1744"
, "Ghosts,19927"
, "giantbomb,7143"
, "gif,122474"
, "gifextra,35175"
, "GifRecipes,21728"
, "gifs,7066012"
, "GifSound,53551"
, "gifsthatendtoosoon,1718"
, "GiftofGames,30220"
, "GifTournament,17834"
, "Gifts,3982"
, "gigantic,3846"
, "GilmoreGirls,5296"
, "gingerkitty,1392"
, "Gintama,3149"
, "GirlGamers,36779"
, "GirlsMirin,21667"
, "GirlsPlayingSports,13143"
, "girls_smiling,8446"
, "GIRLSundPANZER,1248"
, "gis,10635"
, "glasgow,6963"
, "glassheads,25367"
, "glitch_art,43871"
, "Glitch_in_the_Matrix,104084"
, "GlobalOffensive,308503"
, "Glocks,11491"
, "glutenfree,17907"
, "gmod,11149"
, "goats,7944"
, "goddesses,22908"
, "GODZILLA,12182"
, "golang,18078"
, "goldenretrievers,16491"
, "goldredditsays,9226"
, "golf,61420"
, "GolfGTI,6754"
, "GolfReimagined,148"
, "gonecivil,33535"
, "GoNets,2417"
, "goodyearwelt,20776"
, "google,79105"
, "GoogleCardboard,13482"
, "googleplaydeals,22385"
, "gopro,43411"
, "gorillaz,11743"
, "goth,4870"
, "Gotham,20579"
, "GradSchool,20248"
, "Graffiti,66997"
, "grandorder,3226"
, "grandrapids,6316"
, "GrandTheftAutoV,169918"
, "GrandTheftAutoV_PC,38186"
, "graphic_design,79684"
, "GrassHopperVape,1906"
, "gratefuldead,16541"
, "gravityfalls,33891"
, "GreatFist,6"
, "GreatXboxDeals,3977"
, "greece,13562"
, "GreenBayPackers,30530"
, "GreenDawn,33791"
, "greenday,6728"
, "greentext,43301"
, "Greyhounds,5411"
, "greysanatomy,8353"
, "grilledcheese,39396"
, "Grimdawn,2522"
, "grime,9691"
, "grimm,5516"
, "GTA,36641"
, "GTAgifs,21502"
, "gtaonline,27712"
, "GTAV,65342"
, "gtavcustoms,7646"
, "gtfoDerrickandArmand,95"
, "GuessTheMovie,14261"
, "Guildwars2,133098"
, "GuiltyPleasureMusic,13769"
, "guineapigs,9095"
, "Guitar,163275"
, "guitarcirclejerk,3475"
, "GuitarHero,1836"
, "guitarlessons,47594"
, "guitarpedals,19228"
, "guitarporn,10266"
, "guitars,7560"
, "guncontrol,1595"
, "Gundam,14360"
, "gundeals,21504"
, "Gunners,45709"
, "Gunpla,13781"
, "gunpolitics,8277"
, "GunPorn,50580"
, "guns,232698"
, "GunsAreCool,9994"
, "Gunsforsale,13627"
, "h1z1,40035"
, "h3h3productions,22035"
, "Habs,8478"
, "hackernews,6808"
, "hacking,80182"
, "hackintosh,17541"
, "Hadouken,1472"
, "HadToHurt,19860"
, "HailCorporate,60479"
, "Hair,20620"
, "HalfLife,24676"
, "halifax,9732"
, "halo,131907"
, "HaloCirclejerk,524"
, "HaloOnline,12169"
, "HaloStory,8405"
, "Hamilton,5399"
, "Hammers,2399"
, "Hammocks,19164"
, "hamsters,3764"
, "Handwriting,25035"
, "HannibalTV,24096"
, "hapas,587"
, "happy,92205"
, "happycrowds,42881"
, "happygirls,39178"
, "HappyTrees,5981"
, "HappyWars,739"
, "hardbodies,97399"
, "Hardcore,13750"
, "hardcoreaww,43074"
, "hardstyle,10089"
, "hardware,79340"
, "hardwareswap,26206"
, "Harley,10855"
, "HarleyQuinn,5352"
, "Harmontown,10149"
, "HaroldPorn,1873"
, "harrypotter,217025"
, "Haruhi,2355"
, "harvestmoon,6455"
, "haskell,22579"
, "Hatfilms,13319"
, "Hawaii,11018"
, "hawks,17957"
, "headphones,56910"
, "Health,115920"
, "hearthstone,313065"
, "hearthstonecirclejerk,2257"
, "heat,7728"
, "Heavymind,74208"
, "Hedgehog,8897"
, "Helicopters,7842"
, "Helldivers,3062"
, "HelloInternet,7123"
, "help,6051"
, "HelpMeFind,4643"
, "heraldry,4552"
, "HereComesTheBoom,8768"
, "HeresAFunFact,19823"
, "Heroes,4819"
, "HeroesandGenerals,3498"
, "HeroesOfAsgard,11"
, "HeroesofNewerth,10607"
, "heroesofthestorm,118071"
, "HeyCarl,28011"
, "HFY,28174"
, "hiddenwow,8947"
, "HIFW,33805"
, "highdeas,19022"
, "HighHeels,19351"
, "HighQualityGifs,91151"
, "HighschoolDxD,4903"
, "HighStrangeness,4370"
, "HighwayFightSquad,8875"
, "hiking,46682"
, "hillaryclinton,1119"
, "HIMYM,88622"
, "hinduism,5767"
, "Hiphopcirclejerk,8792"
, "hiphopheads,337054"
, "HipHopImages,24218"
, "history,4649879"
, "HistoryPorn,486198"
, "HistoryWhatIf,9016"
, "HiTMAN,3297"
, "hitmanimals,13868"
, "HITsWorthTurkingFor,32723"
, "hittableFaces,4928"
, "hockey,226078"
, "hockeyjerseys,3446"
, "hockeyplayers,7732"
, "hockeyquestionmark,934"
, "hoggit,5964"
, "holdmybeaker,22369"
, "holdmybeer,213117"
, "holdmycatnip,18388"
, "holdmyfries,19601"
, "holdmyjuicebox,27371"
, "HoldMyNip,18121"
, "homeautomation,16888"
, "Homebrewing,120095"
, "homegym,14280"
, "HomeImprovement,54575"
, "homelab,27716"
, "homeland,17083"
, "HomeNetworking,10982"
, "homeowners,9378"
, "HomestarRunner,24853"
, "homestead,47084"
, "homestuck,18689"
, "hometheater,22741"
, "homura,1483"
, "Honda,16355"
, "HongKong,14603"
, "hookah,20289"
, "Hookers,5647"
, "HorriblyDepressing,20009"
, "horror,84436"
, "Horses,11687"
, "Hot100,3252"
, "HotlineMiami,9417"
, "HotWheels,1735"
, "Hot_Women_Gifs,33863"
, "House,27365"
, "HouseOfCards,54259"
, "Houseporn,30968"
, "houston,34659"
, "howardstern,15679"
, "howto,158408"
, "HowToHack,31916"
, "howtonotgiveafuck,147936"
, "howyoudoin,22164"
, "HPfanfiction,6315"
, "HPMOR,8467"
, "HSPulls,2863"
, "htcone,10216"
, "htgawm,6413"
, "htpc,13070"
, "httyd,3841"
, "HumanFanClub,1570"
, "Humanoidencounters,5213"
, "HumanPorn,118208"
, "HumansBeingBros,65185"
, "humblebrag,14155"
, "humor,329136"
, "humorousreviews,19933"
, "hungary,9276"
, "Hungergames,19389"
, "HunterXHunter,13951"
, "Hunting,31309"
, "HuntsvilleAlabama,4067"
, "Huskers,3898"
, "huskies,1980"
, "husky,13747"
, "HVAC,4840"
, "hwatch,980"
, "HybridAnimals,42208"
, "HyruleWarriors,3185"
, "IAmA,9726122"
, "iamverysmart,159490"
, "IASIP,96036"
, "IBO,3428"
, "ICanDrawThat,31539"
, "Iceland,12169"
, "IDAP,30861"
, "ideasfortheadmins,8233"
, "IdentityIrelandForum,34"
, "IdiotsFightingThings,128970"
, "IdiotsInCars,4024"
, "IDontWorkHereLady,37442"
, "ifiwonthelottery,42974"
, "ifyoulikeblank,52089"
, "IgnorantImgur,16797"
, "IHE,1387"
, "iiiiiiitttttttttttt,32382"
, "ik_ihe,1138"
, "IllBeYourGuide,9083"
, "illegaltorrents,11111"
, "illumineighti,490"
, "illusionporn,58662"
, "Illustration,21963"
, "im14andthisisdeep,55244"
, "im14andthisisfunny,25233"
, "ImageComics,6553"
, "Images,47758"
, "ImagesOfUSA,48"
, "ImageStabilization,25762"
, "ImaginaryAngels,2663"
, "ImaginaryAww,7704"
, "ImaginaryAzeroth,3102"
, "ImaginaryBehemoths,9289"
, "ImaginaryCharacters,37374"
, "ImaginaryCityscapes,28484"
, "ImaginaryDragons,5293"
, "ImaginaryFallout,6973"
, "ImaginaryFeels,3287"
, "ImaginaryJedi,13900"
, "ImaginaryLandscapes,98649"
, "ImaginaryLeviathans,24350"
, "imaginarymaps,19317"
, "ImaginaryMindscapes,35118"
, "ImaginaryMonsters,88910"
, "ImaginarySpidey,317"
, "ImaginaryTechnology,55885"
, "ImaginaryTurtleWorlds,9020"
, "ImaginaryWarhammer,4822"
, "ImaginaryWarriors,3478"
, "ImaginaryWesteros,27040"
, "ImaginaryWitches,7657"
, "immigration,2801"
, "incest_relationships,4221"
, "incremental_games,21851"
, "india,46194"
, "IndiaMain,685"
, "Indiana,7645"
, "IndianaHoosiers,961"
, "indianapolis,8382"
, "IndianCountry,1426"
, "indianews,3654"
, "indiangirls,11879"
, "indianpeoplefacebook,54479"
, "indiegames,9359"
, "IndieGaming,64410"
, "indieheads,33941"
, "indieheadscirclejerk,677"
, "Indiemakeupandmore,17239"
, "indie_rock,31056"
, "indonesia,10529"
, "industrialmusic,7165"
, "INDYCAR,5242"
, "infertility,3454"
, "infj,12763"
, "Infographics,54812"
, "infp,14006"
, "InfrastructurePorn,47705"
, "INGLIN,14207"
, "Ingress,26304"
, "InjusticeMobile,2315"
, "Instagram,6611"
, "instantkarma,5075"
, "instant_regret,140320"
, "Insurance,6637"
, "insurgency,11227"
, "Intactivists,1915"
, "Intelligence,16493"
, "InterdimensionalCable,3957"
, "interestingasfuck,585343"
, "InterestingGifs,10988"
, "InteriorDesign,78065"
, "InternetHitlers,582"
, "InternetIsBeautiful,4730001"
, "internetparents,9232"
, "interstellar,11775"
, "inthenews,29637"
, "intj,23690"
, "intothebadlands,922"
, "INTP,19991"
, "introvert,55938"
, "intrusivethoughts,26207"
, "investing,174748"
, "InvisiBall,12331"
, "ios,22523"
, "ios9,6165"
, "iosgaming,29362"
, "iOSProgramming,22218"
, "iOSthemes,25327"
, "Iowa,6674"
, "ipad,45859"
, "iphone,156101"
, "iRacing,4028"
, "iran,6494"
, "iranian,685"
, "ireland,68157"
, "IRLgirls,4787"
, "ironmaiden,2812"
, "IronThronePowers,447"
, "IsItBullshit,18975"
, "islam,29553"
, "IslamUnveiled,1197"
, "isometric,10486"
, "Israel,21403"
, "IsraelPalestine,458"
, "isrconspiracyracist,2250"
, "istp,2848"
, "italy,33816"
, "ITCareerQuestions,8018"
, "ITcrowd,10032"
, "itmejp,7686"
, "itookapicture,177377"
, "ITSAPRANK,15459"
, "itsaunixsystem,34068"
, "iWallpaper,32156"
, "IWantOut,53730"
, "IWantToLearn,165699"
, "iZombie,5513"
, "JacksFilms,1171"
, "jacksonville,4712"
, "JacksonWrites,9891"
, "jag_ivl,802"
, "Jaguars,3980"
, "jailbreak,105777"
, "jakeandamir,11311"
, "JamesBond,14555"
, "JaneTheVirginCW,865"
, "japan,67086"
, "japan_anime,2593"
, "japancirclejerk,2747"
, "JapaneseGameShows,46793"
, "JapaneseWatches,1174"
, "japanlife,12815"
, "japanpics,23576"
, "JapanTravel,9316"
, "JasonEllisShow,1050"
, "java,48594"
, "javahelp,9886"
, "javascript,76138"
, "jayhawks,1941"
, "Jazz,56782"
, "jazzyhiphop,4709"
, "Jeep,30392"
, "jellybeantoes,12844"
, "JenniferLawrence,44301"
, "Jeopardy,6809"
, "jerktalkdiamond,964"
, "JessicaJones,4399"
, "JessicaNigri,27798"
, "JimSterling,2762"
, "Jobs4Bitcoins,9211"
, "jobs,74822"
, "joerogan2,2010"
, "JoeRogan,38103"
, "JohnCena,6286"
, "John_Frusciante,2685"
, "joinsquad,2495"
, "Jokes,4760749"
, "JonTron,27893"
, "Jordansw,28"
, "Journalism,9987"
, "JRPG,27567"
, "Judaism,12546"
, "judo,8048"
, "JurassicPark,17482"
, "JustCause,2668"
, "JustEngaged,4663"
, "Justfuckmyshitup,46142"
, "JusticePorn,431434"
, "JusticeServed,18354"
, "justlegbeardthings,5629"
, "justneckbeardthings,102908"
, "JUSTNOFAMILY,1205"
, "JUSTNOMIL,7008"
, "Justridingalong,1353"
, "Justrolledintotheshop,137533"
, "JustUnsubbed,4916"
, "Juve,2494"
, "juxtaposition,6873"
, "jworg,9"
, "kancolle,4119"
, "kancolle_ja,315"
, "KanMusu,2360"
, "kansascity,14383"
, "KansasCityChiefs,7443"
, "Kanye,16570"
, "Kappa,21399"
, "KarmaConspiracy,59451"
, "KarmaCourt,38476"
, "katawashoujo,11914"
, "katebeckinsale,6904"
, "kateupton,37670"
, "KatherineMcNamara,2116"
, "katyperry,28154"
, "KCRoyals,7173"
, "KDRAMA,7567"
, "kemonomimi,6100"
, "KenM,84239"
, "Kerala,1052"
, "KerbalAcademy,10830"
, "KerbalSpaceProgram,121287"
, "keto,163466"
, "ketogains,25281"
, "ketorecipes,65840"
, "K_gifs,10922"
, "kickstarter,30706"
, "Kikpals,20550"
, "killingfloor,16104"
, "KillLaKill,17992"
, "killthosewhodisagree,10973"
, "kindle,26216"
, "KingdomHearts,30884"
, "KingkillerChronicle,17632"
, "KingOfTheHill,27235"
, "kings,3256"
, "KissAnime,544"
, "KitchenConfidential,34771"
, "kitchener,2626"
, "kitsunemimi,4949"
, "kittens,9183"
, "kitty,3734"
, "knifeclub,18752"
, "knifeparty,2920"
, "Knife_Swap,3636"
, "knitting,40319"
, "knives,47200"
, "knowyourshit,12077"
, "kodi,11841"
, "kohi,2838"
, "kol,4511"
, "k_on,2904"
, "KoopaKiy,10"
, "korea,20000"
, "Korean,13748"
, "KoreanAdvice,6591"
, "koreanvariety,5927"
, "korrasami,6909"
, "KotakuInAction,55472"
, "kotor,9517"
, "kpics,18704"
, "kpop,42729"
, "kratom,6984"
, "kreiswichs,3233"
, "kurdistan,2771"
, "Kuwait,1016"
, "LabourUK,2155"
, "labrador,10332"
, "labrats,7696"
, "LAClippers,4318"
, "lacrosse,9361"
, "LadyBoners,164202"
, "Ladybonersgonecuddly,31680"
, "ladyladyboners,24988"
, "lag_irl,135"
, "lakers,18289"
, "LAlist,7127"
, "languagelearning,60392"
, "lapfoxtrax,1947"
, "LARP,4653"
, "lastimages,31487"
, "LastManonEarthTV,5040"
, "lastweektonight,16324"
, "LateShow,8716"
, "LateStageCapitalism,4528"
, "latin,7977"
, "LatinaCuties,7011"
, "LatinoPeopleTwitter,8501"
, "latterdaysaints,5783"
, "LatvianJokes,29817"
, "law,43785"
, "LawSchool,19983"
, "LazyCats,7604"
, "lbregs,2338"
, "leafs,15694"
, "leagueoflegends,772616"
, "LeagueofLegendsMeta,20592"
, "LeagueOfMemes,25797"
, "LeagueOfMeta,3932"
, "leangains,39589"
, "learnart,34582"
, "learndota2,14717"
, "LearnJapanese,49640"
, "learnjavascript,18589"
, "learnmath,29221"
, "learnprogramming,230718"
, "learnpython,47237"
, "LearnUselessTalents,245147"
, "Leathercraft,11724"
, "leaves,27491"
, "lebanon,2784"
, "lebowski,7553"
, "lectures,51617"
, "ledootgeneration,34532"
, "LeedsUnited,1319"
, "LeftHanging,19665"
, "legaladvice,75471"
, "LegalAdviceUK,2253"
, "LegendsOfTomorrow,6215"
, "LegionOfSkanks,1590"
, "lego,115454"
, "lerightgeneration,2555"
, "LessCredibleDefence,1865"
, "LetsNotMeet,142079"
, "letsplay,20438"
, "LetsTalkMusic,36564"
, "Lettering,13453"
, "lewronggeneration,63017"
, "lexington,4315"
, "lgbt,112855"
, "lgbtaww,6614"
, "LGBTeens,10261"
, "LGBTnews,5280"
, "lgg2,4813"
, "LGG3,13432"
, "lgg4,7273"
, "lgv10,1098"
, "LiaMarieJohnson,8477"
, "Liberal,25497"
, "liberta,614"
, "Libertarian,134095"
, "libertarianmeme,9205"
, "libreoffice,915"
, "LifeAfterNarcissism,4717"
, "lifehacks,458584"
, "lifeisstrange,15466"
, "lifeofnorman,42997"
, "LifeProTips,5364631"
, "Lightbulb,23012"
, "LightNovels,9692"
, "likeus,27387"
, "liluglymane,646"
, "limitless,1450"
, "linguistics,72224"
, "LinusFaces,1808"
, "linux,201492"
, "linux4noobs,37427"
, "LinuxActionShow,9319"
, "linuxadmin,22957"
, "LinuxCirclejerk,2407"
, "linux_gaming,30732"
, "linuxmasterrace,15392"
, "linuxmemes,4847"
, "linuxmint,9610"
, "linuxquestions,18252"
, "listentothis,4542407"
, "litecoin,23043"
, "literature,87101"
, "lithuania,7461"
, "lithuaniaspheres,170"
, "littlebuddies,3042"
, "LiveFromNewYork,14386"
, "LiverpoolFC,33829"
, "livesound,9000"
, "LivestreamFails,46881"
, "loadingicon,25972"
, "lockpicking,41217"
, "logodesign,12138"
, "logophilia,28057"
, "lol,20652"
, "LoLeventVoDs,50281"
, "LoLFanArt,12187"
, "lolphp,5776"
, "london,48744"
, "londonontario,4569"
, "lonely,7462"
, "LONESTAR,3749"
, "longbeach,3595"
, "longboarding,56516"
, "LongDistance,29853"
, "LonghornNation,3756"
, "longisland,7544"
, "longrange,10125"
, "lookatmydog,21461"
, "lootcrate,6258"
, "lootcratespoilers,575"
, "LordsOfMinecraft,2393"
, "loremasters,9296"
, "LosAngeles,63399"
, "losangeleskings,5843"
, "loseit,309143"
, "lost,34892"
, "lostgeneration,25435"
, "lotr,94656"
, "lotro,6488"
, "Louisiana,5949"
, "Louisville,8853"
, "Lovecraft,24501"
, "LoveLive,3799"
, "lowendgaming,18859"
, "lowlevelaware,1655"
, "low_poly,17242"
, "lrcast,4985"
, "LSD,46263"
, "Lubbock,2370"
, "LucidDreaming,145245"
, "Luna_Lovewell,19160"
, "LV426,17086"
, "Lyft,2093"
, "lynxes,1246"
, "M59Gar,936"
, "MAA,1446"
, "mac,50181"
, "MachineLearning,49833"
, "MachinePorn,64281"
, "Machinists,6513"
, "macsetups,15022"
, "Madden,16046"
, "MaddenBros,202"
, "MaddenMobileForums,4792"
, "MaddenUltimateTeam,7095"
, "MadeMeSmile,82836"
, "madisonwi,10112"
, "MadMax,7903"
, "madmen,41301"
, "MadokaMagica,3756"
, "Magic,16256"
, "magicduels,4012"
, "magicskyfairy,14873"
, "magicTCG,148320"
, "Maine,7790"
, "maisiewilliams,5556"
, "makemychoice,22507"
, "MakeNewFriendsHere,15706"
, "MakeupAddiction,273221"
, "MakeupAddictionCanada,1062"
, "makeupexchange,15917"
, "MakeupRehab,7273"
, "makinghiphop,23909"
, "malaysia,5913"
, "Malazan,4952"
, "malefashion,36939"
, "malefashionadvice,538227"
, "malegrooming,38964"
, "malehairadvice,53298"
, "malelifestyle,68079"
, "malelivingspace,63737"
, "mallninjashit,17858"
, "Malware,15488"
, "MAME,6656"
, "manchester,7369"
, "MandelaEffect,11096"
, "manga,68455"
, "maninthehighcastle,2115"
, "ManyATrueNerd,4569"
, "Maplestory,12626"
, "MapPorn,249184"
, "mapporncirclejerk,4503"
, "marchingband,6609"
, "Marijuana,79160"
, "marijuanaenthusiasts,39133"
, "MarineBiologyGifs,3939"
, "Mariners,8905"
, "mariokart,9416"
, "MarioMaker,17040"
, "marketing,46823"
, "Markiplier,7966"
, "MarkMyWords,20219"
, "Marriage,4794"
, "marriedredpill,6000"
, "Mars,7017"
, "martialarts,24258"
, "maru,5669"
, "Marvel,128683"
, "marvelheroes,13004"
, "marvelmemes,1890"
, "MarvelPuzzleQuest,1657"
, "marvelstudios,54535"
, "maryland,10222"
, "mashups,77295"
, "massachusetts,6540"
, "massage,4547"
, "masseffect,90017"
, "MasterofNone,5495"
, "math,149766"
, "mathrock,11746"
, "Mavericks,5516"
, "MawInstallation,3496"
, "maximumfun,3798"
, "maybemaybemaybe,4849"
, "MaymayZone,6883"
, "mazda,8207"
, "mbti,8408"
, "Mcat,3458"
, "MCFC,6483"
, "mcgill,3953"
, "McKaylaMaroney,9991"
, "MCPE,7753"
, "mcpublic,6783"
, "MDMA,15857"
, "mead,11797"
, "MealPrepSunday,88222"
, "mealtimevideos,17079"
, "MeanJokes,48692"
, "MechanicAdvice,27603"
, "mechanical_gifs,42008"
, "MechanicalKeyboards,92032"
, "mechmarket,8275"
, "media_criticism,8430"
, "medical,5429"
, "medicalschool,25219"
, "medicine,62419"
, "Meditation,150324"
, "mega64,4268"
, "megalinks,9435"
, "Megaman,7232"
, "Megaten,15075"
, "Megturney,11259"
, "meirl,13683"
, "me_irl,313822"
, "melbourne,28908"
, "meme,17905"
, "memes,57158"
, "memphis,4942"
, "memphisgrizzlies,2220"
, "MensLib,5130"
, "MensRights,122643"
, "mentalhealth,14177"
, "MEOW_IRL,25889"
, "mercedes_benz,5538"
, "MerylRearSolid,175"
, "metacanada,4182"
, "Metal,109728"
, "Metalcore,27095"
, "metaldetecting,5547"
, "MetalGearPhilanthropy,2032"
, "metalgearsolid,75789"
, "MetalGearSolidV_PC,3184"
, "metaljerk,2685"
, "Metallica,6442"
, "MetalMemes,23036"
, "metanarchism,1560"
, "Metroid,13146"
, "mexico,43480"
, "mfacirclejerk,6074"
, "mflb,23250"
, "mfw,15955"
, "mgo,5968"
, "MGTOW,8676"
, "MHOC,2463"
, "Miami,9203"
, "miamidolphins,8462"
, "MiamiHurricanes,1377"
, "Miata,9770"
, "michaelbaygifs,54261"
, "Michigan,23179"
, "MichiganWolverines,3773"
, "microgrowery,48535"
, "microsoft,33758"
, "Mid_Century,8571"
, "migraine,5398"
, "MiiverseInAction,7435"
, "Mila_Kunis,15215"
, "milanavayntrub,12076"
, "mildlyamusing,20563"
, "mildlydepressing,8976"
, "mildlyinfuriating,266706"
, "mildlyinteresting,5089941"
, "mildlypenis,22377"
, "mildlysatisfying,8432"
, "MildlyStartledCats,10980"
, "mildyinteresting,12729"
, "mileycyrus,13625"
, "Military,76095"
, "MilitaryGfys,21869"
, "MilitaryPorn,104450"
, "MillerPlanetside,1611"
, "millionairemakers,63540"
, "milliondollarextreme,3103"
, "milwaukee,8862"
, "MimicRecipes,29631"
, "mindcrack,49548"
, "mindcrackcirclejerk,2439"
, "Mindfulness,23696"
, "Minecraft,452814"
, "minecraftsuggestions,15064"
, "MineralPorn,24006"
, "MINI,6184"
, "minimalism,181966"
, "MinimalWallpaper,11704"
, "MinionHate,31867"
, "minipainting,8721"
, "Minneapolis,12416"
, "minnesota,19056"
, "minnesotavikings,14502"
, "mirrorsedge,2840"
, "misc,25945"
, "misleadingthumbnails,74200"
, "misophonia,8220"
, "mississauga,3339"
, "mistyfront,5685"
, "MitchellAndWebb,11935"
, "MkeBucks,3085"
, "mlb,29706"
, "MLBTheShow,6142"
, "MLPLounge,11485"
, "MLS,45723"
, "MLTP,816"
, "MMA,135313"
, "MMORPG,29990"
, "ModelAusHR,35"
, "modelmakers,11087"
, "modelparliament,297"
, "Models,17605"
, "ModelsGoneMild,9217"
, "ModelUSGov,2663"
, "Modern_Family,22210"
, "ModernMagic,11226"
, "ModestMouse,8374"
, "Moescape,7400"
, "Mommit,20569"
, "MonarchyOfEquestria,164"
, "Monero,2561"
, "Monitors,9649"
, "monkslookingatbeer,21422"
, "monsteraday,2839"
, "Monstercat,19976"
, "MonstercatCringe,744"
, "MonsterHunter,49260"
, "MonsterMusume,4602"
, "montageparodies,140766"
, "montreal,23757"
, "morbidlybeautiful,20731"
, "morbidquestions,16778"
, "mormon,3610"
, "Morrowind,18329"
, "MortalKombat,24177"
, "MosinNagant,5364"
, "MostBeautiful,12475"
, "mother4,4088"
, "motivation,28121"
, "moto360,16741"
, "MotoG,7346"
, "motogp,12424"
, "motorcitykitties,8291"
, "motorcyclememes,3864"
, "motorcycles,153710"
, "MotoUK,2350"
, "MotoX,15447"
, "MountainWisdom,6372"
, "mountandblade,24536"
, "MoviePosterPorn,64136"
, "movies,8844042"
, "moviescirclejerk,7311"
, "Moviesinthemaking,36474"
, "MovieSuggestions,30708"
, "MrRobot,33987"
, "MRW,8138"
, "msp,2697"
, "MST3K,12731"
, "MTB,44173"
, "MtF,6966"
, "mtgaltered,6674"
, "mtgcube,3449"
, "mtgfinance,10617"
, "MTGLegacy,5388"
, "mturk,16614"
, "muacirclejerk,13973"
, "muacjdiscussion,4956"
, "MuayThai,11935"
, "Multicopter,27369"
, "MultipleSclerosis,3225"
, "Munich,3470"
, "MURICA,182607"
, "Muse,11557"
, "museum,30121"
, "Music,8547159"
, "musicpics,3365"
, "Musicthemetime,4042"
, "musictheory,56442"
, "Mustang,16084"
, "MvC3,7232"
, "mwo,5258"
, "mycology,28804"
, "myfriendwantstoknow,25670"
, "mylittleandysonic1,1981"
, "mylittlepony,66489"
, "mypartneristrans,3779"
, "MyPeopleNeedMe,38060"
, "MysteryDungeon,2024"
, "mythbusters,16717"
, "n64,9489"
, "Nagato,382"
, "namenerds,6336"
, "NamFlashbacks,3190"
, "Nanny,892"
, "nanowrimo,10847"
, "narcos,5824"
, "Naruto,66976"
, "nasa,40516"
, "NASCAR,20166"
, "nashville,11165"
, "NASLSoccer,2026"
, "NatalieDormer,14878"
, "nathanforyou,4854"
, "NationalPark,6253"
, "nattyorjuice,2310"
, "nature,29478"
, "NatureGifs,19405"
, "natureismetal,35697"
, "navy,12037"
, "NavyBlazer,2546"
, "navyseals,1318"
, "NBA2k,22976"
, "nba,329140"
, "nbacirclejerk,3587"
, "NBASpurs,8650"
, "nbastreams,16646"
, "nbaww,7361"
, "NCSU,3852"
, "NeckbeardNests,14207"
, "neckbeardstories,17714"
, "needadvice,24669"
, "Needafriend,21494"
, "needforspeed,4508"
, "Negareddit,6401"
, "nekoatsume,5459"
, "neogaming,6576"
, "neopets,12308"
, "Nepal,2449"
, "nerdcubed,30818"
, "nerdfighters,25840"
, "nerdist,8495"
, "Nerf,10215"
, "netflix,96367"
, "NetflixBestOf,293763"
, "NetflixPals,2"
, "Netrunner,9329"
, "netsec,149780"
, "networking,56778"
, "neuro,29646"
, "NeutralPolitics,48269"
, "NeverBeGameOver,6023"
, "nevertellmetheodds,54203"
, "Neverwinter,10724"
, "newfoundland,3544"
, "NewGirl,11270"
, "newjersey,22791"
, "NewOrleans,14369"
, "newreddits,56764"
, "NewRussia,266"
, "news,7193384"
, "NewSkaters,7125"
, "NewsOfTheStupid,26065"
, "NewsOfTheWeird,23032"
, "newsokunomoral,1668"
, "newsokur,12742"
, "newsokuvip,1422"
, "NewsPorn,27720"
, "newtothenavy,3355"
, "NewYorkIslanders,2747"
, "NewYorkMets,9081"
, "newzealand,58365"
, "nextdoorasians,44027"
, "Nexus,11251"
, "nexus4,14051"
, "Nexus5,32628"
, "nexus5x,4290"
, "nexus6,17044"
, "Nexus6P,14565"
, "NexusNewbies,4554"
, "NFA,3386"
, "nfffffffluuuuuuuuuuuu,10412"
, "nfl,438505"
, "nflcirclejerk,5471"
, "NFL_Draft,10220"
, "NFLRoundTable,5106"
, "nflstreams,45816"
, "NFSRides,331"
, "nhl,48661"
, "NHLHUT,6246"
, "NHLStreams,24573"
, "niceb8m8,2780"
, "niceguys,56186"
, "Nichijou,1794"
, "NichtDerPostillon,1679"
, "Nightshift,3047"
, "nightvale,12825"
, "Nikon,5622"
, "nin,8543"
, "nintendo,111235"
, "nintendomusic,16592"
, "Nirvana,9955"
, "Nisekoi,5857"
, "Nissan,7789"
, "nl_Kripparrian,5710"
, "NLSSCircleJerk,6342"
, "NLTP,1260"
, "nocontext,127222"
, "node,17989"
, "NoFap,176191"
, "NoFapChristians,5780"
, "NoFapWar,8446"
, "noisygifs,26562"
, "NOLAPelicans,1796"
, "NoMansSkyTheGame,28763"
, "nongolfers,23795"
, "nonmonogamy,11653"
, "nonnude,5508"
, "nononono,124473"
, "nonononoyes,227931"
, "Nootropics,64062"
, "NoPoo,12759"
, "Nordiccountries,7445"
, "norge,31328"
, "normaldayinjapan,12500"
, "NorthCarolina,11331"
, "northernireland,6754"
, "northernlion,4198"
, "NorthKoreaNews,28734"
, "Norway,12728"
, "NoShitSherlock,15730"
, "NoSillySuffix,15832"
, "nosleep,4419937"
, "NoSleepOOC,6136"
, "no_sob_story,12490"
, "nostalgia,135018"
, "Nostalrius,1864"
, "NostalriusBegins,2221"
, "NoStupidQuestions,105909"
, "notcirclejerk,3604"
, "notebooks,10292"
, "notinteresting,93212"
, "NotMyJob,9602"
, "NotSoGoodGuyMafia,1"
, "nottheonion,4626814"
, "NotTimAndEric,52386"
, "nova,16149"
, "noveltranslations,6505"
, "nqmod,677"
, "NRIBabes,4104"
, "nrl,7913"
, "NuclearThrone,6138"
, "NUFC,4139"
, "Nujabes,13336"
, "nursing,26360"
, "nutrition,58085"
, "nvidia,13768"
, "NWSL,2055"
, "nyc,93287"
, "NYGiants,14530"
, "nyjets,9260"
, "NYKnicks,10287"
, "NYYankees,5116"
, "oakland,7448"
, "OaklandAthletics,5427"
, "oaklandraiders,8363"
, "oblivion,20697"
, "ObscureMedia,48169"
, "occult,25842"
, "occupywallstreet,31365"
, "OCD,7576"
, "ockytop,1751"
, "OCLions,2234"
, "OCPoetry,8270"
, "oculus,58470"
, "oddlysatisfying,402256"
, "ofcoursethatsathing,68726"
, "offbeat,323485"
, "Offensive_Wallpapers,57976"
, "offmychest,195959"
, "OFWGKTA,19821"
, "Ohio,10967"
, "okc,3844"
, "OkCupid,76965"
, "oklahoma,8846"
, "oldbabies,3981"
, "oldpeoplefacebook,123804"
, "OldSchoolCool,4435183"
, "oliviawilde,18117"
, "Omaha,6706"
, "OnceUponATime,14844"
, "onejob,19142"
, "oneliners,8428"
, "OnePiece,58146"
, "OnePieceTC,4580"
, "oneplus,31264"
, "OnePunchMan,13861"
, "OneTrueBiribiri,2053"
, "onetruegod,85716"
, "onetrueidol,1987"
, "onewordeach,6562"
, "OneY,28710"
, "ontario,13949"
, "Ooer,22033"
, "OopsDidntMeanTo,27372"
, "OOTP,1794"
, "openbroke,7026"
, "opendirectories,34117"
, "opensource,38410"
, "opiates,18779"
, "OpiatesRecovery,5017"
, "opieandanthony,11550"
, "Oppression,2456"
, "OpTicGaming,9421"
, "orangecounty,15315"
, "orangeisthenewblack,37014"
, "OreGairuSNAFU,2685"
, "oregon,12238"
, "orioles,7696"
, "orlando,13168"
, "OrlandoMagic,2489"
, "orphanblack,12331"
, "OrthodoxChristianity,3213"
, "OSHA,106266"
, "OSU,7389"
, "osugame,16754"
, "osx,26645"
, "ottawa,18694"
, "OttawaSenators,4489"
, "Otters,15182"
, "Outlander,4640"
, "OutlandishAlcoholics,310"
, "OutOfTheLoop,352852"
, "OutreachHPG,4306"
, "outrun,21477"
, "outside,169842"
, "overclocking,14365"
, "overlanding,7952"
, "overpopulation,10742"
, "Overwatch,75843"
, "Owls,13402"
, "Pac12,2079"
, "pacers,2643"
, "PacificRim,4808"
, "paintball,13838"
, "painting,19653"
, "pakistan,5580"
, "Paladins,2246"
, "Paleo,82633"
, "Palestine,8236"
, "PandR,80461"
, "PanicHistory,11470"
, "PanPorn,2688"
, "panthers,9700"
, "ParadoxExtra,948"
, "paradoxplaza,36233"
, "paradoxpolitics,4368"
, "Parahumans,2810"
, "Paranormal,82498"
, "Pareidolia,112512"
, "Parenting,89413"
, "paris,9014"
, "parrots,12067"
, "PastAndPresentPics,26758"
, "Patchuu,5314"
, "Pathfinder_RPG,24123"
, "pathofexile,55470"
, "patientgamers,66432"
, "Patriots,35985"
, "Pauper,3510"
, "paydaycirclejerk,750"
, "paydaytheheist,40470"
, "PBSOD,4524"
, "pcgaming,177340"
, "pcmasterrace,499519"
, "pebble,26606"
, "PEDs,2684"
, "peloton,12939"
, "penguins,10697"
, "PenmanshipPorn,120944"
, "Pennsylvania,6406"
, "penspinning,13838"
, "PeopleBeingJerks,31276"
, "pepe,3873"
, "pepethefrog,5498"
, "Perfectfit,58195"
, "perfectloops,87232"
, "PerfectTiming,213955"
, "perktv,4851"
, "Permaculture,32689"
, "personalfinance,4554137"
, "PersonalFinanceCanada,21006"
, "PersonOfInterest,7908"
, "perth,9240"
, "Pets,40721"
, "pettyrevenge,185894"
, "pharmacy,11236"
, "philadelphia,32593"
, "Philippines,41758"
, "philosophy,4513265"
, "PhilosophyofScience,36378"
, "phish,14034"
, "phoenix,13463"
, "photocritique,36970"
, "photography,266257"
, "photoshop,39757"
, "photoshopbattles,4687231"
, "PhotoshopRequest,18145"
, "PHP,40492"
, "Physics,128791"
, "physicsgifs,36540"
, "piano,39324"
, "pic,41129"
, "PickAnAndroidForMe,3855"
, "picrequests,30863"
, "pics,9989676"
, "PictureGame,6213"
, "Pieces,14156"
, "piercing,24957"
, "pimpcats,17733"
, "pinkfloyd,22664"
, "pinsamt,2950"
, "PipeTobacco,16237"
, "Piracy,44568"
, "pitbulls,27622"
, "pitchforkemporium,11008"
, "pittsburgh,20373"
, "Pixar,8458"
, "PixelArt,31539"
, "PixelDungeon,4762"
, "Pizza,47680"
, "PKA,24769"
, "pkmntcg,7333"
, "Planetside,39289"
, "PlantedTank,21275"
, "plastidip,7725"
, "playark,19551"
, "PlayItAgainSam,26060"
, "playrust,28473"
, "playstation,23516"
, "PlayStationPlus,33657"
, "PleX,29450"
, "ploompax,7475"
, "plotholes,25252"
, "ploungeafterdark,1519"
, "Plumbing,4184"
, "podcasts,25805"
, "podemos,11042"
, "Poetry,49882"
, "PointlessStories,15386"
, "Pokeents,9352"
, "pokemon,474684"
, "Pokemongiveaway,23462"
, "pokemongo,5808"
, "PokemonInsurgence,11178"
, "PokemonPlaza,9885"
, "PokemonShuffle,5506"
, "pokemontrades,32149"
, "poker,39081"
, "poland,6554"
, "polandball,183854"
, "Polandballart,5267"
, "polandballgifs,3082"
, "policeporn,7454"
, "POLITIC,26221"
, "PoliticalDiscussion,46733"
, "PoliticalHumor,50628"
, "politicalpartypowers,221"
, "PoliticalScience,4220"
, "PoliticalVideo,3264"
, "politics,3179799"
, "politota,3829"
, "Polska,25211"
, "polyamory,32932"
, "PopArtNouveau,12780"
, "PopCornTime,14295"
, "popheads,3343"
, "popping,63644"
, "poppunkers,22875"
, "pornfree,23763"
, "Porsche,10606"
, "Portal,33665"
, "porterrobinson,3055"
, "Portland,55193"
, "portlandstate,1611"
, "portugal,10848"
, "PORTUGALCARALHO,2199"
, "PostHardcore,24276"
, "postprocessing,19762"
, "postrock,25540"
, "potatosalad,9117"
, "potionseller,5062"
, "pottedcats,736"
, "powerlifting,24249"
, "PowerMetal,8754"
, "powerrangers,6357"
, "PowerShell,14127"
, "powerwashingporn,47175"
, "predaddit,7185"
, "Predators,2547"
, "Prematurecelebration,60825"
, "premed,14042"
, "PremierLeague,10863"
, "preppers,22426"
, "PrettyGirls,119838"
, "PrettyGirlsUglyFaces,40069"
, "PrettyLittleLiars,13195"
, "printSF,24370"
, "prisonarchitect,21737"
, "privacy,57320"
, "processing,3202"
, "productivity,94185"
, "proED,2694"
, "progmetal,29496"
, "programmerchat,2151"
, "ProgrammerHumor,107681"
, "programmerreactions,2708"
, "programming,662121"
, "programmingcirclejerk,3359"
, "progressive,41755"
, "progresspics,159520"
, "progrockmusic,14678"
, "progun,16238"
, "projectcar,16099"
, "projecteternity,15575"
, "ProjectFi,6998"
, "ProjectRunway,3241"
, "projectzomboid,11302"
, "promos,7261"
, "PropagandaPosters,61960"
, "ProRevenge,68628"
, "ProtectAndServe,31841"
, "providence,3433"
, "PS2Cobalt,1330"
, "PS3,70298"
, "PS4,224940"
, "PS4Deals,25738"
, "PS4Planetside2,3392"
, "PSO2,6678"
, "psych,17860"
, "psychedelicrock,16742"
, "psychology,200568"
, "Psychonaut,101049"
, "ptcgo,5105"
, "ptsd,5175"
, "PublicFreakout,88695"
, "PucaTrade,1379"
, "PuertoRico,2914"
, "pugs,27771"
, "punchablefaces,55609"
, "Pundertale,703"
, "punk,39887"
, "Punny,63046"
, "puns,27992"
, "puppies,23155"
, "puppy101,9484"
, "PuppySmiles,10786"
, "Purdue,5756"
, "pureasoiaf,12551"
, "PurplePillDebate,6931"
, "PushBullet,5486"
, "PussyPass,22432"
, "pussypassdenied,61130"
, "putindoingthings,2049"
, "PuzzleAndDragons,16054"
, "pxifrm,115"
, "Python,115556"
, "qotsa,6238"
, "QuakeLive,4660"
, "Quebec,10786"
, "questionablecontent,5683"
, "quilting,7847"
, "QuinnMains,707"
, "quiteinteresting,16331"
, "quityourbullshit,185200"
, "quotes,104379"
, "QuotesPorn,267602"
, "r4r,87824"
, "Rabbits,28734"
, "RachelCook,2362"
, "racism,7995"
, "radiocontrol,12348"
, "radiohead,28111"
, "Radiology,7457"
, "rage,122716"
, "ragecomics,41862"
, "RagenChastain,1722"
, "rails,16064"
, "Rainbow6,9496"
, "RainbowSix,324"
, "RainbowSixSiege,758"
, "rainbow_wolf,275"
, "raining,22091"
, "Rainmeter,61724"
, "raisedbynarcissists,82856"
, "raiseyourdongers,11287"
, "rakugakicho,562"
, "raleigh,9389"
, "rally,15541"
, "ramen,36662"
, "Random_Acts_Of_Amazon,32024"
, "randomactsofamazon,5503"
, "RandomActsofCards,4803"
, "RandomActsOfChristmas,6437"
, "randomactsofcsgo,15588"
, "RandomActsOfGaming,48115"
, "RandomActsofMakeup,16512"
, "RandomActsOfPizza,24170"
, "Random_Acts_Of_Pizza,39302"
, "RandomActsOfPolish,7470"
, "RandomKindness,37441"
, "randomsuperpowers,580"
, "randpaul,5063"
, "rangers,9997"
, "rant,18677"
, "rantgrumps,1462"
, "RantsFromRetail,1673"
, "rapbattles,5800"
, "raspberry_pi,82516"
, "Rateme,41096"
, "rational,3854"
, "RationalPsychonaut,12838"
, "RATS,15845"
, "ravens,11730"
, "rawdenim,25719"
, "razorbacks,1594"
, "RBI,29738"
, "rccars,5804"
, "RCSources,6523"
, "rct,16703"
, "reactiongifs,584267"
, "reactjs,6388"
, "readit,32196"
, "realasians,70113"
, "realdubstep,19599"
, "RealEstate,40152"
, "reallifedoodles,95560"
, "RealLifeFootball,205"
, "realmadrid,10216"
, "REBL,1016"
, "recipes,150726"
, "reckful,895"
, "reddevils,37712"
, "RedditAlternatives,7793"
, "redditblack,1330"
, "RedditDads,2927"
, "RedditDayOf,50174"
, "RedditForGrownups,19457"
, "RedditFox,2195"
, "redditgetsdrawn,95837"
, "redditisfun,21473"
, "RedditLaqueristas,72782"
, "redditrequest,5690"
, "redditsync,47160"
, "RedditWritesSeinfeld,17316"
, "RedHotChiliPeppers,11206"
, "RedLetterMedia,8047"
, "redorchestra,6201"
, "redpandas,20461"
, "RedPillWomen,13048"
, "Reds,5256"
, "Redskins,11116"
, "redsox,18397"
, "ReefTank,9386"
, "Reformed,4638"
, "regularcarreviews,2858"
, "regularshow,22891"
, "relationship_advice,115575"
, "relationships,402654"
, "RelayForReddit,24205"
, "reloading,8744"
, "RenewableEnergy,28148"
, "Rengarmains,1073"
, "Repsneakers,8097"
, "reptiles,11690"
, "Republican,19154"
, "researchchemicals,6883"
, "residentevil,8177"
, "respectporn,22817"
, "respectthreads,9618"
, "restorethefourth,22338"
, "resumes,24186"
, "retiredgif,52689"
, "retrobattlestations,13020"
, "RetroFuturism,82812"
, "retrogaming,22162"
, "RetroPie,3485"
, "ReversedGIFS,10990"
, "reversegif,22540"
, "reynad,1543"
, "rickandmorty,191060"
, "rickygervais,9435"
, "riddles,30867"
, "Rift,9693"
, "Rimarist,7"
, "RimWorld,8322"
, "ripcity,6682"
, "rit,7262"
, "RivalsOfAether,6951"
, "Rivenmains,1199"
, "Roadcam,47238"
, "RoastMe,135768"
, "roblox,3240"
, "Robocraft,7490"
, "robotics,33249"
, "Rochester,7587"
, "Rockband,6734"
, "rocketbeans,15194"
, "RocketLeague,99039"
, "rockets,7814"
, "rockhounds,9937"
, "rocksmith,13141"
, "roguelikes,19191"
, "Roguetroll,10"
, "rojava,1029"
, "Roku,15244"
, "roleplayponies,72"
, "rollercoasters,7167"
, "rolltide,3441"
, "Romania,23826"
, "ronandfez,3299"
, "ronpaul,25443"
, "RoomPorn,290703"
, "roosterteeth,129872"
, "ROTC,1388"
, "RotMG,6409"
, "Rottweiler,4174"
, "Rowing,9961"
, "rpdrcirclejerk,650"
, "rpg,92650"
, "rpg_gamers,25733"
, "RSChronicle,414"
, "RSDarkscape,4701"
, "RTLSDR,12111"
, "ruby,31346"
, "rugbyunion,37219"
, "runescape,54578"
, "running,181129"
, "rupaulsdragrace,24932"
, "rush,8156"
, "russia,17424"
, "russian,10448"
, "rust,13618"
, "rutgers,5881"
, "rva,11277"
, "RWBY,21931"
, "rwbyRP,345"
, "ryuuseigai,254"
, "S2000,2373"
, "Saber,2372"
, "sabres,4881"
, "Sacramento,10144"
, "SacRepublicFC,610"
, "sadboys,8191"
, "sadcomics,17309"
, "sadcringe,4046"
, "SaddlebackLeatherFans,36"
, "Saffron_Regiment,278"
, "SAGAcomic,2783"
, "sailing,24086"
, "sailormoon,10790"
, "Saints,8965"
, "SakuraGakuin,844"
, "sales,9397"
, "SaltLakeCity,10883"
, "samharris,1730"
, "samoyeds,4826"
, "SampleSize,32623"
, "samsung,8048"
, "sanantonio,10644"
, "SanctionedSuicide,2331"
, "SandersForPresident,135167"
, "sandiego,27042"
, "sanfrancisco,48702"
, "SanJose,8772"
, "SanJoseSharks,8349"
, "santashelpers,5881"
, "SantasLittleHelpers,1775"
, "saplings,22583"
, "SarahHyland,7700"
, "SargonofAkkad,2866"
, "saskatchewan,2933"
, "saskatoon,4188"
, "Sat,1626"
, "saudiarabia,2242"
, "saudiprince,3510"
, "SavageGarden,7431"
, "savannah,2471"
, "scala,9586"
, "Scams,7972"
, "ScandinavianInterior,5242"
, "ScarlettJohansson,23948"
, "Scarrapics,7688"
, "ScenesFromAHat,34944"
, "schizophrenia,4014"
, "SchoolIdolFestival,8021"
, "science,9829763"
, "sciencefiction,32395"
, "scientology,6801"
, "scifi,240788"
, "SciFiRealism,9935"
, "scooters,5786"
, "scoreball,4131"
, "Scotch,47164"
, "ScotchSwap,2196"
, "Scotland,20463"
, "ScottishFootball,1859"
, "SCP,26442"
, "ScreamQueensTV,3679"
, "screenshots,26041"
, "Screenwriting,41585"
, "Scrubs,34145"
, "scuba,23021"
, "Seahawks,32797"
, "Seattle,76985"
, "secretsanta,70999"
, "SecretSubreddit,3473"
, "security,13099"
, "seduction,223034"
, "see,41509"
, "seedboxes,7171"
, "seinfeld,44057"
, "seinfeldgifs,16169"
, "SelenaGomez,17076"
, "self,148033"
, "SelfDrivingCars,10923"
, "SelfiesWithGlasses,710"
, "selfimprovement,61452"
, "selfpublish,10471"
, "SEO,27693"
, "serbia,3251"
, "Serendipity,40161"
, "serialkillers,31530"
, "serialpodcast,44131"
, "serialpodcastorigins,686"
, "SeriousConversation,3982"
, "seriouseats,19686"
, "sewing,39017"
, "sex,618677"
, "SexPositive,19089"
, "SexWorkers,6491"
, "sexygirls,12774"
, "sexyhair,1771"
, "sexypizza,8500"
, "SexyWomanOfTheDay,12608"
, "SFGiants,16663"
, "SFM,13371"
, "SFWRedheads,8179"
, "sfw_wtf,11341"
, "Shadowrun,9653"
, "shanghai,4780"
, "Sherlock,68729"
, "shestillsucking,16142"
, "shia,911"
, "shiba,12931"
, "shield,39612"
, "Shihtzu,2478"
, "ShingekiNoKyojin,39537"
, "ShinyPokemon,11639"
, "ShitAmericansSay,22530"
, "ShitCrusaderKingsSay,4260"
, "shitduolingosays,3833"
, "ShitLewisSays,4893"
, "ShitLiberalsSay,2555"
, "ShitPoliticsSays,7330"
, "shitpost,24892"
, "ShitRConservativeSays,5073"
, "ShitRedditSays,76821"
, "Shitstatistssay,7677"
, "shittankiessay,510"
, "ShitTumblrSays,3039"
, "shittyadvice,65894"
, "shittyadviceanimals,12933"
, "shittyama,13610"
, "ShittyAnimalFacts,21590"
, "shittyaskreddit,19674"
, "shittyaskscience,298571"
, "Shitty_Car_Mods,90140"
, "shittyconspiracy,4771"
, "shittydarksouls,5868"
, "shitty_ecr,3511"
, "ShittyFanTheories,14206"
, "shittyfoodporn,118113"
, "shittyHDR,8649"
, "shittyideas,16863"
, "shittykickstarters,31310"
, "ShittyLifeProTips,63163"
, "ShittyMapPorn,19129"
, "shittynosleep,23020"
, "shittyprogramming,25766"
, "shittyreactiongifs,131954"
, "shittyrobots,100978"
, "shittysteamreviews,6744"
, "shittytumblrgifs,16429"
, "ShitWehraboosSay,3385"
, "ShokugekiNoSoma,5245"
, "Shoplifting,2514"
, "short,18239"
, "shorthairedhotties,34837"
, "shortscarystories,63081"
, "Shotguns,6107"
, "ShouldIbuythisgame,36978"
, "showerbeer,32418"
, "Showerthoughts,4878620"
, "shroomers,12562"
, "shrooms,23983"
, "shutupandtakemymoney,260041"
, "Sikh,2030"
, "SiliconValleyHBO,31197"
, "Silverbugs,9665"
, "SimCity,25184"
, "simpleliving,73772"
, "simpsonsdidit,18014"
, "simracing,11072"
, "Simulated,30520"
, "singapore,34968"
, "singing,19015"
, "singularity,29307"
, "Sino,1325"
, "sips,35974"
, "sixers,6060"
, "sixwordstories,28278"
, "sjsucks,3359"
, "sjwhate,7175"
, "skateboarding,70289"
, "skeptic,102973"
, "SketchDaily,45733"
, "skiing,36721"
, "SkincareAddiction,186356"
, "SkinnyWithAbs,26477"
, "skrillex,7759"
, "Skullgirls,8746"
, "SkyDiving,9496"
, "Skyforge,6822"
, "SkyPorn,52048"
, "skyrim,317076"
, "skyrimdadjokes,7082"
, "skyrimmods,43657"
, "SkyrimPorn,14961"
, "slashdiablo,4553"
, "slatestarcodex,1204"
, "slavs_squatting,25530"
, "Sleepycabin,7297"
, "Slipknot,4484"
, "sloths,52076"
, "slowcooking,181706"
, "SlyGifs,31850"
, "sm4sh,4693"
, "smallbusiness,42404"
, "smalldickproblems,2878"
, "SmarterEveryDay,17293"
, "smashbros,193884"
, "smashcirclejerk,3835"
, "smashgifs,11407"
, "Smite,67098"
, "smoking,23275"
, "snakes,15064"
, "snapchat,14894"
, "sneakermarket,7491"
, "Sneakers,62627"
, "snek_irl,6224"
, "Sneks,16810"
, "snes,12996"
, "snowboarding,55293"
, "snowden,6612"
, "SNSD,12988"
, "SoapboxBanhammer,426"
, "soccer,406132"
, "SoccerBetting,7821"
, "soccercirclejerk,8485"
, "soccerspirits,2436"
, "soccerstreams,28855"
, "socialanxiety,33954"
, "SocialEngineering,66828"
, "socialism,55342"
, "Socialistart,2830"
, "socialjustice101,2772"
, "SocialJusticeInAction,5071"
, "socialmedia,24157"
, "socialskills,124187"
, "socialwork,5616"
, "sociopath,3244"
, "sodadungeon,846"
, "sodapoppin,1883"
, "softwaregore,41799"
, "SolForge,2177"
, "solipsism,7371"
, "solotravel,39652"
, "soma,1456"
, "somethingimade,103385"
, "SonicTheHedgehog,4766"
, "SonyXperia,5817"
, "sooners,2834"
, "sophieturner,8412"
, "sorceryofthespectacle,2519"
, "SoundsLikeChewy,350"
, "SoundsLikeMusic,10164"
, "SourceFed,32048"
, "sousvide,11980"
, "southafrica,16286"
, "southpark,151534"
, "soylent,16541"
, "space,4856256"
, "SpaceBuckets,17882"
, "spaceengine,8735"
, "spaceengineers,23681"
, "spaceflight,17886"
, "spaceporn,304852"
, "spacex,42626"
, "spain,6505"
, "Spanish,18226"
, "SpecArt,38694"
, "SpeculativeEvolution,8317"
, "speedrun,41470"
, "spelunky,5475"
, "spicy,26348"
, "spiderbro,20400"
, "Spiderman,17595"
, "spiders,19926"
, "SpideyMeme,43917"
, "spikes,23119"
, "splatoon,26573"
, "SplitDepthGIFS,42588"
, "Spokane,3500"
, "spongebob,25202"
, "Spongebros,9137"
, "sporetraders,1880"
, "sports,5053901"
, "sportsarefun,33800"
, "sportsbook,14530"
, "spotify,32797"
, "spotted,14019"
, "springerspaniel,1026"
, "springfieldMO,2589"
, "Sprint,3308"
, "SQL,12459"
, "SquaredCircle,100115"
, "SquaredCirclejerk,2263"
, "SRSDiscussion,14311"
, "SRSGaming,6438"
, "SRSsucks,13889"
, "SS13,4183"
, "SSBM,18959"
, "SSBPM,23980"
, "StackAdvice,9073"
, "StackGunHeroes,2201"
, "stalker,8405"
, "StallmanWasRight,2158"
, "Stance,11682"
, "Standup,30403"
, "StandUpComedy,68690"
, "standupshots,180743"
, "Staples,1663"
, "starbound,53361"
, "starbucks,13249"
, "Starcaft,5"
, "starcitizen,59168"
, "Starcitizen_trades,4263"
, "starcraft,184091"
, "StardustCrusaders,9178"
, "Stargate,20681"
, "starlets,28960"
, "StarlightStage,1158"
, "starterpacks,25990"
, "StartledCats,96464"
, "startrek,98491"
, "startups,95633"
, "StarVStheForcesofEvil,2331"
, "StarWars,345816"
, "StarWarsBattlefront,50911"
, "starwarscollecting,841"
, "StarWarsEU,7579"
, "StarWarsLeaks,9889"
, "starwarsrebels,4990"
, "starwarsspeculation,831"
, "starwarstrader,1718"
, "statistics,29112"
, "steak,17478"
, "Steam,246860"
, "SteamController,2363"
, "steamdeals,52334"
, "SteamGameSwap,39821"
, "steampunk,33109"
, "steamr,1339"
, "steelers,14770"
, "stencils,18517"
, "stephenking,11385"
, "steroids,21686"
, "stevedangle,854"
, "stevenuniverse,40931"
, "Stims,4400"
, "StLouis,16670"
, "stlouisblues,5825"
, "StLouisRams,4558"
, "sto,8236"
, "StockMarket,30145"
, "stocks,42133"
, "Stoicism,27901"
, "StonerCringe,465"
, "StonerEngineering,62455"
, "StonerPhilosophy,22673"
, "StonerProTips,29743"
, "stonerrock,17254"
, "stopdrinking,32169"
, "StopGaming,4845"
, "StoppedWorking,29609"
, "stopsmoking,39116"
, "StopTouchingMe,19388"
, "StormfrontorSJW,10522"
, "Stormlight_Archive,10108"
, "straightedge,2864"
, "straya,15833"
, "streetart,28859"
, "StreetFighter,19201"
, "StreetFights,40216"
, "streetfoodartists,13113"
, "streetphotography,4566"
, "streetwear,59791"
, "Streisandeffect,479"
, "StudentLoans,9744"
, "stunfisk,12874"
, "subaru,48713"
, "submechanophobia,17428"
, "subnautica,2689"
, "subredditcancer,10423"
, "SubredditDrama,212016"
, "SubredditDramaDrama,6784"
, "subredditoftheday,116920"
, "SubredditSimMeta,18180"
, "SubredditSimulator,100281"
, "succulents,11380"
, "SuddenlyGay,10271"
, "sugarfreemua,8232"
, "SuggestALaptop,21902"
, "suggestmeabook,22247"
, "SuicideWatch,40594"
, "suits,23893"
, "summonerschool,82962"
, "summonerswar,13052"
, "Sundresses,8984"
, "suns,2922"
, "sunsetshimmer,732"
, "Suomi,26735"
, "Superbowl,10765"
, "supergirlTV,5557"
, "superman,13474"
, "supermoto,5606"
, "Supernatural,46900"
, "SuperShibe,52716"
, "Supplements,22667"
, "supremeclothing,15545"
, "Surface,32368"
, "surfing,27387"
, "SurgeryGifs,5944"
, "Survival,73333"
, "survivinginfidelity,2589"
, "survivor,18165"
, "survivorcirclejerk,394"
, "SurvivorRankdownII,88"
, "survivorspoilers,453"
, "sushi,25490"
, "svenskpolitik,43953"
, "Sverige,1102"
, "SVExchange,10736"
, "SwagBucks,8574"
, "SWARJE,50964"
, "SweatyPalms,26722"
, "sweden,85671"
, "sweepstakes,5485"
, "swift,13768"
, "SwiggitySwootyGifs,16194"
, "Swimming,23838"
, "Swingers,15856"
, "Switzerland,7308"
, "swoleacceptance,57610"
, "swordartonline,19915"
, "SwordOrSheath,6251"
, "swrpg,4590"
, "swtor,53799"
, "sydney,22094"
, "SympatheticMonsters,8883"
, "synthesizers,19567"
, "Syracuse,3069"
, "Syraphia,26"
, "SyrianCirclejerkWar,385"
, "syriancivilwar,26280"
, "sysadmin,123602"
, "tabletopgamedesign,10692"
, "tacobell,7914"
, "Tacoma,4034"
, "TACSdiscussion,4031"
, "TagPro,11498"
, "TagProIRL,823"
, "taiwan,7100"
, "TakeshisCastle,284"
, "tales,5922"
, "talesfromcallcenters,16316"
, "TalesFromRetail,232513"
, "talesfromtechsupport,296382"
, "TalesFromTheCustomer,14883"
, "TalesFromTheFrontDesk,9948"
, "TalesFromThePharmacy,10320"
, "TalesFromThePizzaGuy,38007"
, "TalesFromTheSquadCar,20480"
, "TalesFromYourServer,39699"
, "tall,50390"
, "Tallahassee,2862"
, "Talonmains,1440"
, "TameImpala,6037"
, "tampa,11788"
, "TampaBayLightning,3492"
, "TankPorn,9398"
, "tappedout,15964"
, "tarantinogifs,11320"
, "Target,1903"
, "tasker,22637"
, "tattoo,40487"
, "tattoos,434589"
, "TaylorSwift,22392"
, "TaylorSwiftPictures,5578"
, "TaylorSwiftsLegs,8853"
, "tdl,1259"
, "tea,63796"
, "Teachers,29837"
, "teaching,16431"
, "TeamSolomid,14820"
, "tech,82935"
, "technews,17699"
, "TechNewsToday,30782"
, "Techno,16222"
, "technology,5204799"
, "TechoBlanco,1661"
, "techsupport,78211"
, "techsupportgore,109303"
, "techsupportmacgyver,56393"
, "techtheatre,7690"
, "TedCruz,988"
, "teefies,4007"
, "teenagers,105234"
, "TeenMFA,11284"
, "TEFL,13794"
, "Teleshits,10418"
, "television,6011203"
, "TelevisionQuotes,17559"
, "TellMeAFact,23598"
, "telltale,4012"
, "Tennessee,4201"
, "Tennesseetitans,4269"
, "tennis,31624"
, "TeraOnline,18715"
, "Terraria,78686"
, "terriblefacebookmemes,33514"
, "tesdcares,3954"
, "teslamotors,29314"
, "teslore,32384"
, "Texans,10937"
, "texas,32441"
, "TexasRangers,6587"
, "tf2,157238"
, "TF2fashionadvice,6190"
, "tf2shitposterclub,507"
, "tf2trade,13281"
, "tgrp,97"
, "Thailand,8314"
, "thalassophobia,64543"
, "thanksgiving,678"
, "That70sshow,11915"
, "thatHappened,238789"
, "ThatPeelingFeeling,18411"
, "The100,8349"
, "TheAffair,732"
, "TheBluePill,25735"
, "TheBrewery,7802"
, "thebutton,161652"
, "thechapel,1915"
, "TheCompletionist,2587"
, "TheCreatures,12627"
, "The_Crew,4247"
, "TheDarkTower,10781"
, "thedivision,8376"
, "The_Donald,1680"
, "TheExpanse,2150"
, "TheFacebookDelusion,24433"
, "TheForest,8747"
, "TheFrontBottoms,2114"
, "TheGameOfThronesGame,2267"
, "TheGirlSurvivalGuide,56560"
, "thegoodwife,2651"
, "TheHobbit,21547"
, "TheKillers,2316"
, "TheLastAirbender,142647"
, "thelastofus,21644"
, "thelastofusfactions,5769"
, "thelawschool,1305"
, "theleaguefx,17449"
, "TheLeftovers,12448"
, "thelongdark,4192"
, "TheMassive,1864"
, "ThemeParkitect,1508"
, "themindyproject,2318"
, "themoddingofisaac,4680"
, "themountaingoats,3058"
, "thenetherlands,67966"
, "theNvidiaShield,2771"
, "theocho,39803"
, "TheOnion,14325"
, "ThePhenomenon,7304"
, "TheRealmsMC,335"
, "TheRedPill,139577"
, "thereifixedit,10036"
, "thereisnoowl,247"
, "therewasanattempt,16696"
, "TheSimpsons,118309"
, "thesims,43878"
, "thesopranos,7028"
, "TheSquadOnPoint,8807"
, "TheStrokes,4903"
, "Thetruthishere,46694"
, "TheVampireDiaries,6381"
, "thevoice,1175"
, "thewalkingdead,257148"
, "TheWayWeWere,68848"
, "thewestwing,6412"
, "TheWire,21842"
, "theworldisflat,1241"
, "theworldnews,6170"
, "theydidthemath,125881"
, "ThingsCutInHalfPorn,88776"
, "ThingsWhiteFolksLike,97"
, "thinkpad,6659"
, "thisismylifenow,7624"
, "ThisIsNotASafeSpace,1145"
, "ThriftStoreHauls,60871"
, "Throwers,6326"
, "Thunder,5600"
, "TiADiscussion,7104"
, "TibiaMMO,1524"
, "tifu,4785294"
, "TILinIndia,360"
, "tiltshift,26505"
, "TimAndEric,22437"
, "timbers,3840"
, "timberwolves,5029"
, "timetolegalize,10058"
, "tinabelcher,14568"
, "Tinder,178148"
, "TinyHouses,67833"
, "tipofmyjoystick,7822"
, "tipofmytongue,155576"
, "titanfall,30090"
, "titlegore,32415"
, "TMBR,2729"
, "TMNT,8354"
, "tmobile,14739"
, "tobacco_ja,158"
, "TodayIGrandstanded,1472"
, "todayilearned,10011031"
, "Tokyo,8491"
, "TokyoGhoul,10479"
, "tolkienfans,32828"
, "TombRaider,4408"
, "tomwaits,1568"
, "tonightsdinner,39276"
, "ToolBand,16789"
, "Tools,4780"
, "TooMeIrlForMeIrl,481"
, "Toonami,6379"
, "Toontown,4781"
, "toosoon,77090"
, "TopGear,136177"
, "TopMindsOfReddit,9391"
, "topofreddit,4569"
, "TOR,23629"
, "toronto,66122"
, "TorontoAnarchy,95"
, "Torontobluejays,18976"
, "torontoraptors,10952"
, "torrents,56332"
, "totallynotrobots,9466"
, "totalwar,41322"
, "touhou,8449"
, "TowerofGod,4100"
, "TownofSalemgame,5464"
, "Toyota,7056"
, "TPPKappa,272"
, "traaaaaaannnnnnnnnns,2723"
, "trackers,53133"
, "Tradelands,621"
, "TraditionalCurses,8904"
, "trailerparkboys,47748"
, "trailers,30981"
, "traingifs,4196"
, "trains,7737"
, "trance,38049"
, "transformers,8114"
, "transgamers,4169"
, "transgender,21190"
, "transgendercirclejerk,2311"
, "translator,8015"
, "Transmogrification,14579"
, "transpassing,12247"
, "transpositive,7195"
, "transtimelines,13427"
, "trap,53878"
, "trapmuzik,16279"
, "trapproduction,6328"
, "trashpandas,10062"
, "trashy,169388"
, "travel,229376"
, "treecomics,31956"
, "treedibles,13730"
, "treemusic,38739"
, "treeofsavior,10856"
, "trees,810334"
, "TreesSuckingAtThings,32164"
, "trendingsubreddits,12500"
, "tressless,4245"
, "triangle,8951"
, "Tribes,11694"
, "trippinthroughtime,79903"
, "trippy,23788"
, "Troll4Troll,3223"
, "TrollBookClub,2625"
, "TrollDevelopers,879"
, "TrollXChromosomes,178563"
, "TrollXMoms,4640"
, "TrollXWeddings,2970"
, "TrollYChromosome,64300"
, "Trophies,4227"
, "Trove,12525"
, "Trucking,4314"
, "Trucks,19720"
, "trucksim,4914"
, "TrueAnime,7706"
, "TrueAskReddit,78978"
, "TrueAtheism,59089"
, "TrueChristian,9798"
, "TrueDetective,63696"
, "TrueDoTA2,8917"
, "TrueFilm,82190"
, "truegaming,137623"
, "TrueLionhearts,6"
, "TrueOffMyChest,10250"
, "TrueReddit,355484"
, "TrueSTL,4047"
, "truetf2,14280"
, "truewomensliberation,497"
, "truezelda,10426"
, "trump,436"
, "trumpet,4992"
, "TryingForABaby,6930"
, "trypophobia,11299"
, "Tsunderes,3708"
, "TsundereSharks,40487"
, "ttcafterloss,605"
, "tuckedinkitties,14781"
, "Tucson,6725"
, "Tulpas,9496"
, "tulsa,4869"
, "tumblr,142894"
, "TumblrAtRest,20809"
, "TumblrCirclejerk,8206"
, "TumblrInAction,258243"
, "TumblrPls,4025"
, "Turkey,6826"
, "turning,6471"
, "TuxedoCats,3361"
, "TWD,10164"
, "twentyonepilots,7668"
, "twice,669"
, "TwinCities,12115"
, "twinpeaks,14130"
, "Twitch,43528"
, "twitchplayspokemon,49925"
, "TwoBestFriendsPlay,16430"
, "Twokinds,988"
, "TwoXChromosomes,4185231"
, "TwoXSex,15244"
, "typography,45538"
, "TYT,931"
, "UBC,4840"
, "uber,2502"
, "uberdrivers,6229"
, "Ubuntu,60590"
, "UCalgary,1674"
, "ucf,6370"
, "UCSantaBarbara,5088"
, "udub,4305"
, "ufc,22738"
, "UFOs,48910"
, "UGA,4784"
, "uglyduckling,32364"
, "UIUC,11956"
, "ukbike,3128"
, "ukipparty,2191"
, "UKPersonalFinance,10126"
, "ukpolitics,42408"
, "ukraina,12948"
, "UkrainianConflict,21537"
, "uktrees,7946"
, "ukulele,18774"
, "ultimate,17636"
, "ultrahardcore,6749"
, "Ultralight,20511"
, "ultrawidemasterrace,1849"
, "UMD,5213"
, "UNBGBBIIVCHIDCTIICBG,89630"
, "undelete,47051"
, "Underminers,1213"
, "Undertale,23950"
, "Undertem,283"
, "UnearthedArcana,4194"
, "Unexpected,454437"
, "UnexpectedCena,42675"
, "unexpectedjihad,84030"
, "unexpectedmusic,6513"
, "UnexpectedThugLife,207696"
, "unintentionalASMR,7736"
, "UnisonLeague,847"
, "unitedkingdom,118237"
, "unitedstatesofamerica,13605"
, "Unity2D,12204"
, "Unity3D,31991"
, "UniversityOfHouston,2996"
, "unixporn,32974"
, "Unorthodog,14085"
, "unpopularopinion,2633"
, "unrealengine,12071"
, "unrealtournament,3915"
, "UnresolvedMysteries,123566"
, "UnsentLetters,14744"
, "UnsolicitedRedesigns,6108"
, "UnsolvedMysteries,19576"
, "unstirredpaint,7293"
, "unturned,9162"
, "UnusualArt,10748"
, "uofm,6099"
, "uofmn,3849"
, "UofT,6623"
, "UpliftingNews,4441491"
, "Upvoted,18086"
, "UpvotedBecauseGirl,18218"
, "upvotegifs,17815"
, "urbanexploration,76436"
, "UrbanHell,13357"
, "urbanplanning,20087"
, "usanews,4603"
, "USC,3212"
, "usenet,23173"
, "UserCars,6730"
, "userexperience,12158"
, "USMC,10931"
, "uspolitics,6524"
, "ussoccer,13690"
, "Utah,4476"
, "UtahJazz,2145"
, "UTAustin,8554"
, "Utrecht,1156"
, "uvic,1694"
, "uwaterloo,7871"
, "uwotm8,26543"
, "VAC_Porn,9417"
, "vagabond,15251"
, "vainglorygame,4545"
, "valve,13360"
, "vancouver,38148"
, "vandwellers,20578"
, "vapeitforward,6349"
, "VapePorn,10638"
, "Vaping101,10078"
, "Vaping,24139"
, "vaporents,44059"
, "Vaporwave,22466"
, "VaporwaveAesthetics,6500"
, "vargas,3989"
, "vegan,62390"
, "vegancirclejerk,2338"
, "veganrecipes,24643"
, "vegas,11805"
, "vegetarian,44443"
, "VegRecipes,36893"
, "Velo,8444"
, "venturebros,14986"
, "verizon,4884"
, "Vermintide,6883"
, "Veterans,6255"
, "vexillology,46282"
, "vexillologycirclejerk,4132"
, "vfx,11058"
, "vgb,21719"
, "VGHS,3890"
, "victoria2,3678"
, "VictoriaBC,8051"
, "victoriajustice,10163"
, "video,24832"
, "videogamedunkey,12453"
, "videography,16302"
, "videos,9247409"
, "videosplus,1976"
, "VietNam,4321"
, "VillagePorn,48589"
, "vim,25464"
, "Vinesauce,4827"
, "vintageaudio,8157"
, "vinyl,81713"
, "Virginia,7959"
, "VirginiaTech,6843"
, "virtualreality,16951"
, "visualnovels,18966"
, "vita,49605"
, "Vive,6470"
, "vmware,13503"
, "Voat,4851"
, "Vocaloid,10975"
, "Volkswagen,21290"
, "VolleyballGirls,59133"
, "Volvo,6632"
, "VPN,17588"
, "vsauce,3602"
, "VSModels,2908"
, "VXJunkies,9443"
, "vzla,7574"
, "WackyTicTacs,16046"
, "waifuism,1061"
, "wallpaper,161387"
, "wallpaperdump,24528"
, "wallpapers,374610"
, "wallstreetbets,25133"
, "walmart,3298"
, "WaltDisneyWorld,16644"
, "warcraftlore,9359"
, "Warframe,37682"
, "wargame,6285"
, "Warhammer,34751"
, "Warhammer40k,20910"
, "Warmachine,6497"
, "WarOnComcast,9218"
, "WarplanePorn,5297"
, "warriors,13277"
, "WarshipPorn,26919"
, "Warthunder,31860"
, "Washington,8927"
, "washingtondc,36390"
, "washingtonwizards,4192"
, "WastedGifs,119428"
, "WastelandPowers,434"
, "Watches,81459"
, "WatchesCirclejerk,1508"
, "Watchexchange,5194"
, "Watercolor,12336"
, "watercooling,9119"
, "waterporn,59894"
, "Waxpen,2460"
, "Weakpots,2643"
, "WeAreTheMusicMakers,122961"
, "weather,16995"
, "webcomics,81539"
, "web_design,146257"
, "webdev,105268"
, "WebGames,91965"
, "wec,9139"
, "wedding,18085"
, "WeddingPhotography,3016"
, "weddingplanning,26248"
, "weeabootales,23571"
, "weed,10981"
, "weekendgunnit,6415"
, "weightlifting,20232"
, "weightroom,78738"
, "Weird,26971"
, "WeirdWheels,11164"
, "Welding,17441"
, "Wellington,4711"
, "Wellthatsucks,60047"
, "WEPES,2584"
, "WestVirginia,3002"
, "Wet_Shavers,5221"
, "whatcarshouldIbuy,7337"
, "Whatcouldgowrong,234461"
, "Whatisthis,13279"
, "whatisthisthing,171566"
, "WhatsInThisThing,87704"
, "whatstheword,21524"
, "whatsthisbird,6998"
, "whatsthisbug,40683"
, "whatsthisplant,21102"
, "whatsthisrock,4341"
, "WhatsWrongWithYourDog,8502"
, "wheredidthesodago,381556"
, "whiskey,24787"
, "Whiskyporn,4836"
, "whiteknighting,19243"
, "whitepeoplefacebook,10795"
, "whitepeoplegifs,85881"
, "WhitePeopleTwitter,4837"
, "WhiteRights,9339"
, "whitesox,4082"
, "WhiteWolfRPG,3925"
, "whowouldcirclejerk,1245"
, "whowouldwin,94633"
, "Wicca,10118"
, "wicked_edge,77487"
, "WiggleButts,5153"
, "wiiu,81853"
, "WikiInAction,3372"
, "WikiLeaks,35651"
, "wikipedia,156441"
, "wildhockey,6955"
, "WildStar,35041"
, "wince,18160"
, "Windows10,55712"
, "windows,57504"
, "windowsphone,48558"
, "wine,35744"
, "Winnipeg,8798"
, "winnipegjets,3091"
, "winterporn,35946"
, "wisconsin,14546"
, "Wishlist,1910"
, "witcher,84856"
, "wma,5119"
, "woahdude,890116"
, "WonderTrade,6303"
, "woodworking,138992"
, "woofbarkwoof,6057"
, "woof_irl,9024"
, "WordAvalanches,15556"
, "Wordpress,28014"
, "WorkOnline,34955"
, "worldbuilding,62503"
, "worldevents,39549"
, "worldnews,9843404"
, "worldofpvp,3947"
, "WorldofTanks,26078"
, "WorldofTanksXbox,1489"
, "WorldOfWarships,14689"
, "worldpolitics,150119"
, "worldpowers,2447"
, "worldwhisky,4109"
, "WormFanfic,546"
, "worstof,37425"
, "WoT,13538"
, "WouldYouRather,39373"
, "wow,254317"
, "woweconomy,11193"
, "wowservers,2742"
, "wowthissubexists,74412"
, "Wrangler,7569"
, "Wrasslin,6255"
, "WrestleWithThePlot,15936"
, "wrestling,7589"
, "wrestlingisreddit,196"
, "writing,163310"
, "WritingPrompts,4278661"
, "wsgy,2336"
, "wsu,2487"
, "WTF,4692656"
, "wtfstockphotos,22428"
, "WWE,21207"
, "WWEGames,4665"
, "wwe_network,1029"
, "wwesupercard,2258"
, "wwiipics,10467"
, "WWU,1721"
, "xbmc,17678"
, "xbox,13738"
, "xbox360,48571"
, "xboxone,170503"
, "Xcom,23966"
, "xDivinum,2"
, "Xenoblade_Chronicles,4403"
, "XFiles,16183"
, "xkcd,62961"
, "xposed,11730"
, "xTrill,2404"
, "XWingTMG,8024"
, "xxfitness,89703"
, "xxketo,23640"
, "YanetGarcia,8212"
, "yarntrolls,2171"
, "YasuoMains,963"
, "yee,4661"
, "yesyesyesno,15237"
, "yesyesyesyesno,22447"
, "YMS,9789"
, "ynab,17393"
, "yoga,81031"
, "Yogscast,45014"
, "yogscastkim,4241"
, "yokaiwatch,1338"
, "youdontsurf,191966"
, "YouSeeComrade,25241"
, "YouShouldKnow,513161"
, "youtube,34027"
, "youtubecomments,18579"
, "youtubehaiku,194879"
, "yoyhammer,1854"
, "yugioh,30391"
, "yuruyuri,856"
, "yvonnestrahovski,9131"
, "Zappa,5521"
, "zelda,140888"
, "zen,31825"
, "ZenHabits,107887"
, "Zerxee,2"
, "ZettaiRyouiki,13054"
, "zoidberg,6890"
, "zombies,85610"
]
| 59764 | module Sfw (..) where
sfwRaw : List String
sfwRaw =
[ "100yearsago,32345"
, "1200isplenty,40968"
, "12thMan,946"
, "1911,6937"
, "195,10030"
, "2007scape,45053"
, "240sx,3708"
, "30ROCK,20200"
, "336RS,5"
, "3amjokes,48060"
, "3Dmodeling,8997"
, "3Dprinting,45402"
, "3DS,105660"
, "3DSdeals,13270"
, "3dshacks,4549"
, "40kLore,2901"
, "49ers,23227"
, "4ChanMeta,8778"
, "4PanelCringe,17496"
, "4Runner,3143"
, "4x4,18457"
, "4Xgaming,6475"
, "52weeksofcooking,21831"
, "7daystodie,8453"
, "7kglobal,586"
, "80smusic,6852"
, "8chan,9806"
, "90sAlternative,7895"
, "90smusic,6374"
, "911truth,9696"
, "9gag,4223"
, "A858DE45F56D9BC9,11616"
, "AAdiscussions,203"
, "AaronTracker,4"
, "AbandonedPorn,300746"
, "ABCDesis,4339"
, "ableton,18019"
, "ABraThatFits,43569"
, "AcademicBiblical,8561"
, "Acadiana,2074"
, "AccidentalComedy,34518"
, "AccidentalRenaissance,7883"
, "Accounting,29020"
, "AceAttorney,6444"
, "acecombat,1946"
, "AceOfAngels8,1547"
, "ACMilan,3076"
, "ACON_Support,455"
, "acting,13840"
, "ActionFigures,7067"
, "ActLikeYouBelong,20574"
, "ACTrade,10624"
, "actualconspiracies,12269"
, "actuallesbians,50164"
, "<NAME>,5185"
, "Addons4Kodi,4778"
, "Adelaide,6433"
, "ADHD,43331"
, "AdorableDragons,5874"
, "AdrenalinePorn,67900"
, "ads,7112"
, "adultery,4964"
, "adultswim,15055"
, "AdvancedRunning,8663"
, "AdventureCapitalist,2034"
, "adventurerlogkiraigen,3"
, "adventuretime,154732"
, "advertising,22881"
, "Advice,28313"
, "AdviceAnimals,4280324"
, "AdviceAtheists,15199"
, "AdvLog,6"
, "afinil,6147"
, "AFL,12831"
, "AfterEffects,13537"
, "AgainstGamerGate,1828"
, "AgainstHateSubreddits,2564"
, "againstmensrights,8568"
, "<NAME>,20815"
, "agentcarter,8096"
, "aggies,8415"
, "ainbow,39002"
, "AirBnB,3030"
, "AirForce,16643"
, "airsoft,24091"
, "A_irsoft,531"
, "airsoftmarket,3989"
, "ak47,7742"
, "AkameGaKILL,4701"
, "alaska,8188"
, "Albany,4057"
, "alberta,7316"
, "albiononline,2721"
, "AlbumArtPorn,38777"
, "Albuquerque,5171"
, "alcohol,19222"
, "aldub,251"
, "Aleague,4828"
, "alex<NAME>,11623"
, "<NAME>,10418"
, "AlienBlue,205706"
, "aliens,14241"
, "AliensAmongUs,7610"
, "AlisonBrie,39875"
, "allthingsprotoss,8880"
, "AllThingsTerran,9039"
, "allthingszerg,9941"
, "alternativeart,50896"
, "altnewz,6882"
, "AMA,110503"
, "amateurradio,18510"
, "amazon,12531"
, "amazonecho,4205"
, "AmazonTopRated,31361"
, "Amd,15312"
, "americandad,10454"
, "AmericanHorrorStory,41385"
, "AmericanPolitics,7383"
, "amibeingdetained,28268"
, "AmIFreeToGo,18446"
, "amiibo,40041"
, "AmiiboCanada,2665"
, "AmISexy,29827"
, "AmItheAsshole,9068"
, "amiugly,58738"
, "Amsterdam,8891"
, "AnaheimDucks,4120"
, "analog,25027"
, "analogygifs,15193"
, "Anarchism,61152"
, "Anarcho_Capitalism,24470"
, "anarchomemes,2235"
, "Anarchy101,8342"
, "Android,619379"
, "androidapps,71654"
, "androidcirclejerk,10091"
, "androiddev,45103"
, "AndroidGaming,60786"
, "AndroidMasterRace,17075"
, "AndroidQuestions,21961"
, "androidthemes,43273"
, "AndroidTV,2073"
, "AndroidWear,22250"
, "ANGEL,3818"
, "angelsbaseball,4015"
, "AngieVarona,7416"
, "AngieVaronaLegal,14860"
, "angularjs,14290"
, "AnimalCollective,3999"
, "AnimalCrossing,52738"
, "AnimalPorn,58298"
, "Animals,16669"
, "AnimalsBeingBros,155109"
, "AnimalsBeingDerps,68440"
, "AnimalsBeingGeniuses,11587"
, "AnimalsBeingJerks,260301"
, "AnimalTextGifs,16525"
, "animation,30036"
, "anime,329033"
, "AnimeFigures,9580"
, "animegifs,23635"
, "animegifsound,2956"
, "anime_irl,21733"
, "animelegs,1158"
, "animenocontext,17583"
, "animeponytails,1120"
, "AnimeSketch,7131"
, "Animesuggest,33759"
, "Animewallpaper,25418"
, "<NAME>,3919"
, "annakendrick,23257"
, "<NAME>,6710"
, "announcements,9800402"
, "annualkpopawards,63"
, "ANormalDayInRussia,107448"
, "answers,90064"
, "Anthropology,42357"
, "AntiAntiJokes,19258"
, "Anticonsumption,36517"
, "AntiJokes,67527"
, "antinatalism,1278"
, "ANTM,2152"
, "Anxiety,72471"
, "AnythingGoesNews,18624"
, "AnythingGoesPics,24342"
, "aoe2,15746"
, "aphextwin,3243"
, "apink,2849"
, "ApocalypseRising,1312"
, "AppalachianTrail,13382"
, "AppHookup,54908"
, "apple,303477"
, "applehelp,18550"
, "appletv,11595"
, "AppleWatch,17573"
, "ApplyingToCollege,3909"
, "AquamarineVI,258"
, "Aquariums,55476"
, "ar15,25099"
, "arabs,6346"
, "araragi,6637"
, "Archaeology,29159"
, "archeage,18222"
, "ArcherFX,114190"
, "Archery,23167"
, "architecture,66636"
, "ArchitecturePorn,67248"
, "archlinux,26220"
, "arcticmonkeys,7984"
, "arduino,54938"
, "arewerolling,5972"
, "argentina,18793"
, "<NAME>,18748"
, "arielwinter,8131"
, "arizona,9188"
, "ARK,9688"
, "Arkansas,5084"
, "arkfactions,352"
, "arma,27814"
, "armenia,1578"
, "ArmoredWarfare,4370"
, "army,17100"
, "arresteddevelopment,114120"
, "arrow,54555"
, "Art,4418320"
, "ArtefactPorn,52941"
, "artificial,20563"
, "ArtisanVideos,150438"
, "ArtistLounge,4904"
, "ArtPorn,47635"
, "AsABlackMan,5445"
, "asatru,5196"
, "asexuality,9774"
, "Ashens,9899"
, "asheville,5954"
, "AshVsEvilDead,2799"
, "asianamerican,9586"
, "AsianBeauty,33062"
, "AsianCuties,30944"
, "AsianHottiesGIFS,14792"
, "AsianLadyboners,6093"
, "AsianMasculinity,6203"
, "AsianParentStories,9823"
, "AskAcademia,22049"
, "askaconservative,1957"
, "AskAnAmerican,5448"
, "AskAnthropology,26531"
, "askashittydoctor,11900"
, "askcarsales,11328"
, "AskCulinary,91322"
, "AskDocs,11072"
, "AskDoctorSmeeee,6793"
, "askdrugs,11213"
, "AskElectronics,20673"
, "AskEngineers,47497"
, "AskEurope,4997"
, "AskFeminists,8567"
, "AskGames,8898"
, "askgaybros,20243"
, "AskHistorians,462271"
, "AskHistory,10196"
, "AskHR,2694"
, "AskLE,1681"
, "AskMen,220171"
, "AskMenOver30,13031"
, "askMRP,689"
, "AskNetsec,14828"
, "AskNYC,9909"
, "askphilosophy,35904"
, "AskPhysics,8632"
, "Ask_Politics,19137"
, "askportland,2530"
, "AskReddit,10155641"
, "askscience,6895111"
, "AskScienceDiscussion,12244"
, "AskScienceFiction,55288"
, "askseddit,17700"
, "AskSF,3748"
, "AskSocialScience,57653"
, "asktransgender,23115"
, "AskTrollX,8560"
, "asktrp,23896"
, "AskUK,12080"
, "AskVet,8103"
, "AskWomen,225556"
, "askwomenadvice,6981"
, "AskWomenOver30,6563"
, "asmr,112789"
, "asoiaf,244263"
, "asoiafcirclejerk,4344"
, "aspergers,15150"
, "assassinscreed,46238"
, "assettocorsa,6121"
, "Assistance,29810"
, "astrology,8515"
, "Astronomy,141457"
, "astrophotography,57121"
, "Astros,4952"
, "ASU,4409"
, "atheism,2099225"
, "atheistvids,7627"
, "Atlanta,32975"
, "AtlantaHawks,4422"
, "atlbeer,3517"
, "atletico,1135"
, "atmidnight,3523"
, "AubreyPlaza,14920"
, "auckland,5226"
, "Audi,14219"
, "audiobooks,13601"
, "audioengineering,51568"
, "Audiomemes,4680"
, "audiophile,54275"
, "AusFinance,7694"
, "auslaw,4139"
, "Austin,50816"
, "australia,106489"
, "AustralianCattleDog,4919"
, "AustralianMakeup,4210"
, "AustralianPolitics,6610"
, "Austria,17901"
, "Authentic_Vaping,733"
, "autism,10224"
, "AutoDetailing,28181"
, "Automate,16572"
, "Autos,72116"
, "aves,21455"
, "avfc,1877"
, "aviation,65472"
, "awakened,6010"
, "awardtravel,3823"
, "awesome,63586"
, "AwesomeCarMods,14282"
, "Awesomenauts,6926"
, "awfuleverything,8550"
, "awfuleyebrows,16927"
, "aws,7148"
, "aww,8383516"
, "Awwducational,105958"
, "awwnime,43090"
, "awwnverts,13808"
, "awwtf,5978"
, "Awww,30169"
, "awwwtf,52204"
, "ayylmao,12334"
, "AyyMD,2243"
, "AZCardinals,4375"
, "BabyBumps,30685"
, "BabyCorgis,3817"
, "babyelephantgifs,78348"
, "BABYMETAL,4337"
, "backpacking,66411"
, "BacktotheFuture,8217"
, "BackYardChickens,13125"
, "Bacon,23353"
, "baconreader,286837"
, "badcode,11582"
, "Bad_Cop_Follow_Up,383"
, "Bad_Cop_No_Donut,83168"
, "badeconomics,7137"
, "BadguyWolfies,2"
, "badhistory,53746"
, "badlegaladvice,6941"
, "badlinguistics,12134"
, "badmathematics,2022"
, "badMovies,17298"
, "badphilosophy,12828"
, "badpolitics,4844"
, "bad_religion,3771"
, "badroommates,7389"
, "badscience,7812"
, "BadSocialScience,4476"
, "badtattoos,46256"
, "baduk,7264"
, "badukpolitics,345"
, "badwomensanatomy,5426"
, "bagelheads,52"
, "BakaNewsJP,3604"
, "bakchodi,4281"
, "Baking,76381"
, "balisong,2263"
, "baltimore,17454"
, "Bandnames,20585"
, "bangalore,2431"
, "bangtan,716"
, "Banished,21413"
, "BanjoKazooie,2109"
, "banned,779"
, "BannedFrom4chan,10945"
, "bannedfromclubpenguin,49385"
, "bapcsalescanada,10233"
, "bap<NAME>,4425"
, "<NAME>,5677"
, "<NAME>,13022"
, "Barcelona,3289"
, "bardmains,2928"
, "barstoolsports,3779"
, "bartenders,11404"
, "baseball,155176"
, "baseballcirclejerk,2681"
, "BasicIncome,31039"
, "Bass,39616"
, "bassnectar,4105"
, "BatFacts,7222"
, "batman,135188"
, "BatmanArkham,9761"
, "batonrouge,3672"
, "Battlecars,3906"
, "battlecats,2008"
, "Battlefield,28894"
, "battlefield3,51573"
, "battlefield_4,87684"
, "Battlefield_4_CTE,4335"
, "battlefront,8845"
, "battlestations,181457"
, "battlewagon,8473"
, "bayarea,37443"
, "baylor,1774"
, "BBQ,36931"
, "beadsprites,12708"
, "beagle,7016"
, "BeAmazed,49884"
, "BeardedDragons,6346"
, "BeardPorn,19798"
, "beards,107205"
, "beatles,26412"
, "Beatmatch,12427"
, "BeautifulFemales,6427"
, "BeautyBoxes,12831"
, "BeautyGuruChat,2738"
, "BeavisAndButthead,6556"
, "bee_irl,4427"
, "beer,175146"
, "beercirclejerk,1519"
, "beermoney,99255"
, "beerporn,31777"
, "beertrade,12564"
, "beerwithaview,18068"
, "beetlejuicing,11675"
, "beforeandafteredit,8036"
, "BeforeNAfterAdoption,35617"
, "belgium,24164"
, "<NAME>,6409"
, "<NAME>ham,3929"
, "bengals,7308"
, "benzodiazepines,3782"
, "berkeley,10041"
, "<NAME>,9091"
, "<NAME>,11710"
, "berserklejerk,378"
, "bertstrips,73130"
, "<NAME>ge,20487"
, "Bestbuy,1252"
, "bestof,4825375"
, "bestoflegaladvice,24410"
, "BestOfLiveleak,23546"
, "bestofnetflix,47255"
, "BestOfOutrageCulture,8893"
, "BestOfReports,11937"
, "BestOfStreamingVideo,39169"
, "bettafish,8565"
, "BetterEveryLoop,1992"
, "betternews,1997"
, "BetterSubredditdrama,273"
, "beyondthebump,16392"
, "BF_Hardline,12243"
, "bicycletouring,18700"
, "bicycling,167014"
, "bigbangtheory,26548"
, "BigBrother,21975"
, "bigdickproblems,32160"
, "biggestproblem,424"
, "bikecommuting,18540"
, "Bikeporn,20438"
, "bikesgonewild,23533"
, "bikewrench,15542"
, "<NAME>,9891"
, "billiards,7126"
, "bindingofisaac,72273"
, "bioinformatics,9586"
, "biology,75423"
, "bioniclelego,4119"
, "Bioshock,41261"
, "bipolar,15450"
, "BipolarReddit,13766"
, "Birbs,12097"
, "birdpics,14683"
, "BirdsBeingDicks,29020"
, "birdsofprey,3160"
, "birdswitharms,82881"
, "Birmingham,5808"
, "birthcontrol,7624"
, "bisexual,35587"
, "bitchimabus,46877"
, "Bitcoin,176233"
, "BitcoinMarkets,21106"
, "bitcoinxt,13339"
, "bjj,33502"
, "blackberry,6943"
, "blackbookgraffiti,8555"
, "blackcats,3176"
, "blackdesertonline,8926"
, "Blackfellas,4072"
, "blackfriday,13730"
, "blackladies,9569"
, "BlackLivesMatter,564"
, "BlackMetal,11198"
, "blackmirror,5271"
, "blackops3,37209"
, "Blackout2015,32993"
, "blackpeoplegifs,93773"
, "BlackPeopleTwitter,536812"
, "BlackSails,3569"
, "Blacksmith,25543"
, "BlackwellAcademy,472"
, "bladeandsoul,6677"
, "blakelively,4838"
, "bleach,23050"
, "blender,24603"
, "Blep,44001"
, "blindspot,851"
, "Blink182,11129"
, "BlocParty,778"
, "blogsnark,1030"
, "bloodborne,51353"
, "bloodbowl,3653"
, "BloodGulchRP,177"
, "bloomington,3454"
, "blop,8423"
, "BlueJackets,3055"
, "blues,16528"
, "bluesguitarist,4297"
, "blunderyears,90372"
, "BMW,30818"
, "Boardgamedeals,5984"
, "boardgames,117122"
, "BobsBurgers,37735"
, "bodybuilding,117061"
, "bodymods,10743"
, "bodyweightfitness,187214"
, "Boise,4406"
, "BoJackHorseman,22545"
, "BokuNoHeroAcademia,4307"
, "BollywoodRealism,35697"
, "Bombing,11698"
, "bonnaroo,13215"
, "Bonsai,28350"
, "bookporn,42999"
, "books,6272500"
, "booksuggestions,53715"
, "BoomBeach,10288"
, "boop,34592"
, "BorderCollie,5289"
, "Borderlands2,42577"
, "Borderlands,66180"
, "borrow,4287"
, "borussiadortmund,6204"
, "boston,53540"
, "BostonBruins,13916"
, "bostonceltics,11780"
, "BostonTerrier,6458"
, "botsrights,8562"
, "boulder,8485"
, "bouldering,16196"
, "bourbon,27782"
, "Boxer,7302"
, "Boxing,34148"
, "boxoffice,12419"
, "BPD,9526"
, "BPDlovedones,1652"
, "braces,1244"
, "Brampton,1399"
, "brandnew,8326"
, "brasil2,376"
, "brasil,43923"
, "bravefrontier,28337"
, "B<NAME>veryjerk,18373"
, "Braves,11507"
, "BravestWarriors,9697"
, "BravoRealHousewives,3609"
, "Brawlhalla,3280"
, "Breadit,38587"
, "breakingbad,226518"
, "breakingmom,12082"
, "breastfeeding,11418"
, "Briggs,1412"
, "brisbane,15228"
, "bristol,5743"
, "BritishPolitics,3226"
, "britishproblems,112238"
, "BritishSuccess,17782"
, "BritishTV,25517"
, "britpics,17149"
, "Brogress,22861"
, "brokehugs,930"
, "brokengifs,39373"
, "Brooklyn,14035"
, "brooklynninenine,13368"
, "Browns,12674"
, "brum,2583"
, "BSG,17676"
, "btc,5936"
, "buccaneers,4970"
, "buccos,5494"
, "Buddhism,91326"
, "budgetfood,89715"
, "Buffalo,7561"
, "buffalobills,9056"
, "BuffaloWizards,4412"
, "buffy,18868"
, "bugout,11582"
, "buildapc,332244"
, "buildapcforme,36022"
, "buildapcsales,118479"
, "Bulldogs,9916"
, "Bullshitfacts,100"
, "BurningMan,16533"
, "Bushcraft,22441"
, "business,201584"
, "Buttcoin,6712"
, "BuyItForLife,187865"
, "ByTheMods,178"
, "c137,8148"
, "C25K,45786"
, "cablefail,18510"
, "CableManagement,20962"
, "cableporn,58421"
, "<NAME>,499"
, "CafeRacers,10591"
, "CAguns,1342"
, "cahideas,5342"
, "CalamariRaceTeam,8602"
, "Cal<NAME>ary,18553"
, "CalgaryFlames,3872"
, "California,28005"
, "CaliforniaForSanders,2977"
, "Calligraphy,30726"
, "CallOfDuty,18139"
, "calvinandhobbes,109777"
, "<NAME>,4841"
, "camping,52059"
, "CampingandHiking,106021"
, "canada,202444"
, "canadaguns,5588"
, "CanadaPolitics,24321"
, "Canadian_ecigarette,3086"
, "CanadianForces,5094"
, "canberra,3324"
, "cancer,6940"
, "candiceswanepoel,6678"
, "canes,1853"
, "CanineCosplay,2041"
, "cannabis,29817"
, "CannabisExtracts,23362"
, "canon,4748"
, "canucks,12026"
, "caps,7537"
, "capstone,1876"
, "CaptchaArt,16528"
, "<NAME>,5521"
, "<NAME>,10821"
, "carcrash,15916"
, "Cardinals,10645"
, "cardistry,6647"
, "careerguidance,14037"
, "<NAME>letonU,1893"
, "carnivalclan,10"
, "<NAME>,1513"
, "carporn,130914"
, "cars,181029"
, "Cartalk,25622"
, "caseyneistat,4144"
, "cassetteculture,5086"
, "castiron,13780"
, "CastleClash,1702"
, "castles,29368"
, "CastleTV,7685"
, "CasualConversation,105758"
, "casualiama,90386"
, "casualminecrafting,782"
, "casualnintendo,6267"
, "cataclysmdda,2095"
, "CatastrophicFailure,25039"
, "catbellies,8016"
, "CatGifs,27205"
, "CatHighFive,12747"
, "Catholicism,21215"
, "Catloaf,17258"
, "catpictures,55448"
, "cats,312768"
, "CatsAreAssholes,9683"
, "CatsInSinks,8154"
, "CatSlaps,10293"
, "catssittingdown,2902"
, "CatsStandingUp,56499"
, "CautiousBB,2491"
, "CCJ2,992"
, "CCW,26379"
, "CelebGfys,11641"
, "celeb_redheads,5133"
, "CelebrityArmpits,2054"
, "CelebrityFeet,5430"
, "Celebs,174806"
, "Cello,3627"
, "CFB,154117"
, "cfbball,2270"
, "cfbcirclejerk,1170"
, "CFBOffTopic,1829"
, "CFL,4825"
, "CGPGrey,43053"
, "changemyview,214363"
, "charactercrossovers,8297"
, "characterdrawing,11157"
, "CharacterRant,719"
, "Charcuterie,14267"
, "Chargers,9499"
, "Charleston,5065"
, "Charlotte,9223"
, "CharlotteHornets,3203"
, "Chattanooga,4290"
, "Cheese,10036"
, "chelseafc,22362"
, "ChemicalEngineering,5494"
, "chemicalreactiongifs,150902"
, "chemistry,63462"
, "CherokeeXJ,3482"
, "chess,43056"
, "CHIBears,20971"
, "chicago,75767"
, "chicagobulls,18884"
, "chickyboo,66"
, "CHICubs,7236"
, "ChiefKeef,2026"
, "Chihuahua,5681"
, "childfree,91356"
, "ChildrenFallingOver,69583"
, "chile,10669"
, "chiliadmystery,18929"
, "chillmusic,27584"
, "chillstep,11022"
, "China,26200"
, "ChineseLanguage,13675"
, "Chipotle,3245"
, "ChivalryGame,9331"
, "chloegracemoretz,12169"
, "chomsky,4922"
, "Christianity,107140"
, "christmas,10728"
, "chrome,32514"
, "Chromecast,51459"
, "chromeos,19097"
, "ChronicPain,6516"
, "chronotrigger,3598"
, "chuck,8789"
, "churning,32003"
, "cider,5157"
, "Cigarettes,4701"
, "cigars,33349"
, "cincinnati,13085"
, "Cinema4D,6713"
, "Cinemagraphs,112881"
, "CinemaSins,9200"
, "cinematography,15325"
, "CineShots,14842"
, "circlebroke2,6744"
, "circlebroke,34885"
, "circlejerk,271122"
, "circlejerkaustralia,2226"
, "cirkeltrek,2867"
, "CitiesSkylines,98594"
, "CityPorn,151648"
, "civ,133370"
, "civbattleroyale,7742"
, "civbeyondearth,10605"
, "civcirclejerk,3223"
, "Civcraft,7401"
, "civilengineering,4274"
, "CivilizatonExperiment,1265"
, "CivPolitics,21726"
, "CK2GameOfthrones,6724"
, "cky,496"
, "Clannad,3381"
, "ClashOfClans,81525"
, "classic4chan,85772"
, "classicalmusic,64714"
, "classiccars,17450"
, "ClassicRock,10769"
, "ClassyPornstars,15318"
, "cleanjokes,14002"
, "cleganebowl,5624"
, "Cleveland,11225"
, "clevelandcavs,9808"
, "CleverEdits,5346"
, "CLG,13686"
, "ClickerHeroes,15511"
, "climate,12966"
, "climateskeptics,6888"
, "climbing,72122"
, "Cloud9,4537"
, "Coachella,10822"
, "coaxedintoasnafu,17506"
, "cockatiel,2267"
, "cocktails,33081"
, "CodAW,24135"
, "CoDCompetitive,20874"
, "coding,66960"
, "CODZombies,13852"
, "COents,6279"
, "Coffee,110879"
, "Coilporn,13994"
, "coins,10866"
, "Coldplay,5509"
, "collapse,41520"
, "college,28864"
, "CollegeBasketball,61219"
, "collegehockey,3666"
, "Colorado,19638"
, "ColoradoAvalanche,4951"
, "ColoradoSprings,3994"
, "ColorBlind,4621"
, "Colorization,26156"
, "ColorizedHistory,99105"
, "Colts,8260"
, "<NAME>,15298"
, "CombatFootage,77124"
, "combinedgifs,65130"
, "Comcast,2689"
, "comedy,28699"
, "comedybangbang,4013"
, "ComedyCemetery,10477"
, "comeonandslam,35693"
, "comicbookart,22250"
, "ComicBookCollabs,2817"
, "comicbookcollecting,1402"
, "comicbookmovies,17976"
, "comicbooks,160279"
, "comics,441001"
, "ComicWalls,11362"
, "commandline,22571"
, "CommercialCuts,30783"
, "communism101,6139"
, "communism,15299"
, "CommunismWorldwide,1627"
, "community,150790"
, "CompanyOfHeroes,6707"
, "CompetitiveEDH,3559"
, "CompetitiveHalo,3326"
, "CompetitiveHS,47685"
, "CompetitiveWoW,4515"
, "COMPLETEANARCHY,394"
, "compsci,94243"
, "computergraphics,12259"
, "computers,16264"
, "computertechs,15891"
, "confession,113513"
, "confessions,22184"
, "ConfusedTravolta,17331"
, "confusing_perspective,14521"
, "conlangs,8793"
, "Connecticut,10794"
, "Connery,1290"
, "Conservative,52253"
, "conservatives,3923"
, "consoledeals,18933"
, "consoles,5770"
, "conspiracy,345872"
, "conspiracyfact,2849"
, "ConspiracyGrumps,5407"
, "conspiratard,51165"
, "Constantine,4566"
, "Construction,6652"
, "consulting,12968"
, "ContagiousLaughter,132132"
, "contentawarescale,4899"
, "ContestOfChampions,3794"
, "Cooking,333643"
, "cookingvideos,17475"
, "coolgithubprojects,12806"
, "coolguides,94291"
, "copypasta,13476"
, "cordcutters,94372"
, "corgi,83554"
, "CorporateFacepalm,31639"
, "cosplay,137953"
, "cosplaygirls,134349"
, "Costco,3709"
, "counterstrike,22326"
, "counting,8140"
, "country,7503"
, "coupons,40863"
, "cowboybebop,11659"
, "cowboys,18201"
, "Coyotes,1832"
, "coys,13596"
, "CozyPlaces,32862"
, "cpp,33338"
, "C_Programming,18035"
, "Cr1TiKaL,2588"
, "CrackStatus,2292"
, "CraftBeer,10617"
, "crafts,55168"
, "CraftyTrolls,3403"
, "Crainn,1575"
, "CrappyDesign,237472"
, "crappymusic,18421"
, "crappyoffbrands,16576"
, "CrazyHand,9295"
, "CrazyIdeas,181705"
, "CredibleDefense,10878"
, "creepy,4398297"
, "creepygaming,24434"
, "creepyPMs,158516"
, "Cricket,26375"
, "cringe,385431"
, "CringeAnarchy,61496"
, "cringepics,583381"
, "cripplingalcoholism,21723"
, "criterion,4854"
, "criticalrole,2943"
, "CriticalTheory,10699"
, "croatia,11786"
, "crochet,35571"
, "CrohnsDisease,7483"
, "crossdressing,14590"
, "crossfit,36541"
, "CrossfitGirls,8882"
, "CrossStitch,13860"
, "CrossView,17811"
, "CruciblePlaybook,14983"
, "CrusaderKings,36885"
, "crusadersquest,3577"
, "crypto,29585"
, "CryptoCurrency,18837"
, "cscareerquestions,58581"
, "csgo,5317"
, "csgobetting,52532"
, "csgolounge,9997"
, "csgomarketforum,2979"
, "csharp,25499"
, "C_S_T,2115"
, "Cubers,13202"
, "CubeWorld,15976"
, "CucumbersScaringCats,20714"
, "curiosityrover,16986"
, "curlyhair,29461"
, "customhearthstone,4569"
, "custommagic,4485"
, "cute,11253"
, "cutegirlgifs,14393"
, "cuteguys,1369"
, "cutekorean,5063"
, "cutelittlefangs,1166"
, "cutouts,6122"
, "CyanideandHappiness,30836"
, "cyanogenmod,14028"
, "Cyberpunk,82363"
, "cycling,25596"
, "Cynicalbrit,55888"
, "DabArt,1043"
, "Dachshund,15446"
, "daddit,40075"
, "dadjokes,245586"
, "DadReflexes,52100"
, "DAE,17275"
, "DaftPunk,29431"
, "DailyShow,7881"
, "DailyTechNewsShow,5685"
, "DaisyRidley,1327"
, "Dallas,25779"
, "DallasStars,3831"
, "Damnthatsinteresting,146768"
, "dancarlin,3306"
, "dancegavindance,1821"
, "danganronpa,2745"
, "dankchristianmemes,13003"
, "dankmemes,11694"
, "DankNation,1331"
, "DANMAG,5078"
, "Daredevil,8712"
, "DarkEnlightenment,7829"
, "darkestdungeon,8726"
, "DarkFuturology,9937"
, "DarkNetMarketsNoobs,18225"
, "darknetplan,44075"
, "DarkSouls2,71753"
, "darksouls3,13399"
, "darksouls,82119"
, "DarthJarJar,10433"
, "Dashcam,6012"
, "dashcamgifs,13243"
, "DataHoarder,18525"
, "dataisbeautiful,4614966"
, "dataisugly,11323"
, "datascience,11962"
, "Dat<NAME>,9885"
, "dating,13296"
, "dating_advice,37281"
, "<NAME>,2792"
, "davidtennant,5976"
, "dawngate,6220"
, "DaystromInstitute,17624"
, "dayz,112045"
, "dbz,62888"
, "DBZDokkanBattle,4102"
, "DC_Cinematic,6632"
, "DCcomics,69190"
, "dcss,2059"
, "de,25353"
, "DeadBedrooms,29380"
, "deadmau5,12463"
, "deadpool,29636"
, "DeadSpace,5586"
, "deals,25006"
, "DealsReddit,41886"
, "DealWin,80"
, "Deathcore,7633"
, "deathgrips,12664"
, "Debate,5177"
, "DebateAChristian,13626"
, "DebateaCommunist,6179"
, "DebateAnarchism,3414"
, "DebateAnAtheist,15404"
, "DebateCommunism,2942"
, "DebateFascism,1996"
, "DebateReligion,32207"
, "debian,12889"
, "DecidingToBeBetter,93400"
, "declutter,24903"
, "deepdream,20841"
, "deephouse,15805"
, "DeepIntoYouTube,142458"
, "deepweb,14568"
, "defaultgems,39649"
, "Defenders,15206"
, "de_IAmA,97400"
, "Delaware,4180"
, "Delightfullychubby,23120"
, "<NAME>,1397"
, "delusionalartists,77858"
, "democrats,17204"
, "Demotivational,96858"
, "Denmark,37793"
, "Dentistry,8266"
, "<NAME>,4653"
, "<NAME>,30830"
, "<NAME>,14461"
, "denvernuggets,2380"
, "deOhneRegeln,251"
, "depression,124996"
, "DepthHub,229662"
, "DerekSmart,357"
, "DescentIntoTyranny,6177"
, "Design,127308"
, "design_critiques,21406"
, "DesignPorn,99280"
, "DesirePath,37409"
, "DessertPorn,35858"
, "Destiny,12684"
, "DestinyTheGame,237300"
, "DestroyedTanks,4313"
, "DestructiveReaders,5756"
, "Detroit,14930"
, "detroitlions,12057"
, "DetroitPistons,3704"
, "DetroitRedWings,15784"
, "Deusex,9543"
, "devils,5355"
, "devops,10947"
, "<NAME>,43453"
, "DFO,5521"
, "dfsports,10596"
, "dgu,10526"
, "DHMIS,707"
, "diabetes,12708"
, "<NAME>,138207"
, "diablo3,77581"
, "Diablo3witchdoctors,9364"
, "<NAME>,12541"
, "<NAME>,5248"
, "digimon,12964"
, "digitalnomad,16439"
, "DigitalPainting,13354"
, "DimensionalJumping,5966"
, "Dinosaurs,31288"
, "DippingTobacco,6785"
, "dirtgame,3941"
, "Dirtybomb,9965"
, "discgolf,30366"
, "discordapp,1992"
, "discworld,14437"
, "dishonored,10526"
, "disney,60279"
, "Disney_Infinity,3854"
, "Disneyland,14792"
, "DivinityOriginalSin,9870"
, "Divorce,5435"
, "DiWHY,37561"
, "DIY,4962828"
, "DIY_eJuice,20583"
, "django,15141"
, "Djent,10102"
, "DJs,25214"
, "DMT,13018"
, "DnB,32667"
, "DnD,105398"
, "DnDBehindTheScreen,15534"
, "DnDGreentext,17156"
, "dndnext,21755"
, "docker,6166"
, "doctorwho,250183"
, "Documentaries,4580748"
, "Dodgers,10729"
, "DoesAnybodyElse,261602"
, "DoesNotTranslate,9940"
, "dogecoin,83697"
, "dogpictures,77382"
, "dogs,104862"
, "DogShowerThoughts,21093"
, "dogswearinghats,15014"
, "Dogtraining,39134"
, "donaldglover,20005"
, "dontdeadopeninside,3833"
, "DontPanic,11066"
, "dontstarve,19267"
, "doodles,17659"
, "Doom,5036"
, "doommetal,12216"
, "DotA2,258579"
, "dota2circlejerk,2798"
, "dota2dadjokes,3428"
, "Dota2Trade,12728"
, "dotamasterrace,6572"
, "dotnet,14555"
, "douglovesmovies,3111"
, "DowntonAbbey,11680"
, "Drag,5503"
, "dragonage,53735"
, "dragonblaze,1148"
, "dragons,3236"
, "Drama,17506"
, "drawing,75446"
, "Dreadfort,10290"
, "Dreadlocks,5904"
, "Dreamtheater,3460"
, "dresdenfiles,12027"
, "Drifting,13538"
, "DrugArt,8384"
, "DrugNerds,32064"
, "Drugs,228355"
, "drugscirclejerk,3598"
, "DrugStashes,8402"
, "drumcorps,5752"
, "drums,33872"
, "drunk,114115"
, "drunkenpeasants,1757"
, "DrunkOrAKid,65715"
, "drupal,6221"
, "Dualsport,9345"
, "dubai,4584"
, "DubbedGIFS,13450"
, "dubstep,89757"
, "ducks,3072"
, "duelyst,4587"
, "DumpsterDiving,24676"
, "duncantrussell,2897"
, "DunderMifflin,91474"
, "dune,7810"
, "dungeondefenders,5844"
, "DungeonsAndDragons,17802"
, "duolingo,29514"
, "dvdcollection,8984"
, "DvZ,1400"
, "dwarffortress,42783"
, "dxm,2143"
, "dyinglight,11424"
, "dykesgonemild,6450"
, "DynastyFF,3058"
, "E30,2265"
, "EAF,16034"
, "eagles,23209"
, "EA_NHL,11099"
, "earthbound,10060"
, "EarthPorn,6502343"
, "Earwolf,6522"
, "EatCheapAndHealthy,276512"
, "eatsandwiches,57048"
, "Ebay,8418"
, "EBEs,13932"
, "eCards,29022"
, "ECE,26731"
, "ecigclassifieds,11378"
, "ecig_vendors,8038"
, "Economics,236030"
, "economy,59749"
, "ecr_eu,3606"
, "EDC,85291"
, "EDH,21507"
, "Edinburgh,6329"
, "EditingAndLayout,24079"
, "editors,14771"
, "EDM,50366"
, "Edmonton,12765"
, "EdmontonOilers,4661"
, "edmprodcirclejerk,4782"
, "edmproduction,63802"
, "education,47548"
, "educationalgifs,115945"
, "Eesti,6153"
, "eFreebies,53414"
, "Egalitarianism,4904"
, "ElderScrolls,19349"
, "elderscrollsonline,67599"
, "eldertrees,48435"
, "ElectricForest,6570"
, "electricians,9406"
, "electricvehicles,4764"
, "electronic_cigarette,114500"
, "electronicmusic,138356"
, "electronics,53757"
, "EliteDangerous,55641"
, "EliteHudson,1081"
, "EliteLavigny,1954"
, "EliteOne,3825"
, "elonmusk,6205"
, "<NAME>Hos<NAME>,2291"
, "<NAME>anna,6510"
, "ELTP,492"
, "emacs,11891"
, "EmDrive,4569"
, "Emerald_Council,1265"
, "EmeraldPS2,2312"
, "<NAME>,15573"
, "<NAME>,14364"
, "Eminem,13876"
, "<NAME>,5105"
, "EmmaStone,26948"
, "<NAME>,78697"
, "Emo,5639"
, "emojipasta,2438"
, "EmpireDidNothingWrong,5436"
, "ems,17159"
, "emulation,28880"
, "EndlessLegend,5083"
, "EndlessWar,11999"
, "energy,55095"
, "ENFP,7060"
, "engineering,104185"
, "EngineeringPorn,45885"
, "EngineeringStudents,51259"
, "engrish,11043"
, "Enhancement,75265"
, "enlightenedbirdmen,30500"
, "EnoughLibertarianSpam,9844"
, "enoughsandersspam,741"
, "entertainment,173904"
, "Entomology,8920"
, "entp,5604"
, "Entrepreneur,166649"
, "entwives,14075"
, "environment,146550"
, "EOOD,19281"
, "EpicMounts,5474"
, "EQNext,8756"
, "EqualAttraction,9684"
, "Equestrian,5357"
, "ericprydz,1932"
, "esports,11919"
, "ethereum,6650"
, "ethoslab,4633"
, "Etsy,16338"
, "eu4,32332"
, "europe,537859"
, "european,10269"
, "EuropeMeta,259"
, "europes,1507"
, "evangelion,17166"
, "Eve,56006"
, "evenwithcontext,31703"
, "eveological,25"
, "everquest,3755"
, "Everton,5136"
, "everymanshouldknow,242753"
, "EverythingScience,55621"
, "EVEX,12202"
, "EvilLeagueOfEvil,8410"
, "evolution,21123"
, "EvolveGame,9577"
, "excel,38541"
, "exchristian,8523"
, "exjw,8025"
, "exmormon,25885"
, "exmuslim,10826"
, "ExNoContact,3289"
, "exo,1394"
, "exoticspotting,8165"
, "ExpectationVsReality,100161"
, "explainlikedrcox,34458"
, "explainlikeIAmA,96385"
, "ExplainLikeImCalvin,47635"
, "explainlikeimfive,6846145"
, "ExplainLikeImPHD,11743"
, "ExposurePorn,68975"
, "Eyebleach,150127"
, "eyes,17399"
, "F1FeederSeries,1888"
, "f7u12_ham,6379"
, "FA30plus,538"
, "facebookdrama,7467"
, "facebookwins,53333"
, "facepalm,408876"
, "fairytail,18521"
, "fakealbumcovers,4364"
, "fakeid,10282"
, "falcons,8897"
, "Fallout,304961"
, "Fallout4,14098"
, "Fallout4Builds,3199"
, "Fallout4_ja,192"
, "FallOutBoy,5424"
, "falloutequestria,2519"
, "falloutlore,15668"
, "FalloutMods,9901"
, "falloutsettlements,13645"
, "falloutshelter,4096"
, "familyguy,25344"
, "FancyFollicles,77989"
, "fandomnatural,3460"
, "FanFiction,5293"
, "fantanoforever,4289"
, "Fantasy,87143"
, "fantasybaseball,17120"
, "fantasybball,14718"
, "fantasyfootball,160969"
, "Fantasy_Football,5605"
, "fantasyhockey,8947"
, "FantasyPL,17103"
, "FantasyWarTactics,386"
, "fantasywriters,15701"
, "FanTheories,163226"
, "FargoTV,14383"
, "farming,13773"
, "FashionReps,6721"
, "fasting,9539"
, "fatestaynight,6850"
, "fatlogic,116533"
, "fatpeoplestories,107408"
, "Favors,30877"
, "fcbayern,7483"
, "fcs,1613"
, "FearTheWalkingDead,16575"
, "feedthebeast,26505"
, "FeelsLikeTheFirstTime,37234"
, "FellowKids,69315"
, "femalefashionadvice,117403"
, "Feminism,54932"
, "feminisms,29926"
, "FemmeThoughts,7741"
, "FeMRADebates,4088"
, "Fencing,5323"
, "FenerbahceSK,421"
, "ferrets,11126"
, "festivals,17253"
, "Fez,1386"
, "fffffffuuuuuuuuuuuu,586149"
, "FFRecordKeeper,8706"
, "ffxi,4739"
, "ffxiv,84399"
, "FierceFlow,6322"
, "FIFA,56885"
, "FifaCareers,11352"
, "fifthworldproblems,57276"
, "Fighters,10406"
, "Filmmakers,71513"
, "<NAME>,10673"
, "FinalFantasy,50546"
, "finance,69808"
, "FinancialCareers,8026"
, "financialindependence,102734"
, "findapath,21112"
, "findareddit,40022"
, "Finland,9119"
, "Firearms,30216"
, "fireemblem,26359"
, "fireemblemcasual,1316"
, "firefall,4912"
, "Firefighting,9907"
, "firefly,76407"
, "firefox,23600"
, "Fireteams,51572"
, "fireTV,5788"
, "firstimpression,14369"
, "firstworldanarchists,281557"
, "FirstWorldConformists,11139"
, "firstworldproblems,157362"
, "Fishing,54308"
, "FitAndNatural,16547"
, "fitbit,13931"
, "fitmeals,125675"
, "Fitness,4850074"
, "fitnesscirclejerk,7865"
, "Fiveheads,8558"
, "FiveM,1791"
, "fivenightsatfreddys,17394"
, "FixedGearBicycle,23119"
, "Flagstaff,1493"
, "flashlight,12573"
, "FlashTV,47356"
, "flexibility,34107"
, "flicks,12974"
, "flightsim,12125"
, "Flipping,35830"
, "Floof,10597"
, "florida,12400"
, "FloridaGators,4319"
, "FloridaMan,122022"
, "Flyers,11064"
, "flyfishing,12324"
, "flying,30355"
, "fnafcringe,2614"
, "fnv,20981"
, "fo3,8039"
, "fo4,147215"
, "FO4mods,366"
, "FocusST,1754"
, "FoggyPics,10716"
, "folk,13476"
, "FolkPunk,15942"
, "food,4730209"
, "Foodforthought,157028"
, "foodhacks,95996"
, "FoodPorn,413543"
, "Foofighters,8927"
, "football,26489"
, "footballdownload,15273"
, "footballhighlights,27801"
, "footballmanagergames,23502"
, "footbaww,7007"
, "Ford,8074"
, "fordranger,1848"
, "forearmporn,11124"
, "ForeverAlone,42226"
, "ForeverAloneWomen,4718"
, "Forex,8666"
, "forhire,55995"
, "formula1,95331"
, "forsen,2524"
, "forwardsfromgrandma,70486"
, "forwardsfromhitler,5416"
, "forwardsfromreddit,844"
, "<NAME>,14659"
, "foshelter,20679"
, "fountainpens,27552"
, "foxes,40002"
, "F<NAME>,836"
, "fpvracing,5746"
, "fragrance,7844"
, "FragReddit,2859"
, "france,60157"
, "FranceLibre,763"
, "Frat,12810"
, "FRC,4624"
, "FreckledGirls,20055"
, "fredericton,1494"
, "FREE,16458"
, "FreeAtheism,1890"
, "freebies,351125"
, "FreeEBOOKS,45558"
, "FreeGameFindings,18033"
, "FreeGamesOnSteam,17645"
, "FreeKarma,13252"
, "freelance,27254"
, "freemasonry,6723"
, "FreeStuff,2104"
, "Freethought,43922"
, "French,27660"
, "FrenchForeignLegion,1126"
, "fresh_funny,2026"
, "fresno,2417"
, "Frisson,116693"
, "frogdogs,5541"
, "frogpants,924"
, "Frontend,14215"
, "FrontPage,5480"
, "Frozen,10432"
, "Frugal,516065"
, "FrugalFemaleFashion,23062"
, "Frugal_Jerk,30490"
, "frugalmalefashion,186054"
, "FrugalMaleFashionCDN,2892"
, "fsu,4512"
, "ft86,5081"
, "ftlgame,27565"
, "ftm,6808"
, "fuckingmanly,23970"
, "FuckingWithNature,26038"
, "fuckmusic,6714"
, "fuckolly,11440"
, "FuckTammy,2619"
, "Fuee,600"
, "FulfillmentByAmazon,7575"
, "FULLCOMMUNISM,12094"
, "fulllife,3927"
, "FullmetalAlchemist,14565"
, "fullmoviesongoogle,24619"
, "fullmoviesonyoutube,210823"
, "functionalprint,6624"
, "funhaus,49438"
, "funk,5940"
, "funkopop,8582"
, "funny,10101609"
, "FunnyandSad,29572"
, "funnysigns,13588"
, "furry,21671"
, "FurryHate,972"
, "FUTMobile,547"
, "futurama,141894"
, "futurebeats,60157"
, "FutureFight,3503"
, "futurefunk,4594"
, "futureporn,64894"
, "FutureWhatIf,17484"
, "Futurology,4595097"
, "gadgets,4642305"
, "gainit,79436"
, "GakiNoTsukai,19468"
, "galatasaray,1097"
, "galaxynote4,9060"
, "galaxynote5,2911"
, "galaxys5,8896"
, "GalaxyS6,9726"
, "gallifrey,50639"
, "Gameboy,7061"
, "gamecollecting,32836"
, "GameDeals,345705"
, "GameDealsMeta,5785"
, "gamedesign,23159"
, "gamedev,147807"
, "gameDevClassifieds,16322"
, "gamegrumps,82577"
, "gamemaker,9003"
, "gamemusic,44931"
, "gameofthrones,589306"
, "GamePhysics,134872"
, "GamerGhazi,9042"
, "gamernews,105654"
, "gamers,4586"
, "Games,669391"
, "GameSale,7647"
, "GameStop,2927"
, "gameswap,18094"
, "gametales,22621"
, "gamindustri,1854"
, "Gaming4Gamers,31124"
, "gaming,9188228"
, "Gamingcirclejerk,5930"
, "gaminggifs,6554"
, "gamingpc,42932"
, "gamingsuggestions,16755"
, "gangstaswithwaifus,10893"
, "gardening,123705"
, "GarlicBreadMemes,3860"
, "gatech,8121"
, "gats,10032"
, "gay,23383"
, "gaybros,56722"
, "gaybroscirclejerk,2539"
, "gaybrosgonemild,9501"
, "gaymers,43889"
, "GearsOfWar,9954"
, "GearVR,4157"
, "geek,312760"
, "geekboners,5302"
, "GeekPorn,35545"
, "geekygirls,5095"
, "GenderCritical,1916"
, "Gender_Critical,889"
, "GenderCynical,792"
, "genderqueer,9428"
, "gentlemanboners,360639"
, "gentlemanbonersgifs,28072"
, "gentlemangabers,4874"
, "geocaching,21065"
, "geography,19815"
, "geology,29271"
, "geometrydash,601"
, "geopolitics,30051"
, "German,15722"
, "germanshepherds,16158"
, "germany,28099"
, "getdisciplined,151245"
, "GetMotivated,4611698"
, "GetStudying,40202"
, "GettingDoug,1294"
, "GGdiscussion,763"
, "GGFreeForAll,95"
, "ggggg,16811"
, "ghettoglamourshots,38985"
, "ghibli,26297"
, "Ghostbc,1744"
, "Ghosts,19927"
, "giantbomb,7143"
, "gif,122474"
, "gifextra,35175"
, "GifRecipes,21728"
, "gifs,7066012"
, "GifSound,53551"
, "gifsthatendtoosoon,1718"
, "GiftofGames,30220"
, "GifTournament,17834"
, "Gifts,3982"
, "gigantic,3846"
, "GilmoreGirls,5296"
, "gingerkitty,1392"
, "Gintama,3149"
, "GirlGamers,36779"
, "GirlsMirin,21667"
, "GirlsPlayingSports,13143"
, "girls_smiling,8446"
, "GIRLSundPANZER,1248"
, "gis,10635"
, "glasgow,6963"
, "glassheads,25367"
, "glitch_art,43871"
, "Glitch_in_the_Matrix,104084"
, "GlobalOffensive,308503"
, "Glocks,11491"
, "glutenfree,17907"
, "gmod,11149"
, "goats,7944"
, "goddesses,22908"
, "GODZILLA,12182"
, "golang,18078"
, "goldenretrievers,16491"
, "goldredditsays,9226"
, "golf,61420"
, "GolfGTI,6754"
, "GolfReimagined,148"
, "gonecivil,33535"
, "GoNets,2417"
, "goodyearwelt,20776"
, "google,79105"
, "GoogleCardboard,13482"
, "googleplaydeals,22385"
, "gopro,43411"
, "gorillaz,11743"
, "goth,4870"
, "Gotham,20579"
, "GradSchool,20248"
, "Graffiti,66997"
, "grandorder,3226"
, "grandrapids,6316"
, "GrandTheftAutoV,169918"
, "GrandTheftAutoV_PC,38186"
, "graphic_design,79684"
, "GrassHopperVape,1906"
, "gratefuldead,16541"
, "gravityfalls,33891"
, "GreatFist,6"
, "GreatXboxDeals,3977"
, "greece,13562"
, "GreenBayPackers,30530"
, "GreenDawn,33791"
, "greenday,6728"
, "greentext,43301"
, "Greyhounds,5411"
, "greysanatomy,8353"
, "grilledcheese,39396"
, "Grimdawn,2522"
, "grime,9691"
, "grimm,5516"
, "GTA,36641"
, "GTAgifs,21502"
, "gtaonline,27712"
, "GTAV,65342"
, "gtavcustoms,7646"
, "gtfoDerrickandArmand,95"
, "GuessTheMovie,14261"
, "Guildwars2,133098"
, "GuiltyPleasureMusic,13769"
, "guineapigs,9095"
, "Guitar,163275"
, "guitarcirclejerk,3475"
, "GuitarHero,1836"
, "guitarlessons,47594"
, "guitarpedals,19228"
, "guitarporn,10266"
, "guitars,7560"
, "guncontrol,1595"
, "Gundam,14360"
, "gundeals,21504"
, "Gunners,45709"
, "Gunpla,13781"
, "gunpolitics,8277"
, "GunPorn,50580"
, "guns,232698"
, "GunsAreCool,9994"
, "Gunsforsale,13627"
, "h1z1,40035"
, "h3h3productions,22035"
, "Habs,8478"
, "hackernews,6808"
, "hacking,80182"
, "hackintosh,17541"
, "Hadouken,1472"
, "HadToHurt,19860"
, "HailCorporate,60479"
, "Hair,20620"
, "HalfLife,24676"
, "halifax,9732"
, "halo,131907"
, "HaloCirclejerk,524"
, "HaloOnline,12169"
, "HaloStory,8405"
, "Hamilton,5399"
, "Hammers,2399"
, "Hammocks,19164"
, "hamsters,3764"
, "Handwriting,25035"
, "HannibalTV,24096"
, "hapas,587"
, "happy,92205"
, "happycrowds,42881"
, "happygirls,39178"
, "HappyTrees,5981"
, "HappyWars,739"
, "hardbodies,97399"
, "Hardcore,13750"
, "hardcoreaww,43074"
, "hardstyle,10089"
, "hardware,79340"
, "hardwareswap,26206"
, "<NAME>,10855"
, "<NAME>inn,5352"
, "Harmontown,10149"
, "<NAME>,1873"
, "harrypotter,217025"
, "Haruhi,2355"
, "harvestmoon,6455"
, "haskell,22579"
, "Hatfilms,13319"
, "Hawaii,11018"
, "hawks,17957"
, "headphones,56910"
, "Health,115920"
, "hearthstone,313065"
, "hearthstonecirclejerk,2257"
, "heat,7728"
, "Heavymind,74208"
, "Hedgehog,8897"
, "Helicopters,7842"
, "Helldivers,3062"
, "HelloInternet,7123"
, "help,6051"
, "HelpMeFind,4643"
, "heraldry,4552"
, "HereComesTheBoom,8768"
, "HeresAFunFact,19823"
, "Heroes,4819"
, "HeroesandGenerals,3498"
, "HeroesOfAsgard,11"
, "HeroesofNewerth,10607"
, "heroesofthestorm,118071"
, "H<NAME>Carl,28011"
, "HFY,28174"
, "hiddenwow,8947"
, "HIFW,33805"
, "highdeas,19022"
, "HighHeels,19351"
, "HighQualityGifs,91151"
, "HighschoolDxD,4903"
, "HighStrangeness,4370"
, "HighwayFightSquad,8875"
, "hiking,46682"
, "hillaryclinton,1119"
, "HIMYM,88622"
, "hinduism,5767"
, "Hiphopcirclejerk,8792"
, "hiphopheads,337054"
, "HipHopImages,24218"
, "history,4649879"
, "HistoryPorn,486198"
, "HistoryWhatIf,9016"
, "HiTMAN,3297"
, "hitmanimals,13868"
, "HITsWorthTurkingFor,32723"
, "hittableFaces,4928"
, "hockey,226078"
, "hockeyjerseys,3446"
, "hockeyplayers,7732"
, "hockeyquestionmark,934"
, "hoggit,5964"
, "holdmybeaker,22369"
, "holdmybeer,213117"
, "holdmycatnip,18388"
, "holdmyfries,19601"
, "holdmyjuicebox,27371"
, "HoldMyNip,18121"
, "homeautomation,16888"
, "Homebrewing,120095"
, "homegym,14280"
, "HomeImprovement,54575"
, "homelab,27716"
, "homeland,17083"
, "HomeNetworking,10982"
, "homeowners,9378"
, "HomestarRunner,24853"
, "homestead,47084"
, "homestuck,18689"
, "hometheater,22741"
, "homura,1483"
, "Honda,16355"
, "HongKong,14603"
, "hookah,20289"
, "Hookers,5647"
, "HorriblyDepressing,20009"
, "horror,84436"
, "Horses,11687"
, "Hot100,3252"
, "HotlineMiami,9417"
, "HotWheels,1735"
, "Hot_Women_Gifs,33863"
, "House,27365"
, "HouseOfCards,54259"
, "Houseporn,30968"
, "houston,34659"
, "howardstern,15679"
, "howto,158408"
, "HowToHack,31916"
, "howtonotgiveafuck,147936"
, "howyoudoin,22164"
, "HPfanfiction,6315"
, "HPMOR,8467"
, "HSPulls,2863"
, "htcone,10216"
, "htgawm,6413"
, "htpc,13070"
, "httyd,3841"
, "HumanFanClub,1570"
, "Humanoidencounters,5213"
, "HumanPorn,118208"
, "HumansBeingBros,65185"
, "humblebrag,14155"
, "humor,329136"
, "humorousreviews,19933"
, "hungary,9276"
, "Hungergames,19389"
, "HunterXHunter,13951"
, "Hunting,31309"
, "HuntsvilleAlabama,4067"
, "Huskers,3898"
, "huskies,1980"
, "husky,13747"
, "HVAC,4840"
, "hwatch,980"
, "HybridAnimals,42208"
, "HyruleWarriors,3185"
, "IAmA,9726122"
, "iamverysmart,159490"
, "IASIP,96036"
, "IBO,3428"
, "ICanDrawThat,31539"
, "Iceland,12169"
, "IDAP,30861"
, "ideasfortheadmins,8233"
, "IdentityIrelandForum,34"
, "IdiotsFightingThings,128970"
, "IdiotsInCars,4024"
, "IDontWorkHereLady,37442"
, "ifiwonthelottery,42974"
, "ifyoulikeblank,52089"
, "IgnorantImgur,16797"
, "IHE,1387"
, "iiiiiiitttttttttttt,32382"
, "ik_ihe,1138"
, "IllBeYourGuide,9083"
, "illegaltorrents,11111"
, "illumineighti,490"
, "illusionporn,58662"
, "Illustration,21963"
, "im14andthisisdeep,55244"
, "im14andthisisfunny,25233"
, "ImageComics,6553"
, "Images,47758"
, "ImagesOfUSA,48"
, "ImageStabilization,25762"
, "ImaginaryAngels,2663"
, "ImaginaryAww,7704"
, "ImaginaryAzeroth,3102"
, "ImaginaryBehemoths,9289"
, "ImaginaryCharacters,37374"
, "ImaginaryCityscapes,28484"
, "ImaginaryDragons,5293"
, "ImaginaryFallout,6973"
, "ImaginaryFeels,3287"
, "ImaginaryJedi,13900"
, "ImaginaryLandscapes,98649"
, "ImaginaryLeviathans,24350"
, "imaginarymaps,19317"
, "ImaginaryMindscapes,35118"
, "ImaginaryMonsters,88910"
, "ImaginarySpidey,317"
, "ImaginaryTechnology,55885"
, "ImaginaryTurtleWorlds,9020"
, "ImaginaryWarhammer,4822"
, "ImaginaryWarriors,3478"
, "ImaginaryWesteros,27040"
, "ImaginaryWitches,7657"
, "immigration,2801"
, "incest_relationships,4221"
, "incremental_games,21851"
, "india,46194"
, "IndiaMain,685"
, "Indiana,7645"
, "IndianaHoosiers,961"
, "indianapolis,8382"
, "IndianCountry,1426"
, "indianews,3654"
, "indiangirls,11879"
, "indianpeoplefacebook,54479"
, "indiegames,9359"
, "IndieGaming,64410"
, "indieheads,33941"
, "indieheadscirclejerk,677"
, "Indiemakeupandmore,17239"
, "indie_rock,31056"
, "indonesia,10529"
, "industrialmusic,7165"
, "INDYCAR,5242"
, "infertility,3454"
, "infj,12763"
, "Infographics,54812"
, "infp,14006"
, "InfrastructurePorn,47705"
, "INGLIN,14207"
, "Ingress,26304"
, "InjusticeMobile,2315"
, "Instagram,6611"
, "instantkarma,5075"
, "instant_regret,140320"
, "Insurance,6637"
, "insurgency,11227"
, "Intactivists,1915"
, "Intelligence,16493"
, "InterdimensionalCable,3957"
, "interestingasfuck,585343"
, "InterestingGifs,10988"
, "InteriorDesign,78065"
, "InternetHitlers,582"
, "InternetIsBeautiful,4730001"
, "internetparents,9232"
, "interstellar,11775"
, "inthenews,29637"
, "intj,23690"
, "intothebadlands,922"
, "INTP,19991"
, "introvert,55938"
, "intrusivethoughts,26207"
, "investing,174748"
, "InvisiBall,12331"
, "ios,22523"
, "ios9,6165"
, "iosgaming,29362"
, "iOSProgramming,22218"
, "iOSthemes,25327"
, "Iowa,6674"
, "ipad,45859"
, "iphone,156101"
, "iRacing,4028"
, "iran,6494"
, "iranian,685"
, "ireland,68157"
, "IRLgirls,4787"
, "ironmaiden,2812"
, "IronThronePowers,447"
, "IsItBullshit,18975"
, "islam,29553"
, "IslamUnveiled,1197"
, "isometric,10486"
, "Israel,21403"
, "IsraelPalestine,458"
, "isrconspiracyracist,2250"
, "istp,2848"
, "italy,33816"
, "ITCareerQuestions,8018"
, "ITcrowd,10032"
, "itmejp,7686"
, "itookapicture,177377"
, "ITSAPRANK,15459"
, "itsaunixsystem,34068"
, "iWallpaper,32156"
, "IWantOut,53730"
, "IWantToLearn,165699"
, "iZombie,5513"
, "JacksFilms,1171"
, "jacksonville,4712"
, "<NAME>sonWrites,9891"
, "jag_ivl,802"
, "<NAME>,3980"
, "jailbreak,105777"
, "jakeandamir,11311"
, "<NAME>,14555"
, "JaneTheVirginCW,865"
, "japan,67086"
, "japan_anime,2593"
, "japancirclejerk,2747"
, "JapaneseGameShows,46793"
, "JapaneseWatches,1174"
, "japanlife,12815"
, "japanpics,23576"
, "JapanTravel,9316"
, "JasonEllisShow,1050"
, "java,48594"
, "javahelp,9886"
, "javascript,76138"
, "jayhawks,1941"
, "Jazz,56782"
, "jazzyhiphop,4709"
, "J<NAME>,30392"
, "jellybeantoes,12844"
, "<NAME>,44301"
, "Jeopardy,6809"
, "jerktalkdiamond,964"
, "<NAME>,4399"
, "<NAME>,27798"
, "<NAME>,2762"
, "Jobs4Bitcoins,9211"
, "jobs,74822"
, "joerogan2,2010"
, "<NAME>,38103"
, "<NAME>,6286"
, "<NAME>,2685"
, "joinsquad,2495"
, "Jokes,4760749"
, "<NAME>,27893"
, "<NAME>,28"
, "Journalism,9987"
, "JRPG,27567"
, "J<NAME>,12546"
, "judo,8048"
, "J<NAME>assicPark,17482"
, "JustCause,2668"
, "JustEngaged,4663"
, "Justfuckmyshitup,46142"
, "JusticePorn,431434"
, "JusticeServed,18354"
, "justlegbeardthings,5629"
, "justneckbeardthings,102908"
, "JUSTNOFAMILY,1205"
, "JUSTNOMIL,7008"
, "Justridingalong,1353"
, "Justrolledintotheshop,137533"
, "JustUnsubbed,4916"
, "<NAME>,2494"
, "juxtaposition,6873"
, "jworg,9"
, "kancolle,4119"
, "kancolle_ja,315"
, "<NAME>,2360"
, "kansascity,14383"
, "KansasCityChiefs,7443"
, "Kanye,16570"
, "<NAME>,21399"
, "<NAME>,59451"
, "<NAME>,38476"
, "katawashoujo,11914"
, "katebeckinsale,6904"
, "kateupton,37670"
, "<NAME>,2116"
, "katyperry,28154"
, "KCRoyals,7173"
, "KDRAMA,7567"
, "kemonomimi,6100"
, "KenM,84239"
, "<NAME>ala,1052"
, "KerbalAcademy,10830"
, "KerbalSpaceProgram,121287"
, "keto,163466"
, "ketogains,25281"
, "ketorecipes,65840"
, "K_gifs,10922"
, "kickstarter,30706"
, "Kikpals,20550"
, "killingfloor,16104"
, "KillLaKill,17992"
, "killthosewhodisagree,10973"
, "kindle,26216"
, "KingdomHearts,30884"
, "KingkillerChronicle,17632"
, "KingOfTheHill,27235"
, "kings,3256"
, "KissAnime,544"
, "KitchenConfidential,34771"
, "kitchener,2626"
, "kitsunemimi,4949"
, "kittens,9183"
, "kitty,3734"
, "knifeclub,18752"
, "knifeparty,2920"
, "Knife_Swap,3636"
, "knitting,40319"
, "knives,47200"
, "knowyourshit,12077"
, "kodi,11841"
, "kohi,2838"
, "kol,4511"
, "k_on,2904"
, "KoopaKiy,10"
, "korea,20000"
, "Korean,13748"
, "KoreanAdvice,6591"
, "koreanvariety,5927"
, "korrasami,6909"
, "KotakuInAction,55472"
, "kotor,9517"
, "kpics,18704"
, "kpop,42729"
, "kratom,6984"
, "kreiswichs,3233"
, "kurdistan,2771"
, "Kuwait,1016"
, "LabourUK,2155"
, "labrador,10332"
, "labrats,7696"
, "LAClippers,4318"
, "lacrosse,9361"
, "L<NAME>Bon<NAME>,164202"
, "Ladybonersgonecuddly,31680"
, "ladyladyboners,24988"
, "lag_irl,135"
, "lakers,18289"
, "LAlist,7127"
, "languagelearning,60392"
, "lapfoxtrax,1947"
, "LARP,4653"
, "lastimages,31487"
, "LastManonEarthTV,5040"
, "lastweektonight,16324"
, "LateShow,8716"
, "LateStageCapitalism,4528"
, "latin,7977"
, "LatinaCuties,7011"
, "LatinoPeopleTwitter,8501"
, "latterdaysaints,5783"
, "LatvianJokes,29817"
, "law,43785"
, "LawSchool,19983"
, "LazyCats,7604"
, "lbregs,2338"
, "leafs,15694"
, "leagueoflegends,772616"
, "LeagueofLegendsMeta,20592"
, "LeagueOfMemes,25797"
, "LeagueOfMeta,3932"
, "leangains,39589"
, "learnart,34582"
, "learndota2,14717"
, "LearnJapanese,49640"
, "learnjavascript,18589"
, "learnmath,29221"
, "learnprogramming,230718"
, "learnpython,47237"
, "LearnUselessTalents,245147"
, "Leathercraft,11724"
, "leaves,27491"
, "lebanon,2784"
, "lebowski,7553"
, "lectures,51617"
, "ledootgeneration,34532"
, "LeedsUnited,1319"
, "LeftHanging,19665"
, "legaladvice,75471"
, "LegalAdviceUK,2253"
, "LegendsOfTomorrow,6215"
, "LegionOfSkanks,1590"
, "lego,115454"
, "lerightgeneration,2555"
, "LessCredibleDefence,1865"
, "LetsNotMeet,142079"
, "letsplay,20438"
, "LetsTalkMusic,36564"
, "Lettering,13453"
, "lewronggeneration,63017"
, "lexington,4315"
, "lgbt,112855"
, "lgbtaww,6614"
, "LGBTeens,10261"
, "LGBTnews,5280"
, "lgg2,4813"
, "LGG3,13432"
, "lgg4,7273"
, "lgv10,1098"
, "LiaMarieJohn<NAME>,8477"
, "Liberal,25497"
, "liberta,614"
, "Libertarian,134095"
, "libertarianmeme,9205"
, "libreoffice,915"
, "LifeAfterNarcissism,4717"
, "lifehacks,458584"
, "lifeisstrange,15466"
, "lifeofnorman,42997"
, "LifeProTips,5364631"
, "Lightbulb,23012"
, "LightNovels,9692"
, "likeus,27387"
, "liluglymane,646"
, "limitless,1450"
, "linguistics,72224"
, "LinusFaces,1808"
, "linux,201492"
, "linux4noobs,37427"
, "LinuxActionShow,9319"
, "linuxadmin,22957"
, "LinuxCirclejerk,2407"
, "linux_gaming,30732"
, "linuxmasterrace,15392"
, "linuxmemes,4847"
, "linuxmint,9610"
, "linuxquestions,18252"
, "listentothis,4542407"
, "litecoin,23043"
, "literature,87101"
, "lithuania,7461"
, "lithuaniaspheres,170"
, "littlebuddies,3042"
, "LiveFromNewYork,14386"
, "LiverpoolFC,33829"
, "livesound,9000"
, "LivestreamFails,46881"
, "loadingicon,25972"
, "lockpicking,41217"
, "logodesign,12138"
, "logophilia,28057"
, "lol,20652"
, "LoLeventVoDs,50281"
, "LoLFanArt,12187"
, "lolphp,5776"
, "london,48744"
, "londonontario,4569"
, "lonely,7462"
, "LONESTAR,3749"
, "longbeach,3595"
, "longboarding,56516"
, "LongDistance,29853"
, "LonghornNation,3756"
, "longisland,7544"
, "longrange,10125"
, "lookatmydog,21461"
, "lootcrate,6258"
, "lootcratespoilers,575"
, "LordsOfMinecraft,2393"
, "loremasters,9296"
, "LosAngeles,63399"
, "losangeleskings,5843"
, "loseit,309143"
, "lost,34892"
, "lostgeneration,25435"
, "lotr,94656"
, "lotro,6488"
, "Louisiana,5949"
, "Louisville,8853"
, "Lovecraft,24501"
, "LoveLive,3799"
, "lowendgaming,18859"
, "lowlevelaware,1655"
, "low_poly,17242"
, "lrcast,4985"
, "LSD,46263"
, "Lubbock,2370"
, "LucidDreaming,145245"
, "Luna_Lovewell,19160"
, "LV426,17086"
, "Lyft,2093"
, "lynxes,1246"
, "M59Gar,936"
, "MAA,1446"
, "mac,50181"
, "MachineLearning,49833"
, "MachinePorn,64281"
, "Machinists,6513"
, "macsetups,15022"
, "Madden,16046"
, "MaddenBros,202"
, "MaddenMobileForums,4792"
, "MaddenUltimateTeam,7095"
, "MadeMeSmile,82836"
, "madisonwi,10112"
, "MadMax,7903"
, "madmen,41301"
, "MadokaMagica,3756"
, "Magic,16256"
, "magicduels,4012"
, "magicskyfairy,14873"
, "magicTCG,148320"
, "Maine,7790"
, "maisiewilliams,5556"
, "makemychoice,22507"
, "MakeNewFriendsHere,15706"
, "MakeupAddiction,273221"
, "MakeupAddictionCanada,1062"
, "makeupexchange,15917"
, "MakeupRehab,7273"
, "makinghiphop,23909"
, "malaysia,5913"
, "Malazan,4952"
, "malefashion,36939"
, "malefashionadvice,538227"
, "malegrooming,38964"
, "malehairadvice,53298"
, "malelifestyle,68079"
, "malelivingspace,63737"
, "mallninjashit,17858"
, "Malware,15488"
, "MAME,6656"
, "manchester,7369"
, "MandelaEffect,11096"
, "manga,68455"
, "maninthehighcastle,2115"
, "ManyATrueNerd,4569"
, "Maplestory,12626"
, "MapPorn,249184"
, "mapporncirclejerk,4503"
, "marchingband,6609"
, "Marijuana,79160"
, "marijuanaenthusiasts,39133"
, "MarineBiologyGifs,3939"
, "Mariners,8905"
, "mariokart,9416"
, "<NAME>Maker,17040"
, "marketing,46823"
, "<NAME>lier,7966"
, "MarkMyWords,20219"
, "Marriage,4794"
, "marriedredpill,6000"
, "<NAME>,7017"
, "martialarts,24258"
, "maru,5669"
, "Marvel,128683"
, "marvelheroes,13004"
, "marvelmemes,1890"
, "MarvelPuzzleQuest,1657"
, "marvelstudios,54535"
, "maryland,10222"
, "mashups,77295"
, "massachusetts,6540"
, "massage,4547"
, "masseffect,90017"
, "MasterofNone,5495"
, "math,149766"
, "mathrock,11746"
, "Mavericks,5516"
, "MawInstallation,3496"
, "maximumfun,3798"
, "maybemaybemaybe,4849"
, "MaymayZone,6883"
, "mazda,8207"
, "mbti,8408"
, "Mcat,3458"
, "MCFC,6483"
, "mcgill,3953"
, "McKaylaMaroney,9991"
, "MCPE,7753"
, "mcpublic,6783"
, "MDMA,15857"
, "mead,11797"
, "MealPrepSunday,88222"
, "mealtimevideos,17079"
, "MeanJokes,48692"
, "MechanicAdvice,27603"
, "mechanical_gifs,42008"
, "MechanicalKeyboards,92032"
, "mechmarket,8275"
, "media_criticism,8430"
, "medical,5429"
, "medicalschool,25219"
, "medicine,62419"
, "Meditation,150324"
, "mega64,4268"
, "megalinks,9435"
, "Megaman,7232"
, "Megaten,15075"
, "Megturney,11259"
, "meirl,13683"
, "me_irl,313822"
, "melbourne,28908"
, "meme,17905"
, "memes,57158"
, "memphis,4942"
, "memphisgrizzlies,2220"
, "MensLib,5130"
, "MensRights,122643"
, "mentalhealth,14177"
, "MEOW_IRL,25889"
, "mercedes_benz,5538"
, "MerylRearSolid,175"
, "metacanada,4182"
, "Metal,109728"
, "Metalcore,27095"
, "metaldetecting,5547"
, "MetalGearPhilanthropy,2032"
, "metalgearsolid,75789"
, "MetalGearSolidV_PC,3184"
, "metaljerk,2685"
, "Metallica,6442"
, "MetalMemes,23036"
, "metanarchism,1560"
, "Metroid,13146"
, "mexico,43480"
, "mfacirclejerk,6074"
, "mflb,23250"
, "mfw,15955"
, "mgo,5968"
, "MGTOW,8676"
, "MHOC,2463"
, "Miami,9203"
, "miamidolphins,8462"
, "M<NAME>H<NAME>an<NAME>,1377"
, "Miata,9770"
, "michaelbaygifs,54261"
, "Michigan,23179"
, "MichiganWolverines,3773"
, "microgrowery,48535"
, "microsoft,33758"
, "Mid_Century,8571"
, "migraine,5398"
, "MiiverseInAction,7435"
, "Mila_Kunis,15215"
, "milanavayntrub,12076"
, "mildlyamusing,20563"
, "mildlydepressing,8976"
, "mildlyinfuriating,266706"
, "mildlyinteresting,5089941"
, "mildlypenis,22377"
, "mildlysatisfying,8432"
, "MildlyStartledCats,10980"
, "mildyinteresting,12729"
, "mileycyrus,13625"
, "Military,76095"
, "MilitaryGfys,21869"
, "MilitaryPorn,104450"
, "MillerPlanetside,1611"
, "millionairemakers,63540"
, "milliondollarextreme,3103"
, "milwaukee,8862"
, "MimicRecipes,29631"
, "mindcrack,49548"
, "mindcrackcirclejerk,2439"
, "Mindfulness,23696"
, "Minecraft,452814"
, "minecraftsuggestions,15064"
, "MineralPorn,24006"
, "MINI,6184"
, "minimalism,181966"
, "MinimalWallpaper,11704"
, "MinionHate,31867"
, "minipainting,8721"
, "Minneapolis,12416"
, "minnesota,19056"
, "minnesotavikings,14502"
, "mirrorsedge,2840"
, "misc,25945"
, "misleadingthumbnails,74200"
, "misophonia,8220"
, "mississauga,3339"
, "mistyfront,5685"
, "MitchellAndWebb,11935"
, "MkeBucks,3085"
, "mlb,29706"
, "MLBTheShow,6142"
, "MLPLounge,11485"
, "MLS,45723"
, "MLTP,816"
, "MMA,135313"
, "MMORPG,29990"
, "ModelAusHR,35"
, "modelmakers,11087"
, "modelparliament,297"
, "Models,17605"
, "ModelsGoneMild,9217"
, "ModelUSGov,2663"
, "Modern_Family,22210"
, "ModernMagic,11226"
, "ModestMouse,8374"
, "Moescape,7400"
, "Mommit,20569"
, "MonarchyOfEquestria,164"
, "Monero,2561"
, "Monitors,9649"
, "monkslookingatbeer,21422"
, "monsteraday,2839"
, "Monstercat,19976"
, "MonstercatCringe,744"
, "MonsterHunter,49260"
, "MonsterMusume,4602"
, "montageparodies,140766"
, "montreal,23757"
, "morbidlybeautiful,20731"
, "morbidquestions,16778"
, "mormon,3610"
, "Morrowind,18329"
, "MortalKombat,24177"
, "MosinNagant,5364"
, "MostBeautiful,12475"
, "mother4,4088"
, "motivation,28121"
, "moto360,16741"
, "MotoG,7346"
, "motogp,12424"
, "motorcitykitties,8291"
, "motorcyclememes,3864"
, "motorcycles,153710"
, "MotoUK,2350"
, "MotoX,15447"
, "MountainWisdom,6372"
, "mountandblade,24536"
, "MoviePosterPorn,64136"
, "movies,8844042"
, "moviescirclejerk,7311"
, "Moviesinthemaking,36474"
, "MovieSuggestions,30708"
, "MrRobot,33987"
, "MRW,8138"
, "msp,2697"
, "MST3K,12731"
, "MTB,44173"
, "MtF,6966"
, "mtgaltered,6674"
, "mtgcube,3449"
, "mtgfinance,10617"
, "MTGLegacy,5388"
, "mturk,16614"
, "muacirclejerk,13973"
, "muacjdiscussion,4956"
, "MuayThai,11935"
, "Multicopter,27369"
, "MultipleSclerosis,3225"
, "Munich,3470"
, "MURICA,182607"
, "Muse,11557"
, "museum,30121"
, "Music,8547159"
, "musicpics,3365"
, "Musicthemetime,4042"
, "musictheory,56442"
, "Mustang,16084"
, "MvC3,7232"
, "mwo,5258"
, "mycology,28804"
, "myfriendwantstoknow,25670"
, "mylittleandysonic1,1981"
, "mylittlepony,66489"
, "mypartneristrans,3779"
, "MyPeopleNeedMe,38060"
, "MysteryDungeon,2024"
, "mythbusters,16717"
, "n64,9489"
, "N<NAME>ato,382"
, "namenerds,6336"
, "NamFlashbacks,3190"
, "<NAME>,892"
, "nanowrimo,10847"
, "narcos,5824"
, "<NAME>,66976"
, "nasa,40516"
, "NASCAR,20166"
, "nashville,11165"
, "NASLSoccer,2026"
, "<NAME>,14878"
, "nathanforyou,4854"
, "NationalPark,6253"
, "nattyorjuice,2310"
, "nature,29478"
, "NatureGifs,19405"
, "natureismetal,35697"
, "navy,12037"
, "Nav<NAME>Blazer,2546"
, "navyseals,1318"
, "NBA2k,22976"
, "nba,329140"
, "nbacirclejerk,3587"
, "NBASpurs,8650"
, "nbastreams,16646"
, "nbaww,7361"
, "NCSU,3852"
, "NeckbeardNests,14207"
, "neckbeardstories,17714"
, "needadvice,24669"
, "Needafriend,21494"
, "needforspeed,4508"
, "Negareddit,6401"
, "nekoatsume,5459"
, "neogaming,6576"
, "neopets,12308"
, "Nepal,2449"
, "nerdcubed,30818"
, "nerdfighters,25840"
, "nerdist,8495"
, "Nerf,10215"
, "netflix,96367"
, "NetflixBestOf,293763"
, "NetflixPals,2"
, "Netrunner,9329"
, "netsec,149780"
, "networking,56778"
, "neuro,29646"
, "NeutralPolitics,48269"
, "NeverBeGameOver,6023"
, "nevertellmetheodds,54203"
, "Neverwinter,10724"
, "newfoundland,3544"
, "NewGirl,11270"
, "newjersey,22791"
, "NewOrleans,14369"
, "newreddits,56764"
, "NewRussia,266"
, "news,7193384"
, "NewSkaters,7125"
, "NewsOfTheStupid,26065"
, "NewsOfTheWeird,23032"
, "newsokunomoral,1668"
, "newsokur,12742"
, "newsokuvip,1422"
, "NewsPorn,27720"
, "newtothenavy,3355"
, "NewYorkIslanders,2747"
, "NewYorkMets,9081"
, "newzealand,58365"
, "nextdoorasians,44027"
, "Nexus,11251"
, "nexus4,14051"
, "Nexus5,32628"
, "nexus5x,4290"
, "nexus6,17044"
, "Nexus6P,14565"
, "NexusNewbies,4554"
, "NFA,3386"
, "nfffffffluuuuuuuuuuuu,10412"
, "nfl,438505"
, "nflcirclejerk,5471"
, "NFL_Draft,10220"
, "NFLRoundTable,5106"
, "nflstreams,45816"
, "NFSRides,331"
, "nhl,48661"
, "NHLHUT,6246"
, "NHLStreams,24573"
, "niceb8m8,2780"
, "niceguys,56186"
, "Nichijou,1794"
, "NichtDerPostillon,1679"
, "Nightshift,3047"
, "nightvale,12825"
, "Nikon,5622"
, "nin,8543"
, "nintendo,111235"
, "nintendomusic,16592"
, "Nirvana,9955"
, "Nisekoi,5857"
, "Nissan,7789"
, "nl_Kripparrian,5710"
, "NLSSCircleJerk,6342"
, "NLTP,1260"
, "nocontext,127222"
, "node,17989"
, "NoFap,176191"
, "NoFapChristians,5780"
, "NoFapWar,8446"
, "noisygifs,26562"
, "NOLAPelicans,1796"
, "NoMansSkyTheGame,28763"
, "nongolfers,23795"
, "nonmonogamy,11653"
, "nonnude,5508"
, "nononono,124473"
, "nonononoyes,227931"
, "Nootropics,64062"
, "NoPoo,12759"
, "Nordiccountries,7445"
, "norge,31328"
, "normaldayinjapan,12500"
, "NorthCarolina,11331"
, "northernireland,6754"
, "northernlion,4198"
, "NorthKoreaNews,28734"
, "Norway,12728"
, "NoShitSherlock,15730"
, "NoSillySuffix,15832"
, "nosleep,4419937"
, "NoSleepOOC,6136"
, "no_sob_story,12490"
, "nostalgia,135018"
, "Nostalrius,1864"
, "NostalriusBegins,2221"
, "NoStupidQuestions,105909"
, "notcirclejerk,3604"
, "notebooks,10292"
, "notinteresting,93212"
, "NotMyJob,9602"
, "NotSoGoodGuyMafia,1"
, "nottheonion,4626814"
, "NotTimAndEric,52386"
, "nova,16149"
, "noveltranslations,6505"
, "nqmod,677"
, "NRIBabes,4104"
, "nrl,7913"
, "NuclearThrone,6138"
, "NUFC,4139"
, "Nujabes,13336"
, "nursing,26360"
, "nutrition,58085"
, "nvidia,13768"
, "NWSL,2055"
, "nyc,93287"
, "NYGiants,14530"
, "nyjets,9260"
, "NYKnicks,10287"
, "NYYankees,5116"
, "oakland,7448"
, "OaklandAthletics,5427"
, "oaklandraiders,8363"
, "oblivion,20697"
, "ObscureMedia,48169"
, "occult,25842"
, "occupywallstreet,31365"
, "OCD,7576"
, "ockytop,1751"
, "OCLions,2234"
, "OCPoetry,8270"
, "oculus,58470"
, "oddlysatisfying,402256"
, "ofcoursethatsathing,68726"
, "offbeat,323485"
, "Offensive_Wallpapers,57976"
, "offmychest,195959"
, "OFWGKTA,19821"
, "Ohio,10967"
, "okc,3844"
, "OkCupid,76965"
, "oklahoma,8846"
, "oldbabies,3981"
, "oldpeoplefacebook,123804"
, "OldSchoolCool,4435183"
, "oliviawilde,18117"
, "Omaha,6706"
, "OnceUponATime,14844"
, "onejob,19142"
, "oneliners,8428"
, "OnePiece,58146"
, "OnePieceTC,4580"
, "oneplus,31264"
, "OnePunchMan,13861"
, "OneTrueBiribiri,2053"
, "onetruegod,85716"
, "onetrueidol,1987"
, "onewordeach,6562"
, "OneY,28710"
, "ontario,13949"
, "Ooer,22033"
, "OopsDidntMeanTo,27372"
, "OOTP,1794"
, "openbroke,7026"
, "opendirectories,34117"
, "opensource,38410"
, "opiates,18779"
, "OpiatesRecovery,5017"
, "opieandanthony,11550"
, "Oppression,2456"
, "OpTicGaming,9421"
, "orangecounty,15315"
, "orangeisthenewblack,37014"
, "OreGairuSNAFU,2685"
, "oregon,12238"
, "orioles,7696"
, "orlando,13168"
, "OrlandoMagic,2489"
, "orphanblack,12331"
, "OrthodoxChristianity,3213"
, "OSHA,106266"
, "OSU,7389"
, "osugame,16754"
, "osx,26645"
, "ottawa,18694"
, "OttawaSenators,4489"
, "<NAME>,15182"
, "Outlander,4640"
, "OutlandishAlcoholics,310"
, "OutOfTheLoop,352852"
, "OutreachHPG,4306"
, "outrun,21477"
, "outside,169842"
, "overclocking,14365"
, "overlanding,7952"
, "overpopulation,10742"
, "Overwatch,75843"
, "Owls,13402"
, "Pac12,2079"
, "pacers,2643"
, "PacificRim,4808"
, "paintball,13838"
, "painting,19653"
, "pakistan,5580"
, "Paladins,2246"
, "Paleo,82633"
, "Palestine,8236"
, "PandR,80461"
, "PanicHistory,11470"
, "PanPorn,2688"
, "panthers,9700"
, "ParadoxExtra,948"
, "paradoxplaza,36233"
, "paradoxpolitics,4368"
, "Parahumans,2810"
, "Paranormal,82498"
, "Pareidolia,112512"
, "Parenting,89413"
, "paris,9014"
, "parrots,12067"
, "PastAndPresentPics,26758"
, "Patchuu,5314"
, "Pathfinder_RPG,24123"
, "pathofexile,55470"
, "patientgamers,66432"
, "<NAME>,35985"
, "<NAME>uper,3510"
, "paydaycirclejerk,750"
, "paydaytheheist,40470"
, "PBSOD,4524"
, "pcgaming,177340"
, "pcmasterrace,499519"
, "pebble,26606"
, "PEDs,2684"
, "peloton,12939"
, "penguins,10697"
, "Pen<NAME>,120944"
, "Pennsylvania,6406"
, "penspinning,13838"
, "PeopleBeingJerks,31276"
, "pepe,3873"
, "pepethefrog,5498"
, "Perfectfit,58195"
, "perfectloops,87232"
, "PerfectTiming,213955"
, "perktv,4851"
, "Permaculture,32689"
, "personalfinance,4554137"
, "PersonalFinanceCanada,21006"
, "PersonOfInterest,7908"
, "perth,9240"
, "Pets,40721"
, "pettyrevenge,185894"
, "pharmacy,11236"
, "philadelphia,32593"
, "Philippines,41758"
, "philosophy,4513265"
, "PhilosophyofScience,36378"
, "phish,14034"
, "phoenix,13463"
, "photocritique,36970"
, "photography,266257"
, "photoshop,39757"
, "photoshopbattles,4687231"
, "PhotoshopRequest,18145"
, "PHP,40492"
, "Physics,128791"
, "physicsgifs,36540"
, "piano,39324"
, "pic,41129"
, "PickAnAndroidForMe,3855"
, "picrequests,30863"
, "pics,9989676"
, "PictureGame,6213"
, "Pieces,14156"
, "piercing,24957"
, "pimpcats,17733"
, "pinkfloyd,22664"
, "pinsamt,2950"
, "PipeTobacco,16237"
, "Piracy,44568"
, "pitbulls,27622"
, "pitchforkemporium,11008"
, "pittsburgh,20373"
, "Pixar,8458"
, "PixelArt,31539"
, "PixelDungeon,4762"
, "Pizza,47680"
, "PKA,24769"
, "pkmntcg,7333"
, "Planetside,39289"
, "PlantedTank,21275"
, "plastidip,7725"
, "playark,19551"
, "PlayItAgainSam,26060"
, "playrust,28473"
, "playstation,23516"
, "PlayStationPlus,33657"
, "PleX,29450"
, "ploompax,7475"
, "plotholes,25252"
, "ploungeafterdark,1519"
, "Plumbing,4184"
, "podcasts,25805"
, "podemos,11042"
, "Poetry,49882"
, "PointlessStories,15386"
, "Pokeents,9352"
, "pokemon,474684"
, "Pokemongiveaway,23462"
, "pokemongo,5808"
, "PokemonInsurgence,11178"
, "PokemonPlaza,9885"
, "PokemonShuffle,5506"
, "pokemontrades,32149"
, "poker,39081"
, "poland,6554"
, "polandball,183854"
, "Polandballart,5267"
, "polandballgifs,3082"
, "policeporn,7454"
, "POLITIC,26221"
, "PoliticalDiscussion,46733"
, "PoliticalHumor,50628"
, "politicalpartypowers,221"
, "PoliticalScience,4220"
, "PoliticalVideo,3264"
, "politics,3179799"
, "politota,3829"
, "Polska,25211"
, "polyamory,32932"
, "PopArtNouveau,12780"
, "PopCornTime,14295"
, "popheads,3343"
, "popping,63644"
, "poppunkers,22875"
, "pornfree,23763"
, "Porsche,10606"
, "Portal,33665"
, "porterrobinson,3055"
, "Portland,55193"
, "portlandstate,1611"
, "portugal,10848"
, "PORTUGALCARALHO,2199"
, "PostHardcore,24276"
, "postprocessing,19762"
, "postrock,25540"
, "potatosalad,9117"
, "potionseller,5062"
, "pottedcats,736"
, "powerlifting,24249"
, "PowerMetal,8754"
, "powerrangers,6357"
, "PowerShell,14127"
, "powerwashingporn,47175"
, "predaddit,7185"
, "Predators,2547"
, "Prematurecelebration,60825"
, "premed,14042"
, "PremierLeague,10863"
, "preppers,22426"
, "PrettyGirls,119838"
, "PrettyGirlsUglyFaces,40069"
, "PrettyLittleLiars,13195"
, "printSF,24370"
, "prisonarchitect,21737"
, "privacy,57320"
, "processing,3202"
, "productivity,94185"
, "proED,2694"
, "progmetal,29496"
, "programmerchat,2151"
, "ProgrammerHumor,107681"
, "programmerreactions,2708"
, "programming,662121"
, "programmingcirclejerk,3359"
, "progressive,41755"
, "progresspics,159520"
, "progrockmusic,14678"
, "progun,16238"
, "projectcar,16099"
, "projecteternity,15575"
, "ProjectFi,6998"
, "ProjectRunway,3241"
, "projectzomboid,11302"
, "promos,7261"
, "PropagandaPosters,61960"
, "ProRevenge,68628"
, "ProtectAndServe,31841"
, "providence,3433"
, "PS2Cobalt,1330"
, "PS3,70298"
, "PS4,224940"
, "PS4Deals,25738"
, "PS4Planetside2,3392"
, "PSO2,6678"
, "psych,17860"
, "psychedelicrock,16742"
, "psychology,200568"
, "Psychonaut,101049"
, "ptcgo,5105"
, "ptsd,5175"
, "PublicFreakout,88695"
, "PucaTrade,1379"
, "PuertoRico,2914"
, "pugs,27771"
, "punchablefaces,55609"
, "Pundertale,703"
, "punk,39887"
, "Punny,63046"
, "puns,27992"
, "puppies,23155"
, "puppy101,9484"
, "PuppySmiles,10786"
, "Purdue,5756"
, "pureasoiaf,12551"
, "PurplePillDebate,6931"
, "PushBullet,5486"
, "PussyPass,22432"
, "pussypassdenied,61130"
, "putindoingthings,2049"
, "PuzzleAndDragons,16054"
, "pxifrm,115"
, "Python,115556"
, "qotsa,6238"
, "QuakeLive,4660"
, "Quebec,10786"
, "questionablecontent,5683"
, "quilting,7847"
, "QuinnMains,707"
, "quiteinteresting,16331"
, "quityourbullshit,185200"
, "quotes,104379"
, "QuotesPorn,267602"
, "r4r,87824"
, "Rabbits,28734"
, "<NAME>,2362"
, "racism,7995"
, "radiocontrol,12348"
, "radiohead,28111"
, "Radiology,7457"
, "rage,122716"
, "ragecomics,41862"
, "<NAME>,1722"
, "rails,16064"
, "Rainbow6,9496"
, "RainbowSix,324"
, "RainbowSixSiege,758"
, "rainbow_wolf,275"
, "raining,22091"
, "Rainmeter,61724"
, "raisedbynarcissists,82856"
, "raiseyourdongers,11287"
, "rakugakicho,562"
, "raleigh,9389"
, "rally,15541"
, "ramen,36662"
, "Random_Acts_Of_Amazon,32024"
, "randomactsofamazon,5503"
, "RandomActsofCards,4803"
, "RandomActsOfChristmas,6437"
, "randomactsofcsgo,15588"
, "RandomActsOfGaming,48115"
, "RandomActsofMakeup,16512"
, "RandomActsOfPizza,24170"
, "Random_Acts_Of_Pizza,39302"
, "RandomActsOfPolish,7470"
, "RandomKindness,37441"
, "randomsuperpowers,580"
, "randpaul,5063"
, "rangers,9997"
, "rant,18677"
, "rantgrumps,1462"
, "RantsFromRetail,1673"
, "rapbattles,5800"
, "raspberry_pi,82516"
, "Rateme,41096"
, "rational,3854"
, "RationalPsychonaut,12838"
, "RATS,15845"
, "ravens,11730"
, "rawdenim,25719"
, "razorbacks,1594"
, "RBI,29738"
, "rccars,5804"
, "RCSources,6523"
, "rct,16703"
, "reactiongifs,584267"
, "reactjs,6388"
, "readit,32196"
, "realasians,70113"
, "realdubstep,19599"
, "RealEstate,40152"
, "reallifedoodles,95560"
, "RealLifeFootball,205"
, "realmadrid,10216"
, "REBL,1016"
, "recipes,150726"
, "reckful,895"
, "reddevils,37712"
, "RedditAlternatives,7793"
, "redditblack,1330"
, "RedditDads,2927"
, "RedditDayOf,50174"
, "RedditForGrownups,19457"
, "RedditFox,2195"
, "redditgetsdrawn,95837"
, "redditisfun,21473"
, "RedditLaqueristas,72782"
, "redditrequest,5690"
, "redditsync,47160"
, "RedditWritesSeinfeld,17316"
, "RedHotChiliPeppers,11206"
, "RedLetterMedia,8047"
, "redorchestra,6201"
, "redpandas,20461"
, "RedPillWomen,13048"
, "Reds,5256"
, "Redskins,11116"
, "redsox,18397"
, "ReefTank,9386"
, "Reformed,4638"
, "regularcarreviews,2858"
, "regularshow,22891"
, "relationship_advice,115575"
, "relationships,402654"
, "RelayForReddit,24205"
, "reloading,8744"
, "RenewableEnergy,28148"
, "Rengarmains,1073"
, "Repsneakers,8097"
, "reptiles,11690"
, "Republican,19154"
, "researchchemicals,6883"
, "residentevil,8177"
, "respectporn,22817"
, "respectthreads,9618"
, "restorethefourth,22338"
, "resumes,24186"
, "retiredgif,52689"
, "retrobattlestations,13020"
, "RetroFuturism,82812"
, "retrogaming,22162"
, "RetroPie,3485"
, "ReversedGIFS,10990"
, "reversegif,22540"
, "reynad,1543"
, "rickandmorty,191060"
, "rickygervais,9435"
, "riddles,30867"
, "Rift,9693"
, "Rimarist,7"
, "RimWorld,8322"
, "ripcity,6682"
, "rit,7262"
, "RivalsOfAether,6951"
, "Rivenmains,1199"
, "Roadcam,47238"
, "RoastMe,135768"
, "roblox,3240"
, "Robocraft,7490"
, "robotics,33249"
, "Rochester,7587"
, "Rockband,6734"
, "rocketbeans,15194"
, "RocketLeague,99039"
, "rockets,7814"
, "rockhounds,9937"
, "rocksmith,13141"
, "roguelikes,19191"
, "Roguetroll,10"
, "rojava,1029"
, "Roku,15244"
, "roleplayponies,72"
, "rollercoasters,7167"
, "rolltide,3441"
, "Romania,23826"
, "ronandfez,3299"
, "ronpaul,25443"
, "RoomPorn,290703"
, "roosterteeth,129872"
, "ROTC,1388"
, "RotMG,6409"
, "Rottweiler,4174"
, "Rowing,9961"
, "rpdrcirclejerk,650"
, "rpg,92650"
, "rpg_gamers,25733"
, "RSChronicle,414"
, "RSDarkscape,4701"
, "RTLSDR,12111"
, "ruby,31346"
, "rugbyunion,37219"
, "runescape,54578"
, "running,181129"
, "rupaulsdragrace,24932"
, "rush,8156"
, "russia,17424"
, "russian,10448"
, "rust,13618"
, "rutgers,5881"
, "rva,11277"
, "RWBY,21931"
, "rwbyRP,345"
, "ryuuseigai,254"
, "S2000,2373"
, "Saber,2372"
, "sabres,4881"
, "Sacramento,10144"
, "SacRepublicFC,610"
, "sadboys,8191"
, "sadcomics,17309"
, "sadcringe,4046"
, "SaddlebackLeatherFans,36"
, "Saffron_Regiment,278"
, "SAGAcomic,2783"
, "sailing,24086"
, "sailormoon,10790"
, "Saints,8965"
, "SakuraGakuin,844"
, "sales,9397"
, "SaltLakeCity,10883"
, "samharris,1730"
, "samoyeds,4826"
, "SampleSize,32623"
, "samsung,8048"
, "sanantonio,10644"
, "SanctionedSuicide,2331"
, "SandersForPresident,135167"
, "sandiego,27042"
, "sanfrancisco,48702"
, "SanJose,8772"
, "SanJ<NAME>,8349"
, "santashelpers,5881"
, "SantasLittleHelpers,1775"
, "saplings,22583"
, "<NAME>,7700"
, "SargonofAkkad,2866"
, "saskatchewan,2933"
, "saskatoon,4188"
, "Sat,1626"
, "saudiarabia,2242"
, "saudiprince,3510"
, "SavageGarden,7431"
, "savannah,2471"
, "scala,9586"
, "Scams,7972"
, "ScandinavianInterior,5242"
, "<NAME>,23948"
, "Scarrapics,7688"
, "ScenesFromAHat,34944"
, "schizophrenia,4014"
, "SchoolIdolFestival,8021"
, "science,9829763"
, "sciencefiction,32395"
, "scientology,6801"
, "scifi,240788"
, "SciFiRealism,9935"
, "scooters,5786"
, "scoreball,4131"
, "Scotch,47164"
, "ScotchSwap,2196"
, "Scotland,20463"
, "ScottishFootball,1859"
, "SCP,26442"
, "ScreamQueensTV,3679"
, "screenshots,26041"
, "Screenwriting,41585"
, "Scrubs,34145"
, "scuba,23021"
, "Seahawks,32797"
, "Seattle,76985"
, "secretsanta,70999"
, "SecretSubreddit,3473"
, "security,13099"
, "seduction,223034"
, "see,41509"
, "seedboxes,7171"
, "seinfeld,44057"
, "seinfeldgifs,16169"
, "<NAME>,17076"
, "self,148033"
, "SelfDrivingCars,10923"
, "SelfiesWithGlasses,710"
, "selfimprovement,61452"
, "selfpublish,10471"
, "SEO,27693"
, "serbia,3251"
, "Serendipity,40161"
, "serialkillers,31530"
, "serialpodcast,44131"
, "serialpodcastorigins,686"
, "SeriousConversation,3982"
, "seriouseats,19686"
, "sewing,39017"
, "sex,618677"
, "SexPositive,19089"
, "SexWorkers,6491"
, "sexygirls,12774"
, "sexyhair,1771"
, "sexypizza,8500"
, "SexyWomanOfTheDay,12608"
, "SFGiants,16663"
, "SFM,13371"
, "SFWRedheads,8179"
, "sfw_wtf,11341"
, "Shadowrun,9653"
, "shanghai,4780"
, "Sherlock,68729"
, "shestillsucking,16142"
, "shia,911"
, "shiba,12931"
, "shield,39612"
, "Shihtzu,2478"
, "ShingekiNoKyojin,39537"
, "ShinyPokemon,11639"
, "ShitAmericansSay,22530"
, "ShitCrusaderKingsSay,4260"
, "shitduolingosays,3833"
, "ShitLewisSays,4893"
, "ShitLiberalsSay,2555"
, "ShitPoliticsSays,7330"
, "shitpost,24892"
, "ShitRConservativeSays,5073"
, "ShitRedditSays,76821"
, "Shitstatistssay,7677"
, "shittankiessay,510"
, "ShitTumblrSays,3039"
, "shittyadvice,65894"
, "shittyadviceanimals,12933"
, "shittyama,13610"
, "ShittyAnimalFacts,21590"
, "shittyaskreddit,19674"
, "shittyaskscience,298571"
, "Shitty_Car_Mods,90140"
, "shittyconspiracy,4771"
, "shittydarksouls,5868"
, "shitty_ecr,3511"
, "ShittyFanTheories,14206"
, "shittyfoodporn,118113"
, "shittyHDR,8649"
, "shittyideas,16863"
, "shittykickstarters,31310"
, "ShittyLifeProTips,63163"
, "ShittyMapPorn,19129"
, "shittynosleep,23020"
, "shittyprogramming,25766"
, "shittyreactiongifs,131954"
, "shittyrobots,100978"
, "shittysteamreviews,6744"
, "shittytumblrgifs,16429"
, "ShitWehraboosSay,3385"
, "ShokugekiNoSoma,5245"
, "Shoplifting,2514"
, "short,18239"
, "shorthairedhotties,34837"
, "shortscarystories,63081"
, "Shotguns,6107"
, "ShouldIbuythisgame,36978"
, "showerbeer,32418"
, "Showerthoughts,4878620"
, "shroomers,12562"
, "shrooms,23983"
, "shutupandtakemymoney,260041"
, "Sikh,2030"
, "SiliconValleyHBO,31197"
, "Silverbugs,9665"
, "SimCity,25184"
, "simpleliving,73772"
, "simpsonsdidit,18014"
, "simracing,11072"
, "Simulated,30520"
, "singapore,34968"
, "singing,19015"
, "singularity,29307"
, "Sino,1325"
, "sips,35974"
, "sixers,6060"
, "sixwordstories,28278"
, "sjsucks,3359"
, "sjwhate,7175"
, "skateboarding,70289"
, "skeptic,102973"
, "SketchDaily,45733"
, "skiing,36721"
, "SkincareAddiction,186356"
, "SkinnyWithAbs,26477"
, "skrillex,7759"
, "Skullgirls,8746"
, "SkyDiving,9496"
, "Skyforge,6822"
, "SkyPorn,52048"
, "skyrim,317076"
, "skyrimdadjokes,7082"
, "skyrimmods,43657"
, "SkyrimPorn,14961"
, "slashdiablo,4553"
, "slatestarcodex,1204"
, "slavs_squatting,25530"
, "Sleepycabin,7297"
, "Slipknot,4484"
, "sloths,52076"
, "slowcooking,181706"
, "SlyGifs,31850"
, "sm4sh,4693"
, "smallbusiness,42404"
, "smalldickproblems,2878"
, "SmarterEveryDay,17293"
, "smashbros,193884"
, "smashcirclejerk,3835"
, "smashgifs,11407"
, "Smite,67098"
, "smoking,23275"
, "snakes,15064"
, "snapchat,14894"
, "sneakermarket,7491"
, "Sneakers,62627"
, "snek_irl,6224"
, "Sneks,16810"
, "snes,12996"
, "snowboarding,55293"
, "snowden,6612"
, "SNSD,12988"
, "SoapboxBanhammer,426"
, "soccer,406132"
, "SoccerBetting,7821"
, "soccercirclejerk,8485"
, "soccerspirits,2436"
, "soccerstreams,28855"
, "socialanxiety,33954"
, "SocialEngineering,66828"
, "socialism,55342"
, "Socialistart,2830"
, "socialjustice101,2772"
, "SocialJusticeInAction,5071"
, "socialmedia,24157"
, "socialskills,124187"
, "socialwork,5616"
, "sociopath,3244"
, "sodadungeon,846"
, "sodapoppin,1883"
, "softwaregore,41799"
, "SolForge,2177"
, "solipsism,7371"
, "solotravel,39652"
, "soma,1456"
, "somethingimade,103385"
, "SonicTheHedgehog,4766"
, "SonyXperia,5817"
, "sooners,2834"
, "sophieturner,8412"
, "sorceryofthespectacle,2519"
, "SoundsLikeChewy,350"
, "SoundsLikeMusic,10164"
, "SourceFed,32048"
, "sousvide,11980"
, "southafrica,16286"
, "southpark,151534"
, "soylent,16541"
, "space,4856256"
, "SpaceBuckets,17882"
, "spaceengine,8735"
, "spaceengineers,23681"
, "spaceflight,17886"
, "spaceporn,304852"
, "spacex,42626"
, "spain,6505"
, "Spanish,18226"
, "SpecArt,38694"
, "SpeculativeEvolution,8317"
, "speedrun,41470"
, "spelunky,5475"
, "spicy,26348"
, "spiderbro,20400"
, "Spiderman,17595"
, "spiders,19926"
, "SpideyMeme,43917"
, "spikes,23119"
, "splatoon,26573"
, "SplitDepthGIFS,42588"
, "Spokane,3500"
, "spongebob,25202"
, "Spongebros,9137"
, "sporetraders,1880"
, "sports,5053901"
, "sportsarefun,33800"
, "sportsbook,14530"
, "spotify,32797"
, "spotted,14019"
, "springerspaniel,1026"
, "springfieldMO,2589"
, "Sprint,3308"
, "SQL,12459"
, "SquaredCircle,100115"
, "SquaredCirclejerk,2263"
, "SRSDiscussion,14311"
, "SRSGaming,6438"
, "SRSsucks,13889"
, "SS13,4183"
, "SSBM,18959"
, "SSBPM,23980"
, "StackAdvice,9073"
, "StackGunHeroes,2201"
, "stalker,8405"
, "StallmanWasRight,2158"
, "Stance,11682"
, "Standup,30403"
, "StandUpComedy,68690"
, "standupshots,180743"
, "Staples,1663"
, "starbound,53361"
, "starbucks,13249"
, "Starcaft,5"
, "starcitizen,59168"
, "Starcitizen_trades,4263"
, "starcraft,184091"
, "StardustCrusaders,9178"
, "Stargate,20681"
, "starlets,28960"
, "StarlightStage,1158"
, "starterpacks,25990"
, "StartledCats,96464"
, "startrek,98491"
, "startups,95633"
, "StarVStheForcesofEvil,2331"
, "StarWars,345816"
, "StarWarsBattlefront,50911"
, "starwarscollecting,841"
, "StarWarsEU,7579"
, "StarWarsLeaks,9889"
, "starwarsrebels,4990"
, "starwarsspeculation,831"
, "starwarstrader,1718"
, "statistics,29112"
, "steak,17478"
, "Steam,246860"
, "SteamController,2363"
, "steamdeals,52334"
, "SteamGameSwap,39821"
, "steampunk,33109"
, "steamr,1339"
, "steelers,14770"
, "stencils,18517"
, "stephenking,11385"
, "steroids,21686"
, "stevedangle,854"
, "stevenuniverse,40931"
, "Stims,4400"
, "StLouis,16670"
, "stlouisblues,5825"
, "StLouisRams,4558"
, "sto,8236"
, "StockMarket,30145"
, "stocks,42133"
, "Stoicism,27901"
, "StonerCringe,465"
, "StonerEngineering,62455"
, "StonerPhilosophy,22673"
, "StonerProTips,29743"
, "stonerrock,17254"
, "stopdrinking,32169"
, "StopGaming,4845"
, "StoppedWorking,29609"
, "stopsmoking,39116"
, "StopTouchingMe,19388"
, "StormfrontorSJW,10522"
, "Stormlight_Archive,10108"
, "straightedge,2864"
, "straya,15833"
, "streetart,28859"
, "StreetFighter,19201"
, "StreetFights,40216"
, "streetfoodartists,13113"
, "streetphotography,4566"
, "streetwear,59791"
, "Streisandeffect,479"
, "StudentLoans,9744"
, "stunfisk,12874"
, "subaru,48713"
, "submechanophobia,17428"
, "subnautica,2689"
, "subredditcancer,10423"
, "SubredditDrama,212016"
, "SubredditDramaDrama,6784"
, "subredditoftheday,116920"
, "SubredditSimMeta,18180"
, "SubredditSimulator,100281"
, "succulents,11380"
, "SuddenlyGay,10271"
, "sugarfreemua,8232"
, "SuggestALaptop,21902"
, "suggestmeabook,22247"
, "SuicideWatch,40594"
, "suits,23893"
, "summonerschool,82962"
, "summonerswar,13052"
, "Sundresses,8984"
, "suns,2922"
, "sunsetshimmer,732"
, "Suomi,26735"
, "Superbowl,10765"
, "supergirlTV,5557"
, "superman,13474"
, "supermoto,5606"
, "Supernatural,46900"
, "SuperShibe,52716"
, "Supplements,22667"
, "supremeclothing,15545"
, "Surface,32368"
, "surfing,27387"
, "SurgeryGifs,5944"
, "Survival,73333"
, "survivinginfidelity,2589"
, "survivor,18165"
, "survivorcirclejerk,394"
, "SurvivorRankdownII,88"
, "survivorspoilers,453"
, "sushi,25490"
, "svenskpolitik,43953"
, "Sverige,1102"
, "SVExchange,10736"
, "SwagBucks,8574"
, "SWARJE,50964"
, "SweatyPalms,26722"
, "sweden,85671"
, "sweepstakes,5485"
, "swift,13768"
, "SwiggitySwootyGifs,16194"
, "Swimming,23838"
, "Swingers,15856"
, "Switzerland,7308"
, "swoleacceptance,57610"
, "swordartonline,19915"
, "SwordOrSheath,6251"
, "swrpg,4590"
, "swtor,53799"
, "sydney,22094"
, "SympatheticMonsters,8883"
, "synthesizers,19567"
, "Syracuse,3069"
, "Syraphia,26"
, "SyrianCirclejerkWar,385"
, "syriancivilwar,26280"
, "sysadmin,123602"
, "tabletopgamedesign,10692"
, "tacobell,7914"
, "Tacoma,4034"
, "TACSdiscussion,4031"
, "TagPro,11498"
, "TagProIRL,823"
, "taiwan,7100"
, "TakeshisCastle,284"
, "tales,5922"
, "talesfromcallcenters,16316"
, "TalesFromRetail,232513"
, "talesfromtechsupport,296382"
, "TalesFromTheCustomer,14883"
, "TalesFromTheFrontDesk,9948"
, "TalesFromThePharmacy,10320"
, "TalesFromThePizzaGuy,38007"
, "TalesFromTheSquadCar,20480"
, "TalesFromYourServer,39699"
, "tall,50390"
, "Tallahassee,2862"
, "Talonmains,1440"
, "TameImpala,6037"
, "tampa,11788"
, "TampaBayLightning,3492"
, "TankPorn,9398"
, "tappedout,15964"
, "tarantinogifs,11320"
, "Target,1903"
, "tasker,22637"
, "tattoo,40487"
, "tattoos,434589"
, "TaylorSwift,22392"
, "TaylorSwiftPictures,5578"
, "TaylorSwiftsLegs,8853"
, "tdl,1259"
, "tea,63796"
, "Teachers,29837"
, "teaching,16431"
, "TeamSolomid,14820"
, "tech,82935"
, "technews,17699"
, "TechNewsToday,30782"
, "Techno,16222"
, "technology,5204799"
, "TechoBlanco,1661"
, "techsupport,78211"
, "techsupportgore,109303"
, "techsupportmacgyver,56393"
, "techtheatre,7690"
, "T<NAME>,988"
, "teefies,4007"
, "teenagers,105234"
, "TeenMFA,11284"
, "TEFL,13794"
, "Teleshits,10418"
, "television,6011203"
, "TelevisionQuotes,17559"
, "TellMeAFact,23598"
, "telltale,4012"
, "Tennessee,4201"
, "Tennesseetitans,4269"
, "tennis,31624"
, "TeraOnline,18715"
, "Terraria,78686"
, "terriblefacebookmemes,33514"
, "tesdcares,3954"
, "teslamotors,29314"
, "teslore,32384"
, "Texans,10937"
, "texas,32441"
, "TexasRangers,6587"
, "tf2,157238"
, "TF2fashionadvice,6190"
, "tf2shitposterclub,507"
, "tf2trade,13281"
, "tgrp,97"
, "Thailand,8314"
, "thalassophobia,64543"
, "thanksgiving,678"
, "That70sshow,11915"
, "thatHappened,238789"
, "ThatPeelingFeeling,18411"
, "The100,8349"
, "TheAffair,732"
, "TheBluePill,25735"
, "TheBrewery,7802"
, "thebutton,161652"
, "thechapel,1915"
, "TheCompletionist,2587"
, "TheCreatures,12627"
, "The_Crew,4247"
, "TheDarkTower,10781"
, "thedivision,8376"
, "The_Donald,1680"
, "TheExpanse,2150"
, "TheFacebookDelusion,24433"
, "TheForest,8747"
, "TheFrontBottoms,2114"
, "TheGameOfThronesGame,2267"
, "TheGirlSurvivalGuide,56560"
, "thegoodwife,2651"
, "TheHobbit,21547"
, "TheKillers,2316"
, "TheLastAirbender,142647"
, "thelastofus,21644"
, "thelastofusfactions,5769"
, "thelawschool,1305"
, "theleaguefx,17449"
, "TheLeftovers,12448"
, "thelongdark,4192"
, "TheMassive,1864"
, "ThemeParkitect,1508"
, "themindyproject,2318"
, "themoddingofisaac,4680"
, "themountaingoats,3058"
, "thenetherlands,67966"
, "theNvidiaShield,2771"
, "theocho,39803"
, "TheOnion,14325"
, "ThePhenomenon,7304"
, "TheRealmsMC,335"
, "TheRedPill,139577"
, "thereifixedit,10036"
, "thereisnoowl,247"
, "therewasanattempt,16696"
, "TheSimpsons,118309"
, "thesims,43878"
, "thesopranos,7028"
, "TheSquadOnPoint,8807"
, "TheStrokes,4903"
, "Thetruthishere,46694"
, "TheVampireDiaries,6381"
, "thevoice,1175"
, "thewalkingdead,257148"
, "TheWayWeWere,68848"
, "thewestwing,6412"
, "TheWire,21842"
, "theworldisflat,1241"
, "theworldnews,6170"
, "theydidthemath,125881"
, "ThingsCutInHalfPorn,88776"
, "ThingsWhiteFolksLike,97"
, "thinkpad,6659"
, "thisismylifenow,7624"
, "ThisIsNotASafeSpace,1145"
, "ThriftStoreHauls,60871"
, "Throwers,6326"
, "Thunder,5600"
, "TiADiscussion,7104"
, "TibiaMMO,1524"
, "tifu,4785294"
, "TILinIndia,360"
, "tiltshift,26505"
, "TimAndEric,22437"
, "timbers,3840"
, "timberwolves,5029"
, "timetolegalize,10058"
, "tinabelcher,14568"
, "Tinder,178148"
, "TinyHouses,67833"
, "tipofmyjoystick,7822"
, "tipofmytongue,155576"
, "titanfall,30090"
, "titlegore,32415"
, "TMBR,2729"
, "TMNT,8354"
, "tmobile,14739"
, "tobacco_ja,158"
, "TodayIGrandstanded,1472"
, "todayilearned,10011031"
, "Tokyo,8491"
, "TokyoGhoul,10479"
, "tolkienfans,32828"
, "TombRaider,4408"
, "tomwaits,1568"
, "tonightsdinner,39276"
, "ToolBand,16789"
, "Tools,4780"
, "TooMeIrlForMeIrl,481"
, "Toonami,6379"
, "Toontown,4781"
, "toosoon,77090"
, "TopGear,136177"
, "TopMindsOfReddit,9391"
, "topofreddit,4569"
, "TOR,23629"
, "toronto,66122"
, "TorontoAnarchy,95"
, "Torontobluejays,18976"
, "torontoraptors,10952"
, "torrents,56332"
, "totallynotrobots,9466"
, "totalwar,41322"
, "touhou,8449"
, "TowerofGod,4100"
, "TownofSalemgame,5464"
, "Toyota,7056"
, "TPPKappa,272"
, "traaaaaaannnnnnnnnns,2723"
, "trackers,53133"
, "Tradelands,621"
, "TraditionalCurses,8904"
, "trailerparkboys,47748"
, "trailers,30981"
, "traingifs,4196"
, "trains,7737"
, "trance,38049"
, "transformers,8114"
, "transgamers,4169"
, "transgender,21190"
, "transgendercirclejerk,2311"
, "translator,8015"
, "Transmogrification,14579"
, "transpassing,12247"
, "transpositive,7195"
, "transtimelines,13427"
, "trap,53878"
, "trapmuzik,16279"
, "trapproduction,6328"
, "trashpandas,10062"
, "trashy,169388"
, "travel,229376"
, "treecomics,31956"
, "treedibles,13730"
, "treemusic,38739"
, "treeofsavior,10856"
, "trees,810334"
, "TreesSuckingAtThings,32164"
, "trendingsubreddits,12500"
, "tressless,4245"
, "triangle,8951"
, "Tribes,11694"
, "trippinthroughtime,79903"
, "trippy,23788"
, "Troll4Troll,3223"
, "TrollBookClub,2625"
, "TrollDevelopers,879"
, "TrollXChromosomes,178563"
, "TrollXMoms,4640"
, "TrollXWeddings,2970"
, "TrollYChromosome,64300"
, "Trophies,4227"
, "Trove,12525"
, "Trucking,4314"
, "Trucks,19720"
, "trucksim,4914"
, "TrueAnime,7706"
, "TrueAskReddit,78978"
, "TrueAtheism,59089"
, "TrueChristian,9798"
, "TrueDetective,63696"
, "TrueDoTA2,8917"
, "TrueFilm,82190"
, "truegaming,137623"
, "TrueLionhearts,6"
, "TrueOffMyChest,10250"
, "TrueReddit,355484"
, "TrueSTL,4047"
, "truetf2,14280"
, "truewomensliberation,497"
, "truezelda,10426"
, "trump,436"
, "trumpet,4992"
, "TryingForABaby,6930"
, "trypophobia,11299"
, "Tsunderes,3708"
, "TsundereSharks,40487"
, "ttcafterloss,605"
, "tuckedinkitties,14781"
, "T<NAME>,6725"
, "Tulpas,9496"
, "tulsa,4869"
, "tumblr,142894"
, "TumblrAtRest,20809"
, "TumblrCirclejerk,8206"
, "TumblrInAction,258243"
, "TumblrPls,4025"
, "Turkey,6826"
, "turning,6471"
, "TuxedoCats,3361"
, "TWD,10164"
, "twentyonepilots,7668"
, "twice,669"
, "TwinCities,12115"
, "twinpeaks,14130"
, "Twitch,43528"
, "twitchplayspokemon,49925"
, "TwoBestFriendsPlay,16430"
, "Twokinds,988"
, "TwoXChromosomes,4185231"
, "TwoXSex,15244"
, "typography,45538"
, "TYT,931"
, "UBC,4840"
, "uber,2502"
, "uberdrivers,6229"
, "Ubuntu,60590"
, "UCalgary,1674"
, "ucf,6370"
, "UCSantaBarbara,5088"
, "udub,4305"
, "ufc,22738"
, "UFOs,48910"
, "UGA,4784"
, "uglyduckling,32364"
, "UIUC,11956"
, "ukbike,3128"
, "ukipparty,2191"
, "UKPersonalFinance,10126"
, "ukpolitics,42408"
, "ukraina,12948"
, "UkrainianConflict,21537"
, "uktrees,7946"
, "ukulele,18774"
, "ultimate,17636"
, "ultrahardcore,6749"
, "Ultralight,20511"
, "ultrawidemasterrace,1849"
, "UMD,5213"
, "UNBGBBIIVCHIDCTIICBG,89630"
, "undelete,47051"
, "Underminers,1213"
, "Undertale,23950"
, "Undertem,283"
, "UnearthedArcana,4194"
, "Unexpected,454437"
, "UnexpectedCena,42675"
, "unexpectedjihad,84030"
, "unexpectedmusic,6513"
, "UnexpectedThugLife,207696"
, "unintentionalASMR,7736"
, "UnisonLeague,847"
, "unitedkingdom,118237"
, "unitedstatesofamerica,13605"
, "Unity2D,12204"
, "Unity3D,31991"
, "UniversityOfHouston,2996"
, "unixporn,32974"
, "Unorthodog,14085"
, "unpopularopinion,2633"
, "unrealengine,12071"
, "unrealtournament,3915"
, "UnresolvedMysteries,123566"
, "UnsentLetters,14744"
, "UnsolicitedRedesigns,6108"
, "UnsolvedMysteries,19576"
, "unstirredpaint,7293"
, "unturned,9162"
, "UnusualArt,10748"
, "uofm,6099"
, "uofmn,3849"
, "UofT,6623"
, "UpliftingNews,4441491"
, "Upvoted,18086"
, "UpvotedBecauseGirl,18218"
, "upvotegifs,17815"
, "urbanexploration,76436"
, "UrbanHell,13357"
, "urbanplanning,20087"
, "usanews,4603"
, "USC,3212"
, "usenet,23173"
, "UserCars,6730"
, "userexperience,12158"
, "USMC,10931"
, "uspolitics,6524"
, "ussoccer,13690"
, "Utah,4476"
, "UtahJazz,2145"
, "UTAustin,8554"
, "Utrecht,1156"
, "uvic,1694"
, "uwaterloo,7871"
, "uwotm8,26543"
, "VAC_Porn,9417"
, "vagabond,15251"
, "vainglorygame,4545"
, "valve,13360"
, "vancouver,38148"
, "vandwellers,20578"
, "vapeitforward,6349"
, "VapePorn,10638"
, "Vaping101,10078"
, "Vaping,24139"
, "vaporents,44059"
, "Vaporwave,22466"
, "VaporwaveAesthetics,6500"
, "vargas,3989"
, "vegan,62390"
, "vegancirclejerk,2338"
, "veganrecipes,24643"
, "vegas,11805"
, "vegetarian,44443"
, "VegRecipes,36893"
, "Velo,8444"
, "venturebros,14986"
, "verizon,4884"
, "Vermintide,6883"
, "Veterans,6255"
, "vexillology,46282"
, "vexillologycirclejerk,4132"
, "vfx,11058"
, "vgb,21719"
, "VGHS,3890"
, "victoria2,3678"
, "VictoriaBC,8051"
, "victoriajustice,10163"
, "video,24832"
, "videogamedunkey,12453"
, "videography,16302"
, "videos,9247409"
, "videosplus,1976"
, "VietNam,4321"
, "VillagePorn,48589"
, "vim,25464"
, "Vinesauce,4827"
, "vintageaudio,8157"
, "vinyl,81713"
, "Virginia,7959"
, "VirginiaTech,6843"
, "virtualreality,16951"
, "visualnovels,18966"
, "vita,49605"
, "Vive,6470"
, "vmware,13503"
, "Voat,4851"
, "Vocaloid,10975"
, "Volkswagen,21290"
, "VolleyballGirls,59133"
, "Volvo,6632"
, "VPN,17588"
, "vsauce,3602"
, "VSModels,2908"
, "VXJunkies,9443"
, "vzla,7574"
, "WackyTicTacs,16046"
, "waifuism,1061"
, "wallpaper,161387"
, "wallpaperdump,24528"
, "wallpapers,374610"
, "wallstreetbets,25133"
, "walmart,3298"
, "WaltDisneyWorld,16644"
, "warcraftlore,9359"
, "Warframe,37682"
, "wargame,6285"
, "Warhammer,34751"
, "Warhammer40k,20910"
, "Warmachine,6497"
, "WarOnComcast,9218"
, "WarplanePorn,5297"
, "warriors,13277"
, "WarshipPorn,26919"
, "Warthunder,31860"
, "Washington,8927"
, "washingtondc,36390"
, "washingtonwizards,4192"
, "WastedGifs,119428"
, "WastelandPowers,434"
, "Watches,81459"
, "WatchesCirclejerk,1508"
, "Watchexchange,5194"
, "Watercolor,12336"
, "watercooling,9119"
, "waterporn,59894"
, "Waxpen,2460"
, "Weakpots,2643"
, "WeAreTheMusicMakers,122961"
, "weather,16995"
, "webcomics,81539"
, "web_design,146257"
, "webdev,105268"
, "WebGames,91965"
, "wec,9139"
, "wedding,18085"
, "WeddingPhotography,3016"
, "weddingplanning,26248"
, "weeabootales,23571"
, "weed,10981"
, "weekendgunnit,6415"
, "weightlifting,20232"
, "weightroom,78738"
, "Weird,26971"
, "WeirdWheels,11164"
, "Welding,17441"
, "Wellington,4711"
, "Wellthatsucks,60047"
, "WEPES,2584"
, "WestVirginia,3002"
, "Wet_Shavers,5221"
, "whatcarshouldIbuy,7337"
, "Whatcouldgowrong,234461"
, "Whatisthis,13279"
, "whatisthisthing,171566"
, "WhatsInThisThing,87704"
, "whatstheword,21524"
, "whatsthisbird,6998"
, "whatsthisbug,40683"
, "whatsthisplant,21102"
, "whatsthisrock,4341"
, "WhatsWrongWithYourDog,8502"
, "wheredidthesodago,381556"
, "whiskey,24787"
, "Whiskyporn,4836"
, "whiteknighting,19243"
, "whitepeoplefacebook,10795"
, "whitepeoplegifs,85881"
, "WhitePeopleTwitter,4837"
, "WhiteRights,9339"
, "whitesox,4082"
, "WhiteWolfRPG,3925"
, "whowouldcirclejerk,1245"
, "whowouldwin,94633"
, "Wicca,10118"
, "wicked_edge,77487"
, "WiggleButts,5153"
, "wiiu,81853"
, "WikiInAction,3372"
, "WikiLeaks,35651"
, "wikipedia,156441"
, "wildhockey,6955"
, "WildStar,35041"
, "wince,18160"
, "Windows10,55712"
, "windows,57504"
, "windowsphone,48558"
, "wine,35744"
, "Winnipeg,8798"
, "winnipegjets,3091"
, "winterporn,35946"
, "wisconsin,14546"
, "Wishlist,1910"
, "witcher,84856"
, "wma,5119"
, "woahdude,890116"
, "WonderTrade,6303"
, "woodworking,138992"
, "woofbarkwoof,6057"
, "woof_irl,9024"
, "WordAvalanches,15556"
, "Wordpress,28014"
, "WorkOnline,34955"
, "worldbuilding,62503"
, "worldevents,39549"
, "worldnews,9843404"
, "worldofpvp,3947"
, "WorldofTanks,26078"
, "WorldofTanksXbox,1489"
, "WorldOfWarships,14689"
, "worldpolitics,150119"
, "worldpowers,2447"
, "worldwhisky,4109"
, "WormFanfic,546"
, "worstof,37425"
, "WoT,13538"
, "WouldYouRather,39373"
, "wow,254317"
, "woweconomy,11193"
, "wowservers,2742"
, "wowthissubexists,74412"
, "Wrangler,7569"
, "Wrasslin,6255"
, "WrestleWithThePlot,15936"
, "wrestling,7589"
, "wrestlingisreddit,196"
, "writing,163310"
, "WritingPrompts,4278661"
, "wsgy,2336"
, "wsu,2487"
, "WTF,4692656"
, "wtfstockphotos,22428"
, "WWE,21207"
, "WWEGames,4665"
, "wwe_network,1029"
, "wwesupercard,2258"
, "wwiipics,10467"
, "WWU,1721"
, "xbmc,17678"
, "xbox,13738"
, "xbox360,48571"
, "xboxone,170503"
, "Xcom,23966"
, "xDivinum,2"
, "Xenoblade_Chronicles,4403"
, "XFiles,16183"
, "xkcd,62961"
, "xposed,11730"
, "xTrill,2404"
, "XWingTMG,8024"
, "xxfitness,89703"
, "xxketo,23640"
, "YanetGarcia,8212"
, "yarntrolls,2171"
, "YasuoMains,963"
, "yee,4661"
, "yesyesyesno,15237"
, "yesyesyesyesno,22447"
, "YMS,9789"
, "ynab,17393"
, "yoga,81031"
, "Yogscast,45014"
, "yogscastkim,4241"
, "yokaiwatch,1338"
, "youdontsurf,191966"
, "YouSeeComrade,25241"
, "YouShouldKnow,513161"
, "youtube,34027"
, "youtubecomments,18579"
, "youtubehaiku,194879"
, "yoyhammer,1854"
, "yugioh,30391"
, "yuruyuri,856"
, "yvonnestrahovski,9131"
, "Zappa,5521"
, "zelda,140888"
, "zen,31825"
, "ZenHabits,107887"
, "Zerxee,2"
, "ZettaiRyouiki,13054"
, "zoidberg,6890"
, "zombies,85610"
]
| true | module Sfw (..) where
sfwRaw : List String
sfwRaw =
[ "100yearsago,32345"
, "1200isplenty,40968"
, "12thMan,946"
, "1911,6937"
, "195,10030"
, "2007scape,45053"
, "240sx,3708"
, "30ROCK,20200"
, "336RS,5"
, "3amjokes,48060"
, "3Dmodeling,8997"
, "3Dprinting,45402"
, "3DS,105660"
, "3DSdeals,13270"
, "3dshacks,4549"
, "40kLore,2901"
, "49ers,23227"
, "4ChanMeta,8778"
, "4PanelCringe,17496"
, "4Runner,3143"
, "4x4,18457"
, "4Xgaming,6475"
, "52weeksofcooking,21831"
, "7daystodie,8453"
, "7kglobal,586"
, "80smusic,6852"
, "8chan,9806"
, "90sAlternative,7895"
, "90smusic,6374"
, "911truth,9696"
, "9gag,4223"
, "A858DE45F56D9BC9,11616"
, "AAdiscussions,203"
, "AaronTracker,4"
, "AbandonedPorn,300746"
, "ABCDesis,4339"
, "ableton,18019"
, "ABraThatFits,43569"
, "AcademicBiblical,8561"
, "Acadiana,2074"
, "AccidentalComedy,34518"
, "AccidentalRenaissance,7883"
, "Accounting,29020"
, "AceAttorney,6444"
, "acecombat,1946"
, "AceOfAngels8,1547"
, "ACMilan,3076"
, "ACON_Support,455"
, "acting,13840"
, "ActionFigures,7067"
, "ActLikeYouBelong,20574"
, "ACTrade,10624"
, "actualconspiracies,12269"
, "actuallesbians,50164"
, "PI:NAME:<NAME>END_PI,5185"
, "Addons4Kodi,4778"
, "Adelaide,6433"
, "ADHD,43331"
, "AdorableDragons,5874"
, "AdrenalinePorn,67900"
, "ads,7112"
, "adultery,4964"
, "adultswim,15055"
, "AdvancedRunning,8663"
, "AdventureCapitalist,2034"
, "adventurerlogkiraigen,3"
, "adventuretime,154732"
, "advertising,22881"
, "Advice,28313"
, "AdviceAnimals,4280324"
, "AdviceAtheists,15199"
, "AdvLog,6"
, "afinil,6147"
, "AFL,12831"
, "AfterEffects,13537"
, "AgainstGamerGate,1828"
, "AgainstHateSubreddits,2564"
, "againstmensrights,8568"
, "PI:NAME:<NAME>END_PI,20815"
, "agentcarter,8096"
, "aggies,8415"
, "ainbow,39002"
, "AirBnB,3030"
, "AirForce,16643"
, "airsoft,24091"
, "A_irsoft,531"
, "airsoftmarket,3989"
, "ak47,7742"
, "AkameGaKILL,4701"
, "alaska,8188"
, "Albany,4057"
, "alberta,7316"
, "albiononline,2721"
, "AlbumArtPorn,38777"
, "Albuquerque,5171"
, "alcohol,19222"
, "aldub,251"
, "Aleague,4828"
, "alexPI:NAME:<NAME>END_PI,11623"
, "PI:NAME:<NAME>END_PI,10418"
, "AlienBlue,205706"
, "aliens,14241"
, "AliensAmongUs,7610"
, "AlisonBrie,39875"
, "allthingsprotoss,8880"
, "AllThingsTerran,9039"
, "allthingszerg,9941"
, "alternativeart,50896"
, "altnewz,6882"
, "AMA,110503"
, "amateurradio,18510"
, "amazon,12531"
, "amazonecho,4205"
, "AmazonTopRated,31361"
, "Amd,15312"
, "americandad,10454"
, "AmericanHorrorStory,41385"
, "AmericanPolitics,7383"
, "amibeingdetained,28268"
, "AmIFreeToGo,18446"
, "amiibo,40041"
, "AmiiboCanada,2665"
, "AmISexy,29827"
, "AmItheAsshole,9068"
, "amiugly,58738"
, "Amsterdam,8891"
, "AnaheimDucks,4120"
, "analog,25027"
, "analogygifs,15193"
, "Anarchism,61152"
, "Anarcho_Capitalism,24470"
, "anarchomemes,2235"
, "Anarchy101,8342"
, "Android,619379"
, "androidapps,71654"
, "androidcirclejerk,10091"
, "androiddev,45103"
, "AndroidGaming,60786"
, "AndroidMasterRace,17075"
, "AndroidQuestions,21961"
, "androidthemes,43273"
, "AndroidTV,2073"
, "AndroidWear,22250"
, "ANGEL,3818"
, "angelsbaseball,4015"
, "AngieVarona,7416"
, "AngieVaronaLegal,14860"
, "angularjs,14290"
, "AnimalCollective,3999"
, "AnimalCrossing,52738"
, "AnimalPorn,58298"
, "Animals,16669"
, "AnimalsBeingBros,155109"
, "AnimalsBeingDerps,68440"
, "AnimalsBeingGeniuses,11587"
, "AnimalsBeingJerks,260301"
, "AnimalTextGifs,16525"
, "animation,30036"
, "anime,329033"
, "AnimeFigures,9580"
, "animegifs,23635"
, "animegifsound,2956"
, "anime_irl,21733"
, "animelegs,1158"
, "animenocontext,17583"
, "animeponytails,1120"
, "AnimeSketch,7131"
, "Animesuggest,33759"
, "Animewallpaper,25418"
, "PI:NAME:<NAME>END_PI,3919"
, "annakendrick,23257"
, "PI:NAME:<NAME>END_PI,6710"
, "announcements,9800402"
, "annualkpopawards,63"
, "ANormalDayInRussia,107448"
, "answers,90064"
, "Anthropology,42357"
, "AntiAntiJokes,19258"
, "Anticonsumption,36517"
, "AntiJokes,67527"
, "antinatalism,1278"
, "ANTM,2152"
, "Anxiety,72471"
, "AnythingGoesNews,18624"
, "AnythingGoesPics,24342"
, "aoe2,15746"
, "aphextwin,3243"
, "apink,2849"
, "ApocalypseRising,1312"
, "AppalachianTrail,13382"
, "AppHookup,54908"
, "apple,303477"
, "applehelp,18550"
, "appletv,11595"
, "AppleWatch,17573"
, "ApplyingToCollege,3909"
, "AquamarineVI,258"
, "Aquariums,55476"
, "ar15,25099"
, "arabs,6346"
, "araragi,6637"
, "Archaeology,29159"
, "archeage,18222"
, "ArcherFX,114190"
, "Archery,23167"
, "architecture,66636"
, "ArchitecturePorn,67248"
, "archlinux,26220"
, "arcticmonkeys,7984"
, "arduino,54938"
, "arewerolling,5972"
, "argentina,18793"
, "PI:NAME:<NAME>END_PI,18748"
, "arielwinter,8131"
, "arizona,9188"
, "ARK,9688"
, "Arkansas,5084"
, "arkfactions,352"
, "arma,27814"
, "armenia,1578"
, "ArmoredWarfare,4370"
, "army,17100"
, "arresteddevelopment,114120"
, "arrow,54555"
, "Art,4418320"
, "ArtefactPorn,52941"
, "artificial,20563"
, "ArtisanVideos,150438"
, "ArtistLounge,4904"
, "ArtPorn,47635"
, "AsABlackMan,5445"
, "asatru,5196"
, "asexuality,9774"
, "Ashens,9899"
, "asheville,5954"
, "AshVsEvilDead,2799"
, "asianamerican,9586"
, "AsianBeauty,33062"
, "AsianCuties,30944"
, "AsianHottiesGIFS,14792"
, "AsianLadyboners,6093"
, "AsianMasculinity,6203"
, "AsianParentStories,9823"
, "AskAcademia,22049"
, "askaconservative,1957"
, "AskAnAmerican,5448"
, "AskAnthropology,26531"
, "askashittydoctor,11900"
, "askcarsales,11328"
, "AskCulinary,91322"
, "AskDocs,11072"
, "AskDoctorSmeeee,6793"
, "askdrugs,11213"
, "AskElectronics,20673"
, "AskEngineers,47497"
, "AskEurope,4997"
, "AskFeminists,8567"
, "AskGames,8898"
, "askgaybros,20243"
, "AskHistorians,462271"
, "AskHistory,10196"
, "AskHR,2694"
, "AskLE,1681"
, "AskMen,220171"
, "AskMenOver30,13031"
, "askMRP,689"
, "AskNetsec,14828"
, "AskNYC,9909"
, "askphilosophy,35904"
, "AskPhysics,8632"
, "Ask_Politics,19137"
, "askportland,2530"
, "AskReddit,10155641"
, "askscience,6895111"
, "AskScienceDiscussion,12244"
, "AskScienceFiction,55288"
, "askseddit,17700"
, "AskSF,3748"
, "AskSocialScience,57653"
, "asktransgender,23115"
, "AskTrollX,8560"
, "asktrp,23896"
, "AskUK,12080"
, "AskVet,8103"
, "AskWomen,225556"
, "askwomenadvice,6981"
, "AskWomenOver30,6563"
, "asmr,112789"
, "asoiaf,244263"
, "asoiafcirclejerk,4344"
, "aspergers,15150"
, "assassinscreed,46238"
, "assettocorsa,6121"
, "Assistance,29810"
, "astrology,8515"
, "Astronomy,141457"
, "astrophotography,57121"
, "Astros,4952"
, "ASU,4409"
, "atheism,2099225"
, "atheistvids,7627"
, "Atlanta,32975"
, "AtlantaHawks,4422"
, "atlbeer,3517"
, "atletico,1135"
, "atmidnight,3523"
, "AubreyPlaza,14920"
, "auckland,5226"
, "Audi,14219"
, "audiobooks,13601"
, "audioengineering,51568"
, "Audiomemes,4680"
, "audiophile,54275"
, "AusFinance,7694"
, "auslaw,4139"
, "Austin,50816"
, "australia,106489"
, "AustralianCattleDog,4919"
, "AustralianMakeup,4210"
, "AustralianPolitics,6610"
, "Austria,17901"
, "Authentic_Vaping,733"
, "autism,10224"
, "AutoDetailing,28181"
, "Automate,16572"
, "Autos,72116"
, "aves,21455"
, "avfc,1877"
, "aviation,65472"
, "awakened,6010"
, "awardtravel,3823"
, "awesome,63586"
, "AwesomeCarMods,14282"
, "Awesomenauts,6926"
, "awfuleverything,8550"
, "awfuleyebrows,16927"
, "aws,7148"
, "aww,8383516"
, "Awwducational,105958"
, "awwnime,43090"
, "awwnverts,13808"
, "awwtf,5978"
, "Awww,30169"
, "awwwtf,52204"
, "ayylmao,12334"
, "AyyMD,2243"
, "AZCardinals,4375"
, "BabyBumps,30685"
, "BabyCorgis,3817"
, "babyelephantgifs,78348"
, "BABYMETAL,4337"
, "backpacking,66411"
, "BacktotheFuture,8217"
, "BackYardChickens,13125"
, "Bacon,23353"
, "baconreader,286837"
, "badcode,11582"
, "Bad_Cop_Follow_Up,383"
, "Bad_Cop_No_Donut,83168"
, "badeconomics,7137"
, "BadguyWolfies,2"
, "badhistory,53746"
, "badlegaladvice,6941"
, "badlinguistics,12134"
, "badmathematics,2022"
, "badMovies,17298"
, "badphilosophy,12828"
, "badpolitics,4844"
, "bad_religion,3771"
, "badroommates,7389"
, "badscience,7812"
, "BadSocialScience,4476"
, "badtattoos,46256"
, "baduk,7264"
, "badukpolitics,345"
, "badwomensanatomy,5426"
, "bagelheads,52"
, "BakaNewsJP,3604"
, "bakchodi,4281"
, "Baking,76381"
, "balisong,2263"
, "baltimore,17454"
, "Bandnames,20585"
, "bangalore,2431"
, "bangtan,716"
, "Banished,21413"
, "BanjoKazooie,2109"
, "banned,779"
, "BannedFrom4chan,10945"
, "bannedfromclubpenguin,49385"
, "bapcsalescanada,10233"
, "bapPI:NAME:<NAME>END_PI,4425"
, "PI:NAME:<NAME>END_PI,5677"
, "PI:NAME:<NAME>END_PI,13022"
, "Barcelona,3289"
, "bardmains,2928"
, "barstoolsports,3779"
, "bartenders,11404"
, "baseball,155176"
, "baseballcirclejerk,2681"
, "BasicIncome,31039"
, "Bass,39616"
, "bassnectar,4105"
, "BatFacts,7222"
, "batman,135188"
, "BatmanArkham,9761"
, "batonrouge,3672"
, "Battlecars,3906"
, "battlecats,2008"
, "Battlefield,28894"
, "battlefield3,51573"
, "battlefield_4,87684"
, "Battlefield_4_CTE,4335"
, "battlefront,8845"
, "battlestations,181457"
, "battlewagon,8473"
, "bayarea,37443"
, "baylor,1774"
, "BBQ,36931"
, "beadsprites,12708"
, "beagle,7016"
, "BeAmazed,49884"
, "BeardedDragons,6346"
, "BeardPorn,19798"
, "beards,107205"
, "beatles,26412"
, "Beatmatch,12427"
, "BeautifulFemales,6427"
, "BeautyBoxes,12831"
, "BeautyGuruChat,2738"
, "BeavisAndButthead,6556"
, "bee_irl,4427"
, "beer,175146"
, "beercirclejerk,1519"
, "beermoney,99255"
, "beerporn,31777"
, "beertrade,12564"
, "beerwithaview,18068"
, "beetlejuicing,11675"
, "beforeandafteredit,8036"
, "BeforeNAfterAdoption,35617"
, "belgium,24164"
, "PI:NAME:<NAME>END_PI,6409"
, "PI:NAME:<NAME>END_PIham,3929"
, "bengals,7308"
, "benzodiazepines,3782"
, "berkeley,10041"
, "PI:NAME:<NAME>END_PI,9091"
, "PI:NAME:<NAME>END_PI,11710"
, "berserklejerk,378"
, "bertstrips,73130"
, "PI:NAME:<NAME>END_PIge,20487"
, "Bestbuy,1252"
, "bestof,4825375"
, "bestoflegaladvice,24410"
, "BestOfLiveleak,23546"
, "bestofnetflix,47255"
, "BestOfOutrageCulture,8893"
, "BestOfReports,11937"
, "BestOfStreamingVideo,39169"
, "bettafish,8565"
, "BetterEveryLoop,1992"
, "betternews,1997"
, "BetterSubredditdrama,273"
, "beyondthebump,16392"
, "BF_Hardline,12243"
, "bicycletouring,18700"
, "bicycling,167014"
, "bigbangtheory,26548"
, "BigBrother,21975"
, "bigdickproblems,32160"
, "biggestproblem,424"
, "bikecommuting,18540"
, "Bikeporn,20438"
, "bikesgonewild,23533"
, "bikewrench,15542"
, "PI:NAME:<NAME>END_PI,9891"
, "billiards,7126"
, "bindingofisaac,72273"
, "bioinformatics,9586"
, "biology,75423"
, "bioniclelego,4119"
, "Bioshock,41261"
, "bipolar,15450"
, "BipolarReddit,13766"
, "Birbs,12097"
, "birdpics,14683"
, "BirdsBeingDicks,29020"
, "birdsofprey,3160"
, "birdswitharms,82881"
, "Birmingham,5808"
, "birthcontrol,7624"
, "bisexual,35587"
, "bitchimabus,46877"
, "Bitcoin,176233"
, "BitcoinMarkets,21106"
, "bitcoinxt,13339"
, "bjj,33502"
, "blackberry,6943"
, "blackbookgraffiti,8555"
, "blackcats,3176"
, "blackdesertonline,8926"
, "Blackfellas,4072"
, "blackfriday,13730"
, "blackladies,9569"
, "BlackLivesMatter,564"
, "BlackMetal,11198"
, "blackmirror,5271"
, "blackops3,37209"
, "Blackout2015,32993"
, "blackpeoplegifs,93773"
, "BlackPeopleTwitter,536812"
, "BlackSails,3569"
, "Blacksmith,25543"
, "BlackwellAcademy,472"
, "bladeandsoul,6677"
, "blakelively,4838"
, "bleach,23050"
, "blender,24603"
, "Blep,44001"
, "blindspot,851"
, "Blink182,11129"
, "BlocParty,778"
, "blogsnark,1030"
, "bloodborne,51353"
, "bloodbowl,3653"
, "BloodGulchRP,177"
, "bloomington,3454"
, "blop,8423"
, "BlueJackets,3055"
, "blues,16528"
, "bluesguitarist,4297"
, "blunderyears,90372"
, "BMW,30818"
, "Boardgamedeals,5984"
, "boardgames,117122"
, "BobsBurgers,37735"
, "bodybuilding,117061"
, "bodymods,10743"
, "bodyweightfitness,187214"
, "Boise,4406"
, "BoJackHorseman,22545"
, "BokuNoHeroAcademia,4307"
, "BollywoodRealism,35697"
, "Bombing,11698"
, "bonnaroo,13215"
, "Bonsai,28350"
, "bookporn,42999"
, "books,6272500"
, "booksuggestions,53715"
, "BoomBeach,10288"
, "boop,34592"
, "BorderCollie,5289"
, "Borderlands2,42577"
, "Borderlands,66180"
, "borrow,4287"
, "borussiadortmund,6204"
, "boston,53540"
, "BostonBruins,13916"
, "bostonceltics,11780"
, "BostonTerrier,6458"
, "botsrights,8562"
, "boulder,8485"
, "bouldering,16196"
, "bourbon,27782"
, "Boxer,7302"
, "Boxing,34148"
, "boxoffice,12419"
, "BPD,9526"
, "BPDlovedones,1652"
, "braces,1244"
, "Brampton,1399"
, "brandnew,8326"
, "brasil2,376"
, "brasil,43923"
, "bravefrontier,28337"
, "BPI:NAME:<NAME>END_PIveryjerk,18373"
, "Braves,11507"
, "BravestWarriors,9697"
, "BravoRealHousewives,3609"
, "Brawlhalla,3280"
, "Breadit,38587"
, "breakingbad,226518"
, "breakingmom,12082"
, "breastfeeding,11418"
, "Briggs,1412"
, "brisbane,15228"
, "bristol,5743"
, "BritishPolitics,3226"
, "britishproblems,112238"
, "BritishSuccess,17782"
, "BritishTV,25517"
, "britpics,17149"
, "Brogress,22861"
, "brokehugs,930"
, "brokengifs,39373"
, "Brooklyn,14035"
, "brooklynninenine,13368"
, "Browns,12674"
, "brum,2583"
, "BSG,17676"
, "btc,5936"
, "buccaneers,4970"
, "buccos,5494"
, "Buddhism,91326"
, "budgetfood,89715"
, "Buffalo,7561"
, "buffalobills,9056"
, "BuffaloWizards,4412"
, "buffy,18868"
, "bugout,11582"
, "buildapc,332244"
, "buildapcforme,36022"
, "buildapcsales,118479"
, "Bulldogs,9916"
, "Bullshitfacts,100"
, "BurningMan,16533"
, "Bushcraft,22441"
, "business,201584"
, "Buttcoin,6712"
, "BuyItForLife,187865"
, "ByTheMods,178"
, "c137,8148"
, "C25K,45786"
, "cablefail,18510"
, "CableManagement,20962"
, "cableporn,58421"
, "PI:NAME:<NAME>END_PI,499"
, "CafeRacers,10591"
, "CAguns,1342"
, "cahideas,5342"
, "CalamariRaceTeam,8602"
, "CalPI:NAME:<NAME>END_PIary,18553"
, "CalgaryFlames,3872"
, "California,28005"
, "CaliforniaForSanders,2977"
, "Calligraphy,30726"
, "CallOfDuty,18139"
, "calvinandhobbes,109777"
, "PI:NAME:<NAME>END_PI,4841"
, "camping,52059"
, "CampingandHiking,106021"
, "canada,202444"
, "canadaguns,5588"
, "CanadaPolitics,24321"
, "Canadian_ecigarette,3086"
, "CanadianForces,5094"
, "canberra,3324"
, "cancer,6940"
, "candiceswanepoel,6678"
, "canes,1853"
, "CanineCosplay,2041"
, "cannabis,29817"
, "CannabisExtracts,23362"
, "canon,4748"
, "canucks,12026"
, "caps,7537"
, "capstone,1876"
, "CaptchaArt,16528"
, "PI:NAME:<NAME>END_PI,5521"
, "PI:NAME:<NAME>END_PI,10821"
, "carcrash,15916"
, "Cardinals,10645"
, "cardistry,6647"
, "careerguidance,14037"
, "PI:NAME:<NAME>END_PIletonU,1893"
, "carnivalclan,10"
, "PI:NAME:<NAME>END_PI,1513"
, "carporn,130914"
, "cars,181029"
, "Cartalk,25622"
, "caseyneistat,4144"
, "cassetteculture,5086"
, "castiron,13780"
, "CastleClash,1702"
, "castles,29368"
, "CastleTV,7685"
, "CasualConversation,105758"
, "casualiama,90386"
, "casualminecrafting,782"
, "casualnintendo,6267"
, "cataclysmdda,2095"
, "CatastrophicFailure,25039"
, "catbellies,8016"
, "CatGifs,27205"
, "CatHighFive,12747"
, "Catholicism,21215"
, "Catloaf,17258"
, "catpictures,55448"
, "cats,312768"
, "CatsAreAssholes,9683"
, "CatsInSinks,8154"
, "CatSlaps,10293"
, "catssittingdown,2902"
, "CatsStandingUp,56499"
, "CautiousBB,2491"
, "CCJ2,992"
, "CCW,26379"
, "CelebGfys,11641"
, "celeb_redheads,5133"
, "CelebrityArmpits,2054"
, "CelebrityFeet,5430"
, "Celebs,174806"
, "Cello,3627"
, "CFB,154117"
, "cfbball,2270"
, "cfbcirclejerk,1170"
, "CFBOffTopic,1829"
, "CFL,4825"
, "CGPGrey,43053"
, "changemyview,214363"
, "charactercrossovers,8297"
, "characterdrawing,11157"
, "CharacterRant,719"
, "Charcuterie,14267"
, "Chargers,9499"
, "Charleston,5065"
, "Charlotte,9223"
, "CharlotteHornets,3203"
, "Chattanooga,4290"
, "Cheese,10036"
, "chelseafc,22362"
, "ChemicalEngineering,5494"
, "chemicalreactiongifs,150902"
, "chemistry,63462"
, "CherokeeXJ,3482"
, "chess,43056"
, "CHIBears,20971"
, "chicago,75767"
, "chicagobulls,18884"
, "chickyboo,66"
, "CHICubs,7236"
, "ChiefKeef,2026"
, "Chihuahua,5681"
, "childfree,91356"
, "ChildrenFallingOver,69583"
, "chile,10669"
, "chiliadmystery,18929"
, "chillmusic,27584"
, "chillstep,11022"
, "China,26200"
, "ChineseLanguage,13675"
, "Chipotle,3245"
, "ChivalryGame,9331"
, "chloegracemoretz,12169"
, "chomsky,4922"
, "Christianity,107140"
, "christmas,10728"
, "chrome,32514"
, "Chromecast,51459"
, "chromeos,19097"
, "ChronicPain,6516"
, "chronotrigger,3598"
, "chuck,8789"
, "churning,32003"
, "cider,5157"
, "Cigarettes,4701"
, "cigars,33349"
, "cincinnati,13085"
, "Cinema4D,6713"
, "Cinemagraphs,112881"
, "CinemaSins,9200"
, "cinematography,15325"
, "CineShots,14842"
, "circlebroke2,6744"
, "circlebroke,34885"
, "circlejerk,271122"
, "circlejerkaustralia,2226"
, "cirkeltrek,2867"
, "CitiesSkylines,98594"
, "CityPorn,151648"
, "civ,133370"
, "civbattleroyale,7742"
, "civbeyondearth,10605"
, "civcirclejerk,3223"
, "Civcraft,7401"
, "civilengineering,4274"
, "CivilizatonExperiment,1265"
, "CivPolitics,21726"
, "CK2GameOfthrones,6724"
, "cky,496"
, "Clannad,3381"
, "ClashOfClans,81525"
, "classic4chan,85772"
, "classicalmusic,64714"
, "classiccars,17450"
, "ClassicRock,10769"
, "ClassyPornstars,15318"
, "cleanjokes,14002"
, "cleganebowl,5624"
, "Cleveland,11225"
, "clevelandcavs,9808"
, "CleverEdits,5346"
, "CLG,13686"
, "ClickerHeroes,15511"
, "climate,12966"
, "climateskeptics,6888"
, "climbing,72122"
, "Cloud9,4537"
, "Coachella,10822"
, "coaxedintoasnafu,17506"
, "cockatiel,2267"
, "cocktails,33081"
, "CodAW,24135"
, "CoDCompetitive,20874"
, "coding,66960"
, "CODZombies,13852"
, "COents,6279"
, "Coffee,110879"
, "Coilporn,13994"
, "coins,10866"
, "Coldplay,5509"
, "collapse,41520"
, "college,28864"
, "CollegeBasketball,61219"
, "collegehockey,3666"
, "Colorado,19638"
, "ColoradoAvalanche,4951"
, "ColoradoSprings,3994"
, "ColorBlind,4621"
, "Colorization,26156"
, "ColorizedHistory,99105"
, "Colts,8260"
, "PI:NAME:<NAME>END_PI,15298"
, "CombatFootage,77124"
, "combinedgifs,65130"
, "Comcast,2689"
, "comedy,28699"
, "comedybangbang,4013"
, "ComedyCemetery,10477"
, "comeonandslam,35693"
, "comicbookart,22250"
, "ComicBookCollabs,2817"
, "comicbookcollecting,1402"
, "comicbookmovies,17976"
, "comicbooks,160279"
, "comics,441001"
, "ComicWalls,11362"
, "commandline,22571"
, "CommercialCuts,30783"
, "communism101,6139"
, "communism,15299"
, "CommunismWorldwide,1627"
, "community,150790"
, "CompanyOfHeroes,6707"
, "CompetitiveEDH,3559"
, "CompetitiveHalo,3326"
, "CompetitiveHS,47685"
, "CompetitiveWoW,4515"
, "COMPLETEANARCHY,394"
, "compsci,94243"
, "computergraphics,12259"
, "computers,16264"
, "computertechs,15891"
, "confession,113513"
, "confessions,22184"
, "ConfusedTravolta,17331"
, "confusing_perspective,14521"
, "conlangs,8793"
, "Connecticut,10794"
, "Connery,1290"
, "Conservative,52253"
, "conservatives,3923"
, "consoledeals,18933"
, "consoles,5770"
, "conspiracy,345872"
, "conspiracyfact,2849"
, "ConspiracyGrumps,5407"
, "conspiratard,51165"
, "Constantine,4566"
, "Construction,6652"
, "consulting,12968"
, "ContagiousLaughter,132132"
, "contentawarescale,4899"
, "ContestOfChampions,3794"
, "Cooking,333643"
, "cookingvideos,17475"
, "coolgithubprojects,12806"
, "coolguides,94291"
, "copypasta,13476"
, "cordcutters,94372"
, "corgi,83554"
, "CorporateFacepalm,31639"
, "cosplay,137953"
, "cosplaygirls,134349"
, "Costco,3709"
, "counterstrike,22326"
, "counting,8140"
, "country,7503"
, "coupons,40863"
, "cowboybebop,11659"
, "cowboys,18201"
, "Coyotes,1832"
, "coys,13596"
, "CozyPlaces,32862"
, "cpp,33338"
, "C_Programming,18035"
, "Cr1TiKaL,2588"
, "CrackStatus,2292"
, "CraftBeer,10617"
, "crafts,55168"
, "CraftyTrolls,3403"
, "Crainn,1575"
, "CrappyDesign,237472"
, "crappymusic,18421"
, "crappyoffbrands,16576"
, "CrazyHand,9295"
, "CrazyIdeas,181705"
, "CredibleDefense,10878"
, "creepy,4398297"
, "creepygaming,24434"
, "creepyPMs,158516"
, "Cricket,26375"
, "cringe,385431"
, "CringeAnarchy,61496"
, "cringepics,583381"
, "cripplingalcoholism,21723"
, "criterion,4854"
, "criticalrole,2943"
, "CriticalTheory,10699"
, "croatia,11786"
, "crochet,35571"
, "CrohnsDisease,7483"
, "crossdressing,14590"
, "crossfit,36541"
, "CrossfitGirls,8882"
, "CrossStitch,13860"
, "CrossView,17811"
, "CruciblePlaybook,14983"
, "CrusaderKings,36885"
, "crusadersquest,3577"
, "crypto,29585"
, "CryptoCurrency,18837"
, "cscareerquestions,58581"
, "csgo,5317"
, "csgobetting,52532"
, "csgolounge,9997"
, "csgomarketforum,2979"
, "csharp,25499"
, "C_S_T,2115"
, "Cubers,13202"
, "CubeWorld,15976"
, "CucumbersScaringCats,20714"
, "curiosityrover,16986"
, "curlyhair,29461"
, "customhearthstone,4569"
, "custommagic,4485"
, "cute,11253"
, "cutegirlgifs,14393"
, "cuteguys,1369"
, "cutekorean,5063"
, "cutelittlefangs,1166"
, "cutouts,6122"
, "CyanideandHappiness,30836"
, "cyanogenmod,14028"
, "Cyberpunk,82363"
, "cycling,25596"
, "Cynicalbrit,55888"
, "DabArt,1043"
, "Dachshund,15446"
, "daddit,40075"
, "dadjokes,245586"
, "DadReflexes,52100"
, "DAE,17275"
, "DaftPunk,29431"
, "DailyShow,7881"
, "DailyTechNewsShow,5685"
, "DaisyRidley,1327"
, "Dallas,25779"
, "DallasStars,3831"
, "Damnthatsinteresting,146768"
, "dancarlin,3306"
, "dancegavindance,1821"
, "danganronpa,2745"
, "dankchristianmemes,13003"
, "dankmemes,11694"
, "DankNation,1331"
, "DANMAG,5078"
, "Daredevil,8712"
, "DarkEnlightenment,7829"
, "darkestdungeon,8726"
, "DarkFuturology,9937"
, "DarkNetMarketsNoobs,18225"
, "darknetplan,44075"
, "DarkSouls2,71753"
, "darksouls3,13399"
, "darksouls,82119"
, "DarthJarJar,10433"
, "Dashcam,6012"
, "dashcamgifs,13243"
, "DataHoarder,18525"
, "dataisbeautiful,4614966"
, "dataisugly,11323"
, "datascience,11962"
, "DatPI:NAME:<NAME>END_PI,9885"
, "dating,13296"
, "dating_advice,37281"
, "PI:NAME:<NAME>END_PI,2792"
, "davidtennant,5976"
, "dawngate,6220"
, "DaystromInstitute,17624"
, "dayz,112045"
, "dbz,62888"
, "DBZDokkanBattle,4102"
, "DC_Cinematic,6632"
, "DCcomics,69190"
, "dcss,2059"
, "de,25353"
, "DeadBedrooms,29380"
, "deadmau5,12463"
, "deadpool,29636"
, "DeadSpace,5586"
, "deals,25006"
, "DealsReddit,41886"
, "DealWin,80"
, "Deathcore,7633"
, "deathgrips,12664"
, "Debate,5177"
, "DebateAChristian,13626"
, "DebateaCommunist,6179"
, "DebateAnarchism,3414"
, "DebateAnAtheist,15404"
, "DebateCommunism,2942"
, "DebateFascism,1996"
, "DebateReligion,32207"
, "debian,12889"
, "DecidingToBeBetter,93400"
, "declutter,24903"
, "deepdream,20841"
, "deephouse,15805"
, "DeepIntoYouTube,142458"
, "deepweb,14568"
, "defaultgems,39649"
, "Defenders,15206"
, "de_IAmA,97400"
, "Delaware,4180"
, "Delightfullychubby,23120"
, "PI:NAME:<NAME>END_PI,1397"
, "delusionalartists,77858"
, "democrats,17204"
, "Demotivational,96858"
, "Denmark,37793"
, "Dentistry,8266"
, "PI:NAME:<NAME>END_PI,4653"
, "PI:NAME:<NAME>END_PI,30830"
, "PI:NAME:<NAME>END_PI,14461"
, "denvernuggets,2380"
, "deOhneRegeln,251"
, "depression,124996"
, "DepthHub,229662"
, "DerekSmart,357"
, "DescentIntoTyranny,6177"
, "Design,127308"
, "design_critiques,21406"
, "DesignPorn,99280"
, "DesirePath,37409"
, "DessertPorn,35858"
, "Destiny,12684"
, "DestinyTheGame,237300"
, "DestroyedTanks,4313"
, "DestructiveReaders,5756"
, "Detroit,14930"
, "detroitlions,12057"
, "DetroitPistons,3704"
, "DetroitRedWings,15784"
, "Deusex,9543"
, "devils,5355"
, "devops,10947"
, "PI:NAME:<NAME>END_PI,43453"
, "DFO,5521"
, "dfsports,10596"
, "dgu,10526"
, "DHMIS,707"
, "diabetes,12708"
, "PI:NAME:<NAME>END_PI,138207"
, "diablo3,77581"
, "Diablo3witchdoctors,9364"
, "PI:NAME:<NAME>END_PI,12541"
, "PI:NAME:<NAME>END_PI,5248"
, "digimon,12964"
, "digitalnomad,16439"
, "DigitalPainting,13354"
, "DimensionalJumping,5966"
, "Dinosaurs,31288"
, "DippingTobacco,6785"
, "dirtgame,3941"
, "Dirtybomb,9965"
, "discgolf,30366"
, "discordapp,1992"
, "discworld,14437"
, "dishonored,10526"
, "disney,60279"
, "Disney_Infinity,3854"
, "Disneyland,14792"
, "DivinityOriginalSin,9870"
, "Divorce,5435"
, "DiWHY,37561"
, "DIY,4962828"
, "DIY_eJuice,20583"
, "django,15141"
, "Djent,10102"
, "DJs,25214"
, "DMT,13018"
, "DnB,32667"
, "DnD,105398"
, "DnDBehindTheScreen,15534"
, "DnDGreentext,17156"
, "dndnext,21755"
, "docker,6166"
, "doctorwho,250183"
, "Documentaries,4580748"
, "Dodgers,10729"
, "DoesAnybodyElse,261602"
, "DoesNotTranslate,9940"
, "dogecoin,83697"
, "dogpictures,77382"
, "dogs,104862"
, "DogShowerThoughts,21093"
, "dogswearinghats,15014"
, "Dogtraining,39134"
, "donaldglover,20005"
, "dontdeadopeninside,3833"
, "DontPanic,11066"
, "dontstarve,19267"
, "doodles,17659"
, "Doom,5036"
, "doommetal,12216"
, "DotA2,258579"
, "dota2circlejerk,2798"
, "dota2dadjokes,3428"
, "Dota2Trade,12728"
, "dotamasterrace,6572"
, "dotnet,14555"
, "douglovesmovies,3111"
, "DowntonAbbey,11680"
, "Drag,5503"
, "dragonage,53735"
, "dragonblaze,1148"
, "dragons,3236"
, "Drama,17506"
, "drawing,75446"
, "Dreadfort,10290"
, "Dreadlocks,5904"
, "Dreamtheater,3460"
, "dresdenfiles,12027"
, "Drifting,13538"
, "DrugArt,8384"
, "DrugNerds,32064"
, "Drugs,228355"
, "drugscirclejerk,3598"
, "DrugStashes,8402"
, "drumcorps,5752"
, "drums,33872"
, "drunk,114115"
, "drunkenpeasants,1757"
, "DrunkOrAKid,65715"
, "drupal,6221"
, "Dualsport,9345"
, "dubai,4584"
, "DubbedGIFS,13450"
, "dubstep,89757"
, "ducks,3072"
, "duelyst,4587"
, "DumpsterDiving,24676"
, "duncantrussell,2897"
, "DunderMifflin,91474"
, "dune,7810"
, "dungeondefenders,5844"
, "DungeonsAndDragons,17802"
, "duolingo,29514"
, "dvdcollection,8984"
, "DvZ,1400"
, "dwarffortress,42783"
, "dxm,2143"
, "dyinglight,11424"
, "dykesgonemild,6450"
, "DynastyFF,3058"
, "E30,2265"
, "EAF,16034"
, "eagles,23209"
, "EA_NHL,11099"
, "earthbound,10060"
, "EarthPorn,6502343"
, "Earwolf,6522"
, "EatCheapAndHealthy,276512"
, "eatsandwiches,57048"
, "Ebay,8418"
, "EBEs,13932"
, "eCards,29022"
, "ECE,26731"
, "ecigclassifieds,11378"
, "ecig_vendors,8038"
, "Economics,236030"
, "economy,59749"
, "ecr_eu,3606"
, "EDC,85291"
, "EDH,21507"
, "Edinburgh,6329"
, "EditingAndLayout,24079"
, "editors,14771"
, "EDM,50366"
, "Edmonton,12765"
, "EdmontonOilers,4661"
, "edmprodcirclejerk,4782"
, "edmproduction,63802"
, "education,47548"
, "educationalgifs,115945"
, "Eesti,6153"
, "eFreebies,53414"
, "Egalitarianism,4904"
, "ElderScrolls,19349"
, "elderscrollsonline,67599"
, "eldertrees,48435"
, "ElectricForest,6570"
, "electricians,9406"
, "electricvehicles,4764"
, "electronic_cigarette,114500"
, "electronicmusic,138356"
, "electronics,53757"
, "EliteDangerous,55641"
, "EliteHudson,1081"
, "EliteLavigny,1954"
, "EliteOne,3825"
, "elonmusk,6205"
, "PI:NAME:<NAME>END_PIHosPI:NAME:<NAME>END_PI,2291"
, "PI:NAME:<NAME>END_PIanna,6510"
, "ELTP,492"
, "emacs,11891"
, "EmDrive,4569"
, "Emerald_Council,1265"
, "EmeraldPS2,2312"
, "PI:NAME:<NAME>END_PI,15573"
, "PI:NAME:<NAME>END_PI,14364"
, "Eminem,13876"
, "PI:NAME:<NAME>END_PI,5105"
, "EmmaStone,26948"
, "PI:NAME:<NAME>END_PI,78697"
, "Emo,5639"
, "emojipasta,2438"
, "EmpireDidNothingWrong,5436"
, "ems,17159"
, "emulation,28880"
, "EndlessLegend,5083"
, "EndlessWar,11999"
, "energy,55095"
, "ENFP,7060"
, "engineering,104185"
, "EngineeringPorn,45885"
, "EngineeringStudents,51259"
, "engrish,11043"
, "Enhancement,75265"
, "enlightenedbirdmen,30500"
, "EnoughLibertarianSpam,9844"
, "enoughsandersspam,741"
, "entertainment,173904"
, "Entomology,8920"
, "entp,5604"
, "Entrepreneur,166649"
, "entwives,14075"
, "environment,146550"
, "EOOD,19281"
, "EpicMounts,5474"
, "EQNext,8756"
, "EqualAttraction,9684"
, "Equestrian,5357"
, "ericprydz,1932"
, "esports,11919"
, "ethereum,6650"
, "ethoslab,4633"
, "Etsy,16338"
, "eu4,32332"
, "europe,537859"
, "european,10269"
, "EuropeMeta,259"
, "europes,1507"
, "evangelion,17166"
, "Eve,56006"
, "evenwithcontext,31703"
, "eveological,25"
, "everquest,3755"
, "Everton,5136"
, "everymanshouldknow,242753"
, "EverythingScience,55621"
, "EVEX,12202"
, "EvilLeagueOfEvil,8410"
, "evolution,21123"
, "EvolveGame,9577"
, "excel,38541"
, "exchristian,8523"
, "exjw,8025"
, "exmormon,25885"
, "exmuslim,10826"
, "ExNoContact,3289"
, "exo,1394"
, "exoticspotting,8165"
, "ExpectationVsReality,100161"
, "explainlikedrcox,34458"
, "explainlikeIAmA,96385"
, "ExplainLikeImCalvin,47635"
, "explainlikeimfive,6846145"
, "ExplainLikeImPHD,11743"
, "ExposurePorn,68975"
, "Eyebleach,150127"
, "eyes,17399"
, "F1FeederSeries,1888"
, "f7u12_ham,6379"
, "FA30plus,538"
, "facebookdrama,7467"
, "facebookwins,53333"
, "facepalm,408876"
, "fairytail,18521"
, "fakealbumcovers,4364"
, "fakeid,10282"
, "falcons,8897"
, "Fallout,304961"
, "Fallout4,14098"
, "Fallout4Builds,3199"
, "Fallout4_ja,192"
, "FallOutBoy,5424"
, "falloutequestria,2519"
, "falloutlore,15668"
, "FalloutMods,9901"
, "falloutsettlements,13645"
, "falloutshelter,4096"
, "familyguy,25344"
, "FancyFollicles,77989"
, "fandomnatural,3460"
, "FanFiction,5293"
, "fantanoforever,4289"
, "Fantasy,87143"
, "fantasybaseball,17120"
, "fantasybball,14718"
, "fantasyfootball,160969"
, "Fantasy_Football,5605"
, "fantasyhockey,8947"
, "FantasyPL,17103"
, "FantasyWarTactics,386"
, "fantasywriters,15701"
, "FanTheories,163226"
, "FargoTV,14383"
, "farming,13773"
, "FashionReps,6721"
, "fasting,9539"
, "fatestaynight,6850"
, "fatlogic,116533"
, "fatpeoplestories,107408"
, "Favors,30877"
, "fcbayern,7483"
, "fcs,1613"
, "FearTheWalkingDead,16575"
, "feedthebeast,26505"
, "FeelsLikeTheFirstTime,37234"
, "FellowKids,69315"
, "femalefashionadvice,117403"
, "Feminism,54932"
, "feminisms,29926"
, "FemmeThoughts,7741"
, "FeMRADebates,4088"
, "Fencing,5323"
, "FenerbahceSK,421"
, "ferrets,11126"
, "festivals,17253"
, "Fez,1386"
, "fffffffuuuuuuuuuuuu,586149"
, "FFRecordKeeper,8706"
, "ffxi,4739"
, "ffxiv,84399"
, "FierceFlow,6322"
, "FIFA,56885"
, "FifaCareers,11352"
, "fifthworldproblems,57276"
, "Fighters,10406"
, "Filmmakers,71513"
, "PI:NAME:<NAME>END_PI,10673"
, "FinalFantasy,50546"
, "finance,69808"
, "FinancialCareers,8026"
, "financialindependence,102734"
, "findapath,21112"
, "findareddit,40022"
, "Finland,9119"
, "Firearms,30216"
, "fireemblem,26359"
, "fireemblemcasual,1316"
, "firefall,4912"
, "Firefighting,9907"
, "firefly,76407"
, "firefox,23600"
, "Fireteams,51572"
, "fireTV,5788"
, "firstimpression,14369"
, "firstworldanarchists,281557"
, "FirstWorldConformists,11139"
, "firstworldproblems,157362"
, "Fishing,54308"
, "FitAndNatural,16547"
, "fitbit,13931"
, "fitmeals,125675"
, "Fitness,4850074"
, "fitnesscirclejerk,7865"
, "Fiveheads,8558"
, "FiveM,1791"
, "fivenightsatfreddys,17394"
, "FixedGearBicycle,23119"
, "Flagstaff,1493"
, "flashlight,12573"
, "FlashTV,47356"
, "flexibility,34107"
, "flicks,12974"
, "flightsim,12125"
, "Flipping,35830"
, "Floof,10597"
, "florida,12400"
, "FloridaGators,4319"
, "FloridaMan,122022"
, "Flyers,11064"
, "flyfishing,12324"
, "flying,30355"
, "fnafcringe,2614"
, "fnv,20981"
, "fo3,8039"
, "fo4,147215"
, "FO4mods,366"
, "FocusST,1754"
, "FoggyPics,10716"
, "folk,13476"
, "FolkPunk,15942"
, "food,4730209"
, "Foodforthought,157028"
, "foodhacks,95996"
, "FoodPorn,413543"
, "Foofighters,8927"
, "football,26489"
, "footballdownload,15273"
, "footballhighlights,27801"
, "footballmanagergames,23502"
, "footbaww,7007"
, "Ford,8074"
, "fordranger,1848"
, "forearmporn,11124"
, "ForeverAlone,42226"
, "ForeverAloneWomen,4718"
, "Forex,8666"
, "forhire,55995"
, "formula1,95331"
, "forsen,2524"
, "forwardsfromgrandma,70486"
, "forwardsfromhitler,5416"
, "forwardsfromreddit,844"
, "PI:NAME:<NAME>END_PI,14659"
, "foshelter,20679"
, "fountainpens,27552"
, "foxes,40002"
, "FPI:NAME:<NAME>END_PI,836"
, "fpvracing,5746"
, "fragrance,7844"
, "FragReddit,2859"
, "france,60157"
, "FranceLibre,763"
, "Frat,12810"
, "FRC,4624"
, "FreckledGirls,20055"
, "fredericton,1494"
, "FREE,16458"
, "FreeAtheism,1890"
, "freebies,351125"
, "FreeEBOOKS,45558"
, "FreeGameFindings,18033"
, "FreeGamesOnSteam,17645"
, "FreeKarma,13252"
, "freelance,27254"
, "freemasonry,6723"
, "FreeStuff,2104"
, "Freethought,43922"
, "French,27660"
, "FrenchForeignLegion,1126"
, "fresh_funny,2026"
, "fresno,2417"
, "Frisson,116693"
, "frogdogs,5541"
, "frogpants,924"
, "Frontend,14215"
, "FrontPage,5480"
, "Frozen,10432"
, "Frugal,516065"
, "FrugalFemaleFashion,23062"
, "Frugal_Jerk,30490"
, "frugalmalefashion,186054"
, "FrugalMaleFashionCDN,2892"
, "fsu,4512"
, "ft86,5081"
, "ftlgame,27565"
, "ftm,6808"
, "fuckingmanly,23970"
, "FuckingWithNature,26038"
, "fuckmusic,6714"
, "fuckolly,11440"
, "FuckTammy,2619"
, "Fuee,600"
, "FulfillmentByAmazon,7575"
, "FULLCOMMUNISM,12094"
, "fulllife,3927"
, "FullmetalAlchemist,14565"
, "fullmoviesongoogle,24619"
, "fullmoviesonyoutube,210823"
, "functionalprint,6624"
, "funhaus,49438"
, "funk,5940"
, "funkopop,8582"
, "funny,10101609"
, "FunnyandSad,29572"
, "funnysigns,13588"
, "furry,21671"
, "FurryHate,972"
, "FUTMobile,547"
, "futurama,141894"
, "futurebeats,60157"
, "FutureFight,3503"
, "futurefunk,4594"
, "futureporn,64894"
, "FutureWhatIf,17484"
, "Futurology,4595097"
, "gadgets,4642305"
, "gainit,79436"
, "GakiNoTsukai,19468"
, "galatasaray,1097"
, "galaxynote4,9060"
, "galaxynote5,2911"
, "galaxys5,8896"
, "GalaxyS6,9726"
, "gallifrey,50639"
, "Gameboy,7061"
, "gamecollecting,32836"
, "GameDeals,345705"
, "GameDealsMeta,5785"
, "gamedesign,23159"
, "gamedev,147807"
, "gameDevClassifieds,16322"
, "gamegrumps,82577"
, "gamemaker,9003"
, "gamemusic,44931"
, "gameofthrones,589306"
, "GamePhysics,134872"
, "GamerGhazi,9042"
, "gamernews,105654"
, "gamers,4586"
, "Games,669391"
, "GameSale,7647"
, "GameStop,2927"
, "gameswap,18094"
, "gametales,22621"
, "gamindustri,1854"
, "Gaming4Gamers,31124"
, "gaming,9188228"
, "Gamingcirclejerk,5930"
, "gaminggifs,6554"
, "gamingpc,42932"
, "gamingsuggestions,16755"
, "gangstaswithwaifus,10893"
, "gardening,123705"
, "GarlicBreadMemes,3860"
, "gatech,8121"
, "gats,10032"
, "gay,23383"
, "gaybros,56722"
, "gaybroscirclejerk,2539"
, "gaybrosgonemild,9501"
, "gaymers,43889"
, "GearsOfWar,9954"
, "GearVR,4157"
, "geek,312760"
, "geekboners,5302"
, "GeekPorn,35545"
, "geekygirls,5095"
, "GenderCritical,1916"
, "Gender_Critical,889"
, "GenderCynical,792"
, "genderqueer,9428"
, "gentlemanboners,360639"
, "gentlemanbonersgifs,28072"
, "gentlemangabers,4874"
, "geocaching,21065"
, "geography,19815"
, "geology,29271"
, "geometrydash,601"
, "geopolitics,30051"
, "German,15722"
, "germanshepherds,16158"
, "germany,28099"
, "getdisciplined,151245"
, "GetMotivated,4611698"
, "GetStudying,40202"
, "GettingDoug,1294"
, "GGdiscussion,763"
, "GGFreeForAll,95"
, "ggggg,16811"
, "ghettoglamourshots,38985"
, "ghibli,26297"
, "Ghostbc,1744"
, "Ghosts,19927"
, "giantbomb,7143"
, "gif,122474"
, "gifextra,35175"
, "GifRecipes,21728"
, "gifs,7066012"
, "GifSound,53551"
, "gifsthatendtoosoon,1718"
, "GiftofGames,30220"
, "GifTournament,17834"
, "Gifts,3982"
, "gigantic,3846"
, "GilmoreGirls,5296"
, "gingerkitty,1392"
, "Gintama,3149"
, "GirlGamers,36779"
, "GirlsMirin,21667"
, "GirlsPlayingSports,13143"
, "girls_smiling,8446"
, "GIRLSundPANZER,1248"
, "gis,10635"
, "glasgow,6963"
, "glassheads,25367"
, "glitch_art,43871"
, "Glitch_in_the_Matrix,104084"
, "GlobalOffensive,308503"
, "Glocks,11491"
, "glutenfree,17907"
, "gmod,11149"
, "goats,7944"
, "goddesses,22908"
, "GODZILLA,12182"
, "golang,18078"
, "goldenretrievers,16491"
, "goldredditsays,9226"
, "golf,61420"
, "GolfGTI,6754"
, "GolfReimagined,148"
, "gonecivil,33535"
, "GoNets,2417"
, "goodyearwelt,20776"
, "google,79105"
, "GoogleCardboard,13482"
, "googleplaydeals,22385"
, "gopro,43411"
, "gorillaz,11743"
, "goth,4870"
, "Gotham,20579"
, "GradSchool,20248"
, "Graffiti,66997"
, "grandorder,3226"
, "grandrapids,6316"
, "GrandTheftAutoV,169918"
, "GrandTheftAutoV_PC,38186"
, "graphic_design,79684"
, "GrassHopperVape,1906"
, "gratefuldead,16541"
, "gravityfalls,33891"
, "GreatFist,6"
, "GreatXboxDeals,3977"
, "greece,13562"
, "GreenBayPackers,30530"
, "GreenDawn,33791"
, "greenday,6728"
, "greentext,43301"
, "Greyhounds,5411"
, "greysanatomy,8353"
, "grilledcheese,39396"
, "Grimdawn,2522"
, "grime,9691"
, "grimm,5516"
, "GTA,36641"
, "GTAgifs,21502"
, "gtaonline,27712"
, "GTAV,65342"
, "gtavcustoms,7646"
, "gtfoDerrickandArmand,95"
, "GuessTheMovie,14261"
, "Guildwars2,133098"
, "GuiltyPleasureMusic,13769"
, "guineapigs,9095"
, "Guitar,163275"
, "guitarcirclejerk,3475"
, "GuitarHero,1836"
, "guitarlessons,47594"
, "guitarpedals,19228"
, "guitarporn,10266"
, "guitars,7560"
, "guncontrol,1595"
, "Gundam,14360"
, "gundeals,21504"
, "Gunners,45709"
, "Gunpla,13781"
, "gunpolitics,8277"
, "GunPorn,50580"
, "guns,232698"
, "GunsAreCool,9994"
, "Gunsforsale,13627"
, "h1z1,40035"
, "h3h3productions,22035"
, "Habs,8478"
, "hackernews,6808"
, "hacking,80182"
, "hackintosh,17541"
, "Hadouken,1472"
, "HadToHurt,19860"
, "HailCorporate,60479"
, "Hair,20620"
, "HalfLife,24676"
, "halifax,9732"
, "halo,131907"
, "HaloCirclejerk,524"
, "HaloOnline,12169"
, "HaloStory,8405"
, "Hamilton,5399"
, "Hammers,2399"
, "Hammocks,19164"
, "hamsters,3764"
, "Handwriting,25035"
, "HannibalTV,24096"
, "hapas,587"
, "happy,92205"
, "happycrowds,42881"
, "happygirls,39178"
, "HappyTrees,5981"
, "HappyWars,739"
, "hardbodies,97399"
, "Hardcore,13750"
, "hardcoreaww,43074"
, "hardstyle,10089"
, "hardware,79340"
, "hardwareswap,26206"
, "PI:NAME:<NAME>END_PI,10855"
, "PI:NAME:<NAME>END_PIinn,5352"
, "Harmontown,10149"
, "PI:NAME:<NAME>END_PI,1873"
, "harrypotter,217025"
, "Haruhi,2355"
, "harvestmoon,6455"
, "haskell,22579"
, "Hatfilms,13319"
, "Hawaii,11018"
, "hawks,17957"
, "headphones,56910"
, "Health,115920"
, "hearthstone,313065"
, "hearthstonecirclejerk,2257"
, "heat,7728"
, "Heavymind,74208"
, "Hedgehog,8897"
, "Helicopters,7842"
, "Helldivers,3062"
, "HelloInternet,7123"
, "help,6051"
, "HelpMeFind,4643"
, "heraldry,4552"
, "HereComesTheBoom,8768"
, "HeresAFunFact,19823"
, "Heroes,4819"
, "HeroesandGenerals,3498"
, "HeroesOfAsgard,11"
, "HeroesofNewerth,10607"
, "heroesofthestorm,118071"
, "HPI:NAME:<NAME>END_PICarl,28011"
, "HFY,28174"
, "hiddenwow,8947"
, "HIFW,33805"
, "highdeas,19022"
, "HighHeels,19351"
, "HighQualityGifs,91151"
, "HighschoolDxD,4903"
, "HighStrangeness,4370"
, "HighwayFightSquad,8875"
, "hiking,46682"
, "hillaryclinton,1119"
, "HIMYM,88622"
, "hinduism,5767"
, "Hiphopcirclejerk,8792"
, "hiphopheads,337054"
, "HipHopImages,24218"
, "history,4649879"
, "HistoryPorn,486198"
, "HistoryWhatIf,9016"
, "HiTMAN,3297"
, "hitmanimals,13868"
, "HITsWorthTurkingFor,32723"
, "hittableFaces,4928"
, "hockey,226078"
, "hockeyjerseys,3446"
, "hockeyplayers,7732"
, "hockeyquestionmark,934"
, "hoggit,5964"
, "holdmybeaker,22369"
, "holdmybeer,213117"
, "holdmycatnip,18388"
, "holdmyfries,19601"
, "holdmyjuicebox,27371"
, "HoldMyNip,18121"
, "homeautomation,16888"
, "Homebrewing,120095"
, "homegym,14280"
, "HomeImprovement,54575"
, "homelab,27716"
, "homeland,17083"
, "HomeNetworking,10982"
, "homeowners,9378"
, "HomestarRunner,24853"
, "homestead,47084"
, "homestuck,18689"
, "hometheater,22741"
, "homura,1483"
, "Honda,16355"
, "HongKong,14603"
, "hookah,20289"
, "Hookers,5647"
, "HorriblyDepressing,20009"
, "horror,84436"
, "Horses,11687"
, "Hot100,3252"
, "HotlineMiami,9417"
, "HotWheels,1735"
, "Hot_Women_Gifs,33863"
, "House,27365"
, "HouseOfCards,54259"
, "Houseporn,30968"
, "houston,34659"
, "howardstern,15679"
, "howto,158408"
, "HowToHack,31916"
, "howtonotgiveafuck,147936"
, "howyoudoin,22164"
, "HPfanfiction,6315"
, "HPMOR,8467"
, "HSPulls,2863"
, "htcone,10216"
, "htgawm,6413"
, "htpc,13070"
, "httyd,3841"
, "HumanFanClub,1570"
, "Humanoidencounters,5213"
, "HumanPorn,118208"
, "HumansBeingBros,65185"
, "humblebrag,14155"
, "humor,329136"
, "humorousreviews,19933"
, "hungary,9276"
, "Hungergames,19389"
, "HunterXHunter,13951"
, "Hunting,31309"
, "HuntsvilleAlabama,4067"
, "Huskers,3898"
, "huskies,1980"
, "husky,13747"
, "HVAC,4840"
, "hwatch,980"
, "HybridAnimals,42208"
, "HyruleWarriors,3185"
, "IAmA,9726122"
, "iamverysmart,159490"
, "IASIP,96036"
, "IBO,3428"
, "ICanDrawThat,31539"
, "Iceland,12169"
, "IDAP,30861"
, "ideasfortheadmins,8233"
, "IdentityIrelandForum,34"
, "IdiotsFightingThings,128970"
, "IdiotsInCars,4024"
, "IDontWorkHereLady,37442"
, "ifiwonthelottery,42974"
, "ifyoulikeblank,52089"
, "IgnorantImgur,16797"
, "IHE,1387"
, "iiiiiiitttttttttttt,32382"
, "ik_ihe,1138"
, "IllBeYourGuide,9083"
, "illegaltorrents,11111"
, "illumineighti,490"
, "illusionporn,58662"
, "Illustration,21963"
, "im14andthisisdeep,55244"
, "im14andthisisfunny,25233"
, "ImageComics,6553"
, "Images,47758"
, "ImagesOfUSA,48"
, "ImageStabilization,25762"
, "ImaginaryAngels,2663"
, "ImaginaryAww,7704"
, "ImaginaryAzeroth,3102"
, "ImaginaryBehemoths,9289"
, "ImaginaryCharacters,37374"
, "ImaginaryCityscapes,28484"
, "ImaginaryDragons,5293"
, "ImaginaryFallout,6973"
, "ImaginaryFeels,3287"
, "ImaginaryJedi,13900"
, "ImaginaryLandscapes,98649"
, "ImaginaryLeviathans,24350"
, "imaginarymaps,19317"
, "ImaginaryMindscapes,35118"
, "ImaginaryMonsters,88910"
, "ImaginarySpidey,317"
, "ImaginaryTechnology,55885"
, "ImaginaryTurtleWorlds,9020"
, "ImaginaryWarhammer,4822"
, "ImaginaryWarriors,3478"
, "ImaginaryWesteros,27040"
, "ImaginaryWitches,7657"
, "immigration,2801"
, "incest_relationships,4221"
, "incremental_games,21851"
, "india,46194"
, "IndiaMain,685"
, "Indiana,7645"
, "IndianaHoosiers,961"
, "indianapolis,8382"
, "IndianCountry,1426"
, "indianews,3654"
, "indiangirls,11879"
, "indianpeoplefacebook,54479"
, "indiegames,9359"
, "IndieGaming,64410"
, "indieheads,33941"
, "indieheadscirclejerk,677"
, "Indiemakeupandmore,17239"
, "indie_rock,31056"
, "indonesia,10529"
, "industrialmusic,7165"
, "INDYCAR,5242"
, "infertility,3454"
, "infj,12763"
, "Infographics,54812"
, "infp,14006"
, "InfrastructurePorn,47705"
, "INGLIN,14207"
, "Ingress,26304"
, "InjusticeMobile,2315"
, "Instagram,6611"
, "instantkarma,5075"
, "instant_regret,140320"
, "Insurance,6637"
, "insurgency,11227"
, "Intactivists,1915"
, "Intelligence,16493"
, "InterdimensionalCable,3957"
, "interestingasfuck,585343"
, "InterestingGifs,10988"
, "InteriorDesign,78065"
, "InternetHitlers,582"
, "InternetIsBeautiful,4730001"
, "internetparents,9232"
, "interstellar,11775"
, "inthenews,29637"
, "intj,23690"
, "intothebadlands,922"
, "INTP,19991"
, "introvert,55938"
, "intrusivethoughts,26207"
, "investing,174748"
, "InvisiBall,12331"
, "ios,22523"
, "ios9,6165"
, "iosgaming,29362"
, "iOSProgramming,22218"
, "iOSthemes,25327"
, "Iowa,6674"
, "ipad,45859"
, "iphone,156101"
, "iRacing,4028"
, "iran,6494"
, "iranian,685"
, "ireland,68157"
, "IRLgirls,4787"
, "ironmaiden,2812"
, "IronThronePowers,447"
, "IsItBullshit,18975"
, "islam,29553"
, "IslamUnveiled,1197"
, "isometric,10486"
, "Israel,21403"
, "IsraelPalestine,458"
, "isrconspiracyracist,2250"
, "istp,2848"
, "italy,33816"
, "ITCareerQuestions,8018"
, "ITcrowd,10032"
, "itmejp,7686"
, "itookapicture,177377"
, "ITSAPRANK,15459"
, "itsaunixsystem,34068"
, "iWallpaper,32156"
, "IWantOut,53730"
, "IWantToLearn,165699"
, "iZombie,5513"
, "JacksFilms,1171"
, "jacksonville,4712"
, "PI:NAME:<NAME>END_PIsonWrites,9891"
, "jag_ivl,802"
, "PI:NAME:<NAME>END_PI,3980"
, "jailbreak,105777"
, "jakeandamir,11311"
, "PI:NAME:<NAME>END_PI,14555"
, "JaneTheVirginCW,865"
, "japan,67086"
, "japan_anime,2593"
, "japancirclejerk,2747"
, "JapaneseGameShows,46793"
, "JapaneseWatches,1174"
, "japanlife,12815"
, "japanpics,23576"
, "JapanTravel,9316"
, "JasonEllisShow,1050"
, "java,48594"
, "javahelp,9886"
, "javascript,76138"
, "jayhawks,1941"
, "Jazz,56782"
, "jazzyhiphop,4709"
, "JPI:NAME:<NAME>END_PI,30392"
, "jellybeantoes,12844"
, "PI:NAME:<NAME>END_PI,44301"
, "Jeopardy,6809"
, "jerktalkdiamond,964"
, "PI:NAME:<NAME>END_PI,4399"
, "PI:NAME:<NAME>END_PI,27798"
, "PI:NAME:<NAME>END_PI,2762"
, "Jobs4Bitcoins,9211"
, "jobs,74822"
, "joerogan2,2010"
, "PI:NAME:<NAME>END_PI,38103"
, "PI:NAME:<NAME>END_PI,6286"
, "PI:NAME:<NAME>END_PI,2685"
, "joinsquad,2495"
, "Jokes,4760749"
, "PI:NAME:<NAME>END_PI,27893"
, "PI:NAME:<NAME>END_PI,28"
, "Journalism,9987"
, "JRPG,27567"
, "JPI:NAME:<NAME>END_PI,12546"
, "judo,8048"
, "JPI:NAME:<NAME>END_PIassicPark,17482"
, "JustCause,2668"
, "JustEngaged,4663"
, "Justfuckmyshitup,46142"
, "JusticePorn,431434"
, "JusticeServed,18354"
, "justlegbeardthings,5629"
, "justneckbeardthings,102908"
, "JUSTNOFAMILY,1205"
, "JUSTNOMIL,7008"
, "Justridingalong,1353"
, "Justrolledintotheshop,137533"
, "JustUnsubbed,4916"
, "PI:NAME:<NAME>END_PI,2494"
, "juxtaposition,6873"
, "jworg,9"
, "kancolle,4119"
, "kancolle_ja,315"
, "PI:NAME:<NAME>END_PI,2360"
, "kansascity,14383"
, "KansasCityChiefs,7443"
, "Kanye,16570"
, "PI:NAME:<NAME>END_PI,21399"
, "PI:NAME:<NAME>END_PI,59451"
, "PI:NAME:<NAME>END_PI,38476"
, "katawashoujo,11914"
, "katebeckinsale,6904"
, "kateupton,37670"
, "PI:NAME:<NAME>END_PI,2116"
, "katyperry,28154"
, "KCRoyals,7173"
, "KDRAMA,7567"
, "kemonomimi,6100"
, "KenM,84239"
, "PI:NAME:<NAME>END_PIala,1052"
, "KerbalAcademy,10830"
, "KerbalSpaceProgram,121287"
, "keto,163466"
, "ketogains,25281"
, "ketorecipes,65840"
, "K_gifs,10922"
, "kickstarter,30706"
, "Kikpals,20550"
, "killingfloor,16104"
, "KillLaKill,17992"
, "killthosewhodisagree,10973"
, "kindle,26216"
, "KingdomHearts,30884"
, "KingkillerChronicle,17632"
, "KingOfTheHill,27235"
, "kings,3256"
, "KissAnime,544"
, "KitchenConfidential,34771"
, "kitchener,2626"
, "kitsunemimi,4949"
, "kittens,9183"
, "kitty,3734"
, "knifeclub,18752"
, "knifeparty,2920"
, "Knife_Swap,3636"
, "knitting,40319"
, "knives,47200"
, "knowyourshit,12077"
, "kodi,11841"
, "kohi,2838"
, "kol,4511"
, "k_on,2904"
, "KoopaKiy,10"
, "korea,20000"
, "Korean,13748"
, "KoreanAdvice,6591"
, "koreanvariety,5927"
, "korrasami,6909"
, "KotakuInAction,55472"
, "kotor,9517"
, "kpics,18704"
, "kpop,42729"
, "kratom,6984"
, "kreiswichs,3233"
, "kurdistan,2771"
, "Kuwait,1016"
, "LabourUK,2155"
, "labrador,10332"
, "labrats,7696"
, "LAClippers,4318"
, "lacrosse,9361"
, "LPI:NAME:<NAME>END_PIBonPI:NAME:<NAME>END_PI,164202"
, "Ladybonersgonecuddly,31680"
, "ladyladyboners,24988"
, "lag_irl,135"
, "lakers,18289"
, "LAlist,7127"
, "languagelearning,60392"
, "lapfoxtrax,1947"
, "LARP,4653"
, "lastimages,31487"
, "LastManonEarthTV,5040"
, "lastweektonight,16324"
, "LateShow,8716"
, "LateStageCapitalism,4528"
, "latin,7977"
, "LatinaCuties,7011"
, "LatinoPeopleTwitter,8501"
, "latterdaysaints,5783"
, "LatvianJokes,29817"
, "law,43785"
, "LawSchool,19983"
, "LazyCats,7604"
, "lbregs,2338"
, "leafs,15694"
, "leagueoflegends,772616"
, "LeagueofLegendsMeta,20592"
, "LeagueOfMemes,25797"
, "LeagueOfMeta,3932"
, "leangains,39589"
, "learnart,34582"
, "learndota2,14717"
, "LearnJapanese,49640"
, "learnjavascript,18589"
, "learnmath,29221"
, "learnprogramming,230718"
, "learnpython,47237"
, "LearnUselessTalents,245147"
, "Leathercraft,11724"
, "leaves,27491"
, "lebanon,2784"
, "lebowski,7553"
, "lectures,51617"
, "ledootgeneration,34532"
, "LeedsUnited,1319"
, "LeftHanging,19665"
, "legaladvice,75471"
, "LegalAdviceUK,2253"
, "LegendsOfTomorrow,6215"
, "LegionOfSkanks,1590"
, "lego,115454"
, "lerightgeneration,2555"
, "LessCredibleDefence,1865"
, "LetsNotMeet,142079"
, "letsplay,20438"
, "LetsTalkMusic,36564"
, "Lettering,13453"
, "lewronggeneration,63017"
, "lexington,4315"
, "lgbt,112855"
, "lgbtaww,6614"
, "LGBTeens,10261"
, "LGBTnews,5280"
, "lgg2,4813"
, "LGG3,13432"
, "lgg4,7273"
, "lgv10,1098"
, "LiaMarieJohnPI:NAME:<NAME>END_PI,8477"
, "Liberal,25497"
, "liberta,614"
, "Libertarian,134095"
, "libertarianmeme,9205"
, "libreoffice,915"
, "LifeAfterNarcissism,4717"
, "lifehacks,458584"
, "lifeisstrange,15466"
, "lifeofnorman,42997"
, "LifeProTips,5364631"
, "Lightbulb,23012"
, "LightNovels,9692"
, "likeus,27387"
, "liluglymane,646"
, "limitless,1450"
, "linguistics,72224"
, "LinusFaces,1808"
, "linux,201492"
, "linux4noobs,37427"
, "LinuxActionShow,9319"
, "linuxadmin,22957"
, "LinuxCirclejerk,2407"
, "linux_gaming,30732"
, "linuxmasterrace,15392"
, "linuxmemes,4847"
, "linuxmint,9610"
, "linuxquestions,18252"
, "listentothis,4542407"
, "litecoin,23043"
, "literature,87101"
, "lithuania,7461"
, "lithuaniaspheres,170"
, "littlebuddies,3042"
, "LiveFromNewYork,14386"
, "LiverpoolFC,33829"
, "livesound,9000"
, "LivestreamFails,46881"
, "loadingicon,25972"
, "lockpicking,41217"
, "logodesign,12138"
, "logophilia,28057"
, "lol,20652"
, "LoLeventVoDs,50281"
, "LoLFanArt,12187"
, "lolphp,5776"
, "london,48744"
, "londonontario,4569"
, "lonely,7462"
, "LONESTAR,3749"
, "longbeach,3595"
, "longboarding,56516"
, "LongDistance,29853"
, "LonghornNation,3756"
, "longisland,7544"
, "longrange,10125"
, "lookatmydog,21461"
, "lootcrate,6258"
, "lootcratespoilers,575"
, "LordsOfMinecraft,2393"
, "loremasters,9296"
, "LosAngeles,63399"
, "losangeleskings,5843"
, "loseit,309143"
, "lost,34892"
, "lostgeneration,25435"
, "lotr,94656"
, "lotro,6488"
, "Louisiana,5949"
, "Louisville,8853"
, "Lovecraft,24501"
, "LoveLive,3799"
, "lowendgaming,18859"
, "lowlevelaware,1655"
, "low_poly,17242"
, "lrcast,4985"
, "LSD,46263"
, "Lubbock,2370"
, "LucidDreaming,145245"
, "Luna_Lovewell,19160"
, "LV426,17086"
, "Lyft,2093"
, "lynxes,1246"
, "M59Gar,936"
, "MAA,1446"
, "mac,50181"
, "MachineLearning,49833"
, "MachinePorn,64281"
, "Machinists,6513"
, "macsetups,15022"
, "Madden,16046"
, "MaddenBros,202"
, "MaddenMobileForums,4792"
, "MaddenUltimateTeam,7095"
, "MadeMeSmile,82836"
, "madisonwi,10112"
, "MadMax,7903"
, "madmen,41301"
, "MadokaMagica,3756"
, "Magic,16256"
, "magicduels,4012"
, "magicskyfairy,14873"
, "magicTCG,148320"
, "Maine,7790"
, "maisiewilliams,5556"
, "makemychoice,22507"
, "MakeNewFriendsHere,15706"
, "MakeupAddiction,273221"
, "MakeupAddictionCanada,1062"
, "makeupexchange,15917"
, "MakeupRehab,7273"
, "makinghiphop,23909"
, "malaysia,5913"
, "Malazan,4952"
, "malefashion,36939"
, "malefashionadvice,538227"
, "malegrooming,38964"
, "malehairadvice,53298"
, "malelifestyle,68079"
, "malelivingspace,63737"
, "mallninjashit,17858"
, "Malware,15488"
, "MAME,6656"
, "manchester,7369"
, "MandelaEffect,11096"
, "manga,68455"
, "maninthehighcastle,2115"
, "ManyATrueNerd,4569"
, "Maplestory,12626"
, "MapPorn,249184"
, "mapporncirclejerk,4503"
, "marchingband,6609"
, "Marijuana,79160"
, "marijuanaenthusiasts,39133"
, "MarineBiologyGifs,3939"
, "Mariners,8905"
, "mariokart,9416"
, "PI:NAME:<NAME>END_PIMaker,17040"
, "marketing,46823"
, "PI:NAME:<NAME>END_PIlier,7966"
, "MarkMyWords,20219"
, "Marriage,4794"
, "marriedredpill,6000"
, "PI:NAME:<NAME>END_PI,7017"
, "martialarts,24258"
, "maru,5669"
, "Marvel,128683"
, "marvelheroes,13004"
, "marvelmemes,1890"
, "MarvelPuzzleQuest,1657"
, "marvelstudios,54535"
, "maryland,10222"
, "mashups,77295"
, "massachusetts,6540"
, "massage,4547"
, "masseffect,90017"
, "MasterofNone,5495"
, "math,149766"
, "mathrock,11746"
, "Mavericks,5516"
, "MawInstallation,3496"
, "maximumfun,3798"
, "maybemaybemaybe,4849"
, "MaymayZone,6883"
, "mazda,8207"
, "mbti,8408"
, "Mcat,3458"
, "MCFC,6483"
, "mcgill,3953"
, "McKaylaMaroney,9991"
, "MCPE,7753"
, "mcpublic,6783"
, "MDMA,15857"
, "mead,11797"
, "MealPrepSunday,88222"
, "mealtimevideos,17079"
, "MeanJokes,48692"
, "MechanicAdvice,27603"
, "mechanical_gifs,42008"
, "MechanicalKeyboards,92032"
, "mechmarket,8275"
, "media_criticism,8430"
, "medical,5429"
, "medicalschool,25219"
, "medicine,62419"
, "Meditation,150324"
, "mega64,4268"
, "megalinks,9435"
, "Megaman,7232"
, "Megaten,15075"
, "Megturney,11259"
, "meirl,13683"
, "me_irl,313822"
, "melbourne,28908"
, "meme,17905"
, "memes,57158"
, "memphis,4942"
, "memphisgrizzlies,2220"
, "MensLib,5130"
, "MensRights,122643"
, "mentalhealth,14177"
, "MEOW_IRL,25889"
, "mercedes_benz,5538"
, "MerylRearSolid,175"
, "metacanada,4182"
, "Metal,109728"
, "Metalcore,27095"
, "metaldetecting,5547"
, "MetalGearPhilanthropy,2032"
, "metalgearsolid,75789"
, "MetalGearSolidV_PC,3184"
, "metaljerk,2685"
, "Metallica,6442"
, "MetalMemes,23036"
, "metanarchism,1560"
, "Metroid,13146"
, "mexico,43480"
, "mfacirclejerk,6074"
, "mflb,23250"
, "mfw,15955"
, "mgo,5968"
, "MGTOW,8676"
, "MHOC,2463"
, "Miami,9203"
, "miamidolphins,8462"
, "MPI:NAME:<NAME>END_PIHPI:NAME:<NAME>END_PIanPI:NAME:<NAME>END_PI,1377"
, "Miata,9770"
, "michaelbaygifs,54261"
, "Michigan,23179"
, "MichiganWolverines,3773"
, "microgrowery,48535"
, "microsoft,33758"
, "Mid_Century,8571"
, "migraine,5398"
, "MiiverseInAction,7435"
, "Mila_Kunis,15215"
, "milanavayntrub,12076"
, "mildlyamusing,20563"
, "mildlydepressing,8976"
, "mildlyinfuriating,266706"
, "mildlyinteresting,5089941"
, "mildlypenis,22377"
, "mildlysatisfying,8432"
, "MildlyStartledCats,10980"
, "mildyinteresting,12729"
, "mileycyrus,13625"
, "Military,76095"
, "MilitaryGfys,21869"
, "MilitaryPorn,104450"
, "MillerPlanetside,1611"
, "millionairemakers,63540"
, "milliondollarextreme,3103"
, "milwaukee,8862"
, "MimicRecipes,29631"
, "mindcrack,49548"
, "mindcrackcirclejerk,2439"
, "Mindfulness,23696"
, "Minecraft,452814"
, "minecraftsuggestions,15064"
, "MineralPorn,24006"
, "MINI,6184"
, "minimalism,181966"
, "MinimalWallpaper,11704"
, "MinionHate,31867"
, "minipainting,8721"
, "Minneapolis,12416"
, "minnesota,19056"
, "minnesotavikings,14502"
, "mirrorsedge,2840"
, "misc,25945"
, "misleadingthumbnails,74200"
, "misophonia,8220"
, "mississauga,3339"
, "mistyfront,5685"
, "MitchellAndWebb,11935"
, "MkeBucks,3085"
, "mlb,29706"
, "MLBTheShow,6142"
, "MLPLounge,11485"
, "MLS,45723"
, "MLTP,816"
, "MMA,135313"
, "MMORPG,29990"
, "ModelAusHR,35"
, "modelmakers,11087"
, "modelparliament,297"
, "Models,17605"
, "ModelsGoneMild,9217"
, "ModelUSGov,2663"
, "Modern_Family,22210"
, "ModernMagic,11226"
, "ModestMouse,8374"
, "Moescape,7400"
, "Mommit,20569"
, "MonarchyOfEquestria,164"
, "Monero,2561"
, "Monitors,9649"
, "monkslookingatbeer,21422"
, "monsteraday,2839"
, "Monstercat,19976"
, "MonstercatCringe,744"
, "MonsterHunter,49260"
, "MonsterMusume,4602"
, "montageparodies,140766"
, "montreal,23757"
, "morbidlybeautiful,20731"
, "morbidquestions,16778"
, "mormon,3610"
, "Morrowind,18329"
, "MortalKombat,24177"
, "MosinNagant,5364"
, "MostBeautiful,12475"
, "mother4,4088"
, "motivation,28121"
, "moto360,16741"
, "MotoG,7346"
, "motogp,12424"
, "motorcitykitties,8291"
, "motorcyclememes,3864"
, "motorcycles,153710"
, "MotoUK,2350"
, "MotoX,15447"
, "MountainWisdom,6372"
, "mountandblade,24536"
, "MoviePosterPorn,64136"
, "movies,8844042"
, "moviescirclejerk,7311"
, "Moviesinthemaking,36474"
, "MovieSuggestions,30708"
, "MrRobot,33987"
, "MRW,8138"
, "msp,2697"
, "MST3K,12731"
, "MTB,44173"
, "MtF,6966"
, "mtgaltered,6674"
, "mtgcube,3449"
, "mtgfinance,10617"
, "MTGLegacy,5388"
, "mturk,16614"
, "muacirclejerk,13973"
, "muacjdiscussion,4956"
, "MuayThai,11935"
, "Multicopter,27369"
, "MultipleSclerosis,3225"
, "Munich,3470"
, "MURICA,182607"
, "Muse,11557"
, "museum,30121"
, "Music,8547159"
, "musicpics,3365"
, "Musicthemetime,4042"
, "musictheory,56442"
, "Mustang,16084"
, "MvC3,7232"
, "mwo,5258"
, "mycology,28804"
, "myfriendwantstoknow,25670"
, "mylittleandysonic1,1981"
, "mylittlepony,66489"
, "mypartneristrans,3779"
, "MyPeopleNeedMe,38060"
, "MysteryDungeon,2024"
, "mythbusters,16717"
, "n64,9489"
, "NPI:NAME:<NAME>END_PIato,382"
, "namenerds,6336"
, "NamFlashbacks,3190"
, "PI:NAME:<NAME>END_PI,892"
, "nanowrimo,10847"
, "narcos,5824"
, "PI:NAME:<NAME>END_PI,66976"
, "nasa,40516"
, "NASCAR,20166"
, "nashville,11165"
, "NASLSoccer,2026"
, "PI:NAME:<NAME>END_PI,14878"
, "nathanforyou,4854"
, "NationalPark,6253"
, "nattyorjuice,2310"
, "nature,29478"
, "NatureGifs,19405"
, "natureismetal,35697"
, "navy,12037"
, "NavPI:NAME:<NAME>END_PIBlazer,2546"
, "navyseals,1318"
, "NBA2k,22976"
, "nba,329140"
, "nbacirclejerk,3587"
, "NBASpurs,8650"
, "nbastreams,16646"
, "nbaww,7361"
, "NCSU,3852"
, "NeckbeardNests,14207"
, "neckbeardstories,17714"
, "needadvice,24669"
, "Needafriend,21494"
, "needforspeed,4508"
, "Negareddit,6401"
, "nekoatsume,5459"
, "neogaming,6576"
, "neopets,12308"
, "Nepal,2449"
, "nerdcubed,30818"
, "nerdfighters,25840"
, "nerdist,8495"
, "Nerf,10215"
, "netflix,96367"
, "NetflixBestOf,293763"
, "NetflixPals,2"
, "Netrunner,9329"
, "netsec,149780"
, "networking,56778"
, "neuro,29646"
, "NeutralPolitics,48269"
, "NeverBeGameOver,6023"
, "nevertellmetheodds,54203"
, "Neverwinter,10724"
, "newfoundland,3544"
, "NewGirl,11270"
, "newjersey,22791"
, "NewOrleans,14369"
, "newreddits,56764"
, "NewRussia,266"
, "news,7193384"
, "NewSkaters,7125"
, "NewsOfTheStupid,26065"
, "NewsOfTheWeird,23032"
, "newsokunomoral,1668"
, "newsokur,12742"
, "newsokuvip,1422"
, "NewsPorn,27720"
, "newtothenavy,3355"
, "NewYorkIslanders,2747"
, "NewYorkMets,9081"
, "newzealand,58365"
, "nextdoorasians,44027"
, "Nexus,11251"
, "nexus4,14051"
, "Nexus5,32628"
, "nexus5x,4290"
, "nexus6,17044"
, "Nexus6P,14565"
, "NexusNewbies,4554"
, "NFA,3386"
, "nfffffffluuuuuuuuuuuu,10412"
, "nfl,438505"
, "nflcirclejerk,5471"
, "NFL_Draft,10220"
, "NFLRoundTable,5106"
, "nflstreams,45816"
, "NFSRides,331"
, "nhl,48661"
, "NHLHUT,6246"
, "NHLStreams,24573"
, "niceb8m8,2780"
, "niceguys,56186"
, "Nichijou,1794"
, "NichtDerPostillon,1679"
, "Nightshift,3047"
, "nightvale,12825"
, "Nikon,5622"
, "nin,8543"
, "nintendo,111235"
, "nintendomusic,16592"
, "Nirvana,9955"
, "Nisekoi,5857"
, "Nissan,7789"
, "nl_Kripparrian,5710"
, "NLSSCircleJerk,6342"
, "NLTP,1260"
, "nocontext,127222"
, "node,17989"
, "NoFap,176191"
, "NoFapChristians,5780"
, "NoFapWar,8446"
, "noisygifs,26562"
, "NOLAPelicans,1796"
, "NoMansSkyTheGame,28763"
, "nongolfers,23795"
, "nonmonogamy,11653"
, "nonnude,5508"
, "nononono,124473"
, "nonononoyes,227931"
, "Nootropics,64062"
, "NoPoo,12759"
, "Nordiccountries,7445"
, "norge,31328"
, "normaldayinjapan,12500"
, "NorthCarolina,11331"
, "northernireland,6754"
, "northernlion,4198"
, "NorthKoreaNews,28734"
, "Norway,12728"
, "NoShitSherlock,15730"
, "NoSillySuffix,15832"
, "nosleep,4419937"
, "NoSleepOOC,6136"
, "no_sob_story,12490"
, "nostalgia,135018"
, "Nostalrius,1864"
, "NostalriusBegins,2221"
, "NoStupidQuestions,105909"
, "notcirclejerk,3604"
, "notebooks,10292"
, "notinteresting,93212"
, "NotMyJob,9602"
, "NotSoGoodGuyMafia,1"
, "nottheonion,4626814"
, "NotTimAndEric,52386"
, "nova,16149"
, "noveltranslations,6505"
, "nqmod,677"
, "NRIBabes,4104"
, "nrl,7913"
, "NuclearThrone,6138"
, "NUFC,4139"
, "Nujabes,13336"
, "nursing,26360"
, "nutrition,58085"
, "nvidia,13768"
, "NWSL,2055"
, "nyc,93287"
, "NYGiants,14530"
, "nyjets,9260"
, "NYKnicks,10287"
, "NYYankees,5116"
, "oakland,7448"
, "OaklandAthletics,5427"
, "oaklandraiders,8363"
, "oblivion,20697"
, "ObscureMedia,48169"
, "occult,25842"
, "occupywallstreet,31365"
, "OCD,7576"
, "ockytop,1751"
, "OCLions,2234"
, "OCPoetry,8270"
, "oculus,58470"
, "oddlysatisfying,402256"
, "ofcoursethatsathing,68726"
, "offbeat,323485"
, "Offensive_Wallpapers,57976"
, "offmychest,195959"
, "OFWGKTA,19821"
, "Ohio,10967"
, "okc,3844"
, "OkCupid,76965"
, "oklahoma,8846"
, "oldbabies,3981"
, "oldpeoplefacebook,123804"
, "OldSchoolCool,4435183"
, "oliviawilde,18117"
, "Omaha,6706"
, "OnceUponATime,14844"
, "onejob,19142"
, "oneliners,8428"
, "OnePiece,58146"
, "OnePieceTC,4580"
, "oneplus,31264"
, "OnePunchMan,13861"
, "OneTrueBiribiri,2053"
, "onetruegod,85716"
, "onetrueidol,1987"
, "onewordeach,6562"
, "OneY,28710"
, "ontario,13949"
, "Ooer,22033"
, "OopsDidntMeanTo,27372"
, "OOTP,1794"
, "openbroke,7026"
, "opendirectories,34117"
, "opensource,38410"
, "opiates,18779"
, "OpiatesRecovery,5017"
, "opieandanthony,11550"
, "Oppression,2456"
, "OpTicGaming,9421"
, "orangecounty,15315"
, "orangeisthenewblack,37014"
, "OreGairuSNAFU,2685"
, "oregon,12238"
, "orioles,7696"
, "orlando,13168"
, "OrlandoMagic,2489"
, "orphanblack,12331"
, "OrthodoxChristianity,3213"
, "OSHA,106266"
, "OSU,7389"
, "osugame,16754"
, "osx,26645"
, "ottawa,18694"
, "OttawaSenators,4489"
, "PI:NAME:<NAME>END_PI,15182"
, "Outlander,4640"
, "OutlandishAlcoholics,310"
, "OutOfTheLoop,352852"
, "OutreachHPG,4306"
, "outrun,21477"
, "outside,169842"
, "overclocking,14365"
, "overlanding,7952"
, "overpopulation,10742"
, "Overwatch,75843"
, "Owls,13402"
, "Pac12,2079"
, "pacers,2643"
, "PacificRim,4808"
, "paintball,13838"
, "painting,19653"
, "pakistan,5580"
, "Paladins,2246"
, "Paleo,82633"
, "Palestine,8236"
, "PandR,80461"
, "PanicHistory,11470"
, "PanPorn,2688"
, "panthers,9700"
, "ParadoxExtra,948"
, "paradoxplaza,36233"
, "paradoxpolitics,4368"
, "Parahumans,2810"
, "Paranormal,82498"
, "Pareidolia,112512"
, "Parenting,89413"
, "paris,9014"
, "parrots,12067"
, "PastAndPresentPics,26758"
, "Patchuu,5314"
, "Pathfinder_RPG,24123"
, "pathofexile,55470"
, "patientgamers,66432"
, "PI:NAME:<NAME>END_PI,35985"
, "PI:NAME:<NAME>END_PIuper,3510"
, "paydaycirclejerk,750"
, "paydaytheheist,40470"
, "PBSOD,4524"
, "pcgaming,177340"
, "pcmasterrace,499519"
, "pebble,26606"
, "PEDs,2684"
, "peloton,12939"
, "penguins,10697"
, "PenPI:NAME:<NAME>END_PI,120944"
, "Pennsylvania,6406"
, "penspinning,13838"
, "PeopleBeingJerks,31276"
, "pepe,3873"
, "pepethefrog,5498"
, "Perfectfit,58195"
, "perfectloops,87232"
, "PerfectTiming,213955"
, "perktv,4851"
, "Permaculture,32689"
, "personalfinance,4554137"
, "PersonalFinanceCanada,21006"
, "PersonOfInterest,7908"
, "perth,9240"
, "Pets,40721"
, "pettyrevenge,185894"
, "pharmacy,11236"
, "philadelphia,32593"
, "Philippines,41758"
, "philosophy,4513265"
, "PhilosophyofScience,36378"
, "phish,14034"
, "phoenix,13463"
, "photocritique,36970"
, "photography,266257"
, "photoshop,39757"
, "photoshopbattles,4687231"
, "PhotoshopRequest,18145"
, "PHP,40492"
, "Physics,128791"
, "physicsgifs,36540"
, "piano,39324"
, "pic,41129"
, "PickAnAndroidForMe,3855"
, "picrequests,30863"
, "pics,9989676"
, "PictureGame,6213"
, "Pieces,14156"
, "piercing,24957"
, "pimpcats,17733"
, "pinkfloyd,22664"
, "pinsamt,2950"
, "PipeTobacco,16237"
, "Piracy,44568"
, "pitbulls,27622"
, "pitchforkemporium,11008"
, "pittsburgh,20373"
, "Pixar,8458"
, "PixelArt,31539"
, "PixelDungeon,4762"
, "Pizza,47680"
, "PKA,24769"
, "pkmntcg,7333"
, "Planetside,39289"
, "PlantedTank,21275"
, "plastidip,7725"
, "playark,19551"
, "PlayItAgainSam,26060"
, "playrust,28473"
, "playstation,23516"
, "PlayStationPlus,33657"
, "PleX,29450"
, "ploompax,7475"
, "plotholes,25252"
, "ploungeafterdark,1519"
, "Plumbing,4184"
, "podcasts,25805"
, "podemos,11042"
, "Poetry,49882"
, "PointlessStories,15386"
, "Pokeents,9352"
, "pokemon,474684"
, "Pokemongiveaway,23462"
, "pokemongo,5808"
, "PokemonInsurgence,11178"
, "PokemonPlaza,9885"
, "PokemonShuffle,5506"
, "pokemontrades,32149"
, "poker,39081"
, "poland,6554"
, "polandball,183854"
, "Polandballart,5267"
, "polandballgifs,3082"
, "policeporn,7454"
, "POLITIC,26221"
, "PoliticalDiscussion,46733"
, "PoliticalHumor,50628"
, "politicalpartypowers,221"
, "PoliticalScience,4220"
, "PoliticalVideo,3264"
, "politics,3179799"
, "politota,3829"
, "Polska,25211"
, "polyamory,32932"
, "PopArtNouveau,12780"
, "PopCornTime,14295"
, "popheads,3343"
, "popping,63644"
, "poppunkers,22875"
, "pornfree,23763"
, "Porsche,10606"
, "Portal,33665"
, "porterrobinson,3055"
, "Portland,55193"
, "portlandstate,1611"
, "portugal,10848"
, "PORTUGALCARALHO,2199"
, "PostHardcore,24276"
, "postprocessing,19762"
, "postrock,25540"
, "potatosalad,9117"
, "potionseller,5062"
, "pottedcats,736"
, "powerlifting,24249"
, "PowerMetal,8754"
, "powerrangers,6357"
, "PowerShell,14127"
, "powerwashingporn,47175"
, "predaddit,7185"
, "Predators,2547"
, "Prematurecelebration,60825"
, "premed,14042"
, "PremierLeague,10863"
, "preppers,22426"
, "PrettyGirls,119838"
, "PrettyGirlsUglyFaces,40069"
, "PrettyLittleLiars,13195"
, "printSF,24370"
, "prisonarchitect,21737"
, "privacy,57320"
, "processing,3202"
, "productivity,94185"
, "proED,2694"
, "progmetal,29496"
, "programmerchat,2151"
, "ProgrammerHumor,107681"
, "programmerreactions,2708"
, "programming,662121"
, "programmingcirclejerk,3359"
, "progressive,41755"
, "progresspics,159520"
, "progrockmusic,14678"
, "progun,16238"
, "projectcar,16099"
, "projecteternity,15575"
, "ProjectFi,6998"
, "ProjectRunway,3241"
, "projectzomboid,11302"
, "promos,7261"
, "PropagandaPosters,61960"
, "ProRevenge,68628"
, "ProtectAndServe,31841"
, "providence,3433"
, "PS2Cobalt,1330"
, "PS3,70298"
, "PS4,224940"
, "PS4Deals,25738"
, "PS4Planetside2,3392"
, "PSO2,6678"
, "psych,17860"
, "psychedelicrock,16742"
, "psychology,200568"
, "Psychonaut,101049"
, "ptcgo,5105"
, "ptsd,5175"
, "PublicFreakout,88695"
, "PucaTrade,1379"
, "PuertoRico,2914"
, "pugs,27771"
, "punchablefaces,55609"
, "Pundertale,703"
, "punk,39887"
, "Punny,63046"
, "puns,27992"
, "puppies,23155"
, "puppy101,9484"
, "PuppySmiles,10786"
, "Purdue,5756"
, "pureasoiaf,12551"
, "PurplePillDebate,6931"
, "PushBullet,5486"
, "PussyPass,22432"
, "pussypassdenied,61130"
, "putindoingthings,2049"
, "PuzzleAndDragons,16054"
, "pxifrm,115"
, "Python,115556"
, "qotsa,6238"
, "QuakeLive,4660"
, "Quebec,10786"
, "questionablecontent,5683"
, "quilting,7847"
, "QuinnMains,707"
, "quiteinteresting,16331"
, "quityourbullshit,185200"
, "quotes,104379"
, "QuotesPorn,267602"
, "r4r,87824"
, "Rabbits,28734"
, "PI:NAME:<NAME>END_PI,2362"
, "racism,7995"
, "radiocontrol,12348"
, "radiohead,28111"
, "Radiology,7457"
, "rage,122716"
, "ragecomics,41862"
, "PI:NAME:<NAME>END_PI,1722"
, "rails,16064"
, "Rainbow6,9496"
, "RainbowSix,324"
, "RainbowSixSiege,758"
, "rainbow_wolf,275"
, "raining,22091"
, "Rainmeter,61724"
, "raisedbynarcissists,82856"
, "raiseyourdongers,11287"
, "rakugakicho,562"
, "raleigh,9389"
, "rally,15541"
, "ramen,36662"
, "Random_Acts_Of_Amazon,32024"
, "randomactsofamazon,5503"
, "RandomActsofCards,4803"
, "RandomActsOfChristmas,6437"
, "randomactsofcsgo,15588"
, "RandomActsOfGaming,48115"
, "RandomActsofMakeup,16512"
, "RandomActsOfPizza,24170"
, "Random_Acts_Of_Pizza,39302"
, "RandomActsOfPolish,7470"
, "RandomKindness,37441"
, "randomsuperpowers,580"
, "randpaul,5063"
, "rangers,9997"
, "rant,18677"
, "rantgrumps,1462"
, "RantsFromRetail,1673"
, "rapbattles,5800"
, "raspberry_pi,82516"
, "Rateme,41096"
, "rational,3854"
, "RationalPsychonaut,12838"
, "RATS,15845"
, "ravens,11730"
, "rawdenim,25719"
, "razorbacks,1594"
, "RBI,29738"
, "rccars,5804"
, "RCSources,6523"
, "rct,16703"
, "reactiongifs,584267"
, "reactjs,6388"
, "readit,32196"
, "realasians,70113"
, "realdubstep,19599"
, "RealEstate,40152"
, "reallifedoodles,95560"
, "RealLifeFootball,205"
, "realmadrid,10216"
, "REBL,1016"
, "recipes,150726"
, "reckful,895"
, "reddevils,37712"
, "RedditAlternatives,7793"
, "redditblack,1330"
, "RedditDads,2927"
, "RedditDayOf,50174"
, "RedditForGrownups,19457"
, "RedditFox,2195"
, "redditgetsdrawn,95837"
, "redditisfun,21473"
, "RedditLaqueristas,72782"
, "redditrequest,5690"
, "redditsync,47160"
, "RedditWritesSeinfeld,17316"
, "RedHotChiliPeppers,11206"
, "RedLetterMedia,8047"
, "redorchestra,6201"
, "redpandas,20461"
, "RedPillWomen,13048"
, "Reds,5256"
, "Redskins,11116"
, "redsox,18397"
, "ReefTank,9386"
, "Reformed,4638"
, "regularcarreviews,2858"
, "regularshow,22891"
, "relationship_advice,115575"
, "relationships,402654"
, "RelayForReddit,24205"
, "reloading,8744"
, "RenewableEnergy,28148"
, "Rengarmains,1073"
, "Repsneakers,8097"
, "reptiles,11690"
, "Republican,19154"
, "researchchemicals,6883"
, "residentevil,8177"
, "respectporn,22817"
, "respectthreads,9618"
, "restorethefourth,22338"
, "resumes,24186"
, "retiredgif,52689"
, "retrobattlestations,13020"
, "RetroFuturism,82812"
, "retrogaming,22162"
, "RetroPie,3485"
, "ReversedGIFS,10990"
, "reversegif,22540"
, "reynad,1543"
, "rickandmorty,191060"
, "rickygervais,9435"
, "riddles,30867"
, "Rift,9693"
, "Rimarist,7"
, "RimWorld,8322"
, "ripcity,6682"
, "rit,7262"
, "RivalsOfAether,6951"
, "Rivenmains,1199"
, "Roadcam,47238"
, "RoastMe,135768"
, "roblox,3240"
, "Robocraft,7490"
, "robotics,33249"
, "Rochester,7587"
, "Rockband,6734"
, "rocketbeans,15194"
, "RocketLeague,99039"
, "rockets,7814"
, "rockhounds,9937"
, "rocksmith,13141"
, "roguelikes,19191"
, "Roguetroll,10"
, "rojava,1029"
, "Roku,15244"
, "roleplayponies,72"
, "rollercoasters,7167"
, "rolltide,3441"
, "Romania,23826"
, "ronandfez,3299"
, "ronpaul,25443"
, "RoomPorn,290703"
, "roosterteeth,129872"
, "ROTC,1388"
, "RotMG,6409"
, "Rottweiler,4174"
, "Rowing,9961"
, "rpdrcirclejerk,650"
, "rpg,92650"
, "rpg_gamers,25733"
, "RSChronicle,414"
, "RSDarkscape,4701"
, "RTLSDR,12111"
, "ruby,31346"
, "rugbyunion,37219"
, "runescape,54578"
, "running,181129"
, "rupaulsdragrace,24932"
, "rush,8156"
, "russia,17424"
, "russian,10448"
, "rust,13618"
, "rutgers,5881"
, "rva,11277"
, "RWBY,21931"
, "rwbyRP,345"
, "ryuuseigai,254"
, "S2000,2373"
, "Saber,2372"
, "sabres,4881"
, "Sacramento,10144"
, "SacRepublicFC,610"
, "sadboys,8191"
, "sadcomics,17309"
, "sadcringe,4046"
, "SaddlebackLeatherFans,36"
, "Saffron_Regiment,278"
, "SAGAcomic,2783"
, "sailing,24086"
, "sailormoon,10790"
, "Saints,8965"
, "SakuraGakuin,844"
, "sales,9397"
, "SaltLakeCity,10883"
, "samharris,1730"
, "samoyeds,4826"
, "SampleSize,32623"
, "samsung,8048"
, "sanantonio,10644"
, "SanctionedSuicide,2331"
, "SandersForPresident,135167"
, "sandiego,27042"
, "sanfrancisco,48702"
, "SanJose,8772"
, "SanJPI:NAME:<NAME>END_PI,8349"
, "santashelpers,5881"
, "SantasLittleHelpers,1775"
, "saplings,22583"
, "PI:NAME:<NAME>END_PI,7700"
, "SargonofAkkad,2866"
, "saskatchewan,2933"
, "saskatoon,4188"
, "Sat,1626"
, "saudiarabia,2242"
, "saudiprince,3510"
, "SavageGarden,7431"
, "savannah,2471"
, "scala,9586"
, "Scams,7972"
, "ScandinavianInterior,5242"
, "PI:NAME:<NAME>END_PI,23948"
, "Scarrapics,7688"
, "ScenesFromAHat,34944"
, "schizophrenia,4014"
, "SchoolIdolFestival,8021"
, "science,9829763"
, "sciencefiction,32395"
, "scientology,6801"
, "scifi,240788"
, "SciFiRealism,9935"
, "scooters,5786"
, "scoreball,4131"
, "Scotch,47164"
, "ScotchSwap,2196"
, "Scotland,20463"
, "ScottishFootball,1859"
, "SCP,26442"
, "ScreamQueensTV,3679"
, "screenshots,26041"
, "Screenwriting,41585"
, "Scrubs,34145"
, "scuba,23021"
, "Seahawks,32797"
, "Seattle,76985"
, "secretsanta,70999"
, "SecretSubreddit,3473"
, "security,13099"
, "seduction,223034"
, "see,41509"
, "seedboxes,7171"
, "seinfeld,44057"
, "seinfeldgifs,16169"
, "PI:NAME:<NAME>END_PI,17076"
, "self,148033"
, "SelfDrivingCars,10923"
, "SelfiesWithGlasses,710"
, "selfimprovement,61452"
, "selfpublish,10471"
, "SEO,27693"
, "serbia,3251"
, "Serendipity,40161"
, "serialkillers,31530"
, "serialpodcast,44131"
, "serialpodcastorigins,686"
, "SeriousConversation,3982"
, "seriouseats,19686"
, "sewing,39017"
, "sex,618677"
, "SexPositive,19089"
, "SexWorkers,6491"
, "sexygirls,12774"
, "sexyhair,1771"
, "sexypizza,8500"
, "SexyWomanOfTheDay,12608"
, "SFGiants,16663"
, "SFM,13371"
, "SFWRedheads,8179"
, "sfw_wtf,11341"
, "Shadowrun,9653"
, "shanghai,4780"
, "Sherlock,68729"
, "shestillsucking,16142"
, "shia,911"
, "shiba,12931"
, "shield,39612"
, "Shihtzu,2478"
, "ShingekiNoKyojin,39537"
, "ShinyPokemon,11639"
, "ShitAmericansSay,22530"
, "ShitCrusaderKingsSay,4260"
, "shitduolingosays,3833"
, "ShitLewisSays,4893"
, "ShitLiberalsSay,2555"
, "ShitPoliticsSays,7330"
, "shitpost,24892"
, "ShitRConservativeSays,5073"
, "ShitRedditSays,76821"
, "Shitstatistssay,7677"
, "shittankiessay,510"
, "ShitTumblrSays,3039"
, "shittyadvice,65894"
, "shittyadviceanimals,12933"
, "shittyama,13610"
, "ShittyAnimalFacts,21590"
, "shittyaskreddit,19674"
, "shittyaskscience,298571"
, "Shitty_Car_Mods,90140"
, "shittyconspiracy,4771"
, "shittydarksouls,5868"
, "shitty_ecr,3511"
, "ShittyFanTheories,14206"
, "shittyfoodporn,118113"
, "shittyHDR,8649"
, "shittyideas,16863"
, "shittykickstarters,31310"
, "ShittyLifeProTips,63163"
, "ShittyMapPorn,19129"
, "shittynosleep,23020"
, "shittyprogramming,25766"
, "shittyreactiongifs,131954"
, "shittyrobots,100978"
, "shittysteamreviews,6744"
, "shittytumblrgifs,16429"
, "ShitWehraboosSay,3385"
, "ShokugekiNoSoma,5245"
, "Shoplifting,2514"
, "short,18239"
, "shorthairedhotties,34837"
, "shortscarystories,63081"
, "Shotguns,6107"
, "ShouldIbuythisgame,36978"
, "showerbeer,32418"
, "Showerthoughts,4878620"
, "shroomers,12562"
, "shrooms,23983"
, "shutupandtakemymoney,260041"
, "Sikh,2030"
, "SiliconValleyHBO,31197"
, "Silverbugs,9665"
, "SimCity,25184"
, "simpleliving,73772"
, "simpsonsdidit,18014"
, "simracing,11072"
, "Simulated,30520"
, "singapore,34968"
, "singing,19015"
, "singularity,29307"
, "Sino,1325"
, "sips,35974"
, "sixers,6060"
, "sixwordstories,28278"
, "sjsucks,3359"
, "sjwhate,7175"
, "skateboarding,70289"
, "skeptic,102973"
, "SketchDaily,45733"
, "skiing,36721"
, "SkincareAddiction,186356"
, "SkinnyWithAbs,26477"
, "skrillex,7759"
, "Skullgirls,8746"
, "SkyDiving,9496"
, "Skyforge,6822"
, "SkyPorn,52048"
, "skyrim,317076"
, "skyrimdadjokes,7082"
, "skyrimmods,43657"
, "SkyrimPorn,14961"
, "slashdiablo,4553"
, "slatestarcodex,1204"
, "slavs_squatting,25530"
, "Sleepycabin,7297"
, "Slipknot,4484"
, "sloths,52076"
, "slowcooking,181706"
, "SlyGifs,31850"
, "sm4sh,4693"
, "smallbusiness,42404"
, "smalldickproblems,2878"
, "SmarterEveryDay,17293"
, "smashbros,193884"
, "smashcirclejerk,3835"
, "smashgifs,11407"
, "Smite,67098"
, "smoking,23275"
, "snakes,15064"
, "snapchat,14894"
, "sneakermarket,7491"
, "Sneakers,62627"
, "snek_irl,6224"
, "Sneks,16810"
, "snes,12996"
, "snowboarding,55293"
, "snowden,6612"
, "SNSD,12988"
, "SoapboxBanhammer,426"
, "soccer,406132"
, "SoccerBetting,7821"
, "soccercirclejerk,8485"
, "soccerspirits,2436"
, "soccerstreams,28855"
, "socialanxiety,33954"
, "SocialEngineering,66828"
, "socialism,55342"
, "Socialistart,2830"
, "socialjustice101,2772"
, "SocialJusticeInAction,5071"
, "socialmedia,24157"
, "socialskills,124187"
, "socialwork,5616"
, "sociopath,3244"
, "sodadungeon,846"
, "sodapoppin,1883"
, "softwaregore,41799"
, "SolForge,2177"
, "solipsism,7371"
, "solotravel,39652"
, "soma,1456"
, "somethingimade,103385"
, "SonicTheHedgehog,4766"
, "SonyXperia,5817"
, "sooners,2834"
, "sophieturner,8412"
, "sorceryofthespectacle,2519"
, "SoundsLikeChewy,350"
, "SoundsLikeMusic,10164"
, "SourceFed,32048"
, "sousvide,11980"
, "southafrica,16286"
, "southpark,151534"
, "soylent,16541"
, "space,4856256"
, "SpaceBuckets,17882"
, "spaceengine,8735"
, "spaceengineers,23681"
, "spaceflight,17886"
, "spaceporn,304852"
, "spacex,42626"
, "spain,6505"
, "Spanish,18226"
, "SpecArt,38694"
, "SpeculativeEvolution,8317"
, "speedrun,41470"
, "spelunky,5475"
, "spicy,26348"
, "spiderbro,20400"
, "Spiderman,17595"
, "spiders,19926"
, "SpideyMeme,43917"
, "spikes,23119"
, "splatoon,26573"
, "SplitDepthGIFS,42588"
, "Spokane,3500"
, "spongebob,25202"
, "Spongebros,9137"
, "sporetraders,1880"
, "sports,5053901"
, "sportsarefun,33800"
, "sportsbook,14530"
, "spotify,32797"
, "spotted,14019"
, "springerspaniel,1026"
, "springfieldMO,2589"
, "Sprint,3308"
, "SQL,12459"
, "SquaredCircle,100115"
, "SquaredCirclejerk,2263"
, "SRSDiscussion,14311"
, "SRSGaming,6438"
, "SRSsucks,13889"
, "SS13,4183"
, "SSBM,18959"
, "SSBPM,23980"
, "StackAdvice,9073"
, "StackGunHeroes,2201"
, "stalker,8405"
, "StallmanWasRight,2158"
, "Stance,11682"
, "Standup,30403"
, "StandUpComedy,68690"
, "standupshots,180743"
, "Staples,1663"
, "starbound,53361"
, "starbucks,13249"
, "Starcaft,5"
, "starcitizen,59168"
, "Starcitizen_trades,4263"
, "starcraft,184091"
, "StardustCrusaders,9178"
, "Stargate,20681"
, "starlets,28960"
, "StarlightStage,1158"
, "starterpacks,25990"
, "StartledCats,96464"
, "startrek,98491"
, "startups,95633"
, "StarVStheForcesofEvil,2331"
, "StarWars,345816"
, "StarWarsBattlefront,50911"
, "starwarscollecting,841"
, "StarWarsEU,7579"
, "StarWarsLeaks,9889"
, "starwarsrebels,4990"
, "starwarsspeculation,831"
, "starwarstrader,1718"
, "statistics,29112"
, "steak,17478"
, "Steam,246860"
, "SteamController,2363"
, "steamdeals,52334"
, "SteamGameSwap,39821"
, "steampunk,33109"
, "steamr,1339"
, "steelers,14770"
, "stencils,18517"
, "stephenking,11385"
, "steroids,21686"
, "stevedangle,854"
, "stevenuniverse,40931"
, "Stims,4400"
, "StLouis,16670"
, "stlouisblues,5825"
, "StLouisRams,4558"
, "sto,8236"
, "StockMarket,30145"
, "stocks,42133"
, "Stoicism,27901"
, "StonerCringe,465"
, "StonerEngineering,62455"
, "StonerPhilosophy,22673"
, "StonerProTips,29743"
, "stonerrock,17254"
, "stopdrinking,32169"
, "StopGaming,4845"
, "StoppedWorking,29609"
, "stopsmoking,39116"
, "StopTouchingMe,19388"
, "StormfrontorSJW,10522"
, "Stormlight_Archive,10108"
, "straightedge,2864"
, "straya,15833"
, "streetart,28859"
, "StreetFighter,19201"
, "StreetFights,40216"
, "streetfoodartists,13113"
, "streetphotography,4566"
, "streetwear,59791"
, "Streisandeffect,479"
, "StudentLoans,9744"
, "stunfisk,12874"
, "subaru,48713"
, "submechanophobia,17428"
, "subnautica,2689"
, "subredditcancer,10423"
, "SubredditDrama,212016"
, "SubredditDramaDrama,6784"
, "subredditoftheday,116920"
, "SubredditSimMeta,18180"
, "SubredditSimulator,100281"
, "succulents,11380"
, "SuddenlyGay,10271"
, "sugarfreemua,8232"
, "SuggestALaptop,21902"
, "suggestmeabook,22247"
, "SuicideWatch,40594"
, "suits,23893"
, "summonerschool,82962"
, "summonerswar,13052"
, "Sundresses,8984"
, "suns,2922"
, "sunsetshimmer,732"
, "Suomi,26735"
, "Superbowl,10765"
, "supergirlTV,5557"
, "superman,13474"
, "supermoto,5606"
, "Supernatural,46900"
, "SuperShibe,52716"
, "Supplements,22667"
, "supremeclothing,15545"
, "Surface,32368"
, "surfing,27387"
, "SurgeryGifs,5944"
, "Survival,73333"
, "survivinginfidelity,2589"
, "survivor,18165"
, "survivorcirclejerk,394"
, "SurvivorRankdownII,88"
, "survivorspoilers,453"
, "sushi,25490"
, "svenskpolitik,43953"
, "Sverige,1102"
, "SVExchange,10736"
, "SwagBucks,8574"
, "SWARJE,50964"
, "SweatyPalms,26722"
, "sweden,85671"
, "sweepstakes,5485"
, "swift,13768"
, "SwiggitySwootyGifs,16194"
, "Swimming,23838"
, "Swingers,15856"
, "Switzerland,7308"
, "swoleacceptance,57610"
, "swordartonline,19915"
, "SwordOrSheath,6251"
, "swrpg,4590"
, "swtor,53799"
, "sydney,22094"
, "SympatheticMonsters,8883"
, "synthesizers,19567"
, "Syracuse,3069"
, "Syraphia,26"
, "SyrianCirclejerkWar,385"
, "syriancivilwar,26280"
, "sysadmin,123602"
, "tabletopgamedesign,10692"
, "tacobell,7914"
, "Tacoma,4034"
, "TACSdiscussion,4031"
, "TagPro,11498"
, "TagProIRL,823"
, "taiwan,7100"
, "TakeshisCastle,284"
, "tales,5922"
, "talesfromcallcenters,16316"
, "TalesFromRetail,232513"
, "talesfromtechsupport,296382"
, "TalesFromTheCustomer,14883"
, "TalesFromTheFrontDesk,9948"
, "TalesFromThePharmacy,10320"
, "TalesFromThePizzaGuy,38007"
, "TalesFromTheSquadCar,20480"
, "TalesFromYourServer,39699"
, "tall,50390"
, "Tallahassee,2862"
, "Talonmains,1440"
, "TameImpala,6037"
, "tampa,11788"
, "TampaBayLightning,3492"
, "TankPorn,9398"
, "tappedout,15964"
, "tarantinogifs,11320"
, "Target,1903"
, "tasker,22637"
, "tattoo,40487"
, "tattoos,434589"
, "TaylorSwift,22392"
, "TaylorSwiftPictures,5578"
, "TaylorSwiftsLegs,8853"
, "tdl,1259"
, "tea,63796"
, "Teachers,29837"
, "teaching,16431"
, "TeamSolomid,14820"
, "tech,82935"
, "technews,17699"
, "TechNewsToday,30782"
, "Techno,16222"
, "technology,5204799"
, "TechoBlanco,1661"
, "techsupport,78211"
, "techsupportgore,109303"
, "techsupportmacgyver,56393"
, "techtheatre,7690"
, "TPI:NAME:<NAME>END_PI,988"
, "teefies,4007"
, "teenagers,105234"
, "TeenMFA,11284"
, "TEFL,13794"
, "Teleshits,10418"
, "television,6011203"
, "TelevisionQuotes,17559"
, "TellMeAFact,23598"
, "telltale,4012"
, "Tennessee,4201"
, "Tennesseetitans,4269"
, "tennis,31624"
, "TeraOnline,18715"
, "Terraria,78686"
, "terriblefacebookmemes,33514"
, "tesdcares,3954"
, "teslamotors,29314"
, "teslore,32384"
, "Texans,10937"
, "texas,32441"
, "TexasRangers,6587"
, "tf2,157238"
, "TF2fashionadvice,6190"
, "tf2shitposterclub,507"
, "tf2trade,13281"
, "tgrp,97"
, "Thailand,8314"
, "thalassophobia,64543"
, "thanksgiving,678"
, "That70sshow,11915"
, "thatHappened,238789"
, "ThatPeelingFeeling,18411"
, "The100,8349"
, "TheAffair,732"
, "TheBluePill,25735"
, "TheBrewery,7802"
, "thebutton,161652"
, "thechapel,1915"
, "TheCompletionist,2587"
, "TheCreatures,12627"
, "The_Crew,4247"
, "TheDarkTower,10781"
, "thedivision,8376"
, "The_Donald,1680"
, "TheExpanse,2150"
, "TheFacebookDelusion,24433"
, "TheForest,8747"
, "TheFrontBottoms,2114"
, "TheGameOfThronesGame,2267"
, "TheGirlSurvivalGuide,56560"
, "thegoodwife,2651"
, "TheHobbit,21547"
, "TheKillers,2316"
, "TheLastAirbender,142647"
, "thelastofus,21644"
, "thelastofusfactions,5769"
, "thelawschool,1305"
, "theleaguefx,17449"
, "TheLeftovers,12448"
, "thelongdark,4192"
, "TheMassive,1864"
, "ThemeParkitect,1508"
, "themindyproject,2318"
, "themoddingofisaac,4680"
, "themountaingoats,3058"
, "thenetherlands,67966"
, "theNvidiaShield,2771"
, "theocho,39803"
, "TheOnion,14325"
, "ThePhenomenon,7304"
, "TheRealmsMC,335"
, "TheRedPill,139577"
, "thereifixedit,10036"
, "thereisnoowl,247"
, "therewasanattempt,16696"
, "TheSimpsons,118309"
, "thesims,43878"
, "thesopranos,7028"
, "TheSquadOnPoint,8807"
, "TheStrokes,4903"
, "Thetruthishere,46694"
, "TheVampireDiaries,6381"
, "thevoice,1175"
, "thewalkingdead,257148"
, "TheWayWeWere,68848"
, "thewestwing,6412"
, "TheWire,21842"
, "theworldisflat,1241"
, "theworldnews,6170"
, "theydidthemath,125881"
, "ThingsCutInHalfPorn,88776"
, "ThingsWhiteFolksLike,97"
, "thinkpad,6659"
, "thisismylifenow,7624"
, "ThisIsNotASafeSpace,1145"
, "ThriftStoreHauls,60871"
, "Throwers,6326"
, "Thunder,5600"
, "TiADiscussion,7104"
, "TibiaMMO,1524"
, "tifu,4785294"
, "TILinIndia,360"
, "tiltshift,26505"
, "TimAndEric,22437"
, "timbers,3840"
, "timberwolves,5029"
, "timetolegalize,10058"
, "tinabelcher,14568"
, "Tinder,178148"
, "TinyHouses,67833"
, "tipofmyjoystick,7822"
, "tipofmytongue,155576"
, "titanfall,30090"
, "titlegore,32415"
, "TMBR,2729"
, "TMNT,8354"
, "tmobile,14739"
, "tobacco_ja,158"
, "TodayIGrandstanded,1472"
, "todayilearned,10011031"
, "Tokyo,8491"
, "TokyoGhoul,10479"
, "tolkienfans,32828"
, "TombRaider,4408"
, "tomwaits,1568"
, "tonightsdinner,39276"
, "ToolBand,16789"
, "Tools,4780"
, "TooMeIrlForMeIrl,481"
, "Toonami,6379"
, "Toontown,4781"
, "toosoon,77090"
, "TopGear,136177"
, "TopMindsOfReddit,9391"
, "topofreddit,4569"
, "TOR,23629"
, "toronto,66122"
, "TorontoAnarchy,95"
, "Torontobluejays,18976"
, "torontoraptors,10952"
, "torrents,56332"
, "totallynotrobots,9466"
, "totalwar,41322"
, "touhou,8449"
, "TowerofGod,4100"
, "TownofSalemgame,5464"
, "Toyota,7056"
, "TPPKappa,272"
, "traaaaaaannnnnnnnnns,2723"
, "trackers,53133"
, "Tradelands,621"
, "TraditionalCurses,8904"
, "trailerparkboys,47748"
, "trailers,30981"
, "traingifs,4196"
, "trains,7737"
, "trance,38049"
, "transformers,8114"
, "transgamers,4169"
, "transgender,21190"
, "transgendercirclejerk,2311"
, "translator,8015"
, "Transmogrification,14579"
, "transpassing,12247"
, "transpositive,7195"
, "transtimelines,13427"
, "trap,53878"
, "trapmuzik,16279"
, "trapproduction,6328"
, "trashpandas,10062"
, "trashy,169388"
, "travel,229376"
, "treecomics,31956"
, "treedibles,13730"
, "treemusic,38739"
, "treeofsavior,10856"
, "trees,810334"
, "TreesSuckingAtThings,32164"
, "trendingsubreddits,12500"
, "tressless,4245"
, "triangle,8951"
, "Tribes,11694"
, "trippinthroughtime,79903"
, "trippy,23788"
, "Troll4Troll,3223"
, "TrollBookClub,2625"
, "TrollDevelopers,879"
, "TrollXChromosomes,178563"
, "TrollXMoms,4640"
, "TrollXWeddings,2970"
, "TrollYChromosome,64300"
, "Trophies,4227"
, "Trove,12525"
, "Trucking,4314"
, "Trucks,19720"
, "trucksim,4914"
, "TrueAnime,7706"
, "TrueAskReddit,78978"
, "TrueAtheism,59089"
, "TrueChristian,9798"
, "TrueDetective,63696"
, "TrueDoTA2,8917"
, "TrueFilm,82190"
, "truegaming,137623"
, "TrueLionhearts,6"
, "TrueOffMyChest,10250"
, "TrueReddit,355484"
, "TrueSTL,4047"
, "truetf2,14280"
, "truewomensliberation,497"
, "truezelda,10426"
, "trump,436"
, "trumpet,4992"
, "TryingForABaby,6930"
, "trypophobia,11299"
, "Tsunderes,3708"
, "TsundereSharks,40487"
, "ttcafterloss,605"
, "tuckedinkitties,14781"
, "TPI:NAME:<NAME>END_PI,6725"
, "Tulpas,9496"
, "tulsa,4869"
, "tumblr,142894"
, "TumblrAtRest,20809"
, "TumblrCirclejerk,8206"
, "TumblrInAction,258243"
, "TumblrPls,4025"
, "Turkey,6826"
, "turning,6471"
, "TuxedoCats,3361"
, "TWD,10164"
, "twentyonepilots,7668"
, "twice,669"
, "TwinCities,12115"
, "twinpeaks,14130"
, "Twitch,43528"
, "twitchplayspokemon,49925"
, "TwoBestFriendsPlay,16430"
, "Twokinds,988"
, "TwoXChromosomes,4185231"
, "TwoXSex,15244"
, "typography,45538"
, "TYT,931"
, "UBC,4840"
, "uber,2502"
, "uberdrivers,6229"
, "Ubuntu,60590"
, "UCalgary,1674"
, "ucf,6370"
, "UCSantaBarbara,5088"
, "udub,4305"
, "ufc,22738"
, "UFOs,48910"
, "UGA,4784"
, "uglyduckling,32364"
, "UIUC,11956"
, "ukbike,3128"
, "ukipparty,2191"
, "UKPersonalFinance,10126"
, "ukpolitics,42408"
, "ukraina,12948"
, "UkrainianConflict,21537"
, "uktrees,7946"
, "ukulele,18774"
, "ultimate,17636"
, "ultrahardcore,6749"
, "Ultralight,20511"
, "ultrawidemasterrace,1849"
, "UMD,5213"
, "UNBGBBIIVCHIDCTIICBG,89630"
, "undelete,47051"
, "Underminers,1213"
, "Undertale,23950"
, "Undertem,283"
, "UnearthedArcana,4194"
, "Unexpected,454437"
, "UnexpectedCena,42675"
, "unexpectedjihad,84030"
, "unexpectedmusic,6513"
, "UnexpectedThugLife,207696"
, "unintentionalASMR,7736"
, "UnisonLeague,847"
, "unitedkingdom,118237"
, "unitedstatesofamerica,13605"
, "Unity2D,12204"
, "Unity3D,31991"
, "UniversityOfHouston,2996"
, "unixporn,32974"
, "Unorthodog,14085"
, "unpopularopinion,2633"
, "unrealengine,12071"
, "unrealtournament,3915"
, "UnresolvedMysteries,123566"
, "UnsentLetters,14744"
, "UnsolicitedRedesigns,6108"
, "UnsolvedMysteries,19576"
, "unstirredpaint,7293"
, "unturned,9162"
, "UnusualArt,10748"
, "uofm,6099"
, "uofmn,3849"
, "UofT,6623"
, "UpliftingNews,4441491"
, "Upvoted,18086"
, "UpvotedBecauseGirl,18218"
, "upvotegifs,17815"
, "urbanexploration,76436"
, "UrbanHell,13357"
, "urbanplanning,20087"
, "usanews,4603"
, "USC,3212"
, "usenet,23173"
, "UserCars,6730"
, "userexperience,12158"
, "USMC,10931"
, "uspolitics,6524"
, "ussoccer,13690"
, "Utah,4476"
, "UtahJazz,2145"
, "UTAustin,8554"
, "Utrecht,1156"
, "uvic,1694"
, "uwaterloo,7871"
, "uwotm8,26543"
, "VAC_Porn,9417"
, "vagabond,15251"
, "vainglorygame,4545"
, "valve,13360"
, "vancouver,38148"
, "vandwellers,20578"
, "vapeitforward,6349"
, "VapePorn,10638"
, "Vaping101,10078"
, "Vaping,24139"
, "vaporents,44059"
, "Vaporwave,22466"
, "VaporwaveAesthetics,6500"
, "vargas,3989"
, "vegan,62390"
, "vegancirclejerk,2338"
, "veganrecipes,24643"
, "vegas,11805"
, "vegetarian,44443"
, "VegRecipes,36893"
, "Velo,8444"
, "venturebros,14986"
, "verizon,4884"
, "Vermintide,6883"
, "Veterans,6255"
, "vexillology,46282"
, "vexillologycirclejerk,4132"
, "vfx,11058"
, "vgb,21719"
, "VGHS,3890"
, "victoria2,3678"
, "VictoriaBC,8051"
, "victoriajustice,10163"
, "video,24832"
, "videogamedunkey,12453"
, "videography,16302"
, "videos,9247409"
, "videosplus,1976"
, "VietNam,4321"
, "VillagePorn,48589"
, "vim,25464"
, "Vinesauce,4827"
, "vintageaudio,8157"
, "vinyl,81713"
, "Virginia,7959"
, "VirginiaTech,6843"
, "virtualreality,16951"
, "visualnovels,18966"
, "vita,49605"
, "Vive,6470"
, "vmware,13503"
, "Voat,4851"
, "Vocaloid,10975"
, "Volkswagen,21290"
, "VolleyballGirls,59133"
, "Volvo,6632"
, "VPN,17588"
, "vsauce,3602"
, "VSModels,2908"
, "VXJunkies,9443"
, "vzla,7574"
, "WackyTicTacs,16046"
, "waifuism,1061"
, "wallpaper,161387"
, "wallpaperdump,24528"
, "wallpapers,374610"
, "wallstreetbets,25133"
, "walmart,3298"
, "WaltDisneyWorld,16644"
, "warcraftlore,9359"
, "Warframe,37682"
, "wargame,6285"
, "Warhammer,34751"
, "Warhammer40k,20910"
, "Warmachine,6497"
, "WarOnComcast,9218"
, "WarplanePorn,5297"
, "warriors,13277"
, "WarshipPorn,26919"
, "Warthunder,31860"
, "Washington,8927"
, "washingtondc,36390"
, "washingtonwizards,4192"
, "WastedGifs,119428"
, "WastelandPowers,434"
, "Watches,81459"
, "WatchesCirclejerk,1508"
, "Watchexchange,5194"
, "Watercolor,12336"
, "watercooling,9119"
, "waterporn,59894"
, "Waxpen,2460"
, "Weakpots,2643"
, "WeAreTheMusicMakers,122961"
, "weather,16995"
, "webcomics,81539"
, "web_design,146257"
, "webdev,105268"
, "WebGames,91965"
, "wec,9139"
, "wedding,18085"
, "WeddingPhotography,3016"
, "weddingplanning,26248"
, "weeabootales,23571"
, "weed,10981"
, "weekendgunnit,6415"
, "weightlifting,20232"
, "weightroom,78738"
, "Weird,26971"
, "WeirdWheels,11164"
, "Welding,17441"
, "Wellington,4711"
, "Wellthatsucks,60047"
, "WEPES,2584"
, "WestVirginia,3002"
, "Wet_Shavers,5221"
, "whatcarshouldIbuy,7337"
, "Whatcouldgowrong,234461"
, "Whatisthis,13279"
, "whatisthisthing,171566"
, "WhatsInThisThing,87704"
, "whatstheword,21524"
, "whatsthisbird,6998"
, "whatsthisbug,40683"
, "whatsthisplant,21102"
, "whatsthisrock,4341"
, "WhatsWrongWithYourDog,8502"
, "wheredidthesodago,381556"
, "whiskey,24787"
, "Whiskyporn,4836"
, "whiteknighting,19243"
, "whitepeoplefacebook,10795"
, "whitepeoplegifs,85881"
, "WhitePeopleTwitter,4837"
, "WhiteRights,9339"
, "whitesox,4082"
, "WhiteWolfRPG,3925"
, "whowouldcirclejerk,1245"
, "whowouldwin,94633"
, "Wicca,10118"
, "wicked_edge,77487"
, "WiggleButts,5153"
, "wiiu,81853"
, "WikiInAction,3372"
, "WikiLeaks,35651"
, "wikipedia,156441"
, "wildhockey,6955"
, "WildStar,35041"
, "wince,18160"
, "Windows10,55712"
, "windows,57504"
, "windowsphone,48558"
, "wine,35744"
, "Winnipeg,8798"
, "winnipegjets,3091"
, "winterporn,35946"
, "wisconsin,14546"
, "Wishlist,1910"
, "witcher,84856"
, "wma,5119"
, "woahdude,890116"
, "WonderTrade,6303"
, "woodworking,138992"
, "woofbarkwoof,6057"
, "woof_irl,9024"
, "WordAvalanches,15556"
, "Wordpress,28014"
, "WorkOnline,34955"
, "worldbuilding,62503"
, "worldevents,39549"
, "worldnews,9843404"
, "worldofpvp,3947"
, "WorldofTanks,26078"
, "WorldofTanksXbox,1489"
, "WorldOfWarships,14689"
, "worldpolitics,150119"
, "worldpowers,2447"
, "worldwhisky,4109"
, "WormFanfic,546"
, "worstof,37425"
, "WoT,13538"
, "WouldYouRather,39373"
, "wow,254317"
, "woweconomy,11193"
, "wowservers,2742"
, "wowthissubexists,74412"
, "Wrangler,7569"
, "Wrasslin,6255"
, "WrestleWithThePlot,15936"
, "wrestling,7589"
, "wrestlingisreddit,196"
, "writing,163310"
, "WritingPrompts,4278661"
, "wsgy,2336"
, "wsu,2487"
, "WTF,4692656"
, "wtfstockphotos,22428"
, "WWE,21207"
, "WWEGames,4665"
, "wwe_network,1029"
, "wwesupercard,2258"
, "wwiipics,10467"
, "WWU,1721"
, "xbmc,17678"
, "xbox,13738"
, "xbox360,48571"
, "xboxone,170503"
, "Xcom,23966"
, "xDivinum,2"
, "Xenoblade_Chronicles,4403"
, "XFiles,16183"
, "xkcd,62961"
, "xposed,11730"
, "xTrill,2404"
, "XWingTMG,8024"
, "xxfitness,89703"
, "xxketo,23640"
, "YanetGarcia,8212"
, "yarntrolls,2171"
, "YasuoMains,963"
, "yee,4661"
, "yesyesyesno,15237"
, "yesyesyesyesno,22447"
, "YMS,9789"
, "ynab,17393"
, "yoga,81031"
, "Yogscast,45014"
, "yogscastkim,4241"
, "yokaiwatch,1338"
, "youdontsurf,191966"
, "YouSeeComrade,25241"
, "YouShouldKnow,513161"
, "youtube,34027"
, "youtubecomments,18579"
, "youtubehaiku,194879"
, "yoyhammer,1854"
, "yugioh,30391"
, "yuruyuri,856"
, "yvonnestrahovski,9131"
, "Zappa,5521"
, "zelda,140888"
, "zen,31825"
, "ZenHabits,107887"
, "Zerxee,2"
, "ZettaiRyouiki,13054"
, "zoidberg,6890"
, "zombies,85610"
]
| elm |
[
{
"context": "Index document vector support.\n\nCopyright (c) 2016 Robin Luiten\n\n-}\n\nimport Dict\nimport Index.Model exposing (Ind",
"end": 212,
"score": 0.9998332858,
"start": 200,
"tag": "NAME",
"value": "Robin Luiten"
}
] | src/Index/Vector.elm | mthadley/elm-text-search | 43 | module Index.Vector exposing (buildDocVector, getDocVector, getQueryVector, scoreAndCompare, similarityBoost, updateDocVector, updateSetAndVec)
{-| Index document vector support.
Copyright (c) 2016 Robin Luiten
-}
import Dict
import Index.Model exposing (Index(..))
import Index.Utils
import Maybe
import Set exposing (Set)
import SparseVector exposing (SparseVector)
import String
import Trie
{-| Build a query vector and the sets of candidate document matches
for each token in our query tokens.
Each token in our query will have a seperate Set String entry in
the returned List. As all query token document result sets are
intersected together for final list of documents matched. (a logical and
of all the query tokens)
-}
getQueryVector :
List String
-> Index doc
-> ( List (Set String), SparseVector, Index doc )
getQueryVector tokens index =
List.foldr
(buildDocVector (List.length tokens))
( [], SparseVector.empty, index )
tokens
{-| Update query vector elements to create query vector.
Update the list of documents that match for each query token (baseToken).
-}
buildDocVector :
Int
-> String
-> ( List (Set String), SparseVector, Index doc )
-> ( List (Set String), SparseVector, Index doc )
buildDocVector tokensLength baseToken ( docSets, vec, (Index irec) as index ) =
let
termFrequency =
1 / toFloat tokensLength
expandedTokens =
Trie.expand baseToken irec.tokenStore
-- _ = Debug.log("buildDocVector") (tokensLength, baseToken, expandedTokens)
( docs, vecU1, indexU1 ) =
List.foldr
(updateSetAndVec termFrequency baseToken)
( Set.empty, vec, index )
expandedTokens
in
( docs :: docSets, vecU1, indexU1 )
{-| Calculate Term frequency-inverse document frequency (tf-idf).
Union of documents for each expandedToken for this (base)token.
-}
updateSetAndVec :
Float
-> String
-> String
-> ( Set String, SparseVector, Index doc )
-> ( Set String, SparseVector, Index doc )
updateSetAndVec tf token expandedToken ( docSets, vec, (Index irec) as index ) =
let
( (Index u1irec) as u1index, keyIdf ) =
Index.Utils.idf index expandedToken
tfidf =
tf * keyIdf * similarityBoost token expandedToken
-- _ = Debug.log("updateSetAndVec") (tf, token, expandedToken, (similarityBoost token expandedToken), keyIdf, tfidf)
-- _ = Debug.log("updateSetAndVec corpus") (irec.corpusTokensIndex)
u1vec =
Maybe.withDefault vec <|
Maybe.map
(\pos -> SparseVector.insert pos tfidf vec)
(Dict.get expandedToken irec.corpusTokensIndex)
expandedTokenDocSet =
Maybe.withDefault Set.empty <|
Maybe.map
(\dict -> Set.fromList (Dict.keys dict))
(Trie.get expandedToken u1irec.tokenStore)
u1docSets =
Set.union expandedTokenDocSet docSets
-- _ = Debug.log("updateSetAndVec u1docSets u1vec") (expandedToken, u1docSets, u1vec)
in
( u1docSets, u1vec, u1index )
{-| if the expanded token is not an exact match to the token then
penalise the score for this key by how different the key is
to the token.
-}
similarityBoost : String -> String -> Float
similarityBoost token expandedToken =
if expandedToken == token then
1
else
1
/ logBase 10
(toFloat
(max 3
(String.length expandedToken
- String.length token
)
)
)
{-| calculate the score for each doc
-}
scoreAndCompare :
SparseVector
-> String
-> ( Index doc, List ( String, Float ) )
-> ( Index doc, List ( String, Float ) )
scoreAndCompare queryVector ref ( index, docs ) =
let
( u1index, docVector ) =
getDocVector index ref
-- _ = Debug.log("scoreAndCompare") (docVector)
in
( u1index, ( ref, SparseVector.cosineSimilarity queryVector docVector ) :: docs )
{-| build vector for docRef
-}
getDocVector : Index doc -> String -> ( Index doc, SparseVector )
getDocVector ((Index irec) as index) docRef =
Maybe.withDefault ( index, SparseVector.empty ) <|
Maybe.map
(\tokenSet ->
List.foldr
(updateDocVector docRef)
( index, SparseVector.empty )
(Set.toList tokenSet)
)
(Dict.get docRef irec.documentStore)
{-| reducer for docRef docVector for this token
-}
updateDocVector : String -> String -> ( Index doc, SparseVector ) -> ( Index doc, SparseVector )
updateDocVector docRef token (( (Index irec) as index, docVector ) as inputTuple) =
Maybe.withDefault inputTuple <|
Maybe.map2
(\position termFrequency ->
let
( u1index, idfScore ) =
Index.Utils.idf index token
in
( u1index, SparseVector.insert position (termFrequency * idfScore) docVector )
)
(Dict.get token irec.corpusTokensIndex)
(Trie.get token irec.tokenStore
|> Maybe.andThen (Dict.get docRef)
)
| 55148 | module Index.Vector exposing (buildDocVector, getDocVector, getQueryVector, scoreAndCompare, similarityBoost, updateDocVector, updateSetAndVec)
{-| Index document vector support.
Copyright (c) 2016 <NAME>
-}
import Dict
import Index.Model exposing (Index(..))
import Index.Utils
import Maybe
import Set exposing (Set)
import SparseVector exposing (SparseVector)
import String
import Trie
{-| Build a query vector and the sets of candidate document matches
for each token in our query tokens.
Each token in our query will have a seperate Set String entry in
the returned List. As all query token document result sets are
intersected together for final list of documents matched. (a logical and
of all the query tokens)
-}
getQueryVector :
List String
-> Index doc
-> ( List (Set String), SparseVector, Index doc )
getQueryVector tokens index =
List.foldr
(buildDocVector (List.length tokens))
( [], SparseVector.empty, index )
tokens
{-| Update query vector elements to create query vector.
Update the list of documents that match for each query token (baseToken).
-}
buildDocVector :
Int
-> String
-> ( List (Set String), SparseVector, Index doc )
-> ( List (Set String), SparseVector, Index doc )
buildDocVector tokensLength baseToken ( docSets, vec, (Index irec) as index ) =
let
termFrequency =
1 / toFloat tokensLength
expandedTokens =
Trie.expand baseToken irec.tokenStore
-- _ = Debug.log("buildDocVector") (tokensLength, baseToken, expandedTokens)
( docs, vecU1, indexU1 ) =
List.foldr
(updateSetAndVec termFrequency baseToken)
( Set.empty, vec, index )
expandedTokens
in
( docs :: docSets, vecU1, indexU1 )
{-| Calculate Term frequency-inverse document frequency (tf-idf).
Union of documents for each expandedToken for this (base)token.
-}
updateSetAndVec :
Float
-> String
-> String
-> ( Set String, SparseVector, Index doc )
-> ( Set String, SparseVector, Index doc )
updateSetAndVec tf token expandedToken ( docSets, vec, (Index irec) as index ) =
let
( (Index u1irec) as u1index, keyIdf ) =
Index.Utils.idf index expandedToken
tfidf =
tf * keyIdf * similarityBoost token expandedToken
-- _ = Debug.log("updateSetAndVec") (tf, token, expandedToken, (similarityBoost token expandedToken), keyIdf, tfidf)
-- _ = Debug.log("updateSetAndVec corpus") (irec.corpusTokensIndex)
u1vec =
Maybe.withDefault vec <|
Maybe.map
(\pos -> SparseVector.insert pos tfidf vec)
(Dict.get expandedToken irec.corpusTokensIndex)
expandedTokenDocSet =
Maybe.withDefault Set.empty <|
Maybe.map
(\dict -> Set.fromList (Dict.keys dict))
(Trie.get expandedToken u1irec.tokenStore)
u1docSets =
Set.union expandedTokenDocSet docSets
-- _ = Debug.log("updateSetAndVec u1docSets u1vec") (expandedToken, u1docSets, u1vec)
in
( u1docSets, u1vec, u1index )
{-| if the expanded token is not an exact match to the token then
penalise the score for this key by how different the key is
to the token.
-}
similarityBoost : String -> String -> Float
similarityBoost token expandedToken =
if expandedToken == token then
1
else
1
/ logBase 10
(toFloat
(max 3
(String.length expandedToken
- String.length token
)
)
)
{-| calculate the score for each doc
-}
scoreAndCompare :
SparseVector
-> String
-> ( Index doc, List ( String, Float ) )
-> ( Index doc, List ( String, Float ) )
scoreAndCompare queryVector ref ( index, docs ) =
let
( u1index, docVector ) =
getDocVector index ref
-- _ = Debug.log("scoreAndCompare") (docVector)
in
( u1index, ( ref, SparseVector.cosineSimilarity queryVector docVector ) :: docs )
{-| build vector for docRef
-}
getDocVector : Index doc -> String -> ( Index doc, SparseVector )
getDocVector ((Index irec) as index) docRef =
Maybe.withDefault ( index, SparseVector.empty ) <|
Maybe.map
(\tokenSet ->
List.foldr
(updateDocVector docRef)
( index, SparseVector.empty )
(Set.toList tokenSet)
)
(Dict.get docRef irec.documentStore)
{-| reducer for docRef docVector for this token
-}
updateDocVector : String -> String -> ( Index doc, SparseVector ) -> ( Index doc, SparseVector )
updateDocVector docRef token (( (Index irec) as index, docVector ) as inputTuple) =
Maybe.withDefault inputTuple <|
Maybe.map2
(\position termFrequency ->
let
( u1index, idfScore ) =
Index.Utils.idf index token
in
( u1index, SparseVector.insert position (termFrequency * idfScore) docVector )
)
(Dict.get token irec.corpusTokensIndex)
(Trie.get token irec.tokenStore
|> Maybe.andThen (Dict.get docRef)
)
| true | module Index.Vector exposing (buildDocVector, getDocVector, getQueryVector, scoreAndCompare, similarityBoost, updateDocVector, updateSetAndVec)
{-| Index document vector support.
Copyright (c) 2016 PI:NAME:<NAME>END_PI
-}
import Dict
import Index.Model exposing (Index(..))
import Index.Utils
import Maybe
import Set exposing (Set)
import SparseVector exposing (SparseVector)
import String
import Trie
{-| Build a query vector and the sets of candidate document matches
for each token in our query tokens.
Each token in our query will have a seperate Set String entry in
the returned List. As all query token document result sets are
intersected together for final list of documents matched. (a logical and
of all the query tokens)
-}
getQueryVector :
List String
-> Index doc
-> ( List (Set String), SparseVector, Index doc )
getQueryVector tokens index =
List.foldr
(buildDocVector (List.length tokens))
( [], SparseVector.empty, index )
tokens
{-| Update query vector elements to create query vector.
Update the list of documents that match for each query token (baseToken).
-}
buildDocVector :
Int
-> String
-> ( List (Set String), SparseVector, Index doc )
-> ( List (Set String), SparseVector, Index doc )
buildDocVector tokensLength baseToken ( docSets, vec, (Index irec) as index ) =
let
termFrequency =
1 / toFloat tokensLength
expandedTokens =
Trie.expand baseToken irec.tokenStore
-- _ = Debug.log("buildDocVector") (tokensLength, baseToken, expandedTokens)
( docs, vecU1, indexU1 ) =
List.foldr
(updateSetAndVec termFrequency baseToken)
( Set.empty, vec, index )
expandedTokens
in
( docs :: docSets, vecU1, indexU1 )
{-| Calculate Term frequency-inverse document frequency (tf-idf).
Union of documents for each expandedToken for this (base)token.
-}
updateSetAndVec :
Float
-> String
-> String
-> ( Set String, SparseVector, Index doc )
-> ( Set String, SparseVector, Index doc )
updateSetAndVec tf token expandedToken ( docSets, vec, (Index irec) as index ) =
let
( (Index u1irec) as u1index, keyIdf ) =
Index.Utils.idf index expandedToken
tfidf =
tf * keyIdf * similarityBoost token expandedToken
-- _ = Debug.log("updateSetAndVec") (tf, token, expandedToken, (similarityBoost token expandedToken), keyIdf, tfidf)
-- _ = Debug.log("updateSetAndVec corpus") (irec.corpusTokensIndex)
u1vec =
Maybe.withDefault vec <|
Maybe.map
(\pos -> SparseVector.insert pos tfidf vec)
(Dict.get expandedToken irec.corpusTokensIndex)
expandedTokenDocSet =
Maybe.withDefault Set.empty <|
Maybe.map
(\dict -> Set.fromList (Dict.keys dict))
(Trie.get expandedToken u1irec.tokenStore)
u1docSets =
Set.union expandedTokenDocSet docSets
-- _ = Debug.log("updateSetAndVec u1docSets u1vec") (expandedToken, u1docSets, u1vec)
in
( u1docSets, u1vec, u1index )
{-| if the expanded token is not an exact match to the token then
penalise the score for this key by how different the key is
to the token.
-}
similarityBoost : String -> String -> Float
similarityBoost token expandedToken =
if expandedToken == token then
1
else
1
/ logBase 10
(toFloat
(max 3
(String.length expandedToken
- String.length token
)
)
)
{-| calculate the score for each doc
-}
scoreAndCompare :
SparseVector
-> String
-> ( Index doc, List ( String, Float ) )
-> ( Index doc, List ( String, Float ) )
scoreAndCompare queryVector ref ( index, docs ) =
let
( u1index, docVector ) =
getDocVector index ref
-- _ = Debug.log("scoreAndCompare") (docVector)
in
( u1index, ( ref, SparseVector.cosineSimilarity queryVector docVector ) :: docs )
{-| build vector for docRef
-}
getDocVector : Index doc -> String -> ( Index doc, SparseVector )
getDocVector ((Index irec) as index) docRef =
Maybe.withDefault ( index, SparseVector.empty ) <|
Maybe.map
(\tokenSet ->
List.foldr
(updateDocVector docRef)
( index, SparseVector.empty )
(Set.toList tokenSet)
)
(Dict.get docRef irec.documentStore)
{-| reducer for docRef docVector for this token
-}
updateDocVector : String -> String -> ( Index doc, SparseVector ) -> ( Index doc, SparseVector )
updateDocVector docRef token (( (Index irec) as index, docVector ) as inputTuple) =
Maybe.withDefault inputTuple <|
Maybe.map2
(\position termFrequency ->
let
( u1index, idfScore ) =
Index.Utils.idf index token
in
( u1index, SparseVector.insert position (termFrequency * idfScore) docVector )
)
(Dict.get token irec.corpusTokensIndex)
(Trie.get token irec.tokenStore
|> Maybe.andThen (Dict.get docRef)
)
| elm |
[
{
"context": "with elm-3d-scene.\n\nThe “Pod” model is courtesy of Kolja Wilcke <https://twitter.com/01k>\n\n-}\n\nimport Angle expos",
"end": 193,
"score": 0.9998989105,
"start": 181,
"tag": "NAME",
"value": "Kolja Wilcke"
},
{
"context": " is courtesy of Kolja Wilcke <https://twitter.com/01k>\n\n-}\n\nimport Angle exposing (Angle)\nimport Browse",
"end": 218,
"score": 0.9985658526,
"start": 215,
"tag": "USERNAME",
"value": "01k"
},
{
"context": " [ Html.Attributes.href \"https://twitter.com/01k\"\n , Html.Attributes.ta",
"end": 8044,
"score": 0.9979951978,
"start": 8041,
"tag": "USERNAME",
"value": "01k"
},
{
"context": " ]\n [ Html.text \"Kolja Wilcke\"\n ]\n ",
"end": 8191,
"score": 0.9998895526,
"start": 8179,
"tag": "NAME",
"value": "Kolja Wilcke"
}
] | examples/src/Pod.elm | w0rm/elm-obj-file | 22 | module Pod exposing (main)
{-| This example demonstrates how to extract multiple meshes with
shadows from an OBJ file and render with elm-3d-scene.
The “Pod” model is courtesy of Kolja Wilcke <https://twitter.com/01k>
-}
import Angle exposing (Angle)
import Browser
import Browser.Events
import Camera3d
import Color exposing (Color)
import Direction3d
import Html exposing (Html)
import Html.Attributes
import Html.Events
import Http
import Json.Decode
import Length
import Obj.Decode exposing (Decoder, ObjCoordinates)
import Pixels exposing (Pixels)
import Point3d
import Quantity exposing (Quantity)
import Scene3d
import Scene3d.Material exposing (Texture)
import Scene3d.Mesh exposing (Shadow, Textured)
import SketchPlane3d
import Task
import Viewpoint3d
import WebGL.Texture
{-| Custom filter for all objects that start with a prefix.
-}
objectStartsWith : String -> Decoder a -> Decoder a
objectStartsWith prefix =
Obj.Decode.filter
(\{ object } ->
case object of
Just objectName ->
String.startsWith prefix objectName
Nothing ->
False
)
{-| Decode a list of meshes for matching object names.
-}
listOfObjects : Decoder a -> Decoder (List a)
listOfObjects decoder =
Obj.Decode.objectNames
|> Obj.Decode.andThen
(\objectNames ->
objectNames
|> List.map (\objectName -> Obj.Decode.object objectName decoder)
|> Obj.Decode.combine
)
type alias MeshWithShadow =
{ mesh : Textured ObjCoordinates
, shadow : Shadow ObjCoordinates
}
{-| Decode a mesh together with the shadow.
-}
meshWithShadow : Decoder MeshWithShadow
meshWithShadow =
Obj.Decode.map
(\texturedFaces ->
let
mesh =
Scene3d.Mesh.texturedFaces texturedFaces
|> Scene3d.Mesh.cullBackFaces
in
MeshWithShadow mesh (Scene3d.Mesh.shadow mesh)
)
Obj.Decode.texturedFaces
type alias Meshes =
{ pod : MeshWithShadow
, guns : List MeshWithShadow
, wheels : List MeshWithShadow
}
{-| Maps three decoders to get a decoder of the required meshes.
-}
meshes : Decoder Meshes
meshes =
Obj.Decode.map3 Meshes
(objectStartsWith "pod_" meshWithShadow)
(objectStartsWith "gun_" (listOfObjects meshWithShadow))
(objectStartsWith "wheel_" (listOfObjects meshWithShadow))
type alias Model =
{ material : Maybe (Scene3d.Material.Textured ObjCoordinates)
, meshes : Maybe Meshes
, azimuth : Angle
, elevation : Angle
, zoom : Float
, orbiting : Bool
}
type Msg
= LoadedTexture (Result WebGL.Texture.Error (Texture Color))
| LoadedMeshes (Result Http.Error Meshes)
| MouseDown
| MouseUp
| MouseMove (Quantity Float Pixels) (Quantity Float Pixels)
| MouseWheel Float
init : () -> ( Model, Cmd Msg )
init () =
( { material = Nothing
, meshes = Nothing
, azimuth = Angle.degrees -45
, elevation = Angle.degrees 35
, orbiting = False
, zoom = 0
}
, Cmd.batch
[ Scene3d.Material.loadWith Scene3d.Material.nearestNeighborFiltering "Pod.png"
|> Task.attempt LoadedTexture
, Http.get
{ url = "Pod.obj.txt" -- .txt is required to work with `elm reactor`
, expect = Obj.Decode.expectObj LoadedMeshes Length.meters meshes
}
]
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
LoadedTexture result ->
( { model
| material =
result
|> Result.map Scene3d.Material.texturedMatte
|> Result.toMaybe
}
, Cmd.none
)
LoadedMeshes result ->
( { model | meshes = Result.toMaybe result }
, Cmd.none
)
MouseDown ->
( { model | orbiting = True }, Cmd.none )
MouseUp ->
( { model | orbiting = False }, Cmd.none )
MouseMove dx dy ->
if model.orbiting then
let
rotationRate =
Quantity.per Pixels.pixel (Angle.degrees 1)
in
( { model
| azimuth =
model.azimuth
|> Quantity.minus (Quantity.at rotationRate dx)
, elevation =
model.elevation
|> Quantity.plus (Quantity.at rotationRate dy)
|> Quantity.clamp (Angle.degrees -90) (Angle.degrees 90)
}
, Cmd.none
)
else
( model, Cmd.none )
MouseWheel deltaY ->
( { model | zoom = clamp 0 1 (model.zoom - deltaY * 0.002) }, Cmd.none )
view : Model -> Html Msg
view model =
let
camera =
Camera3d.perspective
{ viewpoint =
Viewpoint3d.orbitZ
{ focalPoint = Point3d.meters 0 0 1
, azimuth = model.azimuth
, elevation = model.elevation
, distance = Length.meters (16 - model.zoom * 8)
}
, verticalFieldOfView = Angle.degrees 30
}
in
case ( model.material, model.meshes ) of
( Just material, Just { pod, guns, wheels } ) ->
Html.figure
[ Html.Attributes.style "display" "block"
, Html.Attributes.style "width" "640px"
, Html.Attributes.style "margin" "auto"
, Html.Attributes.style "padding" "20px"
, Html.Events.preventDefaultOn "wheel"
(Json.Decode.map
(\deltaY -> ( MouseWheel deltaY, True ))
(Json.Decode.field "deltaY" Json.Decode.float)
)
]
[ Scene3d.sunny
{ upDirection = Direction3d.z
, sunlightDirection =
Direction3d.fromAzimuthInAndElevationFrom SketchPlane3d.xy
(Angle.degrees 135)
(Angle.degrees -55)
, shadows = True
, camera = camera
, dimensions = ( Pixels.int 640, Pixels.int 640 )
, background = Scene3d.backgroundColor Color.lightGray
, clipDepth = Length.meters 0.1
, entities =
[ Scene3d.meshWithShadow material pod.mesh pod.shadow
, case List.head (List.drop 2 guns) of
Just { mesh, shadow } ->
Scene3d.meshWithShadow material mesh shadow
Nothing ->
Scene3d.nothing
, wheels
|> List.map
(\{ mesh, shadow } ->
Scene3d.meshWithShadow material mesh shadow
)
|> Scene3d.group
, Scene3d.quad (Scene3d.Material.matte Color.lightBlue)
(Point3d.meters -5 5 -0.02)
(Point3d.meters 5 5 -0.02)
(Point3d.meters 5 -5 -0.02)
(Point3d.meters -5 -5 -0.02)
]
}
, Html.figcaption [ Html.Attributes.style "font" "14px/1.5 sans-serif" ]
[ Html.p []
[ Html.text "The “Pod” model is courtesy of "
, Html.a
[ Html.Attributes.href "https://twitter.com/01k"
, Html.Attributes.target "_blank"
]
[ Html.text "Kolja Wilcke"
]
]
]
]
_ ->
Html.text "Loading texture and meshes…"
main : Program () Model Msg
main =
Browser.element
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
subscriptions : Model -> Sub Msg
subscriptions model =
if model.orbiting then
Sub.batch
[ Browser.Events.onMouseMove decodeMouseMove
, Browser.Events.onMouseUp (Json.Decode.succeed MouseUp)
]
else
Browser.Events.onMouseDown (Json.Decode.succeed MouseDown)
decodeMouseMove : Json.Decode.Decoder Msg
decodeMouseMove =
Json.Decode.map2 MouseMove
(Json.Decode.field "movementX" (Json.Decode.map Pixels.float Json.Decode.float))
(Json.Decode.field "movementY" (Json.Decode.map Pixels.float Json.Decode.float))
| 38562 | module Pod exposing (main)
{-| This example demonstrates how to extract multiple meshes with
shadows from an OBJ file and render with elm-3d-scene.
The “Pod” model is courtesy of <NAME> <https://twitter.com/01k>
-}
import Angle exposing (Angle)
import Browser
import Browser.Events
import Camera3d
import Color exposing (Color)
import Direction3d
import Html exposing (Html)
import Html.Attributes
import Html.Events
import Http
import Json.Decode
import Length
import Obj.Decode exposing (Decoder, ObjCoordinates)
import Pixels exposing (Pixels)
import Point3d
import Quantity exposing (Quantity)
import Scene3d
import Scene3d.Material exposing (Texture)
import Scene3d.Mesh exposing (Shadow, Textured)
import SketchPlane3d
import Task
import Viewpoint3d
import WebGL.Texture
{-| Custom filter for all objects that start with a prefix.
-}
objectStartsWith : String -> Decoder a -> Decoder a
objectStartsWith prefix =
Obj.Decode.filter
(\{ object } ->
case object of
Just objectName ->
String.startsWith prefix objectName
Nothing ->
False
)
{-| Decode a list of meshes for matching object names.
-}
listOfObjects : Decoder a -> Decoder (List a)
listOfObjects decoder =
Obj.Decode.objectNames
|> Obj.Decode.andThen
(\objectNames ->
objectNames
|> List.map (\objectName -> Obj.Decode.object objectName decoder)
|> Obj.Decode.combine
)
type alias MeshWithShadow =
{ mesh : Textured ObjCoordinates
, shadow : Shadow ObjCoordinates
}
{-| Decode a mesh together with the shadow.
-}
meshWithShadow : Decoder MeshWithShadow
meshWithShadow =
Obj.Decode.map
(\texturedFaces ->
let
mesh =
Scene3d.Mesh.texturedFaces texturedFaces
|> Scene3d.Mesh.cullBackFaces
in
MeshWithShadow mesh (Scene3d.Mesh.shadow mesh)
)
Obj.Decode.texturedFaces
type alias Meshes =
{ pod : MeshWithShadow
, guns : List MeshWithShadow
, wheels : List MeshWithShadow
}
{-| Maps three decoders to get a decoder of the required meshes.
-}
meshes : Decoder Meshes
meshes =
Obj.Decode.map3 Meshes
(objectStartsWith "pod_" meshWithShadow)
(objectStartsWith "gun_" (listOfObjects meshWithShadow))
(objectStartsWith "wheel_" (listOfObjects meshWithShadow))
type alias Model =
{ material : Maybe (Scene3d.Material.Textured ObjCoordinates)
, meshes : Maybe Meshes
, azimuth : Angle
, elevation : Angle
, zoom : Float
, orbiting : Bool
}
type Msg
= LoadedTexture (Result WebGL.Texture.Error (Texture Color))
| LoadedMeshes (Result Http.Error Meshes)
| MouseDown
| MouseUp
| MouseMove (Quantity Float Pixels) (Quantity Float Pixels)
| MouseWheel Float
init : () -> ( Model, Cmd Msg )
init () =
( { material = Nothing
, meshes = Nothing
, azimuth = Angle.degrees -45
, elevation = Angle.degrees 35
, orbiting = False
, zoom = 0
}
, Cmd.batch
[ Scene3d.Material.loadWith Scene3d.Material.nearestNeighborFiltering "Pod.png"
|> Task.attempt LoadedTexture
, Http.get
{ url = "Pod.obj.txt" -- .txt is required to work with `elm reactor`
, expect = Obj.Decode.expectObj LoadedMeshes Length.meters meshes
}
]
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
LoadedTexture result ->
( { model
| material =
result
|> Result.map Scene3d.Material.texturedMatte
|> Result.toMaybe
}
, Cmd.none
)
LoadedMeshes result ->
( { model | meshes = Result.toMaybe result }
, Cmd.none
)
MouseDown ->
( { model | orbiting = True }, Cmd.none )
MouseUp ->
( { model | orbiting = False }, Cmd.none )
MouseMove dx dy ->
if model.orbiting then
let
rotationRate =
Quantity.per Pixels.pixel (Angle.degrees 1)
in
( { model
| azimuth =
model.azimuth
|> Quantity.minus (Quantity.at rotationRate dx)
, elevation =
model.elevation
|> Quantity.plus (Quantity.at rotationRate dy)
|> Quantity.clamp (Angle.degrees -90) (Angle.degrees 90)
}
, Cmd.none
)
else
( model, Cmd.none )
MouseWheel deltaY ->
( { model | zoom = clamp 0 1 (model.zoom - deltaY * 0.002) }, Cmd.none )
view : Model -> Html Msg
view model =
let
camera =
Camera3d.perspective
{ viewpoint =
Viewpoint3d.orbitZ
{ focalPoint = Point3d.meters 0 0 1
, azimuth = model.azimuth
, elevation = model.elevation
, distance = Length.meters (16 - model.zoom * 8)
}
, verticalFieldOfView = Angle.degrees 30
}
in
case ( model.material, model.meshes ) of
( Just material, Just { pod, guns, wheels } ) ->
Html.figure
[ Html.Attributes.style "display" "block"
, Html.Attributes.style "width" "640px"
, Html.Attributes.style "margin" "auto"
, Html.Attributes.style "padding" "20px"
, Html.Events.preventDefaultOn "wheel"
(Json.Decode.map
(\deltaY -> ( MouseWheel deltaY, True ))
(Json.Decode.field "deltaY" Json.Decode.float)
)
]
[ Scene3d.sunny
{ upDirection = Direction3d.z
, sunlightDirection =
Direction3d.fromAzimuthInAndElevationFrom SketchPlane3d.xy
(Angle.degrees 135)
(Angle.degrees -55)
, shadows = True
, camera = camera
, dimensions = ( Pixels.int 640, Pixels.int 640 )
, background = Scene3d.backgroundColor Color.lightGray
, clipDepth = Length.meters 0.1
, entities =
[ Scene3d.meshWithShadow material pod.mesh pod.shadow
, case List.head (List.drop 2 guns) of
Just { mesh, shadow } ->
Scene3d.meshWithShadow material mesh shadow
Nothing ->
Scene3d.nothing
, wheels
|> List.map
(\{ mesh, shadow } ->
Scene3d.meshWithShadow material mesh shadow
)
|> Scene3d.group
, Scene3d.quad (Scene3d.Material.matte Color.lightBlue)
(Point3d.meters -5 5 -0.02)
(Point3d.meters 5 5 -0.02)
(Point3d.meters 5 -5 -0.02)
(Point3d.meters -5 -5 -0.02)
]
}
, Html.figcaption [ Html.Attributes.style "font" "14px/1.5 sans-serif" ]
[ Html.p []
[ Html.text "The “Pod” model is courtesy of "
, Html.a
[ Html.Attributes.href "https://twitter.com/01k"
, Html.Attributes.target "_blank"
]
[ Html.text "<NAME>"
]
]
]
]
_ ->
Html.text "Loading texture and meshes…"
main : Program () Model Msg
main =
Browser.element
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
subscriptions : Model -> Sub Msg
subscriptions model =
if model.orbiting then
Sub.batch
[ Browser.Events.onMouseMove decodeMouseMove
, Browser.Events.onMouseUp (Json.Decode.succeed MouseUp)
]
else
Browser.Events.onMouseDown (Json.Decode.succeed MouseDown)
decodeMouseMove : Json.Decode.Decoder Msg
decodeMouseMove =
Json.Decode.map2 MouseMove
(Json.Decode.field "movementX" (Json.Decode.map Pixels.float Json.Decode.float))
(Json.Decode.field "movementY" (Json.Decode.map Pixels.float Json.Decode.float))
| true | module Pod exposing (main)
{-| This example demonstrates how to extract multiple meshes with
shadows from an OBJ file and render with elm-3d-scene.
The “Pod” model is courtesy of PI:NAME:<NAME>END_PI <https://twitter.com/01k>
-}
import Angle exposing (Angle)
import Browser
import Browser.Events
import Camera3d
import Color exposing (Color)
import Direction3d
import Html exposing (Html)
import Html.Attributes
import Html.Events
import Http
import Json.Decode
import Length
import Obj.Decode exposing (Decoder, ObjCoordinates)
import Pixels exposing (Pixels)
import Point3d
import Quantity exposing (Quantity)
import Scene3d
import Scene3d.Material exposing (Texture)
import Scene3d.Mesh exposing (Shadow, Textured)
import SketchPlane3d
import Task
import Viewpoint3d
import WebGL.Texture
{-| Custom filter for all objects that start with a prefix.
-}
objectStartsWith : String -> Decoder a -> Decoder a
objectStartsWith prefix =
Obj.Decode.filter
(\{ object } ->
case object of
Just objectName ->
String.startsWith prefix objectName
Nothing ->
False
)
{-| Decode a list of meshes for matching object names.
-}
listOfObjects : Decoder a -> Decoder (List a)
listOfObjects decoder =
Obj.Decode.objectNames
|> Obj.Decode.andThen
(\objectNames ->
objectNames
|> List.map (\objectName -> Obj.Decode.object objectName decoder)
|> Obj.Decode.combine
)
type alias MeshWithShadow =
{ mesh : Textured ObjCoordinates
, shadow : Shadow ObjCoordinates
}
{-| Decode a mesh together with the shadow.
-}
meshWithShadow : Decoder MeshWithShadow
meshWithShadow =
Obj.Decode.map
(\texturedFaces ->
let
mesh =
Scene3d.Mesh.texturedFaces texturedFaces
|> Scene3d.Mesh.cullBackFaces
in
MeshWithShadow mesh (Scene3d.Mesh.shadow mesh)
)
Obj.Decode.texturedFaces
type alias Meshes =
{ pod : MeshWithShadow
, guns : List MeshWithShadow
, wheels : List MeshWithShadow
}
{-| Maps three decoders to get a decoder of the required meshes.
-}
meshes : Decoder Meshes
meshes =
Obj.Decode.map3 Meshes
(objectStartsWith "pod_" meshWithShadow)
(objectStartsWith "gun_" (listOfObjects meshWithShadow))
(objectStartsWith "wheel_" (listOfObjects meshWithShadow))
type alias Model =
{ material : Maybe (Scene3d.Material.Textured ObjCoordinates)
, meshes : Maybe Meshes
, azimuth : Angle
, elevation : Angle
, zoom : Float
, orbiting : Bool
}
type Msg
= LoadedTexture (Result WebGL.Texture.Error (Texture Color))
| LoadedMeshes (Result Http.Error Meshes)
| MouseDown
| MouseUp
| MouseMove (Quantity Float Pixels) (Quantity Float Pixels)
| MouseWheel Float
init : () -> ( Model, Cmd Msg )
init () =
( { material = Nothing
, meshes = Nothing
, azimuth = Angle.degrees -45
, elevation = Angle.degrees 35
, orbiting = False
, zoom = 0
}
, Cmd.batch
[ Scene3d.Material.loadWith Scene3d.Material.nearestNeighborFiltering "Pod.png"
|> Task.attempt LoadedTexture
, Http.get
{ url = "Pod.obj.txt" -- .txt is required to work with `elm reactor`
, expect = Obj.Decode.expectObj LoadedMeshes Length.meters meshes
}
]
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
LoadedTexture result ->
( { model
| material =
result
|> Result.map Scene3d.Material.texturedMatte
|> Result.toMaybe
}
, Cmd.none
)
LoadedMeshes result ->
( { model | meshes = Result.toMaybe result }
, Cmd.none
)
MouseDown ->
( { model | orbiting = True }, Cmd.none )
MouseUp ->
( { model | orbiting = False }, Cmd.none )
MouseMove dx dy ->
if model.orbiting then
let
rotationRate =
Quantity.per Pixels.pixel (Angle.degrees 1)
in
( { model
| azimuth =
model.azimuth
|> Quantity.minus (Quantity.at rotationRate dx)
, elevation =
model.elevation
|> Quantity.plus (Quantity.at rotationRate dy)
|> Quantity.clamp (Angle.degrees -90) (Angle.degrees 90)
}
, Cmd.none
)
else
( model, Cmd.none )
MouseWheel deltaY ->
( { model | zoom = clamp 0 1 (model.zoom - deltaY * 0.002) }, Cmd.none )
view : Model -> Html Msg
view model =
let
camera =
Camera3d.perspective
{ viewpoint =
Viewpoint3d.orbitZ
{ focalPoint = Point3d.meters 0 0 1
, azimuth = model.azimuth
, elevation = model.elevation
, distance = Length.meters (16 - model.zoom * 8)
}
, verticalFieldOfView = Angle.degrees 30
}
in
case ( model.material, model.meshes ) of
( Just material, Just { pod, guns, wheels } ) ->
Html.figure
[ Html.Attributes.style "display" "block"
, Html.Attributes.style "width" "640px"
, Html.Attributes.style "margin" "auto"
, Html.Attributes.style "padding" "20px"
, Html.Events.preventDefaultOn "wheel"
(Json.Decode.map
(\deltaY -> ( MouseWheel deltaY, True ))
(Json.Decode.field "deltaY" Json.Decode.float)
)
]
[ Scene3d.sunny
{ upDirection = Direction3d.z
, sunlightDirection =
Direction3d.fromAzimuthInAndElevationFrom SketchPlane3d.xy
(Angle.degrees 135)
(Angle.degrees -55)
, shadows = True
, camera = camera
, dimensions = ( Pixels.int 640, Pixels.int 640 )
, background = Scene3d.backgroundColor Color.lightGray
, clipDepth = Length.meters 0.1
, entities =
[ Scene3d.meshWithShadow material pod.mesh pod.shadow
, case List.head (List.drop 2 guns) of
Just { mesh, shadow } ->
Scene3d.meshWithShadow material mesh shadow
Nothing ->
Scene3d.nothing
, wheels
|> List.map
(\{ mesh, shadow } ->
Scene3d.meshWithShadow material mesh shadow
)
|> Scene3d.group
, Scene3d.quad (Scene3d.Material.matte Color.lightBlue)
(Point3d.meters -5 5 -0.02)
(Point3d.meters 5 5 -0.02)
(Point3d.meters 5 -5 -0.02)
(Point3d.meters -5 -5 -0.02)
]
}
, Html.figcaption [ Html.Attributes.style "font" "14px/1.5 sans-serif" ]
[ Html.p []
[ Html.text "The “Pod” model is courtesy of "
, Html.a
[ Html.Attributes.href "https://twitter.com/01k"
, Html.Attributes.target "_blank"
]
[ Html.text "PI:NAME:<NAME>END_PI"
]
]
]
]
_ ->
Html.text "Loading texture and meshes…"
main : Program () Model Msg
main =
Browser.element
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
subscriptions : Model -> Sub Msg
subscriptions model =
if model.orbiting then
Sub.batch
[ Browser.Events.onMouseMove decodeMouseMove
, Browser.Events.onMouseUp (Json.Decode.succeed MouseUp)
]
else
Browser.Events.onMouseDown (Json.Decode.succeed MouseDown)
decodeMouseMove : Json.Decode.Decoder Msg
decodeMouseMove =
Json.Decode.map2 MouseMove
(Json.Decode.field "movementX" (Json.Decode.map Pixels.float Json.Decode.float))
(Json.Decode.field "movementY" (Json.Decode.map Pixels.float Json.Decode.float))
| elm |
[
{
"context": " Password password ->\n ({ model | password = password }, Cmd.none)\n\n PasswordAgain password ->\n ",
"end": 1145,
"score": 0.6835051179,
"start": 1137,
"tag": "PASSWORD",
"value": "password"
}
] | index.elm | cy6erskunk/elm-onboarding | 0 | import Html exposing (..)
import Html.App as App
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput, onCheck)
import String
import Http
import Json.Decode as Json
import Json.Decode exposing ((:=))
import Task
import Svg exposing (..)
import Svg.Attributes exposing (..)
import Time exposing (Time, second)
main : Program Never
main = App.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- Model
type alias Model =
{ counter : Int
, name : String
, password : String
, passwordAgain : String
, isRevealed : Bool
, dieFace : Int
, url : String
, reqError : String
, someResponse : ProjectsResponse
, time : Time
, startTime : Time
}
-- Update
type Msg
= Name String
| Password String
| PasswordAgain String
| Reveal Bool
| UpdateUrl String
| SendRequest
| FetchFail Http.Error
| FetchSucceed ProjectsResponse
| Tick Time
update: Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Name name ->
({ model | name = name }, Cmd.none)
Password password ->
({ model | password = password }, Cmd.none)
PasswordAgain password ->
({ model | passwordAgain = password }, Cmd.none)
Reveal doReveal ->
({ model | isRevealed = doReveal }, Cmd.none)
UpdateUrl newUrl ->
({ model | url = newUrl }, Cmd.none)
SendRequest ->
(model, fetchData model.url)
FetchFail error ->
case error of
Http.Timeout ->
({ model | reqError = "Timeout happened :(" }, Cmd.none)
Http.NetworkError ->
({ model | reqError = "NetworkError :'(" }, Cmd.none)
Http.UnexpectedPayload s ->
({ model | reqError = "UnexpectedPayload: " ++ s }, Cmd.none)
Http.BadResponse code str ->
({ model | reqError = (toString code) ++ ": " ++ str }, Cmd.none)
FetchSucceed str ->
({ model | someResponse = str, reqError = "" }, Cmd.none)
Tick newTime ->
({ model
| startTime = if model.startTime == 0 then newTime else model.startTime
, time = if model.startTime == 0 then 1 * Time.second else newTime - model.startTime + 1 * Time.second
}, Cmd.none)
-- View
view: Model -> Html Msg
view model =
div []
[ viewClock model
, viewLoginPassword model
, viewValidation model
, viewHttpReq model
]
viewClock : Model -> Html Msg
viewClock model =
let
angle =
turns (Time.inMinutes model.time - 1/4)
handX =
toString (50 + 40 * cos angle)
handY =
toString (50 + 40 * sin angle)
in
Svg.svg [ viewBox "0 0 100 100", Svg.Attributes.width "100px"]
[ circle [ cx "50", cy "50", r "45", fill "#0b79ce" ] []
, line [ x1 "50", y1 "50", x2 handX, y2 handY, stroke "#023963" ] []
, Svg.text' [ x "25", y "45", fontSize "8px" ] [ Svg.text (toString <| model.time) ]
]
viewLoginPassword: Model -> Html Msg
viewLoginPassword model =
div []
[ input [ Html.Attributes.type' "text", placeholder "Name", onInput Name ] []
, input [ Html.Attributes.type' (if model.isRevealed then "text" else "password"), placeholder "Password", onInput Password ] []
, input [ Html.Attributes.type' (if model.isRevealed then "text" else "password"), placeholder "Password Again", onInput PasswordAgain ] []
, input [ Html.Attributes.type' "checkbox", onCheck Reveal ] []
, Html.text "reveal everything!"
]
viewValidation : Model -> Html Msg
viewValidation model =
let
(color, message) =
if model.password == model.passwordAgain then
if (String.length model.password < 4) then
("salmon", "so weak, sol languid...")
else
("green", "OK")
else
("red", "Are you a terrorist or what?")
in
div [ Html.Attributes.style [("color", color)] ] [ Html.text message ]
viewHttpReq : Model -> Html Msg
viewHttpReq model =
div []
[ input [ onInput UpdateUrl, value model.url ] []
, Html.text (toString model.url)
, button [ onClick SendRequest ] [ Html.text "Go!" ]
, div [] [ Html.text model.reqError ]
, div [] [ Html.text (toString model.someResponse.count) ]
, if (List.length model.someResponse.project) > 0
then Html.ul [] <| List.map (\p ->
Html.li [] [
Html.a [Html.Attributes.target "_blank", href p.href] [Html.text p.name]
]
) model.someResponse.project
else Html.text "no projects ;("
]
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every second Tick
-- INIT
init : (Model, Cmd Msg)
init =
(Model 0 "" "" "" False 1 "http://localhost/" "" emptyProjectsResponse 0 0, Cmd.none)
-- HTTP
fetchData : String -> Cmd Msg
fetchData url =
-- Http.send : Settings -> Request -> Task RawError Response
-- fromJson : Decoder a -> Task RawError Response -> Task Error a
Http.send Http.defaultSettings {
verb = "GET"
, headers = [("Accept", "application/json")]
, url = url
, body = Http.empty
}
|> Http.fromJson decodeResponseJson
|> Task.perform FetchFail FetchSucceed
decodeResponseJson : Json.Decoder ProjectsResponse
decodeResponseJson =
Json.Decode.object3 ProjectsResponse
("count" := Json.Decode.int)
("href" := Json.Decode.string)
("project" := decodeProjectsList
)
decodeProjectsList : Json.Decoder (List Project)
decodeProjectsList =
Json.Decode.object7 Project
("name" := Json.Decode.string)
("id" := Json.Decode.string)
("href" := Json.Decode.string)
("webUrl" := Json.Decode.string)
(Json.Decode.oneOf ["parentProjectId" := Json.Decode.string, Json.Decode.succeed ""])
(Json.Decode.oneOf ["description" := Json.Decode.string, Json.Decode.succeed ""])
(Json.Decode.oneOf ["archived" := Json.Decode.bool, Json.Decode.succeed False])
|> Json.Decode.list
type alias Project =
{ name : String
, id : String
, href : String
, webUrl : String
, parentProjectId : String
, description : String
, archived : Bool
}
type alias ProjectsResponse =
{ count : Int
, href : String
, project : List Project
}
emptyProjectsResponse : ProjectsResponse
emptyProjectsResponse =
{ count = 0
, href = ""
, project = []
} | 33667 | import Html exposing (..)
import Html.App as App
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput, onCheck)
import String
import Http
import Json.Decode as Json
import Json.Decode exposing ((:=))
import Task
import Svg exposing (..)
import Svg.Attributes exposing (..)
import Time exposing (Time, second)
main : Program Never
main = App.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- Model
type alias Model =
{ counter : Int
, name : String
, password : String
, passwordAgain : String
, isRevealed : Bool
, dieFace : Int
, url : String
, reqError : String
, someResponse : ProjectsResponse
, time : Time
, startTime : Time
}
-- Update
type Msg
= Name String
| Password String
| PasswordAgain String
| Reveal Bool
| UpdateUrl String
| SendRequest
| FetchFail Http.Error
| FetchSucceed ProjectsResponse
| Tick Time
update: Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Name name ->
({ model | name = name }, Cmd.none)
Password password ->
({ model | password = <PASSWORD> }, Cmd.none)
PasswordAgain password ->
({ model | passwordAgain = password }, Cmd.none)
Reveal doReveal ->
({ model | isRevealed = doReveal }, Cmd.none)
UpdateUrl newUrl ->
({ model | url = newUrl }, Cmd.none)
SendRequest ->
(model, fetchData model.url)
FetchFail error ->
case error of
Http.Timeout ->
({ model | reqError = "Timeout happened :(" }, Cmd.none)
Http.NetworkError ->
({ model | reqError = "NetworkError :'(" }, Cmd.none)
Http.UnexpectedPayload s ->
({ model | reqError = "UnexpectedPayload: " ++ s }, Cmd.none)
Http.BadResponse code str ->
({ model | reqError = (toString code) ++ ": " ++ str }, Cmd.none)
FetchSucceed str ->
({ model | someResponse = str, reqError = "" }, Cmd.none)
Tick newTime ->
({ model
| startTime = if model.startTime == 0 then newTime else model.startTime
, time = if model.startTime == 0 then 1 * Time.second else newTime - model.startTime + 1 * Time.second
}, Cmd.none)
-- View
view: Model -> Html Msg
view model =
div []
[ viewClock model
, viewLoginPassword model
, viewValidation model
, viewHttpReq model
]
viewClock : Model -> Html Msg
viewClock model =
let
angle =
turns (Time.inMinutes model.time - 1/4)
handX =
toString (50 + 40 * cos angle)
handY =
toString (50 + 40 * sin angle)
in
Svg.svg [ viewBox "0 0 100 100", Svg.Attributes.width "100px"]
[ circle [ cx "50", cy "50", r "45", fill "#0b79ce" ] []
, line [ x1 "50", y1 "50", x2 handX, y2 handY, stroke "#023963" ] []
, Svg.text' [ x "25", y "45", fontSize "8px" ] [ Svg.text (toString <| model.time) ]
]
viewLoginPassword: Model -> Html Msg
viewLoginPassword model =
div []
[ input [ Html.Attributes.type' "text", placeholder "Name", onInput Name ] []
, input [ Html.Attributes.type' (if model.isRevealed then "text" else "password"), placeholder "Password", onInput Password ] []
, input [ Html.Attributes.type' (if model.isRevealed then "text" else "password"), placeholder "Password Again", onInput PasswordAgain ] []
, input [ Html.Attributes.type' "checkbox", onCheck Reveal ] []
, Html.text "reveal everything!"
]
viewValidation : Model -> Html Msg
viewValidation model =
let
(color, message) =
if model.password == model.passwordAgain then
if (String.length model.password < 4) then
("salmon", "so weak, sol languid...")
else
("green", "OK")
else
("red", "Are you a terrorist or what?")
in
div [ Html.Attributes.style [("color", color)] ] [ Html.text message ]
viewHttpReq : Model -> Html Msg
viewHttpReq model =
div []
[ input [ onInput UpdateUrl, value model.url ] []
, Html.text (toString model.url)
, button [ onClick SendRequest ] [ Html.text "Go!" ]
, div [] [ Html.text model.reqError ]
, div [] [ Html.text (toString model.someResponse.count) ]
, if (List.length model.someResponse.project) > 0
then Html.ul [] <| List.map (\p ->
Html.li [] [
Html.a [Html.Attributes.target "_blank", href p.href] [Html.text p.name]
]
) model.someResponse.project
else Html.text "no projects ;("
]
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every second Tick
-- INIT
init : (Model, Cmd Msg)
init =
(Model 0 "" "" "" False 1 "http://localhost/" "" emptyProjectsResponse 0 0, Cmd.none)
-- HTTP
fetchData : String -> Cmd Msg
fetchData url =
-- Http.send : Settings -> Request -> Task RawError Response
-- fromJson : Decoder a -> Task RawError Response -> Task Error a
Http.send Http.defaultSettings {
verb = "GET"
, headers = [("Accept", "application/json")]
, url = url
, body = Http.empty
}
|> Http.fromJson decodeResponseJson
|> Task.perform FetchFail FetchSucceed
decodeResponseJson : Json.Decoder ProjectsResponse
decodeResponseJson =
Json.Decode.object3 ProjectsResponse
("count" := Json.Decode.int)
("href" := Json.Decode.string)
("project" := decodeProjectsList
)
decodeProjectsList : Json.Decoder (List Project)
decodeProjectsList =
Json.Decode.object7 Project
("name" := Json.Decode.string)
("id" := Json.Decode.string)
("href" := Json.Decode.string)
("webUrl" := Json.Decode.string)
(Json.Decode.oneOf ["parentProjectId" := Json.Decode.string, Json.Decode.succeed ""])
(Json.Decode.oneOf ["description" := Json.Decode.string, Json.Decode.succeed ""])
(Json.Decode.oneOf ["archived" := Json.Decode.bool, Json.Decode.succeed False])
|> Json.Decode.list
type alias Project =
{ name : String
, id : String
, href : String
, webUrl : String
, parentProjectId : String
, description : String
, archived : Bool
}
type alias ProjectsResponse =
{ count : Int
, href : String
, project : List Project
}
emptyProjectsResponse : ProjectsResponse
emptyProjectsResponse =
{ count = 0
, href = ""
, project = []
} | true | import Html exposing (..)
import Html.App as App
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput, onCheck)
import String
import Http
import Json.Decode as Json
import Json.Decode exposing ((:=))
import Task
import Svg exposing (..)
import Svg.Attributes exposing (..)
import Time exposing (Time, second)
main : Program Never
main = App.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- Model
type alias Model =
{ counter : Int
, name : String
, password : String
, passwordAgain : String
, isRevealed : Bool
, dieFace : Int
, url : String
, reqError : String
, someResponse : ProjectsResponse
, time : Time
, startTime : Time
}
-- Update
type Msg
= Name String
| Password String
| PasswordAgain String
| Reveal Bool
| UpdateUrl String
| SendRequest
| FetchFail Http.Error
| FetchSucceed ProjectsResponse
| Tick Time
update: Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Name name ->
({ model | name = name }, Cmd.none)
Password password ->
({ model | password = PI:PASSWORD:<PASSWORD>END_PI }, Cmd.none)
PasswordAgain password ->
({ model | passwordAgain = password }, Cmd.none)
Reveal doReveal ->
({ model | isRevealed = doReveal }, Cmd.none)
UpdateUrl newUrl ->
({ model | url = newUrl }, Cmd.none)
SendRequest ->
(model, fetchData model.url)
FetchFail error ->
case error of
Http.Timeout ->
({ model | reqError = "Timeout happened :(" }, Cmd.none)
Http.NetworkError ->
({ model | reqError = "NetworkError :'(" }, Cmd.none)
Http.UnexpectedPayload s ->
({ model | reqError = "UnexpectedPayload: " ++ s }, Cmd.none)
Http.BadResponse code str ->
({ model | reqError = (toString code) ++ ": " ++ str }, Cmd.none)
FetchSucceed str ->
({ model | someResponse = str, reqError = "" }, Cmd.none)
Tick newTime ->
({ model
| startTime = if model.startTime == 0 then newTime else model.startTime
, time = if model.startTime == 0 then 1 * Time.second else newTime - model.startTime + 1 * Time.second
}, Cmd.none)
-- View
view: Model -> Html Msg
view model =
div []
[ viewClock model
, viewLoginPassword model
, viewValidation model
, viewHttpReq model
]
viewClock : Model -> Html Msg
viewClock model =
let
angle =
turns (Time.inMinutes model.time - 1/4)
handX =
toString (50 + 40 * cos angle)
handY =
toString (50 + 40 * sin angle)
in
Svg.svg [ viewBox "0 0 100 100", Svg.Attributes.width "100px"]
[ circle [ cx "50", cy "50", r "45", fill "#0b79ce" ] []
, line [ x1 "50", y1 "50", x2 handX, y2 handY, stroke "#023963" ] []
, Svg.text' [ x "25", y "45", fontSize "8px" ] [ Svg.text (toString <| model.time) ]
]
viewLoginPassword: Model -> Html Msg
viewLoginPassword model =
div []
[ input [ Html.Attributes.type' "text", placeholder "Name", onInput Name ] []
, input [ Html.Attributes.type' (if model.isRevealed then "text" else "password"), placeholder "Password", onInput Password ] []
, input [ Html.Attributes.type' (if model.isRevealed then "text" else "password"), placeholder "Password Again", onInput PasswordAgain ] []
, input [ Html.Attributes.type' "checkbox", onCheck Reveal ] []
, Html.text "reveal everything!"
]
viewValidation : Model -> Html Msg
viewValidation model =
let
(color, message) =
if model.password == model.passwordAgain then
if (String.length model.password < 4) then
("salmon", "so weak, sol languid...")
else
("green", "OK")
else
("red", "Are you a terrorist or what?")
in
div [ Html.Attributes.style [("color", color)] ] [ Html.text message ]
viewHttpReq : Model -> Html Msg
viewHttpReq model =
div []
[ input [ onInput UpdateUrl, value model.url ] []
, Html.text (toString model.url)
, button [ onClick SendRequest ] [ Html.text "Go!" ]
, div [] [ Html.text model.reqError ]
, div [] [ Html.text (toString model.someResponse.count) ]
, if (List.length model.someResponse.project) > 0
then Html.ul [] <| List.map (\p ->
Html.li [] [
Html.a [Html.Attributes.target "_blank", href p.href] [Html.text p.name]
]
) model.someResponse.project
else Html.text "no projects ;("
]
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every second Tick
-- INIT
init : (Model, Cmd Msg)
init =
(Model 0 "" "" "" False 1 "http://localhost/" "" emptyProjectsResponse 0 0, Cmd.none)
-- HTTP
fetchData : String -> Cmd Msg
fetchData url =
-- Http.send : Settings -> Request -> Task RawError Response
-- fromJson : Decoder a -> Task RawError Response -> Task Error a
Http.send Http.defaultSettings {
verb = "GET"
, headers = [("Accept", "application/json")]
, url = url
, body = Http.empty
}
|> Http.fromJson decodeResponseJson
|> Task.perform FetchFail FetchSucceed
decodeResponseJson : Json.Decoder ProjectsResponse
decodeResponseJson =
Json.Decode.object3 ProjectsResponse
("count" := Json.Decode.int)
("href" := Json.Decode.string)
("project" := decodeProjectsList
)
decodeProjectsList : Json.Decoder (List Project)
decodeProjectsList =
Json.Decode.object7 Project
("name" := Json.Decode.string)
("id" := Json.Decode.string)
("href" := Json.Decode.string)
("webUrl" := Json.Decode.string)
(Json.Decode.oneOf ["parentProjectId" := Json.Decode.string, Json.Decode.succeed ""])
(Json.Decode.oneOf ["description" := Json.Decode.string, Json.Decode.succeed ""])
(Json.Decode.oneOf ["archived" := Json.Decode.bool, Json.Decode.succeed False])
|> Json.Decode.list
type alias Project =
{ name : String
, id : String
, href : String
, webUrl : String
, parentProjectId : String
, description : String
, archived : Bool
}
type alias ProjectsResponse =
{ count : Int
, href : String
, project : List Project
}
emptyProjectsResponse : ProjectsResponse
emptyProjectsResponse =
{ count = 0
, href = ""
, project = []
} | elm |
[
{
"context": " \"id\": 1,\n \"properties\": {\n \"name\": \"Bermuda Triangle\",\n \"area\": 1150180\n },\n \"geometr",
"end": 1817,
"score": 0.9037486315,
"start": 1801,
"tag": "NAME",
"value": "Bermuda Triangle"
}
] | examples/Example03.elm | miaEngiadina/elm-mapbox | 1 | module Example03 exposing (main)
import Browser
import Html exposing (div, text)
import Html.Attributes exposing (style)
import Html.Lazy exposing (lazy)
import Json.Decode
import Json.Encode
import LngLat exposing (LngLat)
import Map
import MapCommands
import Mapbox.Cmd.Option as Opt
import Mapbox.Element exposing (..)
import Mapbox.Expression as E exposing (false, float, int, str, true)
import Mapbox.Layer as Layer
import Mapbox.Source as Source
import Mapbox.Style as Style exposing (Style(..))
main =
Browser.document
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.batch
[ Commands.elmMapboxIncoming MapCenter
]
type alias Model =
{ position : LngLat
, zoom : Float
, features : List Json.Encode.Value
}
init : () -> ( Model, Cmd Msg )
init () =
( { position = LngLat 0 0, zoom = 13.8, features = [] }, Cmd.none )
type Msg
= Hover EventData
| Click EventData
| MapCenter Json.Encode.Value
update msg model =
case msg of
Hover { lngLat, renderedFeatures } ->
( { model | position = lngLat, features = renderedFeatures }, Cmd.none )
Click { lngLat, renderedFeatures } ->
( { model | position = lngLat, features = renderedFeatures }, Commands.fitBounds "my-map" [ Opt.linear True, Opt.maxZoom 10 ] ( LngLat.map (\a -> a - 0.2) lngLat, LngLat.map (\a -> a + 0.2) lngLat ) )
MapCenter e ->
( model, Cmd.none )
geojson : Json.Encode.Value
geojson =
Json.Decode.decodeString Json.Decode.value """
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"properties": {
"name": "Bermuda Triangle",
"area": 1150180
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-64.73, 32.31],
[-80.19, 25.76],
[-66.09, 18.43],
[-64.73, 32.31]
]
]
}
}
]
}
""" |> Result.withDefault (Json.Encode.object [])
hoveredFeatures : List Json.Encode.Value -> MapboxAttr msg
hoveredFeatures =
List.map (\feat -> ( feat, [ ( "hover", Json.Encode.bool True ) ] ))
>> featureState
showMap features =
map
[ maxZoom 150
, onMouseMove Hover
, onClick Click
, id "my-map"
, eventFeaturesLayers [ "changes" ]
, hoveredFeatures features
]
(Style
{ transition = Style.defaultTransition
, light = Style.defaultLight
, layers =
(Map.layers
|> Layer.jsonList
)
++ [ Layer.fill "changes"
"changes"
[ Layer.fillOpacity (E.ifElse (E.toBool (E.featureState (str "hover"))) (float 0.9) (float 0.1))
]
]
, sources =
[ Source.vectorFromUrl "mapbox://mapbox.mapbox-streets-v6" "mapbox://mapbox.mapbox-streets-v6"
, Source.vectorFromUrl "mapbox://mapbox.mapbox-terrain-v2" "mapbox://mapbox.mapbox-terrain-v2"
, Source.vectorFromUrl "mapbox://mslee.0fc2f90a" "mapbox://mslee.0fc2f90a"
, Source.geoJSONFromValue "changes" [] geojson
]
, misc =
[ Style.sprite "mapbox://sprites/engiadina/ck0dvc9zq0g2v1cmw9xg18pu7/0y2vnk8n60t1vz01wcpm3bpqa"
, Style.glyphs "mapbox://fonts/engiadina/{fontstack}/{range}.pbf"
, Style.name "Winter"
, Style.defaultCenter <| LngLat 20.39789404164037 43.22523201923144
, Style.defaultZoomLevel 13
, Style.defaultBearing 0
, Style.defaultPitch 0
]
}
)
view model =
{ title = "Mapbox Example"
, body =
[ css
, div [ style "width" "100vw", style "height" "100vh" ]
[ lazy showMap model.features
, div [ style "position" "absolute", style "bottom" "20px", style "left" "20px" ] [ text (LngLat.toString model.position) ]
]
]
}
| 46579 | module Example03 exposing (main)
import Browser
import Html exposing (div, text)
import Html.Attributes exposing (style)
import Html.Lazy exposing (lazy)
import Json.Decode
import Json.Encode
import LngLat exposing (LngLat)
import Map
import MapCommands
import Mapbox.Cmd.Option as Opt
import Mapbox.Element exposing (..)
import Mapbox.Expression as E exposing (false, float, int, str, true)
import Mapbox.Layer as Layer
import Mapbox.Source as Source
import Mapbox.Style as Style exposing (Style(..))
main =
Browser.document
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.batch
[ Commands.elmMapboxIncoming MapCenter
]
type alias Model =
{ position : LngLat
, zoom : Float
, features : List Json.Encode.Value
}
init : () -> ( Model, Cmd Msg )
init () =
( { position = LngLat 0 0, zoom = 13.8, features = [] }, Cmd.none )
type Msg
= Hover EventData
| Click EventData
| MapCenter Json.Encode.Value
update msg model =
case msg of
Hover { lngLat, renderedFeatures } ->
( { model | position = lngLat, features = renderedFeatures }, Cmd.none )
Click { lngLat, renderedFeatures } ->
( { model | position = lngLat, features = renderedFeatures }, Commands.fitBounds "my-map" [ Opt.linear True, Opt.maxZoom 10 ] ( LngLat.map (\a -> a - 0.2) lngLat, LngLat.map (\a -> a + 0.2) lngLat ) )
MapCenter e ->
( model, Cmd.none )
geojson : Json.Encode.Value
geojson =
Json.Decode.decodeString Json.Decode.value """
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"properties": {
"name": "<NAME>",
"area": 1150180
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-64.73, 32.31],
[-80.19, 25.76],
[-66.09, 18.43],
[-64.73, 32.31]
]
]
}
}
]
}
""" |> Result.withDefault (Json.Encode.object [])
hoveredFeatures : List Json.Encode.Value -> MapboxAttr msg
hoveredFeatures =
List.map (\feat -> ( feat, [ ( "hover", Json.Encode.bool True ) ] ))
>> featureState
showMap features =
map
[ maxZoom 150
, onMouseMove Hover
, onClick Click
, id "my-map"
, eventFeaturesLayers [ "changes" ]
, hoveredFeatures features
]
(Style
{ transition = Style.defaultTransition
, light = Style.defaultLight
, layers =
(Map.layers
|> Layer.jsonList
)
++ [ Layer.fill "changes"
"changes"
[ Layer.fillOpacity (E.ifElse (E.toBool (E.featureState (str "hover"))) (float 0.9) (float 0.1))
]
]
, sources =
[ Source.vectorFromUrl "mapbox://mapbox.mapbox-streets-v6" "mapbox://mapbox.mapbox-streets-v6"
, Source.vectorFromUrl "mapbox://mapbox.mapbox-terrain-v2" "mapbox://mapbox.mapbox-terrain-v2"
, Source.vectorFromUrl "mapbox://mslee.0fc2f90a" "mapbox://mslee.0fc2f90a"
, Source.geoJSONFromValue "changes" [] geojson
]
, misc =
[ Style.sprite "mapbox://sprites/engiadina/ck0dvc9zq0g2v1cmw9xg18pu7/0y2vnk8n60t1vz01wcpm3bpqa"
, Style.glyphs "mapbox://fonts/engiadina/{fontstack}/{range}.pbf"
, Style.name "Winter"
, Style.defaultCenter <| LngLat 20.39789404164037 43.22523201923144
, Style.defaultZoomLevel 13
, Style.defaultBearing 0
, Style.defaultPitch 0
]
}
)
view model =
{ title = "Mapbox Example"
, body =
[ css
, div [ style "width" "100vw", style "height" "100vh" ]
[ lazy showMap model.features
, div [ style "position" "absolute", style "bottom" "20px", style "left" "20px" ] [ text (LngLat.toString model.position) ]
]
]
}
| true | module Example03 exposing (main)
import Browser
import Html exposing (div, text)
import Html.Attributes exposing (style)
import Html.Lazy exposing (lazy)
import Json.Decode
import Json.Encode
import LngLat exposing (LngLat)
import Map
import MapCommands
import Mapbox.Cmd.Option as Opt
import Mapbox.Element exposing (..)
import Mapbox.Expression as E exposing (false, float, int, str, true)
import Mapbox.Layer as Layer
import Mapbox.Source as Source
import Mapbox.Style as Style exposing (Style(..))
main =
Browser.document
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.batch
[ Commands.elmMapboxIncoming MapCenter
]
type alias Model =
{ position : LngLat
, zoom : Float
, features : List Json.Encode.Value
}
init : () -> ( Model, Cmd Msg )
init () =
( { position = LngLat 0 0, zoom = 13.8, features = [] }, Cmd.none )
type Msg
= Hover EventData
| Click EventData
| MapCenter Json.Encode.Value
update msg model =
case msg of
Hover { lngLat, renderedFeatures } ->
( { model | position = lngLat, features = renderedFeatures }, Cmd.none )
Click { lngLat, renderedFeatures } ->
( { model | position = lngLat, features = renderedFeatures }, Commands.fitBounds "my-map" [ Opt.linear True, Opt.maxZoom 10 ] ( LngLat.map (\a -> a - 0.2) lngLat, LngLat.map (\a -> a + 0.2) lngLat ) )
MapCenter e ->
( model, Cmd.none )
geojson : Json.Encode.Value
geojson =
Json.Decode.decodeString Json.Decode.value """
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"properties": {
"name": "PI:NAME:<NAME>END_PI",
"area": 1150180
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-64.73, 32.31],
[-80.19, 25.76],
[-66.09, 18.43],
[-64.73, 32.31]
]
]
}
}
]
}
""" |> Result.withDefault (Json.Encode.object [])
hoveredFeatures : List Json.Encode.Value -> MapboxAttr msg
hoveredFeatures =
List.map (\feat -> ( feat, [ ( "hover", Json.Encode.bool True ) ] ))
>> featureState
showMap features =
map
[ maxZoom 150
, onMouseMove Hover
, onClick Click
, id "my-map"
, eventFeaturesLayers [ "changes" ]
, hoveredFeatures features
]
(Style
{ transition = Style.defaultTransition
, light = Style.defaultLight
, layers =
(Map.layers
|> Layer.jsonList
)
++ [ Layer.fill "changes"
"changes"
[ Layer.fillOpacity (E.ifElse (E.toBool (E.featureState (str "hover"))) (float 0.9) (float 0.1))
]
]
, sources =
[ Source.vectorFromUrl "mapbox://mapbox.mapbox-streets-v6" "mapbox://mapbox.mapbox-streets-v6"
, Source.vectorFromUrl "mapbox://mapbox.mapbox-terrain-v2" "mapbox://mapbox.mapbox-terrain-v2"
, Source.vectorFromUrl "mapbox://mslee.0fc2f90a" "mapbox://mslee.0fc2f90a"
, Source.geoJSONFromValue "changes" [] geojson
]
, misc =
[ Style.sprite "mapbox://sprites/engiadina/ck0dvc9zq0g2v1cmw9xg18pu7/0y2vnk8n60t1vz01wcpm3bpqa"
, Style.glyphs "mapbox://fonts/engiadina/{fontstack}/{range}.pbf"
, Style.name "Winter"
, Style.defaultCenter <| LngLat 20.39789404164037 43.22523201923144
, Style.defaultZoomLevel 13
, Style.defaultBearing 0
, Style.defaultPitch 0
]
}
)
view model =
{ title = "Mapbox Example"
, body =
[ css
, div [ style "width" "100vw", style "height" "100vh" ]
[ lazy showMap model.features
, div [ style "position" "absolute", style "bottom" "20px", style "left" "20px" ] [ text (LngLat.toString model.position) ]
]
]
}
| elm |
[
{
"context": "{-\n Operations/Conversion/Regex.elm\n Author: Henrique da Cunha Buss\n Creation: October/2020\n This file contains f",
"end": 71,
"score": 0.9998661876,
"start": 49,
"tag": "NAME",
"value": "Henrique da Cunha Buss"
}
] | src/Operations/Conversion/Regex.elm | NeoVier/LFC01 | 0 | {-
Operations/Conversion/Regex.elm
Author: Henrique da Cunha Buss
Creation: October/2020
This file contains functions to convert Regular Expressions
-}
module Operations.Conversion.Regex exposing (erToAfd)
import Dict exposing (Dict)
import Models.Alphabet as Alphabet
import Models.Automata as Automata
import Models.Regex as Regex exposing (Regex(..))
import Models.State as State
import Models.Transition as Transition
import Utils.Utils as Utils
{-
The following tables show the relationship between RegEx nodes and their
nullable, firstPos and lastPos values
NULLABLE
+---------------------+------------------------------+
| Node n | nullable(n) |
+---------------------+------------------------------+
+---------------------+------------------------------+
| Epsilon | True |
+---------------------+------------------------------+
| leaf with positon i | False |
+---------------------+------------------------------+
| c1 | c2 | nullable(c1) || nullable(c2) |
+---------------------+------------------------------+
| c1 . c2 | nullable(c1) && nullable(c2) |
+---------------------+------------------------------+
| (c1)* | True |
+---------------------+------------------------------+
FIRST POS
+---------------------+-----------------------------------------------------+
| Node n | firstPos(n) |
+---------------------+-----------------------------------------------------+
+---------------------+-----------------------------------------------------+
| Epsilon | {} |
+---------------------+-----------------------------------------------------+
| leaf with positon i | {i} |
+---------------------+-----------------------------------------------------+
| c1 | c2 | firstPos(c1) ++ firstPos(c2) |
+---------------------+-----------------------------------------------------+
| c1 . c2 | if (nullable(c1)) then firstPos(c1) ++ firstPos(c2) |
| | else firstPos(c1) |
+---------------------+-----------------------------------------------------+
| (c1)* | firstPos(c1) |
+---------------------+-----------------------------------------------------+
LAST POS
+---------------------+-----------------------------------------------------+
| Node n | lastPos(n) |
+---------------------+-----------------------------------------------------+
+---------------------+-----------------------------------------------------+
| Epsilon | {} |
+---------------------+-----------------------------------------------------+
| leaf with positon i | {i} |
+---------------------+-----------------------------------------------------+
| c1 | c2 | lastPos(c1) ++ lastPos(c2) |
+---------------------+-----------------------------------------------------+
| c1 . c2 | if (nullable(c2)) then lastPos(c1) ++ lastPos(c2) |
| | else lastPos(c2) |
+---------------------+-----------------------------------------------------+
| (c1)* | lastPos(c1) |
+---------------------+-----------------------------------------------------+
FOLLOW POS
- If n is a (Concat c1 c2) node, for each position i in lastpos(c1), all
positions in firstpos(c2) are in followpos(i)
- If n is a (Star c1) node, and i is a position in lastpos(n), then all
positions in firstpos(n) are in followpos(i)
-}
{- TreeInfo contains all of the needed info to apply the algorithm -}
type alias TreeInfo =
{ nullable : Bool
, firstPos : List Int
, lastPos : List Int
, followPos : Maybe (List Int)
, nodeSymbol : Maybe Alphabet.Symbol
}
{- Shorthand for the kind of Dict used -}
type alias TreeInfoDict =
Dict Int TreeInfo
{- Default empty TreeInfo -}
emptyTreeInfo : TreeInfo
emptyTreeInfo =
{ nullable = False
, firstPos = []
, lastPos = []
, followPos = Nothing
, nodeSymbol = Nothing
}
{- Extract a TreeInfoDict from a Regex -}
treeInfoDict : Regex -> TreeInfoDict
treeInfoDict r =
nullableDict r Dict.empty
|> firstPosDict r
|> lastPosDict r
|> followPosDict r
{- Cleans a TreeInfoDict by removing everything that doesn't represent a leaf
node in the original Regex
-}
cleanTreeInfoDict : TreeInfoDict -> TreeInfoDict
cleanTreeInfoDict infoTree =
Dict.filter (\_ v -> v.nodeSymbol /= Nothing) infoTree
|> Dict.toList
|> List.map (\( k, v ) -> v)
|> (\x ->
List.map2 (\idx v -> ( idx, v ))
(List.range 1 (List.length x))
x
)
|> Dict.fromList
{- Convert a Regular Expression to an AFD -}
erToAfd : Regex -> Automata.AFD
erToAfd r =
let
newR =
Concat r (Symbol (Alphabet.Single '#'))
startingAfd =
{ states = []
, initialState = State.Dead
, finalStates = []
, alphabet = []
, transitions = []
}
dirtyInfoDict =
treeInfoDict newR
rootNodeInfo =
Dict.values dirtyInfoDict
|> Utils.last
in
case rootNodeInfo of
-- Impossible
Nothing ->
startingAfd
Just info ->
let
startingState =
List.map String.fromInt info.firstPos
|> String.join ""
|> State.Valid
in
erToAfdHelp (cleanTreeInfoDict dirtyInfoDict)
[ info.firstPos ]
[]
{ startingAfd | initialState = startingState }
{- Helper function for erToAfd -}
erToAfdHelp :
TreeInfoDict
-> List (List Int)
-> List (List Int)
-> Automata.AFD
-> Automata.AFD
erToAfdHelp treeInfo statesToCreate seenStates partialAfd =
case List.head statesToCreate of
-- We've visited every state
Nothing ->
partialAfd
Just newStateComponents ->
let
symbolGroups =
getSymbolGroups treeInfo newStateComponents
createState components =
List.map String.fromInt components
|> String.join ""
|> State.Valid
newState =
createState newStateComponents
isFinal =
Dict.keys symbolGroups
|> List.member "#"
newStatesComponents =
Dict.values symbolGroups
newTransitions =
Dict.toList symbolGroups
|> List.filterMap
(\( s, v ) ->
if s == "#" then
Nothing
else
Just
{ prevState = newState
, nextState = createState v
, conditions =
case Utils.stringToSymbol s of
Nothing ->
[]
Just c ->
[ c ]
}
)
newSymbolsStr =
List.filter
(\s ->
case Utils.stringToSymbol s of
Nothing ->
False
Just symb ->
not
(List.member symb
partialAfd.alphabet
)
&& s
/= "#"
)
(Dict.keys symbolGroups)
newSymbols =
List.map Utils.stringToSymbol newSymbolsStr
|> Utils.listOfMaybesToMaybeList
|> Maybe.withDefault []
in
if
List.member newStateComponents seenStates
|| List.isEmpty newStateComponents
then
erToAfdHelp treeInfo
(List.drop 1 statesToCreate)
seenStates
partialAfd
else
erToAfdHelp treeInfo
(List.drop 1 statesToCreate ++ newStatesComponents)
(newStateComponents :: seenStates)
{ partialAfd
| states = partialAfd.states ++ [ newState ]
, finalStates =
if isFinal then
partialAfd.finalStates ++ [ newState ]
else
partialAfd.finalStates
, alphabet =
partialAfd.alphabet
++ newSymbols
, transitions = partialAfd.transitions ++ newTransitions
}
{- Given a TreeInfoDict and a list of indexes (a state in the result AFD),
get a Dict saying which symbols reach which state
-}
getSymbolGroups : TreeInfoDict -> List Int -> Dict String (List Int)
getSymbolGroups treeInfo indexes =
List.foldl
(\index acc ->
case Dict.get index treeInfo of
Nothing ->
acc
Just info ->
case info.nodeSymbol of
Nothing ->
acc
Just symbol ->
case info.followPos of
Nothing ->
acc
Just fp ->
Dict.update (Utils.symbolToString symbol)
(\dictValue ->
case dictValue of
Nothing ->
Just fp
Just v ->
Just <|
Utils.removeDuplicates <|
v
++ fp
)
acc
)
Dict.empty
indexes
{- Given a regex and a TreeInfoDict, assign nullable to each node in the
regex
-}
nullableDict : Regex -> TreeInfoDict -> TreeInfoDict
nullableDict r d =
let
idx dict =
Dict.keys dict |> List.maximum |> Maybe.withDefault 0 |> (+) 1
insert v dict =
Dict.insert (idx dict)
{ emptyTreeInfo
| nullable = v
, nodeSymbol =
case r of
Symbol s ->
Just s
_ ->
Nothing
}
dict
compose1 c1 =
insert (nullable r) (nullableDict c1 d)
compose2 c1 c2 =
let
c1Result =
nullableDict c1 d
c2Result =
nullableDict c2 c1Result
in
insert (nullable r) c2Result
in
case r of
Union c1 c2 ->
compose2 c1 c2
Concat c1 c2 ->
compose2 c1 c2
Star c1 ->
compose1 c1
Plus c1 ->
compose1 c1
Question c1 ->
compose1 c1
_ ->
insert (nullable r) d
{- Given a regex and a TreeInfoDict, assign firstPos to each node in the
regex
-}
firstPosDict : Regex -> TreeInfoDict -> TreeInfoDict
firstPosDict r d =
let
idx dict =
Dict.filter (\_ v -> List.isEmpty v.firstPos) dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
update v dict =
Dict.update (idx dict)
(Maybe.map (\info -> { info | firstPos = Utils.removeDuplicates v }))
dict
prevMaxValue dict =
Dict.values dict
|> List.map .firstPos
|> List.concat
|> List.maximum
|> Maybe.withDefault 0
compose1 c1 =
let
c1Result =
firstPosDict c1 d
thisFirstPos =
firstPosFrom (prevMaxValue d) r
in
update thisFirstPos c1Result
compose2 c1 c2 =
let
c1Result =
firstPosDict c1 d
c2Result =
firstPosDict c2 c1Result
in
update (firstPosFrom (prevMaxValue d) r) c2Result
in
case r of
Union c1 c2 ->
compose2 c1 c2
Concat c1 c2 ->
compose2 c1 c2
Star c1 ->
compose1 c1
Plus c1 ->
compose1 c1
Question c1 ->
compose1 c1
_ ->
update (firstPosFrom (prevMaxValue d) r) d
{- Given a regex and a TreeInfoDict, assign lastPos to each node in the regex -}
lastPosDict : Regex -> TreeInfoDict -> TreeInfoDict
lastPosDict r d =
let
idx dict =
Dict.filter (\_ v -> List.isEmpty v.lastPos) dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
update v dict =
Dict.update (idx dict)
(Maybe.map (\info -> { info | lastPos = v }))
dict
prevMaxValue dict =
Dict.values dict
|> List.map .lastPos
|> List.concat
|> List.maximum
|> Maybe.withDefault 0
prevLastPos dict =
Dict.get (idx dict - 1) dict
|> Maybe.map .lastPos
|> Maybe.withDefault []
compose1 c1 =
let
c1Result =
lastPosDict c1 d
thisLastPos =
lastPosFrom (prevMaxValue d) r
c1LastPos =
prevLastPos c1Result
in
update thisLastPos c1Result
compose2 c1 c2 =
let
c1Result =
lastPosDict c1 d
c1LastPos =
prevLastPos c1Result
|> List.map String.fromInt
|> String.join ","
c2Result =
lastPosDict c2 c1Result
c2LastPos =
prevLastPos c2Result
|> List.map String.fromInt
|> String.join ","
in
update
(lastPosFrom (prevMaxValue d) r)
c2Result
in
case r of
Union c1 c2 ->
compose2 c1 c2
Concat c1 c2 ->
compose2 c1 c2
Star c1 ->
compose1 c1
Plus c1 ->
compose1 c1
Question c1 ->
compose1 c1
Symbol s ->
let
symbol =
case s of
Alphabet.Single x ->
String.fromChar x
Alphabet.Group _ ->
"g"
in
update (lastPosFrom (prevMaxValue d) r) d
_ ->
update (lastPosFrom (prevMaxValue d) r) d
{- Given a regex and a TreeInfoDict, assign followPos to each node in the
regex
-}
followPosDict : Regex -> TreeInfoDict -> TreeInfoDict
followPosDict r d =
let
idx dict =
Dict.filter (\_ v -> v.followPos == Nothing) dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
update v dict =
Dict.update (idx dict)
(Maybe.map (\info -> { info | followPos = v }))
dict
findSymbolIndex s dict =
Dict.filter (\_ v -> v.firstPos == [ s ] && v.nodeSymbol /= Nothing)
dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
in
case r of
Star c1 ->
let
c1Result =
followPosDict c1 d
updateFollowPos info newFollowPos =
{ info
| followPos =
case info.followPos of
Nothing ->
Just newFollowPos
Just v ->
Just <|
Utils.removeDuplicates <|
v
++ newFollowPos
}
in
case Dict.get (idx c1Result) c1Result of
-- Impossible
Nothing ->
d
Just treeInfo ->
List.foldl
(\lp acc ->
Dict.update (findSymbolIndex lp acc)
(Maybe.map
(\info ->
updateFollowPos info treeInfo.firstPos
)
)
acc
)
c1Result
treeInfo.lastPos
|> update (Just [])
Concat c1 c2 ->
let
c1Result =
followPosDict c1 d
c1Index =
idx c1Result - 1
c2Result =
followPosDict c2 c1Result
c2Index =
idx c2Result - 1
updateFollowPos info newFollowPos =
{ info
| followPos =
case info.followPos of
Nothing ->
Just newFollowPos
Just v ->
Just <| Utils.removeDuplicates <| v ++ newFollowPos
}
in
case Dict.get c1Index c2Result of
-- Impossible
Nothing ->
d
Just c1Value ->
case Dict.get c2Index c2Result of
-- Impossible
Nothing ->
d
Just c2Value ->
List.foldl
(\lp acc ->
Dict.update (findSymbolIndex lp acc)
(Maybe.map
(\info ->
updateFollowPos info
c2Value.firstPos
)
)
acc
)
c2Result
c1Value.lastPos
|> update (Just [])
Union c1 c2 ->
let
c1Result =
followPosDict c1 d
c2Result =
followPosDict c2 c1Result
in
update (Just []) c2Result
Plus c1 ->
let
c1Result =
followPosDict c1 d
updateFollowPos info newFollowPos =
{ info
| followPos =
case info.followPos of
Nothing ->
Just newFollowPos
Just v ->
Just <| Utils.removeDuplicates <| v ++ newFollowPos
}
in
case Dict.get (idx c1Result) c1Result of
-- Impossible
Nothing ->
d
Just treeInfo ->
List.foldl
(\lp acc ->
Dict.update (findSymbolIndex lp acc)
(Maybe.map
(\info ->
updateFollowPos info treeInfo.firstPos
)
)
acc
)
c1Result
treeInfo.lastPos
|> update (Just [])
Question c1 ->
update (Just []) (followPosDict c1 d)
_ ->
update (Just []) d
{- Get the nullable value of a regex node according to the table at the top of
this file
-}
nullable : Regex -> Bool
nullable r =
case r of
Epsilon ->
True
Symbol _ ->
False
Union c1 c2 ->
nullable c1 || nullable c2
Concat c1 c2 ->
nullable c1 && nullable c2
Star _ ->
True
Plus _ ->
False
Question _ ->
True
{- Get the firstPos value of a regex node according to the table at the top of
this file
-}
firstPos : Regex -> List Int
firstPos =
firstPosFrom 0
{- Get the firstPos giving the first node value -}
firstPosFrom : Int -> Regex -> List Int
firstPosFrom i r =
firstPosHelp i r |> Tuple.first
{- Helper function for firstPos -}
firstPosHelp : Int -> Regex -> ( List Int, Int )
firstPosHelp count r =
case r of
Epsilon ->
( [], count )
Symbol _ ->
( [ count + 1 ], count + 1 )
Union c1 c2 ->
let
( c1FirstPos, c1Count ) =
firstPosHelp count c1
( c2FirstPos, c2Count ) =
firstPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1FirstPos ++ c2FirstPos, c2Count )
Concat c1 c2 ->
let
( c1firstPos, c1Count ) =
firstPosHelp count c1
in
if nullable c1 then
let
( c2firstPos, c2Count ) =
firstPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1firstPos ++ c2firstPos, c2Count )
else
firstPosHelp count c1
Star c1 ->
firstPosHelp count c1
Plus c1 ->
firstPosHelp count c1
Question c1 ->
firstPosHelp count c1
{- Get the lastPos value of a regex node according to the table at the top of
this file
-}
lastPos : Regex -> List Int
lastPos =
lastPosFrom 0
{- Get the firstPos giving the first node value -}
lastPosFrom : Int -> Regex -> List Int
lastPosFrom i r =
lastPosHelp i r |> Tuple.first
{- Helper function for lastPos -}
lastPosHelp : Int -> Regex -> ( List Int, Int )
lastPosHelp count r =
case r of
Epsilon ->
( [], count )
Symbol _ ->
( [ count + 1 ], count + 1 )
Union c1 c2 ->
let
( c1LastPos, c1Count ) =
lastPosHelp count c1
( c2LastPos, c2Count ) =
lastPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1LastPos ++ c2LastPos, c2Count )
Concat c1 c2 ->
if nullable c2 then
let
( c1LastPos, c1Count ) =
lastPosHelp count c1
( c2LastPos, c2Count ) =
lastPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1LastPos ++ c2LastPos, c2Count )
else
let
c1Count =
lastPosHelp count c1 |> Tuple.second
in
lastPosHelp c1Count c2
Star c1 ->
lastPosHelp count c1
Plus c1 ->
lastPosHelp count c1
Question c1 ->
lastPosHelp count c1
{- Given a Regex, counts how many leaf nodes it has -}
getLeafCount : Regex -> Int
getLeafCount r =
case r of
Epsilon ->
1
Symbol _ ->
1
Union c1 c2 ->
getLeafCount c1 + getLeafCount c2
Concat c1 c2 ->
getLeafCount c1 + getLeafCount c2
Star c1 ->
getLeafCount c1
Plus c1 ->
getLeafCount c1
Question c1 ->
getLeafCount c1
| 21110 | {-
Operations/Conversion/Regex.elm
Author: <NAME>
Creation: October/2020
This file contains functions to convert Regular Expressions
-}
module Operations.Conversion.Regex exposing (erToAfd)
import Dict exposing (Dict)
import Models.Alphabet as Alphabet
import Models.Automata as Automata
import Models.Regex as Regex exposing (Regex(..))
import Models.State as State
import Models.Transition as Transition
import Utils.Utils as Utils
{-
The following tables show the relationship between RegEx nodes and their
nullable, firstPos and lastPos values
NULLABLE
+---------------------+------------------------------+
| Node n | nullable(n) |
+---------------------+------------------------------+
+---------------------+------------------------------+
| Epsilon | True |
+---------------------+------------------------------+
| leaf with positon i | False |
+---------------------+------------------------------+
| c1 | c2 | nullable(c1) || nullable(c2) |
+---------------------+------------------------------+
| c1 . c2 | nullable(c1) && nullable(c2) |
+---------------------+------------------------------+
| (c1)* | True |
+---------------------+------------------------------+
FIRST POS
+---------------------+-----------------------------------------------------+
| Node n | firstPos(n) |
+---------------------+-----------------------------------------------------+
+---------------------+-----------------------------------------------------+
| Epsilon | {} |
+---------------------+-----------------------------------------------------+
| leaf with positon i | {i} |
+---------------------+-----------------------------------------------------+
| c1 | c2 | firstPos(c1) ++ firstPos(c2) |
+---------------------+-----------------------------------------------------+
| c1 . c2 | if (nullable(c1)) then firstPos(c1) ++ firstPos(c2) |
| | else firstPos(c1) |
+---------------------+-----------------------------------------------------+
| (c1)* | firstPos(c1) |
+---------------------+-----------------------------------------------------+
LAST POS
+---------------------+-----------------------------------------------------+
| Node n | lastPos(n) |
+---------------------+-----------------------------------------------------+
+---------------------+-----------------------------------------------------+
| Epsilon | {} |
+---------------------+-----------------------------------------------------+
| leaf with positon i | {i} |
+---------------------+-----------------------------------------------------+
| c1 | c2 | lastPos(c1) ++ lastPos(c2) |
+---------------------+-----------------------------------------------------+
| c1 . c2 | if (nullable(c2)) then lastPos(c1) ++ lastPos(c2) |
| | else lastPos(c2) |
+---------------------+-----------------------------------------------------+
| (c1)* | lastPos(c1) |
+---------------------+-----------------------------------------------------+
FOLLOW POS
- If n is a (Concat c1 c2) node, for each position i in lastpos(c1), all
positions in firstpos(c2) are in followpos(i)
- If n is a (Star c1) node, and i is a position in lastpos(n), then all
positions in firstpos(n) are in followpos(i)
-}
{- TreeInfo contains all of the needed info to apply the algorithm -}
type alias TreeInfo =
{ nullable : Bool
, firstPos : List Int
, lastPos : List Int
, followPos : Maybe (List Int)
, nodeSymbol : Maybe Alphabet.Symbol
}
{- Shorthand for the kind of Dict used -}
type alias TreeInfoDict =
Dict Int TreeInfo
{- Default empty TreeInfo -}
emptyTreeInfo : TreeInfo
emptyTreeInfo =
{ nullable = False
, firstPos = []
, lastPos = []
, followPos = Nothing
, nodeSymbol = Nothing
}
{- Extract a TreeInfoDict from a Regex -}
treeInfoDict : Regex -> TreeInfoDict
treeInfoDict r =
nullableDict r Dict.empty
|> firstPosDict r
|> lastPosDict r
|> followPosDict r
{- Cleans a TreeInfoDict by removing everything that doesn't represent a leaf
node in the original Regex
-}
cleanTreeInfoDict : TreeInfoDict -> TreeInfoDict
cleanTreeInfoDict infoTree =
Dict.filter (\_ v -> v.nodeSymbol /= Nothing) infoTree
|> Dict.toList
|> List.map (\( k, v ) -> v)
|> (\x ->
List.map2 (\idx v -> ( idx, v ))
(List.range 1 (List.length x))
x
)
|> Dict.fromList
{- Convert a Regular Expression to an AFD -}
erToAfd : Regex -> Automata.AFD
erToAfd r =
let
newR =
Concat r (Symbol (Alphabet.Single '#'))
startingAfd =
{ states = []
, initialState = State.Dead
, finalStates = []
, alphabet = []
, transitions = []
}
dirtyInfoDict =
treeInfoDict newR
rootNodeInfo =
Dict.values dirtyInfoDict
|> Utils.last
in
case rootNodeInfo of
-- Impossible
Nothing ->
startingAfd
Just info ->
let
startingState =
List.map String.fromInt info.firstPos
|> String.join ""
|> State.Valid
in
erToAfdHelp (cleanTreeInfoDict dirtyInfoDict)
[ info.firstPos ]
[]
{ startingAfd | initialState = startingState }
{- Helper function for erToAfd -}
erToAfdHelp :
TreeInfoDict
-> List (List Int)
-> List (List Int)
-> Automata.AFD
-> Automata.AFD
erToAfdHelp treeInfo statesToCreate seenStates partialAfd =
case List.head statesToCreate of
-- We've visited every state
Nothing ->
partialAfd
Just newStateComponents ->
let
symbolGroups =
getSymbolGroups treeInfo newStateComponents
createState components =
List.map String.fromInt components
|> String.join ""
|> State.Valid
newState =
createState newStateComponents
isFinal =
Dict.keys symbolGroups
|> List.member "#"
newStatesComponents =
Dict.values symbolGroups
newTransitions =
Dict.toList symbolGroups
|> List.filterMap
(\( s, v ) ->
if s == "#" then
Nothing
else
Just
{ prevState = newState
, nextState = createState v
, conditions =
case Utils.stringToSymbol s of
Nothing ->
[]
Just c ->
[ c ]
}
)
newSymbolsStr =
List.filter
(\s ->
case Utils.stringToSymbol s of
Nothing ->
False
Just symb ->
not
(List.member symb
partialAfd.alphabet
)
&& s
/= "#"
)
(Dict.keys symbolGroups)
newSymbols =
List.map Utils.stringToSymbol newSymbolsStr
|> Utils.listOfMaybesToMaybeList
|> Maybe.withDefault []
in
if
List.member newStateComponents seenStates
|| List.isEmpty newStateComponents
then
erToAfdHelp treeInfo
(List.drop 1 statesToCreate)
seenStates
partialAfd
else
erToAfdHelp treeInfo
(List.drop 1 statesToCreate ++ newStatesComponents)
(newStateComponents :: seenStates)
{ partialAfd
| states = partialAfd.states ++ [ newState ]
, finalStates =
if isFinal then
partialAfd.finalStates ++ [ newState ]
else
partialAfd.finalStates
, alphabet =
partialAfd.alphabet
++ newSymbols
, transitions = partialAfd.transitions ++ newTransitions
}
{- Given a TreeInfoDict and a list of indexes (a state in the result AFD),
get a Dict saying which symbols reach which state
-}
getSymbolGroups : TreeInfoDict -> List Int -> Dict String (List Int)
getSymbolGroups treeInfo indexes =
List.foldl
(\index acc ->
case Dict.get index treeInfo of
Nothing ->
acc
Just info ->
case info.nodeSymbol of
Nothing ->
acc
Just symbol ->
case info.followPos of
Nothing ->
acc
Just fp ->
Dict.update (Utils.symbolToString symbol)
(\dictValue ->
case dictValue of
Nothing ->
Just fp
Just v ->
Just <|
Utils.removeDuplicates <|
v
++ fp
)
acc
)
Dict.empty
indexes
{- Given a regex and a TreeInfoDict, assign nullable to each node in the
regex
-}
nullableDict : Regex -> TreeInfoDict -> TreeInfoDict
nullableDict r d =
let
idx dict =
Dict.keys dict |> List.maximum |> Maybe.withDefault 0 |> (+) 1
insert v dict =
Dict.insert (idx dict)
{ emptyTreeInfo
| nullable = v
, nodeSymbol =
case r of
Symbol s ->
Just s
_ ->
Nothing
}
dict
compose1 c1 =
insert (nullable r) (nullableDict c1 d)
compose2 c1 c2 =
let
c1Result =
nullableDict c1 d
c2Result =
nullableDict c2 c1Result
in
insert (nullable r) c2Result
in
case r of
Union c1 c2 ->
compose2 c1 c2
Concat c1 c2 ->
compose2 c1 c2
Star c1 ->
compose1 c1
Plus c1 ->
compose1 c1
Question c1 ->
compose1 c1
_ ->
insert (nullable r) d
{- Given a regex and a TreeInfoDict, assign firstPos to each node in the
regex
-}
firstPosDict : Regex -> TreeInfoDict -> TreeInfoDict
firstPosDict r d =
let
idx dict =
Dict.filter (\_ v -> List.isEmpty v.firstPos) dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
update v dict =
Dict.update (idx dict)
(Maybe.map (\info -> { info | firstPos = Utils.removeDuplicates v }))
dict
prevMaxValue dict =
Dict.values dict
|> List.map .firstPos
|> List.concat
|> List.maximum
|> Maybe.withDefault 0
compose1 c1 =
let
c1Result =
firstPosDict c1 d
thisFirstPos =
firstPosFrom (prevMaxValue d) r
in
update thisFirstPos c1Result
compose2 c1 c2 =
let
c1Result =
firstPosDict c1 d
c2Result =
firstPosDict c2 c1Result
in
update (firstPosFrom (prevMaxValue d) r) c2Result
in
case r of
Union c1 c2 ->
compose2 c1 c2
Concat c1 c2 ->
compose2 c1 c2
Star c1 ->
compose1 c1
Plus c1 ->
compose1 c1
Question c1 ->
compose1 c1
_ ->
update (firstPosFrom (prevMaxValue d) r) d
{- Given a regex and a TreeInfoDict, assign lastPos to each node in the regex -}
lastPosDict : Regex -> TreeInfoDict -> TreeInfoDict
lastPosDict r d =
let
idx dict =
Dict.filter (\_ v -> List.isEmpty v.lastPos) dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
update v dict =
Dict.update (idx dict)
(Maybe.map (\info -> { info | lastPos = v }))
dict
prevMaxValue dict =
Dict.values dict
|> List.map .lastPos
|> List.concat
|> List.maximum
|> Maybe.withDefault 0
prevLastPos dict =
Dict.get (idx dict - 1) dict
|> Maybe.map .lastPos
|> Maybe.withDefault []
compose1 c1 =
let
c1Result =
lastPosDict c1 d
thisLastPos =
lastPosFrom (prevMaxValue d) r
c1LastPos =
prevLastPos c1Result
in
update thisLastPos c1Result
compose2 c1 c2 =
let
c1Result =
lastPosDict c1 d
c1LastPos =
prevLastPos c1Result
|> List.map String.fromInt
|> String.join ","
c2Result =
lastPosDict c2 c1Result
c2LastPos =
prevLastPos c2Result
|> List.map String.fromInt
|> String.join ","
in
update
(lastPosFrom (prevMaxValue d) r)
c2Result
in
case r of
Union c1 c2 ->
compose2 c1 c2
Concat c1 c2 ->
compose2 c1 c2
Star c1 ->
compose1 c1
Plus c1 ->
compose1 c1
Question c1 ->
compose1 c1
Symbol s ->
let
symbol =
case s of
Alphabet.Single x ->
String.fromChar x
Alphabet.Group _ ->
"g"
in
update (lastPosFrom (prevMaxValue d) r) d
_ ->
update (lastPosFrom (prevMaxValue d) r) d
{- Given a regex and a TreeInfoDict, assign followPos to each node in the
regex
-}
followPosDict : Regex -> TreeInfoDict -> TreeInfoDict
followPosDict r d =
let
idx dict =
Dict.filter (\_ v -> v.followPos == Nothing) dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
update v dict =
Dict.update (idx dict)
(Maybe.map (\info -> { info | followPos = v }))
dict
findSymbolIndex s dict =
Dict.filter (\_ v -> v.firstPos == [ s ] && v.nodeSymbol /= Nothing)
dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
in
case r of
Star c1 ->
let
c1Result =
followPosDict c1 d
updateFollowPos info newFollowPos =
{ info
| followPos =
case info.followPos of
Nothing ->
Just newFollowPos
Just v ->
Just <|
Utils.removeDuplicates <|
v
++ newFollowPos
}
in
case Dict.get (idx c1Result) c1Result of
-- Impossible
Nothing ->
d
Just treeInfo ->
List.foldl
(\lp acc ->
Dict.update (findSymbolIndex lp acc)
(Maybe.map
(\info ->
updateFollowPos info treeInfo.firstPos
)
)
acc
)
c1Result
treeInfo.lastPos
|> update (Just [])
Concat c1 c2 ->
let
c1Result =
followPosDict c1 d
c1Index =
idx c1Result - 1
c2Result =
followPosDict c2 c1Result
c2Index =
idx c2Result - 1
updateFollowPos info newFollowPos =
{ info
| followPos =
case info.followPos of
Nothing ->
Just newFollowPos
Just v ->
Just <| Utils.removeDuplicates <| v ++ newFollowPos
}
in
case Dict.get c1Index c2Result of
-- Impossible
Nothing ->
d
Just c1Value ->
case Dict.get c2Index c2Result of
-- Impossible
Nothing ->
d
Just c2Value ->
List.foldl
(\lp acc ->
Dict.update (findSymbolIndex lp acc)
(Maybe.map
(\info ->
updateFollowPos info
c2Value.firstPos
)
)
acc
)
c2Result
c1Value.lastPos
|> update (Just [])
Union c1 c2 ->
let
c1Result =
followPosDict c1 d
c2Result =
followPosDict c2 c1Result
in
update (Just []) c2Result
Plus c1 ->
let
c1Result =
followPosDict c1 d
updateFollowPos info newFollowPos =
{ info
| followPos =
case info.followPos of
Nothing ->
Just newFollowPos
Just v ->
Just <| Utils.removeDuplicates <| v ++ newFollowPos
}
in
case Dict.get (idx c1Result) c1Result of
-- Impossible
Nothing ->
d
Just treeInfo ->
List.foldl
(\lp acc ->
Dict.update (findSymbolIndex lp acc)
(Maybe.map
(\info ->
updateFollowPos info treeInfo.firstPos
)
)
acc
)
c1Result
treeInfo.lastPos
|> update (Just [])
Question c1 ->
update (Just []) (followPosDict c1 d)
_ ->
update (Just []) d
{- Get the nullable value of a regex node according to the table at the top of
this file
-}
nullable : Regex -> Bool
nullable r =
case r of
Epsilon ->
True
Symbol _ ->
False
Union c1 c2 ->
nullable c1 || nullable c2
Concat c1 c2 ->
nullable c1 && nullable c2
Star _ ->
True
Plus _ ->
False
Question _ ->
True
{- Get the firstPos value of a regex node according to the table at the top of
this file
-}
firstPos : Regex -> List Int
firstPos =
firstPosFrom 0
{- Get the firstPos giving the first node value -}
firstPosFrom : Int -> Regex -> List Int
firstPosFrom i r =
firstPosHelp i r |> Tuple.first
{- Helper function for firstPos -}
firstPosHelp : Int -> Regex -> ( List Int, Int )
firstPosHelp count r =
case r of
Epsilon ->
( [], count )
Symbol _ ->
( [ count + 1 ], count + 1 )
Union c1 c2 ->
let
( c1FirstPos, c1Count ) =
firstPosHelp count c1
( c2FirstPos, c2Count ) =
firstPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1FirstPos ++ c2FirstPos, c2Count )
Concat c1 c2 ->
let
( c1firstPos, c1Count ) =
firstPosHelp count c1
in
if nullable c1 then
let
( c2firstPos, c2Count ) =
firstPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1firstPos ++ c2firstPos, c2Count )
else
firstPosHelp count c1
Star c1 ->
firstPosHelp count c1
Plus c1 ->
firstPosHelp count c1
Question c1 ->
firstPosHelp count c1
{- Get the lastPos value of a regex node according to the table at the top of
this file
-}
lastPos : Regex -> List Int
lastPos =
lastPosFrom 0
{- Get the firstPos giving the first node value -}
lastPosFrom : Int -> Regex -> List Int
lastPosFrom i r =
lastPosHelp i r |> Tuple.first
{- Helper function for lastPos -}
lastPosHelp : Int -> Regex -> ( List Int, Int )
lastPosHelp count r =
case r of
Epsilon ->
( [], count )
Symbol _ ->
( [ count + 1 ], count + 1 )
Union c1 c2 ->
let
( c1LastPos, c1Count ) =
lastPosHelp count c1
( c2LastPos, c2Count ) =
lastPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1LastPos ++ c2LastPos, c2Count )
Concat c1 c2 ->
if nullable c2 then
let
( c1LastPos, c1Count ) =
lastPosHelp count c1
( c2LastPos, c2Count ) =
lastPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1LastPos ++ c2LastPos, c2Count )
else
let
c1Count =
lastPosHelp count c1 |> Tuple.second
in
lastPosHelp c1Count c2
Star c1 ->
lastPosHelp count c1
Plus c1 ->
lastPosHelp count c1
Question c1 ->
lastPosHelp count c1
{- Given a Regex, counts how many leaf nodes it has -}
getLeafCount : Regex -> Int
getLeafCount r =
case r of
Epsilon ->
1
Symbol _ ->
1
Union c1 c2 ->
getLeafCount c1 + getLeafCount c2
Concat c1 c2 ->
getLeafCount c1 + getLeafCount c2
Star c1 ->
getLeafCount c1
Plus c1 ->
getLeafCount c1
Question c1 ->
getLeafCount c1
| true | {-
Operations/Conversion/Regex.elm
Author: PI:NAME:<NAME>END_PI
Creation: October/2020
This file contains functions to convert Regular Expressions
-}
module Operations.Conversion.Regex exposing (erToAfd)
import Dict exposing (Dict)
import Models.Alphabet as Alphabet
import Models.Automata as Automata
import Models.Regex as Regex exposing (Regex(..))
import Models.State as State
import Models.Transition as Transition
import Utils.Utils as Utils
{-
The following tables show the relationship between RegEx nodes and their
nullable, firstPos and lastPos values
NULLABLE
+---------------------+------------------------------+
| Node n | nullable(n) |
+---------------------+------------------------------+
+---------------------+------------------------------+
| Epsilon | True |
+---------------------+------------------------------+
| leaf with positon i | False |
+---------------------+------------------------------+
| c1 | c2 | nullable(c1) || nullable(c2) |
+---------------------+------------------------------+
| c1 . c2 | nullable(c1) && nullable(c2) |
+---------------------+------------------------------+
| (c1)* | True |
+---------------------+------------------------------+
FIRST POS
+---------------------+-----------------------------------------------------+
| Node n | firstPos(n) |
+---------------------+-----------------------------------------------------+
+---------------------+-----------------------------------------------------+
| Epsilon | {} |
+---------------------+-----------------------------------------------------+
| leaf with positon i | {i} |
+---------------------+-----------------------------------------------------+
| c1 | c2 | firstPos(c1) ++ firstPos(c2) |
+---------------------+-----------------------------------------------------+
| c1 . c2 | if (nullable(c1)) then firstPos(c1) ++ firstPos(c2) |
| | else firstPos(c1) |
+---------------------+-----------------------------------------------------+
| (c1)* | firstPos(c1) |
+---------------------+-----------------------------------------------------+
LAST POS
+---------------------+-----------------------------------------------------+
| Node n | lastPos(n) |
+---------------------+-----------------------------------------------------+
+---------------------+-----------------------------------------------------+
| Epsilon | {} |
+---------------------+-----------------------------------------------------+
| leaf with positon i | {i} |
+---------------------+-----------------------------------------------------+
| c1 | c2 | lastPos(c1) ++ lastPos(c2) |
+---------------------+-----------------------------------------------------+
| c1 . c2 | if (nullable(c2)) then lastPos(c1) ++ lastPos(c2) |
| | else lastPos(c2) |
+---------------------+-----------------------------------------------------+
| (c1)* | lastPos(c1) |
+---------------------+-----------------------------------------------------+
FOLLOW POS
- If n is a (Concat c1 c2) node, for each position i in lastpos(c1), all
positions in firstpos(c2) are in followpos(i)
- If n is a (Star c1) node, and i is a position in lastpos(n), then all
positions in firstpos(n) are in followpos(i)
-}
{- TreeInfo contains all of the needed info to apply the algorithm -}
type alias TreeInfo =
{ nullable : Bool
, firstPos : List Int
, lastPos : List Int
, followPos : Maybe (List Int)
, nodeSymbol : Maybe Alphabet.Symbol
}
{- Shorthand for the kind of Dict used -}
type alias TreeInfoDict =
Dict Int TreeInfo
{- Default empty TreeInfo -}
emptyTreeInfo : TreeInfo
emptyTreeInfo =
{ nullable = False
, firstPos = []
, lastPos = []
, followPos = Nothing
, nodeSymbol = Nothing
}
{- Extract a TreeInfoDict from a Regex -}
treeInfoDict : Regex -> TreeInfoDict
treeInfoDict r =
nullableDict r Dict.empty
|> firstPosDict r
|> lastPosDict r
|> followPosDict r
{- Cleans a TreeInfoDict by removing everything that doesn't represent a leaf
node in the original Regex
-}
cleanTreeInfoDict : TreeInfoDict -> TreeInfoDict
cleanTreeInfoDict infoTree =
Dict.filter (\_ v -> v.nodeSymbol /= Nothing) infoTree
|> Dict.toList
|> List.map (\( k, v ) -> v)
|> (\x ->
List.map2 (\idx v -> ( idx, v ))
(List.range 1 (List.length x))
x
)
|> Dict.fromList
{- Convert a Regular Expression to an AFD -}
erToAfd : Regex -> Automata.AFD
erToAfd r =
let
newR =
Concat r (Symbol (Alphabet.Single '#'))
startingAfd =
{ states = []
, initialState = State.Dead
, finalStates = []
, alphabet = []
, transitions = []
}
dirtyInfoDict =
treeInfoDict newR
rootNodeInfo =
Dict.values dirtyInfoDict
|> Utils.last
in
case rootNodeInfo of
-- Impossible
Nothing ->
startingAfd
Just info ->
let
startingState =
List.map String.fromInt info.firstPos
|> String.join ""
|> State.Valid
in
erToAfdHelp (cleanTreeInfoDict dirtyInfoDict)
[ info.firstPos ]
[]
{ startingAfd | initialState = startingState }
{- Helper function for erToAfd -}
erToAfdHelp :
TreeInfoDict
-> List (List Int)
-> List (List Int)
-> Automata.AFD
-> Automata.AFD
erToAfdHelp treeInfo statesToCreate seenStates partialAfd =
case List.head statesToCreate of
-- We've visited every state
Nothing ->
partialAfd
Just newStateComponents ->
let
symbolGroups =
getSymbolGroups treeInfo newStateComponents
createState components =
List.map String.fromInt components
|> String.join ""
|> State.Valid
newState =
createState newStateComponents
isFinal =
Dict.keys symbolGroups
|> List.member "#"
newStatesComponents =
Dict.values symbolGroups
newTransitions =
Dict.toList symbolGroups
|> List.filterMap
(\( s, v ) ->
if s == "#" then
Nothing
else
Just
{ prevState = newState
, nextState = createState v
, conditions =
case Utils.stringToSymbol s of
Nothing ->
[]
Just c ->
[ c ]
}
)
newSymbolsStr =
List.filter
(\s ->
case Utils.stringToSymbol s of
Nothing ->
False
Just symb ->
not
(List.member symb
partialAfd.alphabet
)
&& s
/= "#"
)
(Dict.keys symbolGroups)
newSymbols =
List.map Utils.stringToSymbol newSymbolsStr
|> Utils.listOfMaybesToMaybeList
|> Maybe.withDefault []
in
if
List.member newStateComponents seenStates
|| List.isEmpty newStateComponents
then
erToAfdHelp treeInfo
(List.drop 1 statesToCreate)
seenStates
partialAfd
else
erToAfdHelp treeInfo
(List.drop 1 statesToCreate ++ newStatesComponents)
(newStateComponents :: seenStates)
{ partialAfd
| states = partialAfd.states ++ [ newState ]
, finalStates =
if isFinal then
partialAfd.finalStates ++ [ newState ]
else
partialAfd.finalStates
, alphabet =
partialAfd.alphabet
++ newSymbols
, transitions = partialAfd.transitions ++ newTransitions
}
{- Given a TreeInfoDict and a list of indexes (a state in the result AFD),
get a Dict saying which symbols reach which state
-}
getSymbolGroups : TreeInfoDict -> List Int -> Dict String (List Int)
getSymbolGroups treeInfo indexes =
List.foldl
(\index acc ->
case Dict.get index treeInfo of
Nothing ->
acc
Just info ->
case info.nodeSymbol of
Nothing ->
acc
Just symbol ->
case info.followPos of
Nothing ->
acc
Just fp ->
Dict.update (Utils.symbolToString symbol)
(\dictValue ->
case dictValue of
Nothing ->
Just fp
Just v ->
Just <|
Utils.removeDuplicates <|
v
++ fp
)
acc
)
Dict.empty
indexes
{- Given a regex and a TreeInfoDict, assign nullable to each node in the
regex
-}
nullableDict : Regex -> TreeInfoDict -> TreeInfoDict
nullableDict r d =
let
idx dict =
Dict.keys dict |> List.maximum |> Maybe.withDefault 0 |> (+) 1
insert v dict =
Dict.insert (idx dict)
{ emptyTreeInfo
| nullable = v
, nodeSymbol =
case r of
Symbol s ->
Just s
_ ->
Nothing
}
dict
compose1 c1 =
insert (nullable r) (nullableDict c1 d)
compose2 c1 c2 =
let
c1Result =
nullableDict c1 d
c2Result =
nullableDict c2 c1Result
in
insert (nullable r) c2Result
in
case r of
Union c1 c2 ->
compose2 c1 c2
Concat c1 c2 ->
compose2 c1 c2
Star c1 ->
compose1 c1
Plus c1 ->
compose1 c1
Question c1 ->
compose1 c1
_ ->
insert (nullable r) d
{- Given a regex and a TreeInfoDict, assign firstPos to each node in the
regex
-}
firstPosDict : Regex -> TreeInfoDict -> TreeInfoDict
firstPosDict r d =
let
idx dict =
Dict.filter (\_ v -> List.isEmpty v.firstPos) dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
update v dict =
Dict.update (idx dict)
(Maybe.map (\info -> { info | firstPos = Utils.removeDuplicates v }))
dict
prevMaxValue dict =
Dict.values dict
|> List.map .firstPos
|> List.concat
|> List.maximum
|> Maybe.withDefault 0
compose1 c1 =
let
c1Result =
firstPosDict c1 d
thisFirstPos =
firstPosFrom (prevMaxValue d) r
in
update thisFirstPos c1Result
compose2 c1 c2 =
let
c1Result =
firstPosDict c1 d
c2Result =
firstPosDict c2 c1Result
in
update (firstPosFrom (prevMaxValue d) r) c2Result
in
case r of
Union c1 c2 ->
compose2 c1 c2
Concat c1 c2 ->
compose2 c1 c2
Star c1 ->
compose1 c1
Plus c1 ->
compose1 c1
Question c1 ->
compose1 c1
_ ->
update (firstPosFrom (prevMaxValue d) r) d
{- Given a regex and a TreeInfoDict, assign lastPos to each node in the regex -}
lastPosDict : Regex -> TreeInfoDict -> TreeInfoDict
lastPosDict r d =
let
idx dict =
Dict.filter (\_ v -> List.isEmpty v.lastPos) dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
update v dict =
Dict.update (idx dict)
(Maybe.map (\info -> { info | lastPos = v }))
dict
prevMaxValue dict =
Dict.values dict
|> List.map .lastPos
|> List.concat
|> List.maximum
|> Maybe.withDefault 0
prevLastPos dict =
Dict.get (idx dict - 1) dict
|> Maybe.map .lastPos
|> Maybe.withDefault []
compose1 c1 =
let
c1Result =
lastPosDict c1 d
thisLastPos =
lastPosFrom (prevMaxValue d) r
c1LastPos =
prevLastPos c1Result
in
update thisLastPos c1Result
compose2 c1 c2 =
let
c1Result =
lastPosDict c1 d
c1LastPos =
prevLastPos c1Result
|> List.map String.fromInt
|> String.join ","
c2Result =
lastPosDict c2 c1Result
c2LastPos =
prevLastPos c2Result
|> List.map String.fromInt
|> String.join ","
in
update
(lastPosFrom (prevMaxValue d) r)
c2Result
in
case r of
Union c1 c2 ->
compose2 c1 c2
Concat c1 c2 ->
compose2 c1 c2
Star c1 ->
compose1 c1
Plus c1 ->
compose1 c1
Question c1 ->
compose1 c1
Symbol s ->
let
symbol =
case s of
Alphabet.Single x ->
String.fromChar x
Alphabet.Group _ ->
"g"
in
update (lastPosFrom (prevMaxValue d) r) d
_ ->
update (lastPosFrom (prevMaxValue d) r) d
{- Given a regex and a TreeInfoDict, assign followPos to each node in the
regex
-}
followPosDict : Regex -> TreeInfoDict -> TreeInfoDict
followPosDict r d =
let
idx dict =
Dict.filter (\_ v -> v.followPos == Nothing) dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
update v dict =
Dict.update (idx dict)
(Maybe.map (\info -> { info | followPos = v }))
dict
findSymbolIndex s dict =
Dict.filter (\_ v -> v.firstPos == [ s ] && v.nodeSymbol /= Nothing)
dict
|> Dict.keys
|> List.head
|> Maybe.withDefault 0
in
case r of
Star c1 ->
let
c1Result =
followPosDict c1 d
updateFollowPos info newFollowPos =
{ info
| followPos =
case info.followPos of
Nothing ->
Just newFollowPos
Just v ->
Just <|
Utils.removeDuplicates <|
v
++ newFollowPos
}
in
case Dict.get (idx c1Result) c1Result of
-- Impossible
Nothing ->
d
Just treeInfo ->
List.foldl
(\lp acc ->
Dict.update (findSymbolIndex lp acc)
(Maybe.map
(\info ->
updateFollowPos info treeInfo.firstPos
)
)
acc
)
c1Result
treeInfo.lastPos
|> update (Just [])
Concat c1 c2 ->
let
c1Result =
followPosDict c1 d
c1Index =
idx c1Result - 1
c2Result =
followPosDict c2 c1Result
c2Index =
idx c2Result - 1
updateFollowPos info newFollowPos =
{ info
| followPos =
case info.followPos of
Nothing ->
Just newFollowPos
Just v ->
Just <| Utils.removeDuplicates <| v ++ newFollowPos
}
in
case Dict.get c1Index c2Result of
-- Impossible
Nothing ->
d
Just c1Value ->
case Dict.get c2Index c2Result of
-- Impossible
Nothing ->
d
Just c2Value ->
List.foldl
(\lp acc ->
Dict.update (findSymbolIndex lp acc)
(Maybe.map
(\info ->
updateFollowPos info
c2Value.firstPos
)
)
acc
)
c2Result
c1Value.lastPos
|> update (Just [])
Union c1 c2 ->
let
c1Result =
followPosDict c1 d
c2Result =
followPosDict c2 c1Result
in
update (Just []) c2Result
Plus c1 ->
let
c1Result =
followPosDict c1 d
updateFollowPos info newFollowPos =
{ info
| followPos =
case info.followPos of
Nothing ->
Just newFollowPos
Just v ->
Just <| Utils.removeDuplicates <| v ++ newFollowPos
}
in
case Dict.get (idx c1Result) c1Result of
-- Impossible
Nothing ->
d
Just treeInfo ->
List.foldl
(\lp acc ->
Dict.update (findSymbolIndex lp acc)
(Maybe.map
(\info ->
updateFollowPos info treeInfo.firstPos
)
)
acc
)
c1Result
treeInfo.lastPos
|> update (Just [])
Question c1 ->
update (Just []) (followPosDict c1 d)
_ ->
update (Just []) d
{- Get the nullable value of a regex node according to the table at the top of
this file
-}
nullable : Regex -> Bool
nullable r =
case r of
Epsilon ->
True
Symbol _ ->
False
Union c1 c2 ->
nullable c1 || nullable c2
Concat c1 c2 ->
nullable c1 && nullable c2
Star _ ->
True
Plus _ ->
False
Question _ ->
True
{- Get the firstPos value of a regex node according to the table at the top of
this file
-}
firstPos : Regex -> List Int
firstPos =
firstPosFrom 0
{- Get the firstPos giving the first node value -}
firstPosFrom : Int -> Regex -> List Int
firstPosFrom i r =
firstPosHelp i r |> Tuple.first
{- Helper function for firstPos -}
firstPosHelp : Int -> Regex -> ( List Int, Int )
firstPosHelp count r =
case r of
Epsilon ->
( [], count )
Symbol _ ->
( [ count + 1 ], count + 1 )
Union c1 c2 ->
let
( c1FirstPos, c1Count ) =
firstPosHelp count c1
( c2FirstPos, c2Count ) =
firstPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1FirstPos ++ c2FirstPos, c2Count )
Concat c1 c2 ->
let
( c1firstPos, c1Count ) =
firstPosHelp count c1
in
if nullable c1 then
let
( c2firstPos, c2Count ) =
firstPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1firstPos ++ c2firstPos, c2Count )
else
firstPosHelp count c1
Star c1 ->
firstPosHelp count c1
Plus c1 ->
firstPosHelp count c1
Question c1 ->
firstPosHelp count c1
{- Get the lastPos value of a regex node according to the table at the top of
this file
-}
lastPos : Regex -> List Int
lastPos =
lastPosFrom 0
{- Get the firstPos giving the first node value -}
lastPosFrom : Int -> Regex -> List Int
lastPosFrom i r =
lastPosHelp i r |> Tuple.first
{- Helper function for lastPos -}
lastPosHelp : Int -> Regex -> ( List Int, Int )
lastPosHelp count r =
case r of
Epsilon ->
( [], count )
Symbol _ ->
( [ count + 1 ], count + 1 )
Union c1 c2 ->
let
( c1LastPos, c1Count ) =
lastPosHelp count c1
( c2LastPos, c2Count ) =
lastPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1LastPos ++ c2LastPos, c2Count )
Concat c1 c2 ->
if nullable c2 then
let
( c1LastPos, c1Count ) =
lastPosHelp count c1
( c2LastPos, c2Count ) =
lastPosHelp c1Count c2
in
( Utils.removeDuplicates <| c1LastPos ++ c2LastPos, c2Count )
else
let
c1Count =
lastPosHelp count c1 |> Tuple.second
in
lastPosHelp c1Count c2
Star c1 ->
lastPosHelp count c1
Plus c1 ->
lastPosHelp count c1
Question c1 ->
lastPosHelp count c1
{- Given a Regex, counts how many leaf nodes it has -}
getLeafCount : Regex -> Int
getLeafCount r =
case r of
Epsilon ->
1
Symbol _ ->
1
Union c1 c2 ->
getLeafCount c1 + getLeafCount c2
Concat c1 c2 ->
getLeafCount c1 + getLeafCount c2
Star c1 ->
getLeafCount c1
Plus c1 ->
getLeafCount c1
Question c1 ->
getLeafCount c1
| elm |
[
{
"context": "w : Model -> Document Msg\nview _ =\n { title = \"Max Gurewitz\"\n , body =\n [ Element.layout []\n ",
"end": 323,
"score": 0.9997671247,
"start": 311,
"tag": "NAME",
"value": "Max Gurewitz"
}
] | src/Main.elm | maxgurewitz/personal-site-typescript | 0 | module Main exposing (main)
import Browser exposing (Document)
import Element exposing (Element, column, fill, padding, row, spacing, text, width)
type Msg
= NoOp
type BlogEntry
= Mit6824
type alias Model =
{ blogEntry : BlogEntry
}
view : Model -> Document Msg
view _ =
{ title = "Max Gurewitz"
, body =
[ Element.layout []
(column [ width fill ]
[ header
, content
]
)
]
}
header : Element Msg
header =
row [ width fill, padding 20, spacing 20 ] [ text "header" ]
content : Element Msg
content =
row [ width fill ] [ text "content" ]
init : () -> ( Model, Cmd Msg )
init _ =
let
model =
{ blogEntry = Mit6824
}
in
( model, Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update _ model =
( model, Cmd.none )
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
main : Program () Model Msg
main =
Browser.document
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
| 25525 | module Main exposing (main)
import Browser exposing (Document)
import Element exposing (Element, column, fill, padding, row, spacing, text, width)
type Msg
= NoOp
type BlogEntry
= Mit6824
type alias Model =
{ blogEntry : BlogEntry
}
view : Model -> Document Msg
view _ =
{ title = "<NAME>"
, body =
[ Element.layout []
(column [ width fill ]
[ header
, content
]
)
]
}
header : Element Msg
header =
row [ width fill, padding 20, spacing 20 ] [ text "header" ]
content : Element Msg
content =
row [ width fill ] [ text "content" ]
init : () -> ( Model, Cmd Msg )
init _ =
let
model =
{ blogEntry = Mit6824
}
in
( model, Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update _ model =
( model, Cmd.none )
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
main : Program () Model Msg
main =
Browser.document
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
| true | module Main exposing (main)
import Browser exposing (Document)
import Element exposing (Element, column, fill, padding, row, spacing, text, width)
type Msg
= NoOp
type BlogEntry
= Mit6824
type alias Model =
{ blogEntry : BlogEntry
}
view : Model -> Document Msg
view _ =
{ title = "PI:NAME:<NAME>END_PI"
, body =
[ Element.layout []
(column [ width fill ]
[ header
, content
]
)
]
}
header : Element Msg
header =
row [ width fill, padding 20, spacing 20 ] [ text "header" ]
content : Element Msg
content =
row [ width fill ] [ text "content" ]
init : () -> ( Model, Cmd Msg )
init _ =
let
model =
{ blogEntry = Mit6824
}
in
( model, Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update _ model =
( model, Cmd.none )
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
main : Program () Model Msg
main =
Browser.document
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
| elm |
[
{
"context": "\n {\n ix = -1,\n id = \"\",\n name = \"Unknown\",\n mode = Either,\n category = Campaign,",
"end": 3310,
"score": 0.9629718661,
"start": 3303,
"tag": "NAME",
"value": "Unknown"
}
] | src/main-menu/src/Struct/BattleSummary.elm | nsensfel/tacticians | 0 | module Struct.BattleSummary exposing
(
Type,
Category(..),
Mode(..),
get_id,
get_ix,
get_name,
get_mode,
get_category,
get_deadline,
is_players_turn,
is_pending,
is_empty_slot,
get_invasion_category,
decoder,
none
)
-- Elm -------------------------------------------------------------------------
import Json.Decode
import Json.Decode.Pipeline
-- Main Menu -------------------------------------------------------------------
--------------------------------------------------------------------------------
-- TYPES -----------------------------------------------------------------------
--------------------------------------------------------------------------------
type Category =
Invasion
| Event
| Campaign
type Mode =
Attack
| Defend
| Either
type alias Type =
{
ix : Int,
id : String,
name : String,
mode : Mode,
category : Category,
deadline : String,
is_players_turn : Bool,
is_pending : Bool
}
--------------------------------------------------------------------------------
-- LOCAL -----------------------------------------------------------------------
--------------------------------------------------------------------------------
mode_from_string : String -> Mode
mode_from_string str =
case str of
"a" -> Attack
"d" -> Defend
_ -> Either
category_from_string : String -> Category
category_from_string str =
case str of
"i" -> Invasion
"e" -> Event
_ -> Campaign
--------------------------------------------------------------------------------
-- EXPORTED --------------------------------------------------------------------
--------------------------------------------------------------------------------
get_ix : Type -> Int
get_ix t = t.ix
get_id : Type -> String
get_id t = t.id
get_name : Type -> String
get_name t = t.name
get_mode : Type -> Mode
get_mode t = t.mode
get_category : Type -> Category
get_category t = t.category
get_deadline : Type -> String
get_deadline t = t.deadline
is_players_turn : Type -> Bool
is_players_turn t = t.is_players_turn
is_pending : Type -> Bool
is_pending t = t.is_pending
is_empty_slot : Type -> Bool
is_empty_slot t = (t.id == "")
get_invasion_category : Int -> Mode
get_invasion_category ix =
if (ix < 3)
then Attack
else if (ix < 6)
then Either
else Defend
decoder : (Json.Decode.Decoder Type)
decoder =
(Json.Decode.succeed
Type
|> (Json.Decode.Pipeline.required "ix" Json.Decode.int)
|> (Json.Decode.Pipeline.required "id" Json.Decode.string)
|> (Json.Decode.Pipeline.required "nme" Json.Decode.string)
|>
(Json.Decode.Pipeline.required
"mod"
(Json.Decode.map mode_from_string (Json.Decode.string))
)
|>
(Json.Decode.Pipeline.required
"cat"
(Json.Decode.map category_from_string (Json.Decode.string))
)
|> (Json.Decode.Pipeline.required "dln" Json.Decode.string)
|> (Json.Decode.Pipeline.required "ipt" Json.Decode.bool)
|> (Json.Decode.Pipeline.required "ipd" Json.Decode.bool)
)
none : Type
none =
{
ix = -1,
id = "",
name = "Unknown",
mode = Either,
category = Campaign,
deadline = "Never",
is_players_turn = False,
is_pending = False
}
| 1426 | module Struct.BattleSummary exposing
(
Type,
Category(..),
Mode(..),
get_id,
get_ix,
get_name,
get_mode,
get_category,
get_deadline,
is_players_turn,
is_pending,
is_empty_slot,
get_invasion_category,
decoder,
none
)
-- Elm -------------------------------------------------------------------------
import Json.Decode
import Json.Decode.Pipeline
-- Main Menu -------------------------------------------------------------------
--------------------------------------------------------------------------------
-- TYPES -----------------------------------------------------------------------
--------------------------------------------------------------------------------
type Category =
Invasion
| Event
| Campaign
type Mode =
Attack
| Defend
| Either
type alias Type =
{
ix : Int,
id : String,
name : String,
mode : Mode,
category : Category,
deadline : String,
is_players_turn : Bool,
is_pending : Bool
}
--------------------------------------------------------------------------------
-- LOCAL -----------------------------------------------------------------------
--------------------------------------------------------------------------------
mode_from_string : String -> Mode
mode_from_string str =
case str of
"a" -> Attack
"d" -> Defend
_ -> Either
category_from_string : String -> Category
category_from_string str =
case str of
"i" -> Invasion
"e" -> Event
_ -> Campaign
--------------------------------------------------------------------------------
-- EXPORTED --------------------------------------------------------------------
--------------------------------------------------------------------------------
get_ix : Type -> Int
get_ix t = t.ix
get_id : Type -> String
get_id t = t.id
get_name : Type -> String
get_name t = t.name
get_mode : Type -> Mode
get_mode t = t.mode
get_category : Type -> Category
get_category t = t.category
get_deadline : Type -> String
get_deadline t = t.deadline
is_players_turn : Type -> Bool
is_players_turn t = t.is_players_turn
is_pending : Type -> Bool
is_pending t = t.is_pending
is_empty_slot : Type -> Bool
is_empty_slot t = (t.id == "")
get_invasion_category : Int -> Mode
get_invasion_category ix =
if (ix < 3)
then Attack
else if (ix < 6)
then Either
else Defend
decoder : (Json.Decode.Decoder Type)
decoder =
(Json.Decode.succeed
Type
|> (Json.Decode.Pipeline.required "ix" Json.Decode.int)
|> (Json.Decode.Pipeline.required "id" Json.Decode.string)
|> (Json.Decode.Pipeline.required "nme" Json.Decode.string)
|>
(Json.Decode.Pipeline.required
"mod"
(Json.Decode.map mode_from_string (Json.Decode.string))
)
|>
(Json.Decode.Pipeline.required
"cat"
(Json.Decode.map category_from_string (Json.Decode.string))
)
|> (Json.Decode.Pipeline.required "dln" Json.Decode.string)
|> (Json.Decode.Pipeline.required "ipt" Json.Decode.bool)
|> (Json.Decode.Pipeline.required "ipd" Json.Decode.bool)
)
none : Type
none =
{
ix = -1,
id = "",
name = "<NAME>",
mode = Either,
category = Campaign,
deadline = "Never",
is_players_turn = False,
is_pending = False
}
| true | module Struct.BattleSummary exposing
(
Type,
Category(..),
Mode(..),
get_id,
get_ix,
get_name,
get_mode,
get_category,
get_deadline,
is_players_turn,
is_pending,
is_empty_slot,
get_invasion_category,
decoder,
none
)
-- Elm -------------------------------------------------------------------------
import Json.Decode
import Json.Decode.Pipeline
-- Main Menu -------------------------------------------------------------------
--------------------------------------------------------------------------------
-- TYPES -----------------------------------------------------------------------
--------------------------------------------------------------------------------
type Category =
Invasion
| Event
| Campaign
type Mode =
Attack
| Defend
| Either
type alias Type =
{
ix : Int,
id : String,
name : String,
mode : Mode,
category : Category,
deadline : String,
is_players_turn : Bool,
is_pending : Bool
}
--------------------------------------------------------------------------------
-- LOCAL -----------------------------------------------------------------------
--------------------------------------------------------------------------------
mode_from_string : String -> Mode
mode_from_string str =
case str of
"a" -> Attack
"d" -> Defend
_ -> Either
category_from_string : String -> Category
category_from_string str =
case str of
"i" -> Invasion
"e" -> Event
_ -> Campaign
--------------------------------------------------------------------------------
-- EXPORTED --------------------------------------------------------------------
--------------------------------------------------------------------------------
get_ix : Type -> Int
get_ix t = t.ix
get_id : Type -> String
get_id t = t.id
get_name : Type -> String
get_name t = t.name
get_mode : Type -> Mode
get_mode t = t.mode
get_category : Type -> Category
get_category t = t.category
get_deadline : Type -> String
get_deadline t = t.deadline
is_players_turn : Type -> Bool
is_players_turn t = t.is_players_turn
is_pending : Type -> Bool
is_pending t = t.is_pending
is_empty_slot : Type -> Bool
is_empty_slot t = (t.id == "")
get_invasion_category : Int -> Mode
get_invasion_category ix =
if (ix < 3)
then Attack
else if (ix < 6)
then Either
else Defend
decoder : (Json.Decode.Decoder Type)
decoder =
(Json.Decode.succeed
Type
|> (Json.Decode.Pipeline.required "ix" Json.Decode.int)
|> (Json.Decode.Pipeline.required "id" Json.Decode.string)
|> (Json.Decode.Pipeline.required "nme" Json.Decode.string)
|>
(Json.Decode.Pipeline.required
"mod"
(Json.Decode.map mode_from_string (Json.Decode.string))
)
|>
(Json.Decode.Pipeline.required
"cat"
(Json.Decode.map category_from_string (Json.Decode.string))
)
|> (Json.Decode.Pipeline.required "dln" Json.Decode.string)
|> (Json.Decode.Pipeline.required "ipt" Json.Decode.bool)
|> (Json.Decode.Pipeline.required "ipd" Json.Decode.bool)
)
none : Type
none =
{
ix = -1,
id = "",
name = "PI:NAME:<NAME>END_PI",
mode = Either,
category = Campaign,
deadline = "Never",
is_players_turn = False,
is_pending = False
}
| elm |
[
{
"context": "ted\", isSelected )\n ]\n ]\n persona\n",
"end": 4977,
"score": 0.8142311573,
"start": 4970,
"tag": "NAME",
"value": "persona"
}
] | webofneeds/won-owner-webapp/src/main/webapp/elm/AddPersona.elm | Schlizohr/webofneeds | 0 | module AddPersona exposing (main)
import Html exposing (..)
import Html.Attributes as Attributes
import Html.Events as Events
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Extra as Decode
import Maybe.Extra as Maybe
import Palette
import Persona exposing (Persona)
import Widget
main =
Widget.widget
{ init = init
, update = update
, view = view
, subscriptions = \_ -> Sub.none
, propDecoder = propDecoder
}
---- MODEL ----
type alias Id =
String
type Model
= Selecting (Maybe Id)
| AddingPersona Id
---- PROPS ----
type alias Props =
{ postUri : Id
, personas : List Persona
}
propDecoder : Decoder Props
propDecoder =
Decode.map2 Props
(Decode.at [ "post", "uri" ] Decode.string)
(Decode.field "personas" <| Decode.list Persona.decoder)
---- INIT ----
init : Props -> ( Model, Cmd Msg )
init _ =
( Selecting Nothing
, Cmd.none
)
---- UPDATE ----
type Msg
= SelectPersona Id
| AddPersona
selectedPersona : List Persona -> Model -> Maybe Persona
selectedPersona personas model =
let
getPersona id =
personas
|> List.filter (\persona -> persona.uri == id)
|> List.head
in
case model of
Selecting id ->
id |> Maybe.andThen getPersona
AddingPersona id ->
getPersona id
update :
Msg
->
{ model : Model
, props : Props
}
-> ( Model, Cmd Msg )
update msg { model, props } =
case msg of
AddPersona ->
case model of
AddingPersona _ ->
( model, Cmd.none )
Selecting Nothing ->
( model, Cmd.none )
Selecting (Just id) ->
case selectedPersona props.personas model of
Just persona ->
( AddingPersona id
, Persona.connect
{ persona = persona
, atomUrl = props.postUri
}
|> Widget.performAction
)
Nothing ->
( model, Cmd.none )
SelectPersona id ->
case model of
AddingPersona _ ->
( model, Cmd.none )
Selecting _ ->
( Selecting (Just id), Cmd.none )
---- VIEW ----
view :
{ model : Model
, props : Props
}
-> Html Msg
view { model, props } =
let
saving =
case model of
AddingPersona _ ->
True
_ ->
False
selected =
selectedPersona props.personas model
|> Maybe.isJust
in
div
[ Attributes.classList
[ ( "won-add-persona", True )
, ( "saving", saving )
]
]
([ h1 [] [ text "Add a persona to your post" ]
]
++ (if List.isEmpty props.personas then
[ div [] [ text "You have no personas yet" ]
, a
[ Attributes.href "#!/create?useCase=persona"
, Attributes.class "won-button--filled"
, Attributes.class "red"
]
[ text "Create a Persona" ]
]
else
[ personaList props.personas model
, Palette.wonButton
[ Attributes.disabled (not selected)
, Events.onClick AddPersona
, Attributes.class "add-persona-button"
]
[ if saving then
text "Saving..."
else
text "Add"
]
]
)
)
personaSelected : Model -> Persona -> Bool
personaSelected model persona =
case model of
Selecting (Just id) ->
id == persona.uri
AddingPersona id ->
id == persona.uri
Selecting Nothing ->
False
personaList : List Persona -> Model -> Html Msg
personaList personas model =
ul [ Attributes.class "won-persona-list" ]
(personas
|> List.sortBy (.name >> String.toLower)
|> List.map (personaView model)
)
personaView : Model -> Persona -> Html Msg
personaView model persona =
let
isSelected =
personaSelected model persona
in
Persona.inlineView
[ Events.onClick (SelectPersona persona.uri)
, Attributes.classList
[ ( "selected", isSelected )
]
]
persona
| 8486 | module AddPersona exposing (main)
import Html exposing (..)
import Html.Attributes as Attributes
import Html.Events as Events
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Extra as Decode
import Maybe.Extra as Maybe
import Palette
import Persona exposing (Persona)
import Widget
main =
Widget.widget
{ init = init
, update = update
, view = view
, subscriptions = \_ -> Sub.none
, propDecoder = propDecoder
}
---- MODEL ----
type alias Id =
String
type Model
= Selecting (Maybe Id)
| AddingPersona Id
---- PROPS ----
type alias Props =
{ postUri : Id
, personas : List Persona
}
propDecoder : Decoder Props
propDecoder =
Decode.map2 Props
(Decode.at [ "post", "uri" ] Decode.string)
(Decode.field "personas" <| Decode.list Persona.decoder)
---- INIT ----
init : Props -> ( Model, Cmd Msg )
init _ =
( Selecting Nothing
, Cmd.none
)
---- UPDATE ----
type Msg
= SelectPersona Id
| AddPersona
selectedPersona : List Persona -> Model -> Maybe Persona
selectedPersona personas model =
let
getPersona id =
personas
|> List.filter (\persona -> persona.uri == id)
|> List.head
in
case model of
Selecting id ->
id |> Maybe.andThen getPersona
AddingPersona id ->
getPersona id
update :
Msg
->
{ model : Model
, props : Props
}
-> ( Model, Cmd Msg )
update msg { model, props } =
case msg of
AddPersona ->
case model of
AddingPersona _ ->
( model, Cmd.none )
Selecting Nothing ->
( model, Cmd.none )
Selecting (Just id) ->
case selectedPersona props.personas model of
Just persona ->
( AddingPersona id
, Persona.connect
{ persona = persona
, atomUrl = props.postUri
}
|> Widget.performAction
)
Nothing ->
( model, Cmd.none )
SelectPersona id ->
case model of
AddingPersona _ ->
( model, Cmd.none )
Selecting _ ->
( Selecting (Just id), Cmd.none )
---- VIEW ----
view :
{ model : Model
, props : Props
}
-> Html Msg
view { model, props } =
let
saving =
case model of
AddingPersona _ ->
True
_ ->
False
selected =
selectedPersona props.personas model
|> Maybe.isJust
in
div
[ Attributes.classList
[ ( "won-add-persona", True )
, ( "saving", saving )
]
]
([ h1 [] [ text "Add a persona to your post" ]
]
++ (if List.isEmpty props.personas then
[ div [] [ text "You have no personas yet" ]
, a
[ Attributes.href "#!/create?useCase=persona"
, Attributes.class "won-button--filled"
, Attributes.class "red"
]
[ text "Create a Persona" ]
]
else
[ personaList props.personas model
, Palette.wonButton
[ Attributes.disabled (not selected)
, Events.onClick AddPersona
, Attributes.class "add-persona-button"
]
[ if saving then
text "Saving..."
else
text "Add"
]
]
)
)
personaSelected : Model -> Persona -> Bool
personaSelected model persona =
case model of
Selecting (Just id) ->
id == persona.uri
AddingPersona id ->
id == persona.uri
Selecting Nothing ->
False
personaList : List Persona -> Model -> Html Msg
personaList personas model =
ul [ Attributes.class "won-persona-list" ]
(personas
|> List.sortBy (.name >> String.toLower)
|> List.map (personaView model)
)
personaView : Model -> Persona -> Html Msg
personaView model persona =
let
isSelected =
personaSelected model persona
in
Persona.inlineView
[ Events.onClick (SelectPersona persona.uri)
, Attributes.classList
[ ( "selected", isSelected )
]
]
<NAME>
| true | module AddPersona exposing (main)
import Html exposing (..)
import Html.Attributes as Attributes
import Html.Events as Events
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Extra as Decode
import Maybe.Extra as Maybe
import Palette
import Persona exposing (Persona)
import Widget
main =
Widget.widget
{ init = init
, update = update
, view = view
, subscriptions = \_ -> Sub.none
, propDecoder = propDecoder
}
---- MODEL ----
type alias Id =
String
type Model
= Selecting (Maybe Id)
| AddingPersona Id
---- PROPS ----
type alias Props =
{ postUri : Id
, personas : List Persona
}
propDecoder : Decoder Props
propDecoder =
Decode.map2 Props
(Decode.at [ "post", "uri" ] Decode.string)
(Decode.field "personas" <| Decode.list Persona.decoder)
---- INIT ----
init : Props -> ( Model, Cmd Msg )
init _ =
( Selecting Nothing
, Cmd.none
)
---- UPDATE ----
type Msg
= SelectPersona Id
| AddPersona
selectedPersona : List Persona -> Model -> Maybe Persona
selectedPersona personas model =
let
getPersona id =
personas
|> List.filter (\persona -> persona.uri == id)
|> List.head
in
case model of
Selecting id ->
id |> Maybe.andThen getPersona
AddingPersona id ->
getPersona id
update :
Msg
->
{ model : Model
, props : Props
}
-> ( Model, Cmd Msg )
update msg { model, props } =
case msg of
AddPersona ->
case model of
AddingPersona _ ->
( model, Cmd.none )
Selecting Nothing ->
( model, Cmd.none )
Selecting (Just id) ->
case selectedPersona props.personas model of
Just persona ->
( AddingPersona id
, Persona.connect
{ persona = persona
, atomUrl = props.postUri
}
|> Widget.performAction
)
Nothing ->
( model, Cmd.none )
SelectPersona id ->
case model of
AddingPersona _ ->
( model, Cmd.none )
Selecting _ ->
( Selecting (Just id), Cmd.none )
---- VIEW ----
view :
{ model : Model
, props : Props
}
-> Html Msg
view { model, props } =
let
saving =
case model of
AddingPersona _ ->
True
_ ->
False
selected =
selectedPersona props.personas model
|> Maybe.isJust
in
div
[ Attributes.classList
[ ( "won-add-persona", True )
, ( "saving", saving )
]
]
([ h1 [] [ text "Add a persona to your post" ]
]
++ (if List.isEmpty props.personas then
[ div [] [ text "You have no personas yet" ]
, a
[ Attributes.href "#!/create?useCase=persona"
, Attributes.class "won-button--filled"
, Attributes.class "red"
]
[ text "Create a Persona" ]
]
else
[ personaList props.personas model
, Palette.wonButton
[ Attributes.disabled (not selected)
, Events.onClick AddPersona
, Attributes.class "add-persona-button"
]
[ if saving then
text "Saving..."
else
text "Add"
]
]
)
)
personaSelected : Model -> Persona -> Bool
personaSelected model persona =
case model of
Selecting (Just id) ->
id == persona.uri
AddingPersona id ->
id == persona.uri
Selecting Nothing ->
False
personaList : List Persona -> Model -> Html Msg
personaList personas model =
ul [ Attributes.class "won-persona-list" ]
(personas
|> List.sortBy (.name >> String.toLower)
|> List.map (personaView model)
)
personaView : Model -> Persona -> Html Msg
personaView model persona =
let
isSelected =
personaSelected model persona
in
Persona.inlineView
[ Events.onClick (SelectPersona persona.uri)
, Attributes.classList
[ ( "selected", isSelected )
]
]
PI:NAME:<NAME>END_PI
| elm |
[
{
"context": "\" \"author\"\n , attribute \"content\" \"Martin Feineis\"\n ]\n []\n ",
"end": 4744,
"score": 0.9998806119,
"start": 4730,
"tag": "NAME",
"value": "Martin Feineis"
},
{
"context": " \"creator\"\n , attribute \"content\" \"Canena\"\n ]\n []\n ",
"end": 4899,
"score": 0.9994826317,
"start": 4893,
"tag": "NAME",
"value": "Canena"
},
{
"context": "libs/highlight.js/9.15.8/styles/default.min.css\" \"sha256-zcunqSn1llgADaIPFyzrQ8USIjX2VpuxHzUwYisOwo8=\" ",
"end": 5598,
"score": 0.5639659762,
"start": 5595,
"tag": "KEY",
"value": "sha"
},
{
"context": "/highlight.js/9.15.8/styles/default.min.css\" \"sha256-zcunqSn1llgADaIPFyzrQ8USIjX2VpuxHzUwYisOwo8=\" \"anonymous\"\n , cdnStylesheet \"https://",
"end": 5647,
"score": 0.8593790531,
"start": 5599,
"tag": "KEY",
"value": "56-zcunqSn1llgADaIPFyzrQ8USIjX2VpuxHzUwYisOwo8=\""
},
{
"context": "x/libs/highlight.js/9.15.8/styles/xcode.min.css\" \"sha256-fjO4CUN/XJTfsDmlIBojCwY4EV94jfOJpPzqd19TSko=\" \"anonymous\"\n --, cdnStylesheet \"https:",
"end": 5823,
"score": 0.9058992863,
"start": 5771,
"tag": "KEY",
"value": "sha256-fjO4CUN/XJTfsDmlIBojCwY4EV94jfOJpPzqd19TSko=\""
},
{
"context": "/highlight.js/9.15.8/styles/github-gist.min.css\" \"sha256-3bRfCcmMiQbIzvnxDzgFY9bl7dc07xbdX3+Mr4QYTY8=\" \"anonymous\"\n , Styles.styles\n ",
"end": 6007,
"score": 0.9094403982,
"start": 5955,
"tag": "KEY",
"value": "sha256-3bRfCcmMiQbIzvnxDzgFY9bl7dc07xbdX3+Mr4QYTY8=\""
},
{
"context": "/ajax/libs/highlight.js/9.15.8/highlight.min.js\" \"sha256-js+I1fdbke/DJrW2qXQlrw7VUEqmdeFeOW37UC0bEiU=\" \"anonymous\"\n , cdnScript \"https://cdnj",
"end": 6203,
"score": 0.9753750563,
"start": 6151,
"tag": "KEY",
"value": "sha256-js+I1fdbke/DJrW2qXQlrw7VUEqmdeFeOW37UC0bEiU=\""
},
{
"context": "/libs/highlight.js/9.15.8/languages/bash.min.js\" \"sha256-zXrlim8wsIvcEFjsD3THiAfTvtPZifqx8q0rxegiWQc=\" \"anonymous\"\n , cdnScript \"https://cdnj",
"end": 6376,
"score": 0.9803203344,
"start": 6324,
"tag": "KEY",
"value": "sha256-zXrlim8wsIvcEFjsD3THiAfTvtPZifqx8q0rxegiWQc=\""
},
{
"context": "x/libs/highlight.js/9.15.8/languages/elm.min.js\" \"sha256-5ZDjmDRr7i9DNIGlJKzPImNcoVZ2KGsPch+qoZuYq5M=\" \"anonymous\"\n , cdnScript \"https://cdnj",
"end": 6548,
"score": 0.990177691,
"start": 6496,
"tag": "KEY",
"value": "sha256-5ZDjmDRr7i9DNIGlJKzPImNcoVZ2KGsPch+qoZuYq5M=\""
},
{
"context": "highlight.js/9.15.8/languages/javascript.min.js\" \"sha256-x3ducqWgfzH2JLxwkA7vfwbJC7nZgvdypVl0Gy0L/z0=\" \"anonymous\"\n , inlineScript \"hljs.init",
"end": 6727,
"score": 0.9922290444,
"start": 6675,
"tag": "KEY",
"value": "sha256-x3ducqWgfzH2JLxwkA7vfwbJC7nZgvdypVl0Gy0L/z0=\""
},
{
"context": "e.com/ajax/libs/require.js/2.3.6/require.min.js\" \"sha256-1fEPhSsRKlFKGfK3eO710tEweHh1fwokU5wFGDHO+vg=\" \"anonymous\"\n , stylesheet \"https://fon",
"end": 7219,
"score": 0.9887548089,
"start": 7167,
"tag": "KEY",
"value": "sha256-1fEPhSsRKlFKGfK3eO710tEweHh1fwokU5wFGDHO+vg=\""
}
] | src/_layouts/Elmstatic.elm | canena/canena.github.io | 0 | module Elmstatic exposing
( Content
, Layout
, Page
, Post
, PostList
, decodePage
, decodePost
, decodePostList
, htmlTemplate
, inlineScript
, layout
, script
, stylesheet
)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Json.Decode
import Styles
type alias Post =
{ date : String
, imports : List String
, link : String
, markdown : String
, section : String
, siteTitle : String
, tags : List String
, title : String
}
type alias Page =
{ imports : List String
, markdown : String
, siteTitle : String
, title : String
}
type alias PostList =
{ imports : List String
, posts : List Post
, section : String
, siteTitle : String
, title : String
}
type alias Content a =
{ a | imports : List String, siteTitle : String, title : String }
type alias Layout =
Program Json.Decode.Value Json.Decode.Value Never
decodePage : Json.Decode.Decoder Page
decodePage =
Json.Decode.map4 Page
decodeImports
(Json.Decode.field "markdown" Json.Decode.string)
(Json.Decode.field "siteTitle" Json.Decode.string)
(Json.Decode.field "title" Json.Decode.string)
decodePost : Json.Decode.Decoder Post
decodePost =
Json.Decode.map8 Post
(Json.Decode.field "date" Json.Decode.string)
decodeImports
(Json.Decode.field "link" Json.Decode.string)
(Json.Decode.field "markdown" Json.Decode.string)
(Json.Decode.field "section" Json.Decode.string)
(Json.Decode.field "siteTitle" Json.Decode.string)
(Json.Decode.field "tags" <| Json.Decode.list Json.Decode.string)
(Json.Decode.field "title" Json.Decode.string)
decodePostList : Json.Decode.Decoder PostList
decodePostList =
Json.Decode.map5 PostList
decodeImports
(Json.Decode.field "posts" <| Json.Decode.list decodePost)
(Json.Decode.field "section" Json.Decode.string)
(Json.Decode.field "siteTitle" Json.Decode.string)
(Json.Decode.field "title" Json.Decode.string)
decodeImports : Json.Decode.Decoder (List String)
decodeImports =
Json.Decode.maybe (Json.Decode.field "imports" Json.Decode.string)
|> Json.Decode.andThen
(\maybeEntry ->
case maybeEntry of
Nothing ->
Json.Decode.succeed []
Just "" ->
Json.Decode.succeed []
Just value ->
String.split " " value
|> List.map String.trim
|> Json.Decode.succeed
)
decodeBoolMeta : String -> Json.Decode.Decoder Bool
decodeBoolMeta prop =
Json.Decode.maybe (Json.Decode.field prop Json.Decode.string)
|> Json.Decode.andThen
(\value ->
case value of
Nothing ->
Json.Decode.succeed False
Just "true" ->
Json.Decode.succeed True
Just _ ->
Json.Decode.succeed False
)
script : String -> Html Never
script src =
node "citatsmle-script" [ attribute "src" src ] []
cdnScript : String -> String -> String -> Html Never
cdnScript src integrity crossorigin =
node "citatsmle-script"
[ attribute "src" src
, attribute "integrity" integrity
, attribute "crossorigin" crossorigin
]
[]
inlineScript : String -> Html Never
inlineScript js =
node "citatsmle-script" [] [ text js ]
stylesheet : String -> Html Never
stylesheet href =
node "link" [ attribute "href" href, attribute "rel" "stylesheet", attribute "type" "text/css" ] []
cdnStylesheet : String -> String -> String -> Html Never
cdnStylesheet href integrity crossorigin =
node "link"
[ attribute "href" href
, attribute "rel" "stylesheet"
, attribute "type" "text/css"
, attribute "integrity" integrity
, attribute "crossorigin" crossorigin
]
[]
htmlTemplate : String -> List (Html Never) -> Html Never
htmlTemplate title contentNodes =
node "html"
[ attribute "lang" "en"
, class "ui-layout no-js"
]
[ node "head"
[]
[ node "meta" [ attribute "charset" "utf-8" ] []
, node "meta"
[ attribute "http-equiv" "X-UA-Compatible"
, attribute "content" "IE=edge"
]
[]
, node "meta"
[ attribute "name" "author"
, attribute "content" "Martin Feineis"
]
[]
, node "meta"
[ attribute "name" "creator"
, attribute "content" "Canena"
]
[]
, node "meta"
[ attribute "name" "description"
, attribute "content" "A blog about life"
]
[]
, node "meta"
[ attribute "name" "viewport"
, attribute "content" "width=device-width, user-scalable=yes, initial-scale=1.0, minimum-scale=1.0"
]
[]
, node "title" [] [ text title ]
, stylesheet "/style/normalize-8.0.1.css"
, stylesheet "/style/styles.css?v1"
--, cdnStylesheet "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/styles/default.min.css" "sha256-zcunqSn1llgADaIPFyzrQ8USIjX2VpuxHzUwYisOwo8=" "anonymous"
, cdnStylesheet "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/styles/xcode.min.css" "sha256-fjO4CUN/XJTfsDmlIBojCwY4EV94jfOJpPzqd19TSko=" "anonymous"
--, cdnStylesheet "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/styles/github-gist.min.css" "sha256-3bRfCcmMiQbIzvnxDzgFY9bl7dc07xbdX3+Mr4QYTY8=" "anonymous"
, Styles.styles
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/highlight.min.js" "sha256-js+I1fdbke/DJrW2qXQlrw7VUEqmdeFeOW37UC0bEiU=" "anonymous"
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/languages/bash.min.js" "sha256-zXrlim8wsIvcEFjsD3THiAfTvtPZifqx8q0rxegiWQc=" "anonymous"
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/languages/elm.min.js" "sha256-5ZDjmDRr7i9DNIGlJKzPImNcoVZ2KGsPch+qoZuYq5M=" "anonymous"
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/languages/javascript.min.js" "sha256-x3ducqWgfzH2JLxwkA7vfwbJC7nZgvdypVl0Gy0L/z0=" "anonymous"
, inlineScript "hljs.initHighlightingOnLoad();"
, inlineScript """
var requirejs = {
baseUrl: \"/js\",
paths: {
greeshka: \"libs/greeshka-0.3.0\",
mathjax: \"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"
}
};
"""
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" "sha256-1fEPhSsRKlFKGfK3eO710tEweHh1fwokU5wFGDHO+vg=" "anonymous"
, stylesheet "https://fonts.googleapis.com/css?family=Roboto+Condensed|Inconsolata"
, inlineScript "document.querySelector('html').classList.remove('no-js');"
]
, node "body" [] contentNodes
]
layout : Json.Decode.Decoder (Content content) -> (Content content -> List (Html Never)) -> Layout
layout decoder view =
Browser.document
{ init = \contentJson -> ( contentJson, Cmd.none )
, view =
\contentJson ->
case Json.Decode.decodeValue decoder contentJson of
Err error ->
{ title = ""
, body = [ htmlTemplate "Error" [ Html.text <| Json.Decode.errorToString error ] ]
}
Ok content ->
let
amdImports =
content.imports
|> List.map (\it -> "\"" ++ it ++ "\"")
|> String.join ", "
in
{ title = ""
, body =
[ htmlTemplate content.siteTitle <|
List.concat
[ view content
, if List.isEmpty content.imports then
[ text "" ]
else
[ inlineScript <|
"require([" ++ amdImports ++ "]);"
]
]
]
}
, update = \msg contentJson -> ( contentJson, Cmd.none )
, subscriptions = \_ -> Sub.none
}
| 16632 | module Elmstatic exposing
( Content
, Layout
, Page
, Post
, PostList
, decodePage
, decodePost
, decodePostList
, htmlTemplate
, inlineScript
, layout
, script
, stylesheet
)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Json.Decode
import Styles
type alias Post =
{ date : String
, imports : List String
, link : String
, markdown : String
, section : String
, siteTitle : String
, tags : List String
, title : String
}
type alias Page =
{ imports : List String
, markdown : String
, siteTitle : String
, title : String
}
type alias PostList =
{ imports : List String
, posts : List Post
, section : String
, siteTitle : String
, title : String
}
type alias Content a =
{ a | imports : List String, siteTitle : String, title : String }
type alias Layout =
Program Json.Decode.Value Json.Decode.Value Never
decodePage : Json.Decode.Decoder Page
decodePage =
Json.Decode.map4 Page
decodeImports
(Json.Decode.field "markdown" Json.Decode.string)
(Json.Decode.field "siteTitle" Json.Decode.string)
(Json.Decode.field "title" Json.Decode.string)
decodePost : Json.Decode.Decoder Post
decodePost =
Json.Decode.map8 Post
(Json.Decode.field "date" Json.Decode.string)
decodeImports
(Json.Decode.field "link" Json.Decode.string)
(Json.Decode.field "markdown" Json.Decode.string)
(Json.Decode.field "section" Json.Decode.string)
(Json.Decode.field "siteTitle" Json.Decode.string)
(Json.Decode.field "tags" <| Json.Decode.list Json.Decode.string)
(Json.Decode.field "title" Json.Decode.string)
decodePostList : Json.Decode.Decoder PostList
decodePostList =
Json.Decode.map5 PostList
decodeImports
(Json.Decode.field "posts" <| Json.Decode.list decodePost)
(Json.Decode.field "section" Json.Decode.string)
(Json.Decode.field "siteTitle" Json.Decode.string)
(Json.Decode.field "title" Json.Decode.string)
decodeImports : Json.Decode.Decoder (List String)
decodeImports =
Json.Decode.maybe (Json.Decode.field "imports" Json.Decode.string)
|> Json.Decode.andThen
(\maybeEntry ->
case maybeEntry of
Nothing ->
Json.Decode.succeed []
Just "" ->
Json.Decode.succeed []
Just value ->
String.split " " value
|> List.map String.trim
|> Json.Decode.succeed
)
decodeBoolMeta : String -> Json.Decode.Decoder Bool
decodeBoolMeta prop =
Json.Decode.maybe (Json.Decode.field prop Json.Decode.string)
|> Json.Decode.andThen
(\value ->
case value of
Nothing ->
Json.Decode.succeed False
Just "true" ->
Json.Decode.succeed True
Just _ ->
Json.Decode.succeed False
)
script : String -> Html Never
script src =
node "citatsmle-script" [ attribute "src" src ] []
cdnScript : String -> String -> String -> Html Never
cdnScript src integrity crossorigin =
node "citatsmle-script"
[ attribute "src" src
, attribute "integrity" integrity
, attribute "crossorigin" crossorigin
]
[]
inlineScript : String -> Html Never
inlineScript js =
node "citatsmle-script" [] [ text js ]
stylesheet : String -> Html Never
stylesheet href =
node "link" [ attribute "href" href, attribute "rel" "stylesheet", attribute "type" "text/css" ] []
cdnStylesheet : String -> String -> String -> Html Never
cdnStylesheet href integrity crossorigin =
node "link"
[ attribute "href" href
, attribute "rel" "stylesheet"
, attribute "type" "text/css"
, attribute "integrity" integrity
, attribute "crossorigin" crossorigin
]
[]
htmlTemplate : String -> List (Html Never) -> Html Never
htmlTemplate title contentNodes =
node "html"
[ attribute "lang" "en"
, class "ui-layout no-js"
]
[ node "head"
[]
[ node "meta" [ attribute "charset" "utf-8" ] []
, node "meta"
[ attribute "http-equiv" "X-UA-Compatible"
, attribute "content" "IE=edge"
]
[]
, node "meta"
[ attribute "name" "author"
, attribute "content" "<NAME>"
]
[]
, node "meta"
[ attribute "name" "creator"
, attribute "content" "<NAME>"
]
[]
, node "meta"
[ attribute "name" "description"
, attribute "content" "A blog about life"
]
[]
, node "meta"
[ attribute "name" "viewport"
, attribute "content" "width=device-width, user-scalable=yes, initial-scale=1.0, minimum-scale=1.0"
]
[]
, node "title" [] [ text title ]
, stylesheet "/style/normalize-8.0.1.css"
, stylesheet "/style/styles.css?v1"
--, cdnStylesheet "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/styles/default.min.css" "<KEY>2<KEY> "anonymous"
, cdnStylesheet "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/styles/xcode.min.css" "<KEY> "anonymous"
--, cdnStylesheet "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/styles/github-gist.min.css" "<KEY> "anonymous"
, Styles.styles
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/highlight.min.js" "<KEY> "anonymous"
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/languages/bash.min.js" "<KEY> "anonymous"
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/languages/elm.min.js" "<KEY> "anonymous"
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/languages/javascript.min.js" "<KEY> "anonymous"
, inlineScript "hljs.initHighlightingOnLoad();"
, inlineScript """
var requirejs = {
baseUrl: \"/js\",
paths: {
greeshka: \"libs/greeshka-0.3.0\",
mathjax: \"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"
}
};
"""
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" "<KEY> "anonymous"
, stylesheet "https://fonts.googleapis.com/css?family=Roboto+Condensed|Inconsolata"
, inlineScript "document.querySelector('html').classList.remove('no-js');"
]
, node "body" [] contentNodes
]
layout : Json.Decode.Decoder (Content content) -> (Content content -> List (Html Never)) -> Layout
layout decoder view =
Browser.document
{ init = \contentJson -> ( contentJson, Cmd.none )
, view =
\contentJson ->
case Json.Decode.decodeValue decoder contentJson of
Err error ->
{ title = ""
, body = [ htmlTemplate "Error" [ Html.text <| Json.Decode.errorToString error ] ]
}
Ok content ->
let
amdImports =
content.imports
|> List.map (\it -> "\"" ++ it ++ "\"")
|> String.join ", "
in
{ title = ""
, body =
[ htmlTemplate content.siteTitle <|
List.concat
[ view content
, if List.isEmpty content.imports then
[ text "" ]
else
[ inlineScript <|
"require([" ++ amdImports ++ "]);"
]
]
]
}
, update = \msg contentJson -> ( contentJson, Cmd.none )
, subscriptions = \_ -> Sub.none
}
| true | module Elmstatic exposing
( Content
, Layout
, Page
, Post
, PostList
, decodePage
, decodePost
, decodePostList
, htmlTemplate
, inlineScript
, layout
, script
, stylesheet
)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Json.Decode
import Styles
type alias Post =
{ date : String
, imports : List String
, link : String
, markdown : String
, section : String
, siteTitle : String
, tags : List String
, title : String
}
type alias Page =
{ imports : List String
, markdown : String
, siteTitle : String
, title : String
}
type alias PostList =
{ imports : List String
, posts : List Post
, section : String
, siteTitle : String
, title : String
}
type alias Content a =
{ a | imports : List String, siteTitle : String, title : String }
type alias Layout =
Program Json.Decode.Value Json.Decode.Value Never
decodePage : Json.Decode.Decoder Page
decodePage =
Json.Decode.map4 Page
decodeImports
(Json.Decode.field "markdown" Json.Decode.string)
(Json.Decode.field "siteTitle" Json.Decode.string)
(Json.Decode.field "title" Json.Decode.string)
decodePost : Json.Decode.Decoder Post
decodePost =
Json.Decode.map8 Post
(Json.Decode.field "date" Json.Decode.string)
decodeImports
(Json.Decode.field "link" Json.Decode.string)
(Json.Decode.field "markdown" Json.Decode.string)
(Json.Decode.field "section" Json.Decode.string)
(Json.Decode.field "siteTitle" Json.Decode.string)
(Json.Decode.field "tags" <| Json.Decode.list Json.Decode.string)
(Json.Decode.field "title" Json.Decode.string)
decodePostList : Json.Decode.Decoder PostList
decodePostList =
Json.Decode.map5 PostList
decodeImports
(Json.Decode.field "posts" <| Json.Decode.list decodePost)
(Json.Decode.field "section" Json.Decode.string)
(Json.Decode.field "siteTitle" Json.Decode.string)
(Json.Decode.field "title" Json.Decode.string)
decodeImports : Json.Decode.Decoder (List String)
decodeImports =
Json.Decode.maybe (Json.Decode.field "imports" Json.Decode.string)
|> Json.Decode.andThen
(\maybeEntry ->
case maybeEntry of
Nothing ->
Json.Decode.succeed []
Just "" ->
Json.Decode.succeed []
Just value ->
String.split " " value
|> List.map String.trim
|> Json.Decode.succeed
)
decodeBoolMeta : String -> Json.Decode.Decoder Bool
decodeBoolMeta prop =
Json.Decode.maybe (Json.Decode.field prop Json.Decode.string)
|> Json.Decode.andThen
(\value ->
case value of
Nothing ->
Json.Decode.succeed False
Just "true" ->
Json.Decode.succeed True
Just _ ->
Json.Decode.succeed False
)
script : String -> Html Never
script src =
node "citatsmle-script" [ attribute "src" src ] []
cdnScript : String -> String -> String -> Html Never
cdnScript src integrity crossorigin =
node "citatsmle-script"
[ attribute "src" src
, attribute "integrity" integrity
, attribute "crossorigin" crossorigin
]
[]
inlineScript : String -> Html Never
inlineScript js =
node "citatsmle-script" [] [ text js ]
stylesheet : String -> Html Never
stylesheet href =
node "link" [ attribute "href" href, attribute "rel" "stylesheet", attribute "type" "text/css" ] []
cdnStylesheet : String -> String -> String -> Html Never
cdnStylesheet href integrity crossorigin =
node "link"
[ attribute "href" href
, attribute "rel" "stylesheet"
, attribute "type" "text/css"
, attribute "integrity" integrity
, attribute "crossorigin" crossorigin
]
[]
htmlTemplate : String -> List (Html Never) -> Html Never
htmlTemplate title contentNodes =
node "html"
[ attribute "lang" "en"
, class "ui-layout no-js"
]
[ node "head"
[]
[ node "meta" [ attribute "charset" "utf-8" ] []
, node "meta"
[ attribute "http-equiv" "X-UA-Compatible"
, attribute "content" "IE=edge"
]
[]
, node "meta"
[ attribute "name" "author"
, attribute "content" "PI:NAME:<NAME>END_PI"
]
[]
, node "meta"
[ attribute "name" "creator"
, attribute "content" "PI:NAME:<NAME>END_PI"
]
[]
, node "meta"
[ attribute "name" "description"
, attribute "content" "A blog about life"
]
[]
, node "meta"
[ attribute "name" "viewport"
, attribute "content" "width=device-width, user-scalable=yes, initial-scale=1.0, minimum-scale=1.0"
]
[]
, node "title" [] [ text title ]
, stylesheet "/style/normalize-8.0.1.css"
, stylesheet "/style/styles.css?v1"
--, cdnStylesheet "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/styles/default.min.css" "PI:KEY:<KEY>END_PI2PI:KEY:<KEY>END_PI "anonymous"
, cdnStylesheet "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/styles/xcode.min.css" "PI:KEY:<KEY>END_PI "anonymous"
--, cdnStylesheet "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/styles/github-gist.min.css" "PI:KEY:<KEY>END_PI "anonymous"
, Styles.styles
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/highlight.min.js" "PI:KEY:<KEY>END_PI "anonymous"
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/languages/bash.min.js" "PI:KEY:<KEY>END_PI "anonymous"
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/languages/elm.min.js" "PI:KEY:<KEY>END_PI "anonymous"
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/languages/javascript.min.js" "PI:KEY:<KEY>END_PI "anonymous"
, inlineScript "hljs.initHighlightingOnLoad();"
, inlineScript """
var requirejs = {
baseUrl: \"/js\",
paths: {
greeshka: \"libs/greeshka-0.3.0\",
mathjax: \"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"
}
};
"""
, cdnScript "https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" "PI:KEY:<KEY>END_PI "anonymous"
, stylesheet "https://fonts.googleapis.com/css?family=Roboto+Condensed|Inconsolata"
, inlineScript "document.querySelector('html').classList.remove('no-js');"
]
, node "body" [] contentNodes
]
layout : Json.Decode.Decoder (Content content) -> (Content content -> List (Html Never)) -> Layout
layout decoder view =
Browser.document
{ init = \contentJson -> ( contentJson, Cmd.none )
, view =
\contentJson ->
case Json.Decode.decodeValue decoder contentJson of
Err error ->
{ title = ""
, body = [ htmlTemplate "Error" [ Html.text <| Json.Decode.errorToString error ] ]
}
Ok content ->
let
amdImports =
content.imports
|> List.map (\it -> "\"" ++ it ++ "\"")
|> String.join ", "
in
{ title = ""
, body =
[ htmlTemplate content.siteTitle <|
List.concat
[ view content
, if List.isEmpty content.imports then
[ text "" ]
else
[ inlineScript <|
"require([" ++ amdImports ++ "]);"
]
]
]
}
, update = \msg contentJson -> ( contentJson, Cmd.none )
, subscriptions = \_ -> Sub.none
}
| elm |
[
{
"context": "Type\ndefault =\n {\n id = \"0\",\n name = \"Username\",\n query_url = \"http://127.0.0.1/\",\n ca",
"end": 3612,
"score": 0.5137959719,
"start": 3604,
"tag": "NAME",
"value": "Username"
}
] | src/shared/Struct/Player.elm | nsensfel/tacticians-extension | 0 | module Struct.Player exposing
(
Type,
get_id,
set_id,
get_query_url,
set_query_url,
get_username,
set_username,
get_campaigns,
get_invasions,
get_events,
set_battles,
has_active_battles,
decoder,
encode,
default
)
-- Elm -------------------------------------------------------------------------
import Json.Decode
import Json.Decode.Pipeline
import Json.Encode
-- Extension -------------------------------------------------------------------
import Struct.BattleSummary
--------------------------------------------------------------------------------
-- TYPES -----------------------------------------------------------------------
--------------------------------------------------------------------------------
type alias Type =
{
id : String,
name : String,
query_url : String,
campaigns : (List Struct.BattleSummary.Type),
invasions : (List Struct.BattleSummary.Type),
events : (List Struct.BattleSummary.Type)
}
--------------------------------------------------------------------------------
-- LOCAL -----------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- EXPORTED --------------------------------------------------------------------
--------------------------------------------------------------------------------
get_id : Type -> String
get_id t = t.id
set_id : String -> Type -> Type
set_id str t = {t | id = str}
get_username : Type -> String
get_username t = t.name
set_username : String -> Type -> Type
set_username str t = {t | name = str}
get_query_url : Type -> String
get_query_url t = t.query_url
set_query_url : String -> Type -> Type
set_query_url str t = {t | query_url = str}
get_campaigns : Type -> (List Struct.BattleSummary.Type)
get_campaigns t = t.campaigns
get_invasions : Type -> (List Struct.BattleSummary.Type)
get_invasions t = t.invasions
get_events : Type -> (List Struct.BattleSummary.Type)
get_events t = t.events
set_battles : (
(List Struct.BattleSummary.Type) ->
(List Struct.BattleSummary.Type) ->
(List Struct.BattleSummary.Type) ->
Type ->
Type
)
set_battles campaigns invasions events t =
{t |
campaigns =
(List.filter (Struct.BattleSummary.is_players_turn) campaigns),
invasions =
(List.filter (Struct.BattleSummary.is_players_turn) invasions),
events = (List.filter (Struct.BattleSummary.is_players_turn) events)
}
has_active_battles : Type -> Bool
has_active_battles t =
(
(
(List.length t.campaigns)
+ (List.length t.invasions)
+ (List.length t.events)
)
> 0
)
decoder : (Json.Decode.Decoder Type)
decoder =
(Json.Decode.Pipeline.decode
Type
|> (Json.Decode.Pipeline.required "id" Json.Decode.string)
|> (Json.Decode.Pipeline.required "name" Json.Decode.string)
|> (Json.Decode.Pipeline.required "query_url" Json.Decode.string)
|> (Json.Decode.Pipeline.hardcoded [])
|> (Json.Decode.Pipeline.hardcoded [])
|> (Json.Decode.Pipeline.hardcoded [])
)
encode : Type -> Json.Encode.Value
encode t =
(Json.Encode.object
[
("id", (Json.Encode.string t.id)),
("name", (Json.Encode.string t.name)),
("query_url", (Json.Encode.string t.query_url))
]
)
default : Type
default =
{
id = "0",
name = "Username",
query_url = "http://127.0.0.1/",
campaigns = [],
invasions = [],
events = []
}
| 11471 | module Struct.Player exposing
(
Type,
get_id,
set_id,
get_query_url,
set_query_url,
get_username,
set_username,
get_campaigns,
get_invasions,
get_events,
set_battles,
has_active_battles,
decoder,
encode,
default
)
-- Elm -------------------------------------------------------------------------
import Json.Decode
import Json.Decode.Pipeline
import Json.Encode
-- Extension -------------------------------------------------------------------
import Struct.BattleSummary
--------------------------------------------------------------------------------
-- TYPES -----------------------------------------------------------------------
--------------------------------------------------------------------------------
type alias Type =
{
id : String,
name : String,
query_url : String,
campaigns : (List Struct.BattleSummary.Type),
invasions : (List Struct.BattleSummary.Type),
events : (List Struct.BattleSummary.Type)
}
--------------------------------------------------------------------------------
-- LOCAL -----------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- EXPORTED --------------------------------------------------------------------
--------------------------------------------------------------------------------
get_id : Type -> String
get_id t = t.id
set_id : String -> Type -> Type
set_id str t = {t | id = str}
get_username : Type -> String
get_username t = t.name
set_username : String -> Type -> Type
set_username str t = {t | name = str}
get_query_url : Type -> String
get_query_url t = t.query_url
set_query_url : String -> Type -> Type
set_query_url str t = {t | query_url = str}
get_campaigns : Type -> (List Struct.BattleSummary.Type)
get_campaigns t = t.campaigns
get_invasions : Type -> (List Struct.BattleSummary.Type)
get_invasions t = t.invasions
get_events : Type -> (List Struct.BattleSummary.Type)
get_events t = t.events
set_battles : (
(List Struct.BattleSummary.Type) ->
(List Struct.BattleSummary.Type) ->
(List Struct.BattleSummary.Type) ->
Type ->
Type
)
set_battles campaigns invasions events t =
{t |
campaigns =
(List.filter (Struct.BattleSummary.is_players_turn) campaigns),
invasions =
(List.filter (Struct.BattleSummary.is_players_turn) invasions),
events = (List.filter (Struct.BattleSummary.is_players_turn) events)
}
has_active_battles : Type -> Bool
has_active_battles t =
(
(
(List.length t.campaigns)
+ (List.length t.invasions)
+ (List.length t.events)
)
> 0
)
decoder : (Json.Decode.Decoder Type)
decoder =
(Json.Decode.Pipeline.decode
Type
|> (Json.Decode.Pipeline.required "id" Json.Decode.string)
|> (Json.Decode.Pipeline.required "name" Json.Decode.string)
|> (Json.Decode.Pipeline.required "query_url" Json.Decode.string)
|> (Json.Decode.Pipeline.hardcoded [])
|> (Json.Decode.Pipeline.hardcoded [])
|> (Json.Decode.Pipeline.hardcoded [])
)
encode : Type -> Json.Encode.Value
encode t =
(Json.Encode.object
[
("id", (Json.Encode.string t.id)),
("name", (Json.Encode.string t.name)),
("query_url", (Json.Encode.string t.query_url))
]
)
default : Type
default =
{
id = "0",
name = "<NAME>",
query_url = "http://127.0.0.1/",
campaigns = [],
invasions = [],
events = []
}
| true | module Struct.Player exposing
(
Type,
get_id,
set_id,
get_query_url,
set_query_url,
get_username,
set_username,
get_campaigns,
get_invasions,
get_events,
set_battles,
has_active_battles,
decoder,
encode,
default
)
-- Elm -------------------------------------------------------------------------
import Json.Decode
import Json.Decode.Pipeline
import Json.Encode
-- Extension -------------------------------------------------------------------
import Struct.BattleSummary
--------------------------------------------------------------------------------
-- TYPES -----------------------------------------------------------------------
--------------------------------------------------------------------------------
type alias Type =
{
id : String,
name : String,
query_url : String,
campaigns : (List Struct.BattleSummary.Type),
invasions : (List Struct.BattleSummary.Type),
events : (List Struct.BattleSummary.Type)
}
--------------------------------------------------------------------------------
-- LOCAL -----------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- EXPORTED --------------------------------------------------------------------
--------------------------------------------------------------------------------
get_id : Type -> String
get_id t = t.id
set_id : String -> Type -> Type
set_id str t = {t | id = str}
get_username : Type -> String
get_username t = t.name
set_username : String -> Type -> Type
set_username str t = {t | name = str}
get_query_url : Type -> String
get_query_url t = t.query_url
set_query_url : String -> Type -> Type
set_query_url str t = {t | query_url = str}
get_campaigns : Type -> (List Struct.BattleSummary.Type)
get_campaigns t = t.campaigns
get_invasions : Type -> (List Struct.BattleSummary.Type)
get_invasions t = t.invasions
get_events : Type -> (List Struct.BattleSummary.Type)
get_events t = t.events
set_battles : (
(List Struct.BattleSummary.Type) ->
(List Struct.BattleSummary.Type) ->
(List Struct.BattleSummary.Type) ->
Type ->
Type
)
set_battles campaigns invasions events t =
{t |
campaigns =
(List.filter (Struct.BattleSummary.is_players_turn) campaigns),
invasions =
(List.filter (Struct.BattleSummary.is_players_turn) invasions),
events = (List.filter (Struct.BattleSummary.is_players_turn) events)
}
has_active_battles : Type -> Bool
has_active_battles t =
(
(
(List.length t.campaigns)
+ (List.length t.invasions)
+ (List.length t.events)
)
> 0
)
decoder : (Json.Decode.Decoder Type)
decoder =
(Json.Decode.Pipeline.decode
Type
|> (Json.Decode.Pipeline.required "id" Json.Decode.string)
|> (Json.Decode.Pipeline.required "name" Json.Decode.string)
|> (Json.Decode.Pipeline.required "query_url" Json.Decode.string)
|> (Json.Decode.Pipeline.hardcoded [])
|> (Json.Decode.Pipeline.hardcoded [])
|> (Json.Decode.Pipeline.hardcoded [])
)
encode : Type -> Json.Encode.Value
encode t =
(Json.Encode.object
[
("id", (Json.Encode.string t.id)),
("name", (Json.Encode.string t.name)),
("query_url", (Json.Encode.string t.query_url))
]
)
default : Type
default =
{
id = "0",
name = "PI:NAME:<NAME>END_PI",
query_url = "http://127.0.0.1/",
campaigns = [],
invasions = [],
events = []
}
| elm |
[
{
"context": " from a tuple.\n\n first (3, 4) == 3\n first (\"john\", \"doe\") == \"john\"\n\n-}\nfirst : ( a1, a2 ) -> a1\nf",
"end": 301,
"score": 0.9770154953,
"start": 297,
"tag": "NAME",
"value": "john"
},
{
"context": "tuple.\n\n first (3, 4) == 3\n first (\"john\", \"doe\") == \"john\"\n\n-}\nfirst : ( a1, a2 ) -> a1\nfirst =\n",
"end": 308,
"score": 0.9182914495,
"start": 305,
"tag": "NAME",
"value": "doe"
},
{
"context": " first (3, 4) == 3\n first (\"john\", \"doe\") == \"john\"\n\n-}\nfirst : ( a1, a2 ) -> a1\nfirst =\n fst\n\n\n{",
"end": 319,
"score": 0.9827225804,
"start": 315,
"tag": "NAME",
"value": "john"
},
{
"context": "rom a tuple.\n\n second (3, 4) == 4\n second (\"john\", \"doe\") == \"doe\"\n\n-}\nsecond : ( a1, a2 ) -> a2\ns",
"end": 452,
"score": 0.9765284061,
"start": 448,
"tag": "NAME",
"value": "john"
},
{
"context": "ple.\n\n second (3, 4) == 4\n second (\"john\", \"doe\") == \"doe\"\n\n-}\nsecond : ( a1, a2 ) -> a2\nsecond =",
"end": 459,
"score": 0.9772950411,
"start": 456,
"tag": "NAME",
"value": "doe"
},
{
"context": "second (3, 4) == 4\n second (\"john\", \"doe\") == \"doe\"\n\n-}\nsecond : ( a1, a2 ) -> a2\nsecond =\n snd\n\n",
"end": 469,
"score": 0.8820415139,
"start": 466,
"tag": "NAME",
"value": "doe"
}
] | src/Tuple018.elm | Gizra/elm-compat-017 | 1 | module Tuple018
exposing
( first
, second
, mapFirst
, mapSecond
)
{-| The `Tuple` module was new in Elm 0.18. So, here it is!
@docs first, second, mapFirst, mapSecond
-}
{-| Extract the first value from a tuple.
first (3, 4) == 3
first ("john", "doe") == "john"
-}
first : ( a1, a2 ) -> a1
first =
fst
{-| Extract the second value from a tuple.
second (3, 4) == 4
second ("john", "doe") == "doe"
-}
second : ( a1, a2 ) -> a2
second =
snd
{-| Transform the first value in a tuple.
import String
mapFirst String.reverse ("stressed", 16) == ("desserts", 16)
mapFirst String.length ("stressed", 16) == (8, 16)
-}
mapFirst : (a -> b) -> ( a, a2 ) -> ( b, a2 )
mapFirst func ( x, y ) =
( func x, y )
{-| Transform the second value in a tuple.
import String
mapSecond sqrt ("stressed", 16) == ("stressed", 4)
mapSecond (\x -> x + 1) ("stressed", 16) == ("stressed", 17)
-}
mapSecond : (a -> b) -> ( a1, a ) -> ( a1, b )
mapSecond func ( x, y ) =
( x, func y )
| 48922 | module Tuple018
exposing
( first
, second
, mapFirst
, mapSecond
)
{-| The `Tuple` module was new in Elm 0.18. So, here it is!
@docs first, second, mapFirst, mapSecond
-}
{-| Extract the first value from a tuple.
first (3, 4) == 3
first ("<NAME>", "<NAME>") == "<NAME>"
-}
first : ( a1, a2 ) -> a1
first =
fst
{-| Extract the second value from a tuple.
second (3, 4) == 4
second ("<NAME>", "<NAME>") == "<NAME>"
-}
second : ( a1, a2 ) -> a2
second =
snd
{-| Transform the first value in a tuple.
import String
mapFirst String.reverse ("stressed", 16) == ("desserts", 16)
mapFirst String.length ("stressed", 16) == (8, 16)
-}
mapFirst : (a -> b) -> ( a, a2 ) -> ( b, a2 )
mapFirst func ( x, y ) =
( func x, y )
{-| Transform the second value in a tuple.
import String
mapSecond sqrt ("stressed", 16) == ("stressed", 4)
mapSecond (\x -> x + 1) ("stressed", 16) == ("stressed", 17)
-}
mapSecond : (a -> b) -> ( a1, a ) -> ( a1, b )
mapSecond func ( x, y ) =
( x, func y )
| true | module Tuple018
exposing
( first
, second
, mapFirst
, mapSecond
)
{-| The `Tuple` module was new in Elm 0.18. So, here it is!
@docs first, second, mapFirst, mapSecond
-}
{-| Extract the first value from a tuple.
first (3, 4) == 3
first ("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI") == "PI:NAME:<NAME>END_PI"
-}
first : ( a1, a2 ) -> a1
first =
fst
{-| Extract the second value from a tuple.
second (3, 4) == 4
second ("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI") == "PI:NAME:<NAME>END_PI"
-}
second : ( a1, a2 ) -> a2
second =
snd
{-| Transform the first value in a tuple.
import String
mapFirst String.reverse ("stressed", 16) == ("desserts", 16)
mapFirst String.length ("stressed", 16) == (8, 16)
-}
mapFirst : (a -> b) -> ( a, a2 ) -> ( b, a2 )
mapFirst func ( x, y ) =
( func x, y )
{-| Transform the second value in a tuple.
import String
mapSecond sqrt ("stressed", 16) == ("stressed", 4)
mapSecond (\x -> x + 1) ("stressed", 16) == ("stressed", 17)
-}
mapSecond : (a -> b) -> ( a1, a ) -> ( a1, b )
mapSecond func ( x, y ) =
( x, func y )
| elm |
[
{
"context": "nprint :bar\\nend\\n\"\n { name = \"foo\"\n , requiredArguments = [ \"bar",
"end": 3372,
"score": 0.5650268793,
"start": 3369,
"tag": "NAME",
"value": "foo"
}
] | tests/Test/Parser.elm | cruessler/elm-logo | 2 | module Test.Parser exposing (..)
import Compiler.Ast as Ast
import Compiler.Parser as Parser exposing (defaultState)
import Compiler.Parser.Value as Value
import Expect exposing (Expectation)
import Parser.Advanced as Parser exposing (DeadEnd)
import Test exposing (..)
import Vm.Command as C
import Vm.Type as Type
value : Test
value =
let
integer =
Parser.run Value.value "1234"
word =
Parser.run Value.value "\"word"
wordInVerticalBars =
Parser.run Value.value """"|make "a [|"""
list =
Parser.run Value.value "[ 1234 word ]"
nestedList =
Parser.run Value.value "[ 1234 [ 1234 ] ]"
emptyList =
Parser.run Value.value "[ ]"
fail =
Parser.run Value.value " [ 1 2"
in
describe "parse simple values" <|
[ test "parse integer" <|
\_ -> Expect.equal integer (Ok <| Ast.Value <| Type.Int 1234)
, test "parse word" <|
\_ -> Expect.equal word (Ok <| Ast.Value <| Type.Word "word")
, test "parse word in vertical bars" <|
\_ -> Expect.equal wordInVerticalBars (Ok <| Ast.Value <| Type.Word "make \"a [")
, test "parse list" <|
\_ ->
Expect.equal list
(Ok <| Ast.Value <| Type.List [ Type.Int 1234, Type.Word "word" ])
, test "parse nested list" <|
\_ ->
Expect.equal nestedList
(Ok <|
Ast.Value <|
Type.List [ Type.Int 1234, Type.List [ Type.Int 1234 ] ]
)
, test "parse empty list" <|
\_ ->
Expect.equal emptyList
(Ok <| Ast.Value <| Type.List [])
, test "fail when given string cannot be parsed" <|
\_ -> Expect.err fail
]
parsesFunction : String -> Ast.Function -> Expectation
parsesFunction source function =
let
result =
Parser.run (Parser.functionDefinition defaultState) source
in
Expect.equal result (Ok function)
functionDefinition : Test
functionDefinition =
describe "define a function" <|
[ test "with mandatory arguments and no body" <|
\_ ->
parsesFunction "to foo :bar :baz\nend\n"
{ name = "foo"
, requiredArguments = [ "bar", "baz" ]
, optionalArguments = []
, body = []
}
, test "with mandatory argument and body" <|
\_ ->
parsesFunction "to foo :bar\nprint :bar\nprint :baz\nend\n"
{ name = "foo"
, requiredArguments = [ "bar" ]
, optionalArguments = []
, body =
[ Ast.Command1
{ name = "print", f = C.print }
(Ast.Variable "bar")
, Ast.Command1
{ name = "print", f = C.print }
(Ast.Variable "baz")
]
}
, test "with optional arguments" <|
\_ ->
parsesFunction "to foo :bar [:baz \"baz]\nprint :bar\nend\n"
{ name = "foo"
, requiredArguments = [ "bar" ]
, optionalArguments = [ ( "baz", Ast.Value <| Type.Word <| "baz" ) ]
, body =
[ Ast.Command1
{ name = "print", f = C.print }
(Ast.Variable "bar")
]
}
, test "without arguments" <|
\_ ->
parsesFunction "to foo\nend\n"
{ name = "foo"
, requiredArguments = []
, optionalArguments = []
, body = []
}
]
parsesArithmeticExpression : String -> Test
parsesArithmeticExpression expression =
let
match : Result (List (DeadEnd context problem)) Ast.Node -> Expectation
match result =
case result of
Ok _ ->
Expect.pass
Err _ ->
Expect.fail <| "could not parse expression \"" ++ expression ++ "\""
in
test expression <|
\_ ->
match
(Parser.run
(Parser.arithmeticExpression defaultState)
expression
)
arithmetic : Test
arithmetic =
describe "arithmetic" <|
[ parsesArithmeticExpression "5 * 5"
, parsesArithmeticExpression "5*5"
, parsesArithmeticExpression "(5 * 5)"
, parsesArithmeticExpression "(5*5)"
, parsesArithmeticExpression "((5 * 5))"
, parsesArithmeticExpression "5"
, parsesArithmeticExpression "4 - 4"
, parsesArithmeticExpression "4 - 4 + 4 - 4"
, parsesArithmeticExpression "5 / 10"
, parsesArithmeticExpression "5 / 10 + 10"
, parsesArithmeticExpression "10 + 10 * 10"
, parsesArithmeticExpression "10 + 10 + 10"
, parsesArithmeticExpression "((10 + 10) + 10)"
, parsesArithmeticExpression "(10 + 10 + 10)"
, parsesArithmeticExpression "10 * 10 * 10"
, parsesArithmeticExpression "(10 * 10 * 10)"
, parsesArithmeticExpression "((10 * 10) * 10)"
, parsesArithmeticExpression ":depth - 1"
, parsesArithmeticExpression ":depth / 1"
, parsesArithmeticExpression "(:depth - 1)"
, parsesArithmeticExpression "(sum 1 1)"
, parsesArithmeticExpression "(? 1)"
, parsesArithmeticExpression "(minus :size/2) + 5"
, parsesArithmeticExpression "(minus :size+2) + 5"
, parsesArithmeticExpression "(:zr + :az*:az)"
, parsesArithmeticExpression "(:az*:az - :bz*:bz)"
, parsesArithmeticExpression "(:zr + :az*:az - :bz*:bz)"
, parsesArithmeticExpression "(sum :zr :zi)"
, parsesArithmeticExpression "(sum :zr (1))"
, parsesArithmeticExpression "(sum :zr (sum 1 1))"
, parsesArithmeticExpression "(sum :zr (1 + 1))"
, parsesArithmeticExpression "(sum :zr (:count + 1))"
, parsesArithmeticExpression "(sum (:count + 1) (:zi + 2*:bar))"
]
parsesBooleanExpression : String -> Test
parsesBooleanExpression expression =
let
match : Result (List (DeadEnd context problem)) Ast.Node -> Expectation
match result =
case result of
Ok _ ->
Expect.pass
Err _ ->
Expect.fail <| "could not parse expression \"" ++ expression ++ "\""
in
test expression <|
\_ ->
match
(Parser.run
(Parser.booleanExpression defaultState)
expression
)
booleanAlgebra : Test
booleanAlgebra =
describe "boolean algebra" <|
[ parsesBooleanExpression "1 + 1 = 1"
, parsesBooleanExpression "1 <> 1"
, parsesBooleanExpression "2 * (3 + 1) = (4 + 4) * 7"
]
| 16377 | module Test.Parser exposing (..)
import Compiler.Ast as Ast
import Compiler.Parser as Parser exposing (defaultState)
import Compiler.Parser.Value as Value
import Expect exposing (Expectation)
import Parser.Advanced as Parser exposing (DeadEnd)
import Test exposing (..)
import Vm.Command as C
import Vm.Type as Type
value : Test
value =
let
integer =
Parser.run Value.value "1234"
word =
Parser.run Value.value "\"word"
wordInVerticalBars =
Parser.run Value.value """"|make "a [|"""
list =
Parser.run Value.value "[ 1234 word ]"
nestedList =
Parser.run Value.value "[ 1234 [ 1234 ] ]"
emptyList =
Parser.run Value.value "[ ]"
fail =
Parser.run Value.value " [ 1 2"
in
describe "parse simple values" <|
[ test "parse integer" <|
\_ -> Expect.equal integer (Ok <| Ast.Value <| Type.Int 1234)
, test "parse word" <|
\_ -> Expect.equal word (Ok <| Ast.Value <| Type.Word "word")
, test "parse word in vertical bars" <|
\_ -> Expect.equal wordInVerticalBars (Ok <| Ast.Value <| Type.Word "make \"a [")
, test "parse list" <|
\_ ->
Expect.equal list
(Ok <| Ast.Value <| Type.List [ Type.Int 1234, Type.Word "word" ])
, test "parse nested list" <|
\_ ->
Expect.equal nestedList
(Ok <|
Ast.Value <|
Type.List [ Type.Int 1234, Type.List [ Type.Int 1234 ] ]
)
, test "parse empty list" <|
\_ ->
Expect.equal emptyList
(Ok <| Ast.Value <| Type.List [])
, test "fail when given string cannot be parsed" <|
\_ -> Expect.err fail
]
parsesFunction : String -> Ast.Function -> Expectation
parsesFunction source function =
let
result =
Parser.run (Parser.functionDefinition defaultState) source
in
Expect.equal result (Ok function)
functionDefinition : Test
functionDefinition =
describe "define a function" <|
[ test "with mandatory arguments and no body" <|
\_ ->
parsesFunction "to foo :bar :baz\nend\n"
{ name = "foo"
, requiredArguments = [ "bar", "baz" ]
, optionalArguments = []
, body = []
}
, test "with mandatory argument and body" <|
\_ ->
parsesFunction "to foo :bar\nprint :bar\nprint :baz\nend\n"
{ name = "foo"
, requiredArguments = [ "bar" ]
, optionalArguments = []
, body =
[ Ast.Command1
{ name = "print", f = C.print }
(Ast.Variable "bar")
, Ast.Command1
{ name = "print", f = C.print }
(Ast.Variable "baz")
]
}
, test "with optional arguments" <|
\_ ->
parsesFunction "to foo :bar [:baz \"baz]\nprint :bar\nend\n"
{ name = "<NAME>"
, requiredArguments = [ "bar" ]
, optionalArguments = [ ( "baz", Ast.Value <| Type.Word <| "baz" ) ]
, body =
[ Ast.Command1
{ name = "print", f = C.print }
(Ast.Variable "bar")
]
}
, test "without arguments" <|
\_ ->
parsesFunction "to foo\nend\n"
{ name = "foo"
, requiredArguments = []
, optionalArguments = []
, body = []
}
]
parsesArithmeticExpression : String -> Test
parsesArithmeticExpression expression =
let
match : Result (List (DeadEnd context problem)) Ast.Node -> Expectation
match result =
case result of
Ok _ ->
Expect.pass
Err _ ->
Expect.fail <| "could not parse expression \"" ++ expression ++ "\""
in
test expression <|
\_ ->
match
(Parser.run
(Parser.arithmeticExpression defaultState)
expression
)
arithmetic : Test
arithmetic =
describe "arithmetic" <|
[ parsesArithmeticExpression "5 * 5"
, parsesArithmeticExpression "5*5"
, parsesArithmeticExpression "(5 * 5)"
, parsesArithmeticExpression "(5*5)"
, parsesArithmeticExpression "((5 * 5))"
, parsesArithmeticExpression "5"
, parsesArithmeticExpression "4 - 4"
, parsesArithmeticExpression "4 - 4 + 4 - 4"
, parsesArithmeticExpression "5 / 10"
, parsesArithmeticExpression "5 / 10 + 10"
, parsesArithmeticExpression "10 + 10 * 10"
, parsesArithmeticExpression "10 + 10 + 10"
, parsesArithmeticExpression "((10 + 10) + 10)"
, parsesArithmeticExpression "(10 + 10 + 10)"
, parsesArithmeticExpression "10 * 10 * 10"
, parsesArithmeticExpression "(10 * 10 * 10)"
, parsesArithmeticExpression "((10 * 10) * 10)"
, parsesArithmeticExpression ":depth - 1"
, parsesArithmeticExpression ":depth / 1"
, parsesArithmeticExpression "(:depth - 1)"
, parsesArithmeticExpression "(sum 1 1)"
, parsesArithmeticExpression "(? 1)"
, parsesArithmeticExpression "(minus :size/2) + 5"
, parsesArithmeticExpression "(minus :size+2) + 5"
, parsesArithmeticExpression "(:zr + :az*:az)"
, parsesArithmeticExpression "(:az*:az - :bz*:bz)"
, parsesArithmeticExpression "(:zr + :az*:az - :bz*:bz)"
, parsesArithmeticExpression "(sum :zr :zi)"
, parsesArithmeticExpression "(sum :zr (1))"
, parsesArithmeticExpression "(sum :zr (sum 1 1))"
, parsesArithmeticExpression "(sum :zr (1 + 1))"
, parsesArithmeticExpression "(sum :zr (:count + 1))"
, parsesArithmeticExpression "(sum (:count + 1) (:zi + 2*:bar))"
]
parsesBooleanExpression : String -> Test
parsesBooleanExpression expression =
let
match : Result (List (DeadEnd context problem)) Ast.Node -> Expectation
match result =
case result of
Ok _ ->
Expect.pass
Err _ ->
Expect.fail <| "could not parse expression \"" ++ expression ++ "\""
in
test expression <|
\_ ->
match
(Parser.run
(Parser.booleanExpression defaultState)
expression
)
booleanAlgebra : Test
booleanAlgebra =
describe "boolean algebra" <|
[ parsesBooleanExpression "1 + 1 = 1"
, parsesBooleanExpression "1 <> 1"
, parsesBooleanExpression "2 * (3 + 1) = (4 + 4) * 7"
]
| true | module Test.Parser exposing (..)
import Compiler.Ast as Ast
import Compiler.Parser as Parser exposing (defaultState)
import Compiler.Parser.Value as Value
import Expect exposing (Expectation)
import Parser.Advanced as Parser exposing (DeadEnd)
import Test exposing (..)
import Vm.Command as C
import Vm.Type as Type
value : Test
value =
let
integer =
Parser.run Value.value "1234"
word =
Parser.run Value.value "\"word"
wordInVerticalBars =
Parser.run Value.value """"|make "a [|"""
list =
Parser.run Value.value "[ 1234 word ]"
nestedList =
Parser.run Value.value "[ 1234 [ 1234 ] ]"
emptyList =
Parser.run Value.value "[ ]"
fail =
Parser.run Value.value " [ 1 2"
in
describe "parse simple values" <|
[ test "parse integer" <|
\_ -> Expect.equal integer (Ok <| Ast.Value <| Type.Int 1234)
, test "parse word" <|
\_ -> Expect.equal word (Ok <| Ast.Value <| Type.Word "word")
, test "parse word in vertical bars" <|
\_ -> Expect.equal wordInVerticalBars (Ok <| Ast.Value <| Type.Word "make \"a [")
, test "parse list" <|
\_ ->
Expect.equal list
(Ok <| Ast.Value <| Type.List [ Type.Int 1234, Type.Word "word" ])
, test "parse nested list" <|
\_ ->
Expect.equal nestedList
(Ok <|
Ast.Value <|
Type.List [ Type.Int 1234, Type.List [ Type.Int 1234 ] ]
)
, test "parse empty list" <|
\_ ->
Expect.equal emptyList
(Ok <| Ast.Value <| Type.List [])
, test "fail when given string cannot be parsed" <|
\_ -> Expect.err fail
]
parsesFunction : String -> Ast.Function -> Expectation
parsesFunction source function =
let
result =
Parser.run (Parser.functionDefinition defaultState) source
in
Expect.equal result (Ok function)
functionDefinition : Test
functionDefinition =
describe "define a function" <|
[ test "with mandatory arguments and no body" <|
\_ ->
parsesFunction "to foo :bar :baz\nend\n"
{ name = "foo"
, requiredArguments = [ "bar", "baz" ]
, optionalArguments = []
, body = []
}
, test "with mandatory argument and body" <|
\_ ->
parsesFunction "to foo :bar\nprint :bar\nprint :baz\nend\n"
{ name = "foo"
, requiredArguments = [ "bar" ]
, optionalArguments = []
, body =
[ Ast.Command1
{ name = "print", f = C.print }
(Ast.Variable "bar")
, Ast.Command1
{ name = "print", f = C.print }
(Ast.Variable "baz")
]
}
, test "with optional arguments" <|
\_ ->
parsesFunction "to foo :bar [:baz \"baz]\nprint :bar\nend\n"
{ name = "PI:NAME:<NAME>END_PI"
, requiredArguments = [ "bar" ]
, optionalArguments = [ ( "baz", Ast.Value <| Type.Word <| "baz" ) ]
, body =
[ Ast.Command1
{ name = "print", f = C.print }
(Ast.Variable "bar")
]
}
, test "without arguments" <|
\_ ->
parsesFunction "to foo\nend\n"
{ name = "foo"
, requiredArguments = []
, optionalArguments = []
, body = []
}
]
parsesArithmeticExpression : String -> Test
parsesArithmeticExpression expression =
let
match : Result (List (DeadEnd context problem)) Ast.Node -> Expectation
match result =
case result of
Ok _ ->
Expect.pass
Err _ ->
Expect.fail <| "could not parse expression \"" ++ expression ++ "\""
in
test expression <|
\_ ->
match
(Parser.run
(Parser.arithmeticExpression defaultState)
expression
)
arithmetic : Test
arithmetic =
describe "arithmetic" <|
[ parsesArithmeticExpression "5 * 5"
, parsesArithmeticExpression "5*5"
, parsesArithmeticExpression "(5 * 5)"
, parsesArithmeticExpression "(5*5)"
, parsesArithmeticExpression "((5 * 5))"
, parsesArithmeticExpression "5"
, parsesArithmeticExpression "4 - 4"
, parsesArithmeticExpression "4 - 4 + 4 - 4"
, parsesArithmeticExpression "5 / 10"
, parsesArithmeticExpression "5 / 10 + 10"
, parsesArithmeticExpression "10 + 10 * 10"
, parsesArithmeticExpression "10 + 10 + 10"
, parsesArithmeticExpression "((10 + 10) + 10)"
, parsesArithmeticExpression "(10 + 10 + 10)"
, parsesArithmeticExpression "10 * 10 * 10"
, parsesArithmeticExpression "(10 * 10 * 10)"
, parsesArithmeticExpression "((10 * 10) * 10)"
, parsesArithmeticExpression ":depth - 1"
, parsesArithmeticExpression ":depth / 1"
, parsesArithmeticExpression "(:depth - 1)"
, parsesArithmeticExpression "(sum 1 1)"
, parsesArithmeticExpression "(? 1)"
, parsesArithmeticExpression "(minus :size/2) + 5"
, parsesArithmeticExpression "(minus :size+2) + 5"
, parsesArithmeticExpression "(:zr + :az*:az)"
, parsesArithmeticExpression "(:az*:az - :bz*:bz)"
, parsesArithmeticExpression "(:zr + :az*:az - :bz*:bz)"
, parsesArithmeticExpression "(sum :zr :zi)"
, parsesArithmeticExpression "(sum :zr (1))"
, parsesArithmeticExpression "(sum :zr (sum 1 1))"
, parsesArithmeticExpression "(sum :zr (1 + 1))"
, parsesArithmeticExpression "(sum :zr (:count + 1))"
, parsesArithmeticExpression "(sum (:count + 1) (:zi + 2*:bar))"
]
parsesBooleanExpression : String -> Test
parsesBooleanExpression expression =
let
match : Result (List (DeadEnd context problem)) Ast.Node -> Expectation
match result =
case result of
Ok _ ->
Expect.pass
Err _ ->
Expect.fail <| "could not parse expression \"" ++ expression ++ "\""
in
test expression <|
\_ ->
match
(Parser.run
(Parser.booleanExpression defaultState)
expression
)
booleanAlgebra : Test
booleanAlgebra =
describe "boolean algebra" <|
[ parsesBooleanExpression "1 + 1 = 1"
, parsesBooleanExpression "1 <> 1"
, parsesBooleanExpression "2 * (3 + 1) = (4 + 4) * 7"
]
| elm |
[
{
"context": "ord transformer\n\n@docs trimmer\n\nCopyright (c) 2016 Robin Luiten\n\n-}\n\nimport Regex\n exposing\n ( Regex\n ",
"end": 424,
"score": 0.9998582602,
"start": 412,
"tag": "NAME",
"value": "Robin Luiten"
}
] | src/TokenProcessors.elm | eniac314/elm-text-search | 43 | module TokenProcessors exposing
( tokenizer
, tokenizerList
, tokenizerWith
, tokenizerWithRegex
, tokenizerWithRegexList
, trimmer
, tokenizerWithList
)
{-| TokenProcessors for strings.
## Create a tokenizer
@docs tokenizer
@docs tokenizerList
@docs tokenizerWith
@docs tokenizerWithRegex
@docs tokenizerWithRegexList
## Word transformer
@docs trimmer
Copyright (c) 2016 Robin Luiten
-}
import Regex
exposing
( Regex
-- , HowMany(..)
, fromString
, replace
, split
)
import String exposing (toLower, trim)
forceRegex : String -> Regex
forceRegex =
Maybe.withDefault Regex.never << fromString
defaultSeparator : Regex
defaultSeparator =
forceRegex "[\\s\\-]+"
{-| Tokenize a String.
Will not return any empty string tokens.
By default this splits on whitespace and hyphens.
-}
tokenizer : String -> List String
tokenizer =
tokenizerWithRegex defaultSeparator
{-| Tokenize a List String.
Will not return any empty string tokens.
By default this splits on whitespace and hyphens.
-}
tokenizerList : List String -> List String
tokenizerList =
tokenizerWithRegexList defaultSeparator
{-| Tokenize a string.
Will not return any empty string tokens.
Supply your own regex for splitting the string.
-}
tokenizerWithRegex : Regex -> String -> List String
tokenizerWithRegex seperatorRegex data =
let
splitter =
split seperatorRegex << toLower << trim
in
List.filter
(\token -> String.length token > 0)
(splitter data)
tokenizerWithRegexList : Regex -> List String -> List String
tokenizerWithRegexList seperatorRegex listData =
let
splitter =
split seperatorRegex << toLower << trim
-- List.foldr (\set agg -> Set.intersect set agg) h tail
-- tokens : List String
tokens =
List.foldr
(\str agg ->
List.append agg (splitter str)
)
[]
listData
in
List.filter
(\token -> String.length token > 0)
tokens
{-| Tokenize a String.
Will not return any empty string tokens.
Supply your own String which is turned into a regex for splitting the string.
-}
tokenizerWith : String -> String -> List String
tokenizerWith seperatorPattern =
tokenizerWithRegex (forceRegex seperatorPattern)
{-| Tokenize a List String.
Will not return any empty string tokens.
Supply your own String which is turned into a regex for splitting the string.
-}
tokenizerWithList : String -> List String -> List String
tokenizerWithList seperatorPattern =
tokenizerWithRegexList (forceRegex seperatorPattern)
trimmerRegex =
forceRegex "^\\W+|\\W+$"
{-| Remove non word characters from start and end of tokens
-}
trimmer : String -> String
trimmer =
replace trimmerRegex (\_ -> "")
| 14824 | module TokenProcessors exposing
( tokenizer
, tokenizerList
, tokenizerWith
, tokenizerWithRegex
, tokenizerWithRegexList
, trimmer
, tokenizerWithList
)
{-| TokenProcessors for strings.
## Create a tokenizer
@docs tokenizer
@docs tokenizerList
@docs tokenizerWith
@docs tokenizerWithRegex
@docs tokenizerWithRegexList
## Word transformer
@docs trimmer
Copyright (c) 2016 <NAME>
-}
import Regex
exposing
( Regex
-- , HowMany(..)
, fromString
, replace
, split
)
import String exposing (toLower, trim)
forceRegex : String -> Regex
forceRegex =
Maybe.withDefault Regex.never << fromString
defaultSeparator : Regex
defaultSeparator =
forceRegex "[\\s\\-]+"
{-| Tokenize a String.
Will not return any empty string tokens.
By default this splits on whitespace and hyphens.
-}
tokenizer : String -> List String
tokenizer =
tokenizerWithRegex defaultSeparator
{-| Tokenize a List String.
Will not return any empty string tokens.
By default this splits on whitespace and hyphens.
-}
tokenizerList : List String -> List String
tokenizerList =
tokenizerWithRegexList defaultSeparator
{-| Tokenize a string.
Will not return any empty string tokens.
Supply your own regex for splitting the string.
-}
tokenizerWithRegex : Regex -> String -> List String
tokenizerWithRegex seperatorRegex data =
let
splitter =
split seperatorRegex << toLower << trim
in
List.filter
(\token -> String.length token > 0)
(splitter data)
tokenizerWithRegexList : Regex -> List String -> List String
tokenizerWithRegexList seperatorRegex listData =
let
splitter =
split seperatorRegex << toLower << trim
-- List.foldr (\set agg -> Set.intersect set agg) h tail
-- tokens : List String
tokens =
List.foldr
(\str agg ->
List.append agg (splitter str)
)
[]
listData
in
List.filter
(\token -> String.length token > 0)
tokens
{-| Tokenize a String.
Will not return any empty string tokens.
Supply your own String which is turned into a regex for splitting the string.
-}
tokenizerWith : String -> String -> List String
tokenizerWith seperatorPattern =
tokenizerWithRegex (forceRegex seperatorPattern)
{-| Tokenize a List String.
Will not return any empty string tokens.
Supply your own String which is turned into a regex for splitting the string.
-}
tokenizerWithList : String -> List String -> List String
tokenizerWithList seperatorPattern =
tokenizerWithRegexList (forceRegex seperatorPattern)
trimmerRegex =
forceRegex "^\\W+|\\W+$"
{-| Remove non word characters from start and end of tokens
-}
trimmer : String -> String
trimmer =
replace trimmerRegex (\_ -> "")
| true | module TokenProcessors exposing
( tokenizer
, tokenizerList
, tokenizerWith
, tokenizerWithRegex
, tokenizerWithRegexList
, trimmer
, tokenizerWithList
)
{-| TokenProcessors for strings.
## Create a tokenizer
@docs tokenizer
@docs tokenizerList
@docs tokenizerWith
@docs tokenizerWithRegex
@docs tokenizerWithRegexList
## Word transformer
@docs trimmer
Copyright (c) 2016 PI:NAME:<NAME>END_PI
-}
import Regex
exposing
( Regex
-- , HowMany(..)
, fromString
, replace
, split
)
import String exposing (toLower, trim)
forceRegex : String -> Regex
forceRegex =
Maybe.withDefault Regex.never << fromString
defaultSeparator : Regex
defaultSeparator =
forceRegex "[\\s\\-]+"
{-| Tokenize a String.
Will not return any empty string tokens.
By default this splits on whitespace and hyphens.
-}
tokenizer : String -> List String
tokenizer =
tokenizerWithRegex defaultSeparator
{-| Tokenize a List String.
Will not return any empty string tokens.
By default this splits on whitespace and hyphens.
-}
tokenizerList : List String -> List String
tokenizerList =
tokenizerWithRegexList defaultSeparator
{-| Tokenize a string.
Will not return any empty string tokens.
Supply your own regex for splitting the string.
-}
tokenizerWithRegex : Regex -> String -> List String
tokenizerWithRegex seperatorRegex data =
let
splitter =
split seperatorRegex << toLower << trim
in
List.filter
(\token -> String.length token > 0)
(splitter data)
tokenizerWithRegexList : Regex -> List String -> List String
tokenizerWithRegexList seperatorRegex listData =
let
splitter =
split seperatorRegex << toLower << trim
-- List.foldr (\set agg -> Set.intersect set agg) h tail
-- tokens : List String
tokens =
List.foldr
(\str agg ->
List.append agg (splitter str)
)
[]
listData
in
List.filter
(\token -> String.length token > 0)
tokens
{-| Tokenize a String.
Will not return any empty string tokens.
Supply your own String which is turned into a regex for splitting the string.
-}
tokenizerWith : String -> String -> List String
tokenizerWith seperatorPattern =
tokenizerWithRegex (forceRegex seperatorPattern)
{-| Tokenize a List String.
Will not return any empty string tokens.
Supply your own String which is turned into a regex for splitting the string.
-}
tokenizerWithList : String -> List String -> List String
tokenizerWithList seperatorPattern =
tokenizerWithRegexList (forceRegex seperatorPattern)
trimmerRegex =
forceRegex "^\\W+|\\W+$"
{-| Remove non word characters from start and end of tokens
-}
trimmer : String -> String
trimmer =
replace trimmerRegex (\_ -> "")
| elm |
[
{
"context": " , codeUsage = \"\"\"\nlet model =\n { labelText = \"Hello world\"\n , dropDownValue = \"Some value you dete",
"end": 2363,
"score": 0.5735661983,
"start": 2358,
"tag": "NAME",
"value": "Hello"
}
] | docs/src/Dropdown.elm | InsideSalesOfficial/isdc-elm-ui | 5 | module Dropdown exposing (..)
import Css exposing (..)
import Dict as Dict exposing (Dict)
import DocsLayout exposing (..)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (..)
import Isdc.Ui.Color.Css as Color
import Isdc.Ui.Dropdown exposing (..)
import Isdc.Ui.Theme as Theme
import Maybe as Maybe
type Msg
= Open
| Cancel
| Save
| Toggle String
| Search String
type alias Model =
{ optionsChecked : Dict String Bool
, open : Bool
, search : String
}
dropdownModel : Model
dropdownModel =
{ optionsChecked = Dict.empty
, open = False
, search = ""
}
update : Msg -> Model -> Model
update msg model =
case msg of
Open ->
{ model | open = model.open == False }
Cancel ->
{ model | open = False }
Save ->
{ model | open = False }
Toggle value ->
let
updated =
Dict.update
value
(\val -> Maybe.withDefault False val |> not |> Just)
model.optionsChecked
in
{ model | optionsChecked = updated }
Search search ->
{ model | search = search }
dropdownProps : Model -> DropDownProperties Msg
dropdownProps model =
{ labelText = "Hello world"
, dropDownValue = "Some value you determine"
, options =
[ { label = "Foo"
, value = "foo"
, checked = Maybe.withDefault False <| Dict.get "foo" model.optionsChecked
}
, { label = "Bar"
, value = "bar"
, checked = Maybe.withDefault False <| Dict.get "bar" model.optionsChecked
}
]
, open = model.open
, openMessage = Open
, toggleMessage = Toggle
, searchMessage = Search
, saveMessage = Save
, cancelMessage = Cancel
, search = model.search
, theme = Theme.Dark
}
view model =
let
props =
dropdownProps model
in
story
{ title = "Isdc.Ui.Dropdown exposing (..)"
, chapters =
[ { heading = "multiCheckDropdown : DropDownProperties msg -> Html msg"
, example = div [ css [ marginBottom (px 200) ] ] [ multiCheckDropdown props ]
, codeUsage = """
let model =
{ 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 = ""
, Theme.Dark
}
in multiCheckDropdown model"""
}
, { heading = "multiCheckDropdown : DropDownProperties msg -> Html msg"
, example = div [ css [ backgroundColor Color.primary01, padding (px 24), Css.height (px 200), marginBottom (px 200) ] ] [ multiCheckDropdown { props | theme = Theme.New } ]
, codeUsage = """
let model =
{ 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 = ""
, Theme.New
}
in multiCheckDropdown model"""
}
]
}
| 19603 | module Dropdown exposing (..)
import Css exposing (..)
import Dict as Dict exposing (Dict)
import DocsLayout exposing (..)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (..)
import Isdc.Ui.Color.Css as Color
import Isdc.Ui.Dropdown exposing (..)
import Isdc.Ui.Theme as Theme
import Maybe as Maybe
type Msg
= Open
| Cancel
| Save
| Toggle String
| Search String
type alias Model =
{ optionsChecked : Dict String Bool
, open : Bool
, search : String
}
dropdownModel : Model
dropdownModel =
{ optionsChecked = Dict.empty
, open = False
, search = ""
}
update : Msg -> Model -> Model
update msg model =
case msg of
Open ->
{ model | open = model.open == False }
Cancel ->
{ model | open = False }
Save ->
{ model | open = False }
Toggle value ->
let
updated =
Dict.update
value
(\val -> Maybe.withDefault False val |> not |> Just)
model.optionsChecked
in
{ model | optionsChecked = updated }
Search search ->
{ model | search = search }
dropdownProps : Model -> DropDownProperties Msg
dropdownProps model =
{ labelText = "Hello world"
, dropDownValue = "Some value you determine"
, options =
[ { label = "Foo"
, value = "foo"
, checked = Maybe.withDefault False <| Dict.get "foo" model.optionsChecked
}
, { label = "Bar"
, value = "bar"
, checked = Maybe.withDefault False <| Dict.get "bar" model.optionsChecked
}
]
, open = model.open
, openMessage = Open
, toggleMessage = Toggle
, searchMessage = Search
, saveMessage = Save
, cancelMessage = Cancel
, search = model.search
, theme = Theme.Dark
}
view model =
let
props =
dropdownProps model
in
story
{ title = "Isdc.Ui.Dropdown exposing (..)"
, chapters =
[ { heading = "multiCheckDropdown : DropDownProperties msg -> Html msg"
, example = div [ css [ marginBottom (px 200) ] ] [ multiCheckDropdown props ]
, codeUsage = """
let model =
{ labelText = "<NAME> 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 = ""
, Theme.Dark
}
in multiCheckDropdown model"""
}
, { heading = "multiCheckDropdown : DropDownProperties msg -> Html msg"
, example = div [ css [ backgroundColor Color.primary01, padding (px 24), Css.height (px 200), marginBottom (px 200) ] ] [ multiCheckDropdown { props | theme = Theme.New } ]
, codeUsage = """
let model =
{ 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 = ""
, Theme.New
}
in multiCheckDropdown model"""
}
]
}
| true | module Dropdown exposing (..)
import Css exposing (..)
import Dict as Dict exposing (Dict)
import DocsLayout exposing (..)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (..)
import Isdc.Ui.Color.Css as Color
import Isdc.Ui.Dropdown exposing (..)
import Isdc.Ui.Theme as Theme
import Maybe as Maybe
type Msg
= Open
| Cancel
| Save
| Toggle String
| Search String
type alias Model =
{ optionsChecked : Dict String Bool
, open : Bool
, search : String
}
dropdownModel : Model
dropdownModel =
{ optionsChecked = Dict.empty
, open = False
, search = ""
}
update : Msg -> Model -> Model
update msg model =
case msg of
Open ->
{ model | open = model.open == False }
Cancel ->
{ model | open = False }
Save ->
{ model | open = False }
Toggle value ->
let
updated =
Dict.update
value
(\val -> Maybe.withDefault False val |> not |> Just)
model.optionsChecked
in
{ model | optionsChecked = updated }
Search search ->
{ model | search = search }
dropdownProps : Model -> DropDownProperties Msg
dropdownProps model =
{ labelText = "Hello world"
, dropDownValue = "Some value you determine"
, options =
[ { label = "Foo"
, value = "foo"
, checked = Maybe.withDefault False <| Dict.get "foo" model.optionsChecked
}
, { label = "Bar"
, value = "bar"
, checked = Maybe.withDefault False <| Dict.get "bar" model.optionsChecked
}
]
, open = model.open
, openMessage = Open
, toggleMessage = Toggle
, searchMessage = Search
, saveMessage = Save
, cancelMessage = Cancel
, search = model.search
, theme = Theme.Dark
}
view model =
let
props =
dropdownProps model
in
story
{ title = "Isdc.Ui.Dropdown exposing (..)"
, chapters =
[ { heading = "multiCheckDropdown : DropDownProperties msg -> Html msg"
, example = div [ css [ marginBottom (px 200) ] ] [ multiCheckDropdown props ]
, codeUsage = """
let model =
{ labelText = "PI:NAME:<NAME>END_PI 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 = ""
, Theme.Dark
}
in multiCheckDropdown model"""
}
, { heading = "multiCheckDropdown : DropDownProperties msg -> Html msg"
, example = div [ css [ backgroundColor Color.primary01, padding (px 24), Css.height (px 200), marginBottom (px 200) ] ] [ multiCheckDropdown { props | theme = Theme.New } ]
, codeUsage = """
let model =
{ 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 = ""
, Theme.New
}
in multiCheckDropdown model"""
}
]
}
| elm |
[
{
"context": " , if (not <| data.user.password == data.user.retryPassword)\n && ((not <| isEmpty data.user.retr",
"end": 2815,
"score": 0.751739502,
"start": 2797,
"tag": "PASSWORD",
"value": "user.retryPassword"
}
] | src/User/View/Register.elm | hel-repo/hel-face | 3 | module User.View.Register exposing (..)
import Html exposing (..)
import Html.Attributes exposing (class, href)
import String exposing (isEmpty)
import Material.Button as Button
import Material.Card as Card
import Material.Elevation as Elevation
import Material.Grid exposing (..)
import Material.Options as Options exposing (cs)
import Material.Spinner as Loading
import Material.Textfield as Textfield
import Material.Typography as Typo
import Base.Messages exposing (Msg(..))
import Base.Network.Url as Url
import User.Localization as L
import User.Messages as UMsg
import User.Models exposing (UserData)
register : UserData -> Html Msg
register data =
Card.view
[ Elevation.e2 ]
[ Card.title [ Card.border ] [ Card.head [] [ text (L.get data.session.lang L.registration) ] ]
, Card.text [ ]
[ div [ ]
[ Textfield.render Mdl [10] data.mdl
[ Textfield.label (L.get data.session.lang L.nickname)
, Textfield.floatingLabel
, Textfield.text_
, Textfield.value data.user.nickname
, Options.onInput <| UMsg.InputNickname >> UserMsg
, if data.validate && isEmpty data.user.nickname then
Textfield.error (L.get data.session.lang L.cantBeEmpty)
else
Options.nop
] []
]
, div [ ]
[ Textfield.render Mdl [11] data.mdl
[ Textfield.label (L.get data.session.lang L.email)
, Textfield.floatingLabel
, Textfield.text_
, Textfield.value data.user.email
, Options.onInput <| UMsg.InputEmail >> UserMsg
, if data.validate && isEmpty data.user.email then
Textfield.error (L.get data.session.lang L.cantBeEmpty)
else
Options.nop
] []
]
, div [ ]
[ Textfield.render Mdl [12] data.mdl
[ Textfield.label (L.get data.session.lang L.password)
, Textfield.floatingLabel
, Textfield.password
, Textfield.value data.user.password
, Options.onInput <| UMsg.InputPassword >> UserMsg
, if data.validate && isEmpty data.user.password then
Textfield.error (L.get data.session.lang L.cantBeEmpty)
else
Options.nop
] []
]
, div [ ]
[ Textfield.render Mdl [13] data.mdl
[ Textfield.label (L.get data.session.lang L.retryPassword)
, Textfield.floatingLabel
, Textfield.password
, Textfield.value data.user.retryPassword
, Options.onInput <| UMsg.InputRetryPassword >> UserMsg
, if (not <| data.user.password == data.user.retryPassword)
&& ((not <| isEmpty data.user.retryPassword) || data.validate) then
Textfield.error <| (L.get data.session.lang L.doesNotMatch)
else
Options.nop
] []
]
, div [ class "profile-panel" ]
[ Button.render Mdl [14] data.mdl
[ Button.raised
, Button.ripple
, Options.onClick <| UserMsg (UMsg.Register data.user)
]
[ text (L.get data.session.lang L.register)]
, Options.styled p
[ Typo.subhead, cs "auth-alter" ]
[ text (L.get data.session.lang L.or) ]
, Options.styled p
[ Typo.subhead, cs "auth-alter" ]
[ a [ href Url.auth ] [ text (L.get data.session.lang L.login) ] ]
]
]
]
view : UserData -> Html Msg
view data =
if data.loading then
Loading.spinner
[ Loading.active True
, cs "spinner"
]
else
div
[ class "page auth-card" ]
[ grid [ ]
[ cell [ size All 3, size Tablet 0 ] [ ]
, cell [ size All 6, size Tablet 8 ] [ register data ]
, cell [ size All 3, size Tablet 0 ] [ ]
]
]
| 32398 | module User.View.Register exposing (..)
import Html exposing (..)
import Html.Attributes exposing (class, href)
import String exposing (isEmpty)
import Material.Button as Button
import Material.Card as Card
import Material.Elevation as Elevation
import Material.Grid exposing (..)
import Material.Options as Options exposing (cs)
import Material.Spinner as Loading
import Material.Textfield as Textfield
import Material.Typography as Typo
import Base.Messages exposing (Msg(..))
import Base.Network.Url as Url
import User.Localization as L
import User.Messages as UMsg
import User.Models exposing (UserData)
register : UserData -> Html Msg
register data =
Card.view
[ Elevation.e2 ]
[ Card.title [ Card.border ] [ Card.head [] [ text (L.get data.session.lang L.registration) ] ]
, Card.text [ ]
[ div [ ]
[ Textfield.render Mdl [10] data.mdl
[ Textfield.label (L.get data.session.lang L.nickname)
, Textfield.floatingLabel
, Textfield.text_
, Textfield.value data.user.nickname
, Options.onInput <| UMsg.InputNickname >> UserMsg
, if data.validate && isEmpty data.user.nickname then
Textfield.error (L.get data.session.lang L.cantBeEmpty)
else
Options.nop
] []
]
, div [ ]
[ Textfield.render Mdl [11] data.mdl
[ Textfield.label (L.get data.session.lang L.email)
, Textfield.floatingLabel
, Textfield.text_
, Textfield.value data.user.email
, Options.onInput <| UMsg.InputEmail >> UserMsg
, if data.validate && isEmpty data.user.email then
Textfield.error (L.get data.session.lang L.cantBeEmpty)
else
Options.nop
] []
]
, div [ ]
[ Textfield.render Mdl [12] data.mdl
[ Textfield.label (L.get data.session.lang L.password)
, Textfield.floatingLabel
, Textfield.password
, Textfield.value data.user.password
, Options.onInput <| UMsg.InputPassword >> UserMsg
, if data.validate && isEmpty data.user.password then
Textfield.error (L.get data.session.lang L.cantBeEmpty)
else
Options.nop
] []
]
, div [ ]
[ Textfield.render Mdl [13] data.mdl
[ Textfield.label (L.get data.session.lang L.retryPassword)
, Textfield.floatingLabel
, Textfield.password
, Textfield.value data.user.retryPassword
, Options.onInput <| UMsg.InputRetryPassword >> UserMsg
, if (not <| data.user.password == data.<PASSWORD>)
&& ((not <| isEmpty data.user.retryPassword) || data.validate) then
Textfield.error <| (L.get data.session.lang L.doesNotMatch)
else
Options.nop
] []
]
, div [ class "profile-panel" ]
[ Button.render Mdl [14] data.mdl
[ Button.raised
, Button.ripple
, Options.onClick <| UserMsg (UMsg.Register data.user)
]
[ text (L.get data.session.lang L.register)]
, Options.styled p
[ Typo.subhead, cs "auth-alter" ]
[ text (L.get data.session.lang L.or) ]
, Options.styled p
[ Typo.subhead, cs "auth-alter" ]
[ a [ href Url.auth ] [ text (L.get data.session.lang L.login) ] ]
]
]
]
view : UserData -> Html Msg
view data =
if data.loading then
Loading.spinner
[ Loading.active True
, cs "spinner"
]
else
div
[ class "page auth-card" ]
[ grid [ ]
[ cell [ size All 3, size Tablet 0 ] [ ]
, cell [ size All 6, size Tablet 8 ] [ register data ]
, cell [ size All 3, size Tablet 0 ] [ ]
]
]
| true | module User.View.Register exposing (..)
import Html exposing (..)
import Html.Attributes exposing (class, href)
import String exposing (isEmpty)
import Material.Button as Button
import Material.Card as Card
import Material.Elevation as Elevation
import Material.Grid exposing (..)
import Material.Options as Options exposing (cs)
import Material.Spinner as Loading
import Material.Textfield as Textfield
import Material.Typography as Typo
import Base.Messages exposing (Msg(..))
import Base.Network.Url as Url
import User.Localization as L
import User.Messages as UMsg
import User.Models exposing (UserData)
register : UserData -> Html Msg
register data =
Card.view
[ Elevation.e2 ]
[ Card.title [ Card.border ] [ Card.head [] [ text (L.get data.session.lang L.registration) ] ]
, Card.text [ ]
[ div [ ]
[ Textfield.render Mdl [10] data.mdl
[ Textfield.label (L.get data.session.lang L.nickname)
, Textfield.floatingLabel
, Textfield.text_
, Textfield.value data.user.nickname
, Options.onInput <| UMsg.InputNickname >> UserMsg
, if data.validate && isEmpty data.user.nickname then
Textfield.error (L.get data.session.lang L.cantBeEmpty)
else
Options.nop
] []
]
, div [ ]
[ Textfield.render Mdl [11] data.mdl
[ Textfield.label (L.get data.session.lang L.email)
, Textfield.floatingLabel
, Textfield.text_
, Textfield.value data.user.email
, Options.onInput <| UMsg.InputEmail >> UserMsg
, if data.validate && isEmpty data.user.email then
Textfield.error (L.get data.session.lang L.cantBeEmpty)
else
Options.nop
] []
]
, div [ ]
[ Textfield.render Mdl [12] data.mdl
[ Textfield.label (L.get data.session.lang L.password)
, Textfield.floatingLabel
, Textfield.password
, Textfield.value data.user.password
, Options.onInput <| UMsg.InputPassword >> UserMsg
, if data.validate && isEmpty data.user.password then
Textfield.error (L.get data.session.lang L.cantBeEmpty)
else
Options.nop
] []
]
, div [ ]
[ Textfield.render Mdl [13] data.mdl
[ Textfield.label (L.get data.session.lang L.retryPassword)
, Textfield.floatingLabel
, Textfield.password
, Textfield.value data.user.retryPassword
, Options.onInput <| UMsg.InputRetryPassword >> UserMsg
, if (not <| data.user.password == data.PI:PASSWORD:<PASSWORD>END_PI)
&& ((not <| isEmpty data.user.retryPassword) || data.validate) then
Textfield.error <| (L.get data.session.lang L.doesNotMatch)
else
Options.nop
] []
]
, div [ class "profile-panel" ]
[ Button.render Mdl [14] data.mdl
[ Button.raised
, Button.ripple
, Options.onClick <| UserMsg (UMsg.Register data.user)
]
[ text (L.get data.session.lang L.register)]
, Options.styled p
[ Typo.subhead, cs "auth-alter" ]
[ text (L.get data.session.lang L.or) ]
, Options.styled p
[ Typo.subhead, cs "auth-alter" ]
[ a [ href Url.auth ] [ text (L.get data.session.lang L.login) ] ]
]
]
]
view : UserData -> Html Msg
view data =
if data.loading then
Loading.spinner
[ Loading.active True
, cs "spinner"
]
else
div
[ class "page auth-card" ]
[ grid [ ]
[ cell [ size All 3, size Tablet 0 ] [ ]
, cell [ size All 6, size Tablet 8 ] [ register data ]
, cell [ size All 3, size Tablet 0 ] [ ]
]
]
| elm |
[
{
"context": " { authUrl = authUrl\n , token = authToken\n , projectsAvailable = RemoteData",
"end": 73234,
"score": 0.8749072552,
"start": 73230,
"tag": "PASSWORD",
"value": "auth"
}
] | src/State/State.elm | c-mart/exosphere | 0 | module State.State exposing (update)
import AppUrl.Builder
import AppUrl.Parser
import Browser.Navigation
import Helpers.ExoSetupStatus
import Helpers.GetterSetters as GetterSetters
import Helpers.Helpers as Helpers
import Helpers.RemoteDataPlusPlus as RDPP
import Helpers.ServerResourceUsage
import Helpers.Url as UrlHelpers
import Http
import LocalStorage.LocalStorage as LocalStorage
import Maybe
import OpenStack.ServerPassword as OSServerPassword
import OpenStack.ServerTags as OSServerTags
import OpenStack.ServerVolumes as OSSvrVols
import OpenStack.Types as OSTypes
import OpenStack.Volumes as OSVolumes
import Orchestration.Orchestration as Orchestration
import Ports
import RemoteData
import Rest.ApiModelHelpers as ApiModelHelpers
import Rest.Glance
import Rest.Keystone
import Rest.Neutron
import Rest.Nova
import State.Auth
import State.Error
import State.ViewState as ViewStateHelpers
import Style.Toast
import Style.Widgets.NumericTextInput.NumericTextInput
import Task
import Time
import Toasty
import Types.Defaults as Defaults
import Types.Error as Error exposing (ErrorContext, ErrorLevel(..))
import Types.Guacamole as GuacTypes
import Types.HelperTypes as HelperTypes
import Types.ServerResourceUsage
import Types.Types
exposing
( Endpoints
, ExoSetupStatus(..)
, HttpRequestMethod(..)
, LoginView(..)
, Model
, Msg(..)
, NewServerNetworkOptions(..)
, NonProjectViewConstructor(..)
, OpenstackLoginFormEntryType(..)
, OpenstackLoginViewParams
, Project
, ProjectSecret(..)
, ProjectSpecificMsgConstructor(..)
, ProjectViewConstructor(..)
, Server
, ServerFromExoProps
, ServerOrigin(..)
, ServerSpecificMsgConstructor(..)
, TickInterval
, UnscopedProviderProject
, ViewState(..)
, currentExoServerVersion
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
{- We want to `setStorage` on every update. This function adds the setStorage
command for every step of the update function.
-}
let
( newModel, cmds ) =
updateUnderlying msg model
orchestrationTimeCmd =
-- Each trip through the runtime, we get the time and feed it to orchestration module
case msg of
DoOrchestration _ ->
Cmd.none
Tick _ _ ->
Cmd.none
_ ->
Task.perform (\posix -> DoOrchestration posix) Time.now
in
( newModel
, Cmd.batch
[ Ports.setStorage (LocalStorage.generateStoredState newModel)
, orchestrationTimeCmd
, cmds
]
)
updateUnderlying : Msg -> Model -> ( Model, Cmd Msg )
updateUnderlying msg model =
case msg of
ToastyMsg subMsg ->
Toasty.update Style.Toast.toastConfig ToastyMsg subMsg model
MsgChangeWindowSize x y ->
( { model | windowSize = { width = x, height = y } }, Cmd.none )
Tick interval time ->
processTick model interval time
DoOrchestration posixTime ->
Orchestration.orchModel model posixTime
SetNonProjectView nonProjectViewConstructor ->
ViewStateHelpers.setNonProjectView nonProjectViewConstructor model
HandleApiErrorWithBody errorContext error ->
State.Error.processSynchronousApiError model errorContext error
RequestUnscopedToken openstackLoginUnscoped ->
let
creds =
-- Ensure auth URL includes port number and version
{ openstackLoginUnscoped
| authUrl =
State.Auth.authUrlWithPortAndVersion openstackLoginUnscoped.authUrl
}
in
( model, Rest.Keystone.requestUnscopedAuthToken model.cloudCorsProxyUrl creds )
JetstreamLogin jetstreamCreds ->
let
openstackCredsList =
State.Auth.jetstreamToOpenstackCreds jetstreamCreds
cmds =
List.map
(\creds -> Rest.Keystone.requestUnscopedAuthToken model.cloudCorsProxyUrl creds)
openstackCredsList
in
( model, Cmd.batch cmds )
ReceiveScopedAuthToken ( metadata, response ) ->
case Rest.Keystone.decodeScopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
model
(ErrorContext
"decode scoped auth token"
ErrorCrit
Nothing
)
error
Ok authToken ->
case Helpers.serviceCatalogToEndpoints authToken.catalog of
Err e ->
State.Error.processStringError
model
(ErrorContext
"Decode project endpoints"
ErrorCrit
(Just "Please check with your cloud administrator or the Exosphere developers.")
)
e
Ok endpoints ->
let
projectId =
authToken.project.uuid
in
-- If we don't have a project with same name + authUrl then create one, if we do then update its OSTypes.AuthToken
-- This code ensures we don't end up with duplicate projects on the same provider in our model.
case
GetterSetters.projectLookup model <| projectId
of
Nothing ->
createProject model authToken endpoints
Just project ->
-- If we don't have an application credential for this project yet, then get one
let
appCredCmd =
case project.secret of
ApplicationCredential _ ->
Cmd.none
_ ->
Rest.Keystone.requestAppCredential
model.clientUuid
model.clientCurrentTime
project
( newModel, updateTokenCmd ) =
State.Auth.projectUpdateAuthToken model project authToken
in
( newModel, Cmd.batch [ appCredCmd, updateTokenCmd ] )
ReceiveUnscopedAuthToken keystoneUrl ( metadata, response ) ->
case Rest.Keystone.decodeUnscopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
model
(ErrorContext
"decode scoped auth token"
ErrorCrit
Nothing
)
error
Ok authToken ->
case
GetterSetters.providerLookup model keystoneUrl
of
Just unscopedProvider ->
-- We already have an unscoped provider in the model with the same auth URL, update its token
State.Auth.unscopedProviderUpdateAuthToken
model
unscopedProvider
authToken
Nothing ->
-- We don't have an unscoped provider with the same auth URL, create it
createUnscopedProvider model authToken keystoneUrl
ReceiveUnscopedProjects keystoneUrl unscopedProjects ->
case
GetterSetters.providerLookup model keystoneUrl
of
Just provider ->
let
newProvider =
{ provider | projectsAvailable = RemoteData.Success unscopedProjects }
newModel =
GetterSetters.modelUpdateUnscopedProvider model newProvider
in
-- If we are not already on a SelectProjects view, then go there
case newModel.viewState of
NonProjectView (SelectProjects _ _) ->
( newModel, Cmd.none )
_ ->
ViewStateHelpers.modelUpdateViewState
(NonProjectView <|
SelectProjects newProvider.authUrl []
)
newModel
Nothing ->
-- Provider not found, may have been removed, nothing to do
( model, Cmd.none )
RequestProjectLoginFromProvider keystoneUrl desiredProjects ->
case GetterSetters.providerLookup model keystoneUrl of
Just provider ->
let
buildLoginRequest : UnscopedProviderProject -> Cmd Msg
buildLoginRequest project =
Rest.Keystone.requestScopedAuthToken
model.cloudCorsProxyUrl
<|
OSTypes.TokenCreds
keystoneUrl
provider.token
project.project.uuid
loginRequests =
List.map buildLoginRequest desiredProjects
|> Cmd.batch
-- Remove unscoped provider from model now that we have selected projects from it
newUnscopedProviders =
List.filter
(\p -> p.authUrl /= keystoneUrl)
model.unscopedProviders
-- If we still have at least one unscoped provider in the model then ask the user to choose projects from it
newViewStateFunc =
case List.head newUnscopedProviders of
Just unscopedProvider ->
ViewStateHelpers.setNonProjectView
(SelectProjects unscopedProvider.authUrl [])
Nothing ->
-- If we have at least one project then show it, else show the login page
case List.head model.projects of
Just project ->
ViewStateHelpers.setProjectView
project
<|
AllResources Defaults.allResourcesListViewParams
Nothing ->
ViewStateHelpers.setNonProjectView
LoginPicker
modelUpdatedUnscopedProviders =
{ model | unscopedProviders = newUnscopedProviders }
in
( modelUpdatedUnscopedProviders, loginRequests )
|> Helpers.pipelineCmd newViewStateFunc
Nothing ->
State.Error.processStringError
model
(ErrorContext
("look for OpenStack provider with Keystone URL " ++ keystoneUrl)
ErrorCrit
Nothing
)
"Provider could not found in Exosphere's list of Providers."
ProjectMsg projectIdentifier innerMsg ->
case GetterSetters.projectLookup model projectIdentifier of
Nothing ->
-- Project not found, may have been removed, nothing to do
( model, Cmd.none )
Just project ->
processProjectSpecificMsg model project innerMsg
{- Form inputs -}
SubmitOpenRc openstackCreds openRc ->
let
newCreds =
State.Auth.processOpenRc openstackCreds openRc
newViewState =
NonProjectView <| Login <| LoginOpenstack <| OpenstackLoginViewParams newCreds openRc LoginViewCredsEntry
in
ViewStateHelpers.modelUpdateViewState newViewState model
OpenNewWindow url ->
( model, Ports.openNewWindow url )
NavigateToUrl url ->
( model, Browser.Navigation.load url )
UrlChange url ->
-- This handles presses of the browser back/forward button
let
exoJustSetThisUrl =
-- If this is a URL that Exosphere just set via StateHelpers.updateViewState, then ignore it
UrlHelpers.urlPathQueryMatches url model.prevUrl
in
if exoJustSetThisUrl then
( model, Cmd.none )
else
case
AppUrl.Parser.urlToViewState
model.urlPathPrefix
(ViewStateHelpers.defaultViewState model)
url
of
Just newViewState ->
( { model
| viewState = newViewState
, prevUrl = AppUrl.Builder.viewStateToUrl model.urlPathPrefix newViewState
}
, Cmd.none
)
Nothing ->
( { model
| viewState = NonProjectView PageNotFound
}
, Cmd.none
)
SetStyle styleMode ->
let
oldStyle =
model.style
newStyle =
{ oldStyle | styleMode = styleMode }
in
( { model | style = newStyle }, Cmd.none )
NoOp ->
( model, Cmd.none )
processTick : Model -> TickInterval -> Time.Posix -> ( Model, Cmd Msg )
processTick model interval time =
let
serverVolsNeedFrequentPoll : Project -> Server -> Bool
serverVolsNeedFrequentPoll project server =
GetterSetters.getVolsAttachedToServer project server
|> List.any volNeedsFrequentPoll
volNeedsFrequentPoll volume =
not <|
List.member
volume.status
[ OSTypes.Available
, OSTypes.Maintenance
, OSTypes.InUse
, OSTypes.Error
, OSTypes.ErrorDeleting
, OSTypes.ErrorBackingUp
, OSTypes.ErrorRestoring
, OSTypes.ErrorExtending
]
viewIndependentCmd =
if interval == 5 then
Task.perform (\posix -> DoOrchestration posix) Time.now
else
Cmd.none
( viewDependentModel, viewDependentCmd ) =
{- TODO move some of this to Orchestration? -}
case model.viewState of
NonProjectView _ ->
( model, Cmd.none )
ProjectView projectName _ projectViewState ->
case GetterSetters.projectLookup model projectName of
Nothing ->
{- Should this throw an error? -}
( model, Cmd.none )
Just project ->
let
pollVolumes : ( Model, Cmd Msg )
pollVolumes =
( model
, case interval of
5 ->
if List.any volNeedsFrequentPoll (RemoteData.withDefault [] project.volumes) then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
in
case projectViewState of
AllResources _ ->
pollVolumes
ServerDetail serverUuid _ ->
let
volCmd =
OSVolumes.requestVolumes project
in
case interval of
5 ->
case GetterSetters.serverLookup project serverUuid of
Just server ->
( model
, if serverVolsNeedFrequentPoll project server then
volCmd
else
Cmd.none
)
Nothing ->
( model, Cmd.none )
300 ->
( model, volCmd )
_ ->
( model, Cmd.none )
ListProjectVolumes _ ->
pollVolumes
VolumeDetail volumeUuid _ ->
( model
, case interval of
5 ->
case GetterSetters.volumeLookup project volumeUuid of
Nothing ->
Cmd.none
Just volume ->
if volNeedsFrequentPoll volume then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
_ ->
( model, Cmd.none )
in
( { viewDependentModel | clientCurrentTime = time }
, Cmd.batch
[ viewDependentCmd
, viewIndependentCmd
]
)
processProjectSpecificMsg : Model -> Project -> ProjectSpecificMsgConstructor -> ( Model, Cmd Msg )
processProjectSpecificMsg model project msg =
case msg of
SetProjectView projectViewConstructor ->
ViewStateHelpers.setProjectView project projectViewConstructor model
PrepareCredentialedRequest requestProto posixTime ->
let
-- Add proxy URL
requestNeedingToken =
requestProto model.cloudCorsProxyUrl
currentTimeMillis =
posixTime |> Time.posixToMillis
tokenExpireTimeMillis =
project.auth.expiresAt |> Time.posixToMillis
tokenExpired =
-- Token expiring within 5 minutes
tokenExpireTimeMillis < currentTimeMillis + 300000
in
if not tokenExpired then
-- Token still valid, fire the request with current token
( model, requestNeedingToken project.auth.tokenValue )
else
-- Token is expired (or nearly expired) so we add request to list of pending requests and refresh that token
let
newPQRs =
requestNeedingToken :: project.pendingCredentialedRequests
newProject =
{ project | pendingCredentialedRequests = newPQRs }
newModel =
GetterSetters.modelUpdateProject model newProject
cmdResult =
State.Auth.requestAuthToken newModel newProject
in
case cmdResult of
Err e ->
let
errorContext =
ErrorContext
("Refresh authentication token for project " ++ project.auth.project.name)
ErrorCrit
(Just "Please remove this project from Exosphere and add it again.")
in
State.Error.processStringError newModel errorContext e
Ok cmd ->
( newModel, cmd )
ToggleCreatePopup ->
case model.viewState of
ProjectView projectId viewParams viewConstructor ->
let
newViewState =
ProjectView
projectId
{ viewParams
| createPopup = not viewParams.createPopup
}
viewConstructor
in
ViewStateHelpers.modelUpdateViewState newViewState model
_ ->
( model, Cmd.none )
RemoveProject ->
let
newProjects =
List.filter (\p -> p.auth.project.uuid /= project.auth.project.uuid) model.projects
newViewState =
case model.viewState of
NonProjectView _ ->
-- If we are not in a project-specific view then stay there
model.viewState
ProjectView _ _ _ ->
-- If we have any projects switch to the first one in the list, otherwise switch to login view
case List.head newProjects of
Just p ->
ProjectView
p.auth.project.uuid
Defaults.projectViewParams
<|
AllResources
Defaults.allResourcesListViewParams
Nothing ->
NonProjectView <| LoginPicker
modelUpdatedProjects =
{ model | projects = newProjects }
in
ViewStateHelpers.modelUpdateViewState newViewState modelUpdatedProjects
ServerMsg serverUuid serverMsgConstructor ->
case GetterSetters.serverLookup project serverUuid of
Nothing ->
let
errorContext =
ErrorContext
"receive results of API call for a specific server"
ErrorDebug
Nothing
in
State.Error.processStringError
model
errorContext
(String.join " "
[ "Instance"
, serverUuid
, "does not exist in the model, it may have been deleted."
]
)
Just server ->
processServerSpecificMsg model project server serverMsgConstructor
RequestServers ->
ApiModelHelpers.requestServers project.auth.project.uuid model
RequestCreateServer viewParams networkUuid ->
let
createServerRequest =
{ name = viewParams.serverName
, count = viewParams.count
, imageUuid = viewParams.imageUuid
, flavorUuid = viewParams.flavorUuid
, volBackedSizeGb =
viewParams.volSizeTextInput
|> Maybe.andThen Style.Widgets.NumericTextInput.NumericTextInput.toMaybe
, networkUuid = networkUuid
, keypairName = viewParams.keypairName
, userData =
Helpers.renderUserDataTemplate
project
viewParams.userDataTemplate
viewParams.keypairName
(viewParams.deployGuacamole |> Maybe.withDefault False)
viewParams.deployDesktopEnvironment
viewParams.installOperatingSystemUpdates
model.instanceConfigMgtRepoUrl
model.instanceConfigMgtRepoCheckout
, metadata =
Helpers.newServerMetadata
currentExoServerVersion
model.clientUuid
(viewParams.deployGuacamole |> Maybe.withDefault False)
viewParams.deployDesktopEnvironment
project.auth.user.name
viewParams.floatingIpCreationOption
}
in
( model, Rest.Nova.requestCreateServer project createServerRequest )
RequestCreateVolume name size ->
let
createVolumeRequest =
{ name = name
, size = size
}
in
( model, OSVolumes.requestCreateVolume project createVolumeRequest )
RequestDeleteVolume volumeUuid ->
( model, OSVolumes.requestDeleteVolume project volumeUuid )
RequestDetachVolume volumeUuid ->
let
maybeVolume =
OSVolumes.volumeLookup project volumeUuid
maybeServerUuid =
maybeVolume
|> Maybe.map (GetterSetters.getServersWithVolAttached project)
|> Maybe.andThen List.head
in
case maybeServerUuid of
Just serverUuid ->
( model, OSSvrVols.requestDetachVolume project serverUuid volumeUuid )
Nothing ->
State.Error.processStringError
model
(ErrorContext
("look for server UUID with attached volume " ++ volumeUuid)
ErrorCrit
Nothing
)
"Could not determine server attached to this volume."
RequestDeleteFloatingIp floatingIpAddress ->
( model, Rest.Neutron.requestDeleteFloatingIp project floatingIpAddress )
RequestAssignFloatingIp port_ floatingIpUuid ->
let
( newModel, setViewCmd ) =
ViewStateHelpers.setProjectView project (ListFloatingIps Defaults.floatingIpListViewParams) model
in
( newModel
, Cmd.batch
[ setViewCmd
, Rest.Neutron.requestAssignFloatingIp project port_ floatingIpUuid
]
)
RequestUnassignFloatingIp floatingIpUuid ->
( model, Rest.Neutron.requestUnassignFloatingIp project floatingIpUuid )
ReceiveImages images ->
Rest.Glance.receiveImages model project images
RequestDeleteServers serverUuidsToDelete ->
let
applyDelete : OSTypes.ServerUuid -> ( Project, Cmd Msg ) -> ( Project, Cmd Msg )
applyDelete serverUuid projCmdTuple =
let
( delServerProj, delServerCmd ) =
requestDeleteServer (Tuple.first projCmdTuple) serverUuid False
in
( delServerProj, Cmd.batch [ Tuple.second projCmdTuple, delServerCmd ] )
( newProject, cmd ) =
List.foldl
applyDelete
( project, Cmd.none )
serverUuidsToDelete
in
( GetterSetters.modelUpdateProject model newProject
, cmd
)
ReceiveServers errorContext result ->
case result of
Ok servers ->
Rest.Nova.receiveServers model project servers
Err e ->
let
oldServersData =
project.servers.data
newProject =
{ project
| servers =
RDPP.RemoteDataPlusPlus
oldServersData
(RDPP.NotLoading (Just ( e, model.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext e
ReceiveServer serverUuid errorContext result ->
case result of
Ok server ->
Rest.Nova.receiveServer model project server
Err httpErrorWithBody ->
let
httpError =
httpErrorWithBody.error
non404 =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server not in project, may have been deleted, ignoring this error
( model, Cmd.none )
Just server ->
-- Reset receivedTime and loadingSeparately
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps
| receivedTime = Nothing
, loadingSeparately = False
}
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext httpErrorWithBody
in
case httpError of
Http.BadStatus code ->
if code == 404 then
let
newErrorContext =
{ errorContext
| level = Error.ErrorDebug
, actionContext =
errorContext.actionContext
++ " -- 404 means server may have been deleted"
}
newProject =
GetterSetters.projectDeleteServer project serverUuid
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel newErrorContext httpErrorWithBody
else
non404
_ ->
non404
ReceiveFlavors flavors ->
Rest.Nova.receiveFlavors model project flavors
RequestKeypairs ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success _ ->
project.keypairs
_ ->
RemoteData.Loading
newProject =
{ project | keypairs = newKeypairs }
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel
, Rest.Nova.requestKeypairs newProject
)
ReceiveKeypairs keypairs ->
Rest.Nova.receiveKeypairs model project keypairs
RequestCreateKeypair keypairName publicKey ->
( model, Rest.Nova.requestCreateKeypair project keypairName publicKey )
ReceiveCreateKeypair keypair ->
let
newProject =
GetterSetters.projectUpdateKeypair project keypair
newModel =
GetterSetters.modelUpdateProject model newProject
in
ViewStateHelpers.setProjectView newProject (ListKeypairs Defaults.keypairListViewParams) newModel
RequestDeleteKeypair keypairName ->
( model, Rest.Nova.requestDeleteKeypair project keypairName )
ReceiveDeleteKeypair errorContext keypairName result ->
case result of
Err httpError ->
State.Error.processStringError model errorContext (Helpers.httpErrorToString httpError)
Ok () ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success keypairs ->
keypairs
|> List.filter (\k -> k.name /= keypairName)
|> RemoteData.Success
_ ->
project.keypairs
newProject =
{ project | keypairs = newKeypairs }
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
ReceiveCreateServer _ ->
let
newViewState =
ProjectView
project.auth.project.uuid
Defaults.projectViewParams
<|
AllResources
Defaults.allResourcesListViewParams
in
( model, Cmd.none )
|> Helpers.pipelineCmd
(ApiModelHelpers.requestServers project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestNetworks project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts project.auth.project.uuid)
|> Helpers.pipelineCmd
(ViewStateHelpers.modelUpdateViewState newViewState)
ReceiveNetworks errorContext result ->
case result of
Ok networks ->
Rest.Neutron.receiveNetworks model project networks
Err httpError ->
let
oldNetworksData =
project.networks.data
newProject =
{ project
| networks =
RDPP.RemoteDataPlusPlus
oldNetworksData
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext httpError
ReceiveAutoAllocatedNetwork errorContext result ->
let
newProject =
case result of
Ok netUuid ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave netUuid model.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
Err httpError ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
project.autoAllocatedNetworkUuid.data
(RDPP.NotLoading
(Just
( httpError
, model.clientCurrentTime
)
)
)
}
newViewState =
case model.viewState of
ProjectView _ viewParams projectViewConstructor ->
case projectViewConstructor of
CreateServer createServerViewParams ->
if createServerViewParams.networkUuid == Nothing then
case Helpers.newServerNetworkOptions newProject of
AutoSelectedNetwork netUuid ->
ProjectView
project.auth.project.uuid
viewParams
(CreateServer
{ createServerViewParams
| networkUuid = Just netUuid
}
)
_ ->
model.viewState
else
model.viewState
_ ->
model.viewState
_ ->
model.viewState
newModel =
GetterSetters.modelUpdateProject
{ model | viewState = newViewState }
newProject
in
case result of
Ok _ ->
ApiModelHelpers.requestNetworks project.auth.project.uuid newModel
Err httpError ->
State.Error.processSynchronousApiError newModel errorContext httpError
|> Helpers.pipelineCmd (ApiModelHelpers.requestNetworks project.auth.project.uuid)
ReceiveFloatingIps ips ->
Rest.Neutron.receiveFloatingIps model project ips
ReceivePorts errorContext result ->
case result of
Ok ports ->
let
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave ports model.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
Err httpError ->
let
oldPortsData =
project.ports.data
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
oldPortsData
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext httpError
ReceiveDeleteFloatingIp uuid ->
Rest.Neutron.receiveDeleteFloatingIp model project uuid
ReceiveAssignFloatingIp floatingIp ->
-- TODO update servers so that new assignment is reflected in the UI
let
newProject =
processNewFloatingIp model.clientCurrentTime project floatingIp
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
ReceiveUnassignFloatingIp floatingIp ->
-- TODO update servers so that unassignment is reflected in the UI
let
newProject =
processNewFloatingIp model.clientCurrentTime project floatingIp
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
ReceiveSecurityGroups groups ->
Rest.Neutron.receiveSecurityGroupsAndEnsureExoGroup model project groups
ReceiveCreateExoSecurityGroup group ->
Rest.Neutron.receiveCreateExoSecurityGroupAndRequestCreateRules model project group
ReceiveCreateVolume ->
{- Should we add new volume to model now? -}
ViewStateHelpers.setProjectView project (ListProjectVolumes Defaults.volumeListViewParams) model
ReceiveVolumes volumes ->
let
-- Look for any server backing volumes that were created with no name, and give them a reasonable name
updateVolNameCmds : List (Cmd Msg)
updateVolNameCmds =
RDPP.withDefault [] project.servers
-- List of tuples containing server and Maybe boot vol
|> List.map
(\s ->
( s
, Helpers.getBootVol
(RemoteData.withDefault
[]
project.volumes
)
s.osProps.uuid
)
)
-- We only care about servers created by exosphere
|> List.filter
(\t ->
case Tuple.first t |> .exoProps |> .serverOrigin of
ServerFromExo _ ->
True
ServerNotFromExo ->
False
)
-- We only care about servers created as current OpenStack user
|> List.filter
(\t ->
(Tuple.first t).osProps.details.userUuid
== project.auth.user.uuid
)
-- We only care about servers with a non-empty name
|> List.filter
(\t ->
Tuple.first t
|> .osProps
|> .name
|> String.isEmpty
|> not
)
-- We only care about volume-backed servers
|> List.filterMap
(\t ->
case t of
( server, Just vol ) ->
-- Flatten second part of tuple
Just ( server, vol )
_ ->
Nothing
)
-- We only care about unnamed backing volumes
|> List.filter
(\t ->
Tuple.second t
|> .name
|> String.isEmpty
)
|> List.map
(\t ->
OSVolumes.requestUpdateVolumeName
project
(t |> Tuple.second |> .uuid)
("boot-vol-"
++ (t |> Tuple.first |> .osProps |> .name)
)
)
newProject =
{ project | volumes = RemoteData.succeed volumes }
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.batch updateVolNameCmds )
ReceiveDeleteVolume ->
( model, OSVolumes.requestVolumes project )
ReceiveUpdateVolumeName ->
( model, OSVolumes.requestVolumes project )
ReceiveAttachVolume attachment ->
ViewStateHelpers.setProjectView project (MountVolInstructions attachment) model
ReceiveDetachVolume ->
ViewStateHelpers.setProjectView project (ListProjectVolumes Defaults.volumeListViewParams) model
ReceiveAppCredential appCredential ->
let
newProject =
{ project | secret = ApplicationCredential appCredential }
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
ReceiveComputeQuota quota ->
let
newProject =
{ project | computeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
ReceiveVolumeQuota quota ->
let
newProject =
{ project | volumeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
processServerSpecificMsg : Model -> Project -> Server -> ServerSpecificMsgConstructor -> ( Model, Cmd Msg )
processServerSpecificMsg model project server serverMsgConstructor =
case serverMsgConstructor of
RequestServer ->
ApiModelHelpers.requestServer project.auth.project.uuid server.osProps.uuid model
RequestDeleteServer retainFloatingIps ->
let
( newProject, cmd ) =
requestDeleteServer project server.osProps.uuid retainFloatingIps
in
( GetterSetters.modelUpdateProject model newProject, cmd )
RequestAttachVolume volumeUuid ->
( model, OSSvrVols.requestAttachVolume project server.osProps.uuid volumeUuid )
RequestCreateServerImage imageName ->
let
newViewState =
ProjectView
project.auth.project.uuid
{ createPopup = False }
<|
AllResources
Defaults.allResourcesListViewParams
createImageCmd =
Rest.Nova.requestCreateServerImage project server.osProps.uuid imageName
in
( model, createImageCmd )
|> Helpers.pipelineCmd
(ViewStateHelpers.modelUpdateViewState newViewState)
RequestSetServerName newServerName ->
( model, Rest.Nova.requestSetServerName project server.osProps.uuid newServerName )
ReceiveServerEvents _ result ->
case result of
Ok serverEvents ->
let
newServer =
{ server | events = RemoteData.Success serverEvents }
newProject =
GetterSetters.projectUpdateServer project newServer
in
( GetterSetters.modelUpdateProject model newProject
, Cmd.none
)
Err _ ->
-- Dropping this on the floor for now, someday we may want to do something different
( model, Cmd.none )
ReceiveConsoleUrl url ->
Rest.Nova.receiveConsoleUrl model project server url
ReceiveDeleteServer ->
let
( serverDeletedModel, urlCmd ) =
let
newViewState =
case model.viewState of
ProjectView projectId viewParams (ServerDetail viewServerUuid _) ->
if viewServerUuid == server.osProps.uuid then
ProjectView
projectId
viewParams
(AllResources
Defaults.allResourcesListViewParams
)
else
model.viewState
_ ->
model.viewState
newProject =
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | deletionAttempted = True }
newServer =
{ server | exoProps = newExoProps }
in
GetterSetters.projectUpdateServer project newServer
modelUpdatedProject =
GetterSetters.modelUpdateProject model newProject
in
ViewStateHelpers.modelUpdateViewState newViewState modelUpdatedProject
in
( serverDeletedModel, urlCmd )
ReceiveCreateFloatingIp errorContext result ->
case result of
Ok ip ->
Rest.Neutron.receiveCreateFloatingIp model project server ip
Err httpErrorWithBody ->
let
newErrorContext =
if GetterSetters.serverPresentNotDeleting model server.osProps.uuid then
errorContext
else
{ errorContext | level = ErrorDebug }
in
State.Error.processSynchronousApiError model newErrorContext httpErrorWithBody
ReceiveServerPassword password ->
if String.isEmpty password then
( model, Cmd.none )
else
let
tag =
"exoPw:" ++ password
cmd =
case server.exoProps.serverOrigin of
ServerNotFromExo ->
Cmd.none
ServerFromExo serverFromExoProps ->
if serverFromExoProps.exoServerVersion >= 1 then
Cmd.batch
[ OSServerTags.requestCreateServerTag project server.osProps.uuid tag
, OSServerPassword.requestClearServerPassword project server.osProps.uuid
]
else
Cmd.none
in
( model, cmd )
ReceiveSetServerName _ errorContext result ->
case result of
Err e ->
State.Error.processSynchronousApiError model errorContext e
Ok actualNewServerName ->
let
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | name = actualNewServerName }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
modelWithUpdatedProject =
GetterSetters.modelUpdateProject model newProject
-- Only update the view if we are on the server details view for the server we're interested in
updatedView =
case model.viewState of
ProjectView projectIdentifier projectViewParams (ServerDetail serverUuid_ serverDetailViewParams) ->
if server.osProps.uuid == serverUuid_ then
let
newServerDetailsViewParams =
{ serverDetailViewParams
| serverNamePendingConfirmation = Nothing
}
in
ProjectView projectIdentifier
projectViewParams
(ServerDetail serverUuid_ newServerDetailsViewParams)
else
model.viewState
_ ->
model.viewState
-- Later, maybe: Check that newServerName == actualNewServerName
in
ViewStateHelpers.modelUpdateViewState updatedView modelWithUpdatedProject
ReceiveSetServerMetadata intendedMetadataItem errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError model errorContext e
Ok newServerMetadata ->
-- Update the model after ensuring the intended metadata item was actually added
if List.member intendedMetadataItem newServerMetadata then
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = newServerMetadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
else
-- This is bonkers, throw an error
State.Error.processStringError
model
errorContext
"The metadata items returned by OpenStack did not include the metadata item that we tried to set."
ReceiveDeleteServerMetadata metadataKey errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError model errorContext e
Ok _ ->
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = List.filter (\i -> i.key /= metadataKey) oldServerDetails.metadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
ReceiveGuacamoleAuthToken result ->
let
errorContext =
ErrorContext
"Receive a response from Guacamole auth token API"
ErrorDebug
Nothing
modelUpdateGuacProps : ServerFromExoProps -> GuacTypes.LaunchedWithGuacProps -> Model
modelUpdateGuacProps exoOriginProps guacProps =
let
newOriginProps =
{ exoOriginProps | guacamoleStatus = GuacTypes.LaunchedWithGuacamole guacProps }
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
newModel
in
case server.exoProps.serverOrigin of
ServerFromExo exoOriginProps ->
case exoOriginProps.guacamoleStatus of
GuacTypes.LaunchedWithGuacamole oldGuacProps ->
let
newGuacProps =
case result of
Ok tokenValue ->
if server.osProps.details.openstackStatus == OSTypes.ServerActive then
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
tokenValue
model.clientCurrentTime
)
(RDPP.NotLoading Nothing)
}
else
-- Server is not active, this token won't work, so we don't store it
{ oldGuacProps
| authToken =
RDPP.empty
}
Err e ->
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
oldGuacProps.authToken.data
(RDPP.NotLoading (Just ( e, model.clientCurrentTime )))
}
in
( modelUpdateGuacProps
exoOriginProps
newGuacProps
, Cmd.none
)
GuacTypes.NotLaunchedWithGuacamole ->
State.Error.processStringError
model
errorContext
"Server does not appear to have been launched with Guacamole support"
ServerNotFromExo ->
State.Error.processStringError
model
errorContext
"Server does not appear to have been launched from Exosphere"
RequestServerAction func targetStatuses ->
let
oldExoProps =
server.exoProps
newServer =
Server server.osProps { oldExoProps | targetOpenstackStatus = targetStatuses } server.events
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, func newProject newServer )
ReceiveConsoleLog errorContext result ->
case server.exoProps.serverOrigin of
ServerNotFromExo ->
( model, Cmd.none )
ServerFromExo exoOriginProps ->
let
oldExoSetupStatus =
case exoOriginProps.exoSetupStatus.data of
RDPP.DontHave ->
ExoSetupUnknown
RDPP.DoHave s _ ->
s
( newExoSetupStatusRDPP, exoSetupStatusMetadataCmd ) =
case result of
Err httpError ->
( RDPP.RemoteDataPlusPlus
exoOriginProps.exoSetupStatus.data
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
, Cmd.none
)
Ok consoleLog ->
let
newExoSetupStatus =
Helpers.ExoSetupStatus.parseConsoleLogExoSetupStatus
oldExoSetupStatus
consoleLog
server.osProps.details.created
model.clientCurrentTime
cmd =
if newExoSetupStatus == oldExoSetupStatus then
Cmd.none
else
let
value =
Helpers.ExoSetupStatus.exoSetupStatusToStr newExoSetupStatus
metadataItem =
OSTypes.MetadataItem
"exoSetup"
value
in
Rest.Nova.requestSetServerMetadata project server.osProps.uuid metadataItem
in
( RDPP.RemoteDataPlusPlus
(RDPP.DoHave
newExoSetupStatus
model.clientCurrentTime
)
(RDPP.NotLoading Nothing)
, cmd
)
newResourceUsage =
case result of
Err httpError ->
RDPP.RemoteDataPlusPlus
exoOriginProps.resourceUsage.data
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
Ok consoleLog ->
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
(Helpers.ServerResourceUsage.parseConsoleLog
consoleLog
(RDPP.withDefault
Types.ServerResourceUsage.emptyResourceUsageHistory
exoOriginProps.resourceUsage
)
)
model.clientCurrentTime
)
(RDPP.NotLoading Nothing)
newOriginProps =
{ exoOriginProps
| resourceUsage = newResourceUsage
, exoSetupStatus = newExoSetupStatusRDPP
}
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
case result of
Err httpError ->
State.Error.processSynchronousApiError newModel errorContext httpError
Ok _ ->
( newModel, exoSetupStatusMetadataCmd )
processNewFloatingIp : Time.Posix -> Project -> OSTypes.FloatingIp -> Project
processNewFloatingIp time project floatingIp =
let
otherIps =
project.floatingIps
|> RDPP.withDefault []
|> List.filter (\i -> i.uuid /= floatingIp.uuid)
newIps =
floatingIp :: otherIps
in
{ project
| floatingIps =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave newIps time)
(RDPP.NotLoading Nothing)
}
createProject : Model -> OSTypes.ScopedAuthToken -> Endpoints -> ( Model, Cmd Msg )
createProject model authToken endpoints =
let
newProject =
{ secret = NoProjectSecret
, auth = authToken
-- Maybe todo, eliminate parallel data structures in auth and endpoints?
, endpoints = endpoints
, images = []
, servers = RDPP.RemoteDataPlusPlus RDPP.DontHave RDPP.Loading
, flavors = []
, keypairs = RemoteData.NotAsked
, volumes = RemoteData.NotAsked
, networks = RDPP.empty
, autoAllocatedNetworkUuid = RDPP.empty
, floatingIps = RDPP.empty
, ports = RDPP.empty
, securityGroups = []
, computeQuota = RemoteData.NotAsked
, volumeQuota = RemoteData.NotAsked
, pendingCredentialedRequests = []
}
newProjects =
newProject :: model.projects
newViewStateFunc =
-- If the user is selecting projects from an unscoped provider then don't interrupt them
case model.viewState of
NonProjectView (SelectProjects _ _) ->
\model_ -> ( model_, Cmd.none )
NonProjectView _ ->
ViewStateHelpers.setProjectView newProject <|
AllResources Defaults.allResourcesListViewParams
ProjectView _ _ _ ->
ViewStateHelpers.setProjectView newProject <|
AllResources Defaults.allResourcesListViewParams
newModel =
{ model
| projects = newProjects
}
in
( newModel
, [ Rest.Nova.requestServers
, Rest.Neutron.requestSecurityGroups
, Rest.Keystone.requestAppCredential model.clientUuid model.clientCurrentTime
]
|> List.map (\x -> x newProject)
|> Cmd.batch
)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestFloatingIps newProject.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts newProject.auth.project.uuid)
|> Helpers.pipelineCmd newViewStateFunc
createUnscopedProvider : Model -> OSTypes.UnscopedAuthToken -> HelperTypes.Url -> ( Model, Cmd Msg )
createUnscopedProvider model authToken authUrl =
let
newProvider =
{ authUrl = authUrl
, token = authToken
, projectsAvailable = RemoteData.Loading
}
newProviders =
newProvider :: model.unscopedProviders
in
( { model | unscopedProviders = newProviders }
, Rest.Keystone.requestUnscopedProjects newProvider model.cloudCorsProxyUrl
)
requestDeleteServer : Project -> OSTypes.ServerUuid -> Bool -> ( Project, Cmd Msg )
requestDeleteServer project serverUuid retainFloatingIps =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server likely deleted already, do nothing
( project, Cmd.none )
Just server ->
let
oldExoProps =
server.exoProps
newServer =
{ server | exoProps = { oldExoProps | deletionAttempted = True } }
deleteFloatingIpCmds =
if retainFloatingIps then
[]
else
GetterSetters.getServerFloatingIps project server.osProps.uuid
|> List.map .uuid
|> List.map (Rest.Neutron.requestDeleteFloatingIp project)
newProject =
GetterSetters.projectUpdateServer project newServer
in
( newProject
, Cmd.batch
[ Rest.Nova.requestDeleteServer newProject newServer
, Cmd.batch deleteFloatingIpCmds
]
)
| 4054 | module State.State exposing (update)
import AppUrl.Builder
import AppUrl.Parser
import Browser.Navigation
import Helpers.ExoSetupStatus
import Helpers.GetterSetters as GetterSetters
import Helpers.Helpers as Helpers
import Helpers.RemoteDataPlusPlus as RDPP
import Helpers.ServerResourceUsage
import Helpers.Url as UrlHelpers
import Http
import LocalStorage.LocalStorage as LocalStorage
import Maybe
import OpenStack.ServerPassword as OSServerPassword
import OpenStack.ServerTags as OSServerTags
import OpenStack.ServerVolumes as OSSvrVols
import OpenStack.Types as OSTypes
import OpenStack.Volumes as OSVolumes
import Orchestration.Orchestration as Orchestration
import Ports
import RemoteData
import Rest.ApiModelHelpers as ApiModelHelpers
import Rest.Glance
import Rest.Keystone
import Rest.Neutron
import Rest.Nova
import State.Auth
import State.Error
import State.ViewState as ViewStateHelpers
import Style.Toast
import Style.Widgets.NumericTextInput.NumericTextInput
import Task
import Time
import Toasty
import Types.Defaults as Defaults
import Types.Error as Error exposing (ErrorContext, ErrorLevel(..))
import Types.Guacamole as GuacTypes
import Types.HelperTypes as HelperTypes
import Types.ServerResourceUsage
import Types.Types
exposing
( Endpoints
, ExoSetupStatus(..)
, HttpRequestMethod(..)
, LoginView(..)
, Model
, Msg(..)
, NewServerNetworkOptions(..)
, NonProjectViewConstructor(..)
, OpenstackLoginFormEntryType(..)
, OpenstackLoginViewParams
, Project
, ProjectSecret(..)
, ProjectSpecificMsgConstructor(..)
, ProjectViewConstructor(..)
, Server
, ServerFromExoProps
, ServerOrigin(..)
, ServerSpecificMsgConstructor(..)
, TickInterval
, UnscopedProviderProject
, ViewState(..)
, currentExoServerVersion
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
{- We want to `setStorage` on every update. This function adds the setStorage
command for every step of the update function.
-}
let
( newModel, cmds ) =
updateUnderlying msg model
orchestrationTimeCmd =
-- Each trip through the runtime, we get the time and feed it to orchestration module
case msg of
DoOrchestration _ ->
Cmd.none
Tick _ _ ->
Cmd.none
_ ->
Task.perform (\posix -> DoOrchestration posix) Time.now
in
( newModel
, Cmd.batch
[ Ports.setStorage (LocalStorage.generateStoredState newModel)
, orchestrationTimeCmd
, cmds
]
)
updateUnderlying : Msg -> Model -> ( Model, Cmd Msg )
updateUnderlying msg model =
case msg of
ToastyMsg subMsg ->
Toasty.update Style.Toast.toastConfig ToastyMsg subMsg model
MsgChangeWindowSize x y ->
( { model | windowSize = { width = x, height = y } }, Cmd.none )
Tick interval time ->
processTick model interval time
DoOrchestration posixTime ->
Orchestration.orchModel model posixTime
SetNonProjectView nonProjectViewConstructor ->
ViewStateHelpers.setNonProjectView nonProjectViewConstructor model
HandleApiErrorWithBody errorContext error ->
State.Error.processSynchronousApiError model errorContext error
RequestUnscopedToken openstackLoginUnscoped ->
let
creds =
-- Ensure auth URL includes port number and version
{ openstackLoginUnscoped
| authUrl =
State.Auth.authUrlWithPortAndVersion openstackLoginUnscoped.authUrl
}
in
( model, Rest.Keystone.requestUnscopedAuthToken model.cloudCorsProxyUrl creds )
JetstreamLogin jetstreamCreds ->
let
openstackCredsList =
State.Auth.jetstreamToOpenstackCreds jetstreamCreds
cmds =
List.map
(\creds -> Rest.Keystone.requestUnscopedAuthToken model.cloudCorsProxyUrl creds)
openstackCredsList
in
( model, Cmd.batch cmds )
ReceiveScopedAuthToken ( metadata, response ) ->
case Rest.Keystone.decodeScopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
model
(ErrorContext
"decode scoped auth token"
ErrorCrit
Nothing
)
error
Ok authToken ->
case Helpers.serviceCatalogToEndpoints authToken.catalog of
Err e ->
State.Error.processStringError
model
(ErrorContext
"Decode project endpoints"
ErrorCrit
(Just "Please check with your cloud administrator or the Exosphere developers.")
)
e
Ok endpoints ->
let
projectId =
authToken.project.uuid
in
-- If we don't have a project with same name + authUrl then create one, if we do then update its OSTypes.AuthToken
-- This code ensures we don't end up with duplicate projects on the same provider in our model.
case
GetterSetters.projectLookup model <| projectId
of
Nothing ->
createProject model authToken endpoints
Just project ->
-- If we don't have an application credential for this project yet, then get one
let
appCredCmd =
case project.secret of
ApplicationCredential _ ->
Cmd.none
_ ->
Rest.Keystone.requestAppCredential
model.clientUuid
model.clientCurrentTime
project
( newModel, updateTokenCmd ) =
State.Auth.projectUpdateAuthToken model project authToken
in
( newModel, Cmd.batch [ appCredCmd, updateTokenCmd ] )
ReceiveUnscopedAuthToken keystoneUrl ( metadata, response ) ->
case Rest.Keystone.decodeUnscopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
model
(ErrorContext
"decode scoped auth token"
ErrorCrit
Nothing
)
error
Ok authToken ->
case
GetterSetters.providerLookup model keystoneUrl
of
Just unscopedProvider ->
-- We already have an unscoped provider in the model with the same auth URL, update its token
State.Auth.unscopedProviderUpdateAuthToken
model
unscopedProvider
authToken
Nothing ->
-- We don't have an unscoped provider with the same auth URL, create it
createUnscopedProvider model authToken keystoneUrl
ReceiveUnscopedProjects keystoneUrl unscopedProjects ->
case
GetterSetters.providerLookup model keystoneUrl
of
Just provider ->
let
newProvider =
{ provider | projectsAvailable = RemoteData.Success unscopedProjects }
newModel =
GetterSetters.modelUpdateUnscopedProvider model newProvider
in
-- If we are not already on a SelectProjects view, then go there
case newModel.viewState of
NonProjectView (SelectProjects _ _) ->
( newModel, Cmd.none )
_ ->
ViewStateHelpers.modelUpdateViewState
(NonProjectView <|
SelectProjects newProvider.authUrl []
)
newModel
Nothing ->
-- Provider not found, may have been removed, nothing to do
( model, Cmd.none )
RequestProjectLoginFromProvider keystoneUrl desiredProjects ->
case GetterSetters.providerLookup model keystoneUrl of
Just provider ->
let
buildLoginRequest : UnscopedProviderProject -> Cmd Msg
buildLoginRequest project =
Rest.Keystone.requestScopedAuthToken
model.cloudCorsProxyUrl
<|
OSTypes.TokenCreds
keystoneUrl
provider.token
project.project.uuid
loginRequests =
List.map buildLoginRequest desiredProjects
|> Cmd.batch
-- Remove unscoped provider from model now that we have selected projects from it
newUnscopedProviders =
List.filter
(\p -> p.authUrl /= keystoneUrl)
model.unscopedProviders
-- If we still have at least one unscoped provider in the model then ask the user to choose projects from it
newViewStateFunc =
case List.head newUnscopedProviders of
Just unscopedProvider ->
ViewStateHelpers.setNonProjectView
(SelectProjects unscopedProvider.authUrl [])
Nothing ->
-- If we have at least one project then show it, else show the login page
case List.head model.projects of
Just project ->
ViewStateHelpers.setProjectView
project
<|
AllResources Defaults.allResourcesListViewParams
Nothing ->
ViewStateHelpers.setNonProjectView
LoginPicker
modelUpdatedUnscopedProviders =
{ model | unscopedProviders = newUnscopedProviders }
in
( modelUpdatedUnscopedProviders, loginRequests )
|> Helpers.pipelineCmd newViewStateFunc
Nothing ->
State.Error.processStringError
model
(ErrorContext
("look for OpenStack provider with Keystone URL " ++ keystoneUrl)
ErrorCrit
Nothing
)
"Provider could not found in Exosphere's list of Providers."
ProjectMsg projectIdentifier innerMsg ->
case GetterSetters.projectLookup model projectIdentifier of
Nothing ->
-- Project not found, may have been removed, nothing to do
( model, Cmd.none )
Just project ->
processProjectSpecificMsg model project innerMsg
{- Form inputs -}
SubmitOpenRc openstackCreds openRc ->
let
newCreds =
State.Auth.processOpenRc openstackCreds openRc
newViewState =
NonProjectView <| Login <| LoginOpenstack <| OpenstackLoginViewParams newCreds openRc LoginViewCredsEntry
in
ViewStateHelpers.modelUpdateViewState newViewState model
OpenNewWindow url ->
( model, Ports.openNewWindow url )
NavigateToUrl url ->
( model, Browser.Navigation.load url )
UrlChange url ->
-- This handles presses of the browser back/forward button
let
exoJustSetThisUrl =
-- If this is a URL that Exosphere just set via StateHelpers.updateViewState, then ignore it
UrlHelpers.urlPathQueryMatches url model.prevUrl
in
if exoJustSetThisUrl then
( model, Cmd.none )
else
case
AppUrl.Parser.urlToViewState
model.urlPathPrefix
(ViewStateHelpers.defaultViewState model)
url
of
Just newViewState ->
( { model
| viewState = newViewState
, prevUrl = AppUrl.Builder.viewStateToUrl model.urlPathPrefix newViewState
}
, Cmd.none
)
Nothing ->
( { model
| viewState = NonProjectView PageNotFound
}
, Cmd.none
)
SetStyle styleMode ->
let
oldStyle =
model.style
newStyle =
{ oldStyle | styleMode = styleMode }
in
( { model | style = newStyle }, Cmd.none )
NoOp ->
( model, Cmd.none )
processTick : Model -> TickInterval -> Time.Posix -> ( Model, Cmd Msg )
processTick model interval time =
let
serverVolsNeedFrequentPoll : Project -> Server -> Bool
serverVolsNeedFrequentPoll project server =
GetterSetters.getVolsAttachedToServer project server
|> List.any volNeedsFrequentPoll
volNeedsFrequentPoll volume =
not <|
List.member
volume.status
[ OSTypes.Available
, OSTypes.Maintenance
, OSTypes.InUse
, OSTypes.Error
, OSTypes.ErrorDeleting
, OSTypes.ErrorBackingUp
, OSTypes.ErrorRestoring
, OSTypes.ErrorExtending
]
viewIndependentCmd =
if interval == 5 then
Task.perform (\posix -> DoOrchestration posix) Time.now
else
Cmd.none
( viewDependentModel, viewDependentCmd ) =
{- TODO move some of this to Orchestration? -}
case model.viewState of
NonProjectView _ ->
( model, Cmd.none )
ProjectView projectName _ projectViewState ->
case GetterSetters.projectLookup model projectName of
Nothing ->
{- Should this throw an error? -}
( model, Cmd.none )
Just project ->
let
pollVolumes : ( Model, Cmd Msg )
pollVolumes =
( model
, case interval of
5 ->
if List.any volNeedsFrequentPoll (RemoteData.withDefault [] project.volumes) then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
in
case projectViewState of
AllResources _ ->
pollVolumes
ServerDetail serverUuid _ ->
let
volCmd =
OSVolumes.requestVolumes project
in
case interval of
5 ->
case GetterSetters.serverLookup project serverUuid of
Just server ->
( model
, if serverVolsNeedFrequentPoll project server then
volCmd
else
Cmd.none
)
Nothing ->
( model, Cmd.none )
300 ->
( model, volCmd )
_ ->
( model, Cmd.none )
ListProjectVolumes _ ->
pollVolumes
VolumeDetail volumeUuid _ ->
( model
, case interval of
5 ->
case GetterSetters.volumeLookup project volumeUuid of
Nothing ->
Cmd.none
Just volume ->
if volNeedsFrequentPoll volume then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
_ ->
( model, Cmd.none )
in
( { viewDependentModel | clientCurrentTime = time }
, Cmd.batch
[ viewDependentCmd
, viewIndependentCmd
]
)
processProjectSpecificMsg : Model -> Project -> ProjectSpecificMsgConstructor -> ( Model, Cmd Msg )
processProjectSpecificMsg model project msg =
case msg of
SetProjectView projectViewConstructor ->
ViewStateHelpers.setProjectView project projectViewConstructor model
PrepareCredentialedRequest requestProto posixTime ->
let
-- Add proxy URL
requestNeedingToken =
requestProto model.cloudCorsProxyUrl
currentTimeMillis =
posixTime |> Time.posixToMillis
tokenExpireTimeMillis =
project.auth.expiresAt |> Time.posixToMillis
tokenExpired =
-- Token expiring within 5 minutes
tokenExpireTimeMillis < currentTimeMillis + 300000
in
if not tokenExpired then
-- Token still valid, fire the request with current token
( model, requestNeedingToken project.auth.tokenValue )
else
-- Token is expired (or nearly expired) so we add request to list of pending requests and refresh that token
let
newPQRs =
requestNeedingToken :: project.pendingCredentialedRequests
newProject =
{ project | pendingCredentialedRequests = newPQRs }
newModel =
GetterSetters.modelUpdateProject model newProject
cmdResult =
State.Auth.requestAuthToken newModel newProject
in
case cmdResult of
Err e ->
let
errorContext =
ErrorContext
("Refresh authentication token for project " ++ project.auth.project.name)
ErrorCrit
(Just "Please remove this project from Exosphere and add it again.")
in
State.Error.processStringError newModel errorContext e
Ok cmd ->
( newModel, cmd )
ToggleCreatePopup ->
case model.viewState of
ProjectView projectId viewParams viewConstructor ->
let
newViewState =
ProjectView
projectId
{ viewParams
| createPopup = not viewParams.createPopup
}
viewConstructor
in
ViewStateHelpers.modelUpdateViewState newViewState model
_ ->
( model, Cmd.none )
RemoveProject ->
let
newProjects =
List.filter (\p -> p.auth.project.uuid /= project.auth.project.uuid) model.projects
newViewState =
case model.viewState of
NonProjectView _ ->
-- If we are not in a project-specific view then stay there
model.viewState
ProjectView _ _ _ ->
-- If we have any projects switch to the first one in the list, otherwise switch to login view
case List.head newProjects of
Just p ->
ProjectView
p.auth.project.uuid
Defaults.projectViewParams
<|
AllResources
Defaults.allResourcesListViewParams
Nothing ->
NonProjectView <| LoginPicker
modelUpdatedProjects =
{ model | projects = newProjects }
in
ViewStateHelpers.modelUpdateViewState newViewState modelUpdatedProjects
ServerMsg serverUuid serverMsgConstructor ->
case GetterSetters.serverLookup project serverUuid of
Nothing ->
let
errorContext =
ErrorContext
"receive results of API call for a specific server"
ErrorDebug
Nothing
in
State.Error.processStringError
model
errorContext
(String.join " "
[ "Instance"
, serverUuid
, "does not exist in the model, it may have been deleted."
]
)
Just server ->
processServerSpecificMsg model project server serverMsgConstructor
RequestServers ->
ApiModelHelpers.requestServers project.auth.project.uuid model
RequestCreateServer viewParams networkUuid ->
let
createServerRequest =
{ name = viewParams.serverName
, count = viewParams.count
, imageUuid = viewParams.imageUuid
, flavorUuid = viewParams.flavorUuid
, volBackedSizeGb =
viewParams.volSizeTextInput
|> Maybe.andThen Style.Widgets.NumericTextInput.NumericTextInput.toMaybe
, networkUuid = networkUuid
, keypairName = viewParams.keypairName
, userData =
Helpers.renderUserDataTemplate
project
viewParams.userDataTemplate
viewParams.keypairName
(viewParams.deployGuacamole |> Maybe.withDefault False)
viewParams.deployDesktopEnvironment
viewParams.installOperatingSystemUpdates
model.instanceConfigMgtRepoUrl
model.instanceConfigMgtRepoCheckout
, metadata =
Helpers.newServerMetadata
currentExoServerVersion
model.clientUuid
(viewParams.deployGuacamole |> Maybe.withDefault False)
viewParams.deployDesktopEnvironment
project.auth.user.name
viewParams.floatingIpCreationOption
}
in
( model, Rest.Nova.requestCreateServer project createServerRequest )
RequestCreateVolume name size ->
let
createVolumeRequest =
{ name = name
, size = size
}
in
( model, OSVolumes.requestCreateVolume project createVolumeRequest )
RequestDeleteVolume volumeUuid ->
( model, OSVolumes.requestDeleteVolume project volumeUuid )
RequestDetachVolume volumeUuid ->
let
maybeVolume =
OSVolumes.volumeLookup project volumeUuid
maybeServerUuid =
maybeVolume
|> Maybe.map (GetterSetters.getServersWithVolAttached project)
|> Maybe.andThen List.head
in
case maybeServerUuid of
Just serverUuid ->
( model, OSSvrVols.requestDetachVolume project serverUuid volumeUuid )
Nothing ->
State.Error.processStringError
model
(ErrorContext
("look for server UUID with attached volume " ++ volumeUuid)
ErrorCrit
Nothing
)
"Could not determine server attached to this volume."
RequestDeleteFloatingIp floatingIpAddress ->
( model, Rest.Neutron.requestDeleteFloatingIp project floatingIpAddress )
RequestAssignFloatingIp port_ floatingIpUuid ->
let
( newModel, setViewCmd ) =
ViewStateHelpers.setProjectView project (ListFloatingIps Defaults.floatingIpListViewParams) model
in
( newModel
, Cmd.batch
[ setViewCmd
, Rest.Neutron.requestAssignFloatingIp project port_ floatingIpUuid
]
)
RequestUnassignFloatingIp floatingIpUuid ->
( model, Rest.Neutron.requestUnassignFloatingIp project floatingIpUuid )
ReceiveImages images ->
Rest.Glance.receiveImages model project images
RequestDeleteServers serverUuidsToDelete ->
let
applyDelete : OSTypes.ServerUuid -> ( Project, Cmd Msg ) -> ( Project, Cmd Msg )
applyDelete serverUuid projCmdTuple =
let
( delServerProj, delServerCmd ) =
requestDeleteServer (Tuple.first projCmdTuple) serverUuid False
in
( delServerProj, Cmd.batch [ Tuple.second projCmdTuple, delServerCmd ] )
( newProject, cmd ) =
List.foldl
applyDelete
( project, Cmd.none )
serverUuidsToDelete
in
( GetterSetters.modelUpdateProject model newProject
, cmd
)
ReceiveServers errorContext result ->
case result of
Ok servers ->
Rest.Nova.receiveServers model project servers
Err e ->
let
oldServersData =
project.servers.data
newProject =
{ project
| servers =
RDPP.RemoteDataPlusPlus
oldServersData
(RDPP.NotLoading (Just ( e, model.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext e
ReceiveServer serverUuid errorContext result ->
case result of
Ok server ->
Rest.Nova.receiveServer model project server
Err httpErrorWithBody ->
let
httpError =
httpErrorWithBody.error
non404 =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server not in project, may have been deleted, ignoring this error
( model, Cmd.none )
Just server ->
-- Reset receivedTime and loadingSeparately
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps
| receivedTime = Nothing
, loadingSeparately = False
}
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext httpErrorWithBody
in
case httpError of
Http.BadStatus code ->
if code == 404 then
let
newErrorContext =
{ errorContext
| level = Error.ErrorDebug
, actionContext =
errorContext.actionContext
++ " -- 404 means server may have been deleted"
}
newProject =
GetterSetters.projectDeleteServer project serverUuid
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel newErrorContext httpErrorWithBody
else
non404
_ ->
non404
ReceiveFlavors flavors ->
Rest.Nova.receiveFlavors model project flavors
RequestKeypairs ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success _ ->
project.keypairs
_ ->
RemoteData.Loading
newProject =
{ project | keypairs = newKeypairs }
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel
, Rest.Nova.requestKeypairs newProject
)
ReceiveKeypairs keypairs ->
Rest.Nova.receiveKeypairs model project keypairs
RequestCreateKeypair keypairName publicKey ->
( model, Rest.Nova.requestCreateKeypair project keypairName publicKey )
ReceiveCreateKeypair keypair ->
let
newProject =
GetterSetters.projectUpdateKeypair project keypair
newModel =
GetterSetters.modelUpdateProject model newProject
in
ViewStateHelpers.setProjectView newProject (ListKeypairs Defaults.keypairListViewParams) newModel
RequestDeleteKeypair keypairName ->
( model, Rest.Nova.requestDeleteKeypair project keypairName )
ReceiveDeleteKeypair errorContext keypairName result ->
case result of
Err httpError ->
State.Error.processStringError model errorContext (Helpers.httpErrorToString httpError)
Ok () ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success keypairs ->
keypairs
|> List.filter (\k -> k.name /= keypairName)
|> RemoteData.Success
_ ->
project.keypairs
newProject =
{ project | keypairs = newKeypairs }
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
ReceiveCreateServer _ ->
let
newViewState =
ProjectView
project.auth.project.uuid
Defaults.projectViewParams
<|
AllResources
Defaults.allResourcesListViewParams
in
( model, Cmd.none )
|> Helpers.pipelineCmd
(ApiModelHelpers.requestServers project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestNetworks project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts project.auth.project.uuid)
|> Helpers.pipelineCmd
(ViewStateHelpers.modelUpdateViewState newViewState)
ReceiveNetworks errorContext result ->
case result of
Ok networks ->
Rest.Neutron.receiveNetworks model project networks
Err httpError ->
let
oldNetworksData =
project.networks.data
newProject =
{ project
| networks =
RDPP.RemoteDataPlusPlus
oldNetworksData
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext httpError
ReceiveAutoAllocatedNetwork errorContext result ->
let
newProject =
case result of
Ok netUuid ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave netUuid model.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
Err httpError ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
project.autoAllocatedNetworkUuid.data
(RDPP.NotLoading
(Just
( httpError
, model.clientCurrentTime
)
)
)
}
newViewState =
case model.viewState of
ProjectView _ viewParams projectViewConstructor ->
case projectViewConstructor of
CreateServer createServerViewParams ->
if createServerViewParams.networkUuid == Nothing then
case Helpers.newServerNetworkOptions newProject of
AutoSelectedNetwork netUuid ->
ProjectView
project.auth.project.uuid
viewParams
(CreateServer
{ createServerViewParams
| networkUuid = Just netUuid
}
)
_ ->
model.viewState
else
model.viewState
_ ->
model.viewState
_ ->
model.viewState
newModel =
GetterSetters.modelUpdateProject
{ model | viewState = newViewState }
newProject
in
case result of
Ok _ ->
ApiModelHelpers.requestNetworks project.auth.project.uuid newModel
Err httpError ->
State.Error.processSynchronousApiError newModel errorContext httpError
|> Helpers.pipelineCmd (ApiModelHelpers.requestNetworks project.auth.project.uuid)
ReceiveFloatingIps ips ->
Rest.Neutron.receiveFloatingIps model project ips
ReceivePorts errorContext result ->
case result of
Ok ports ->
let
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave ports model.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
Err httpError ->
let
oldPortsData =
project.ports.data
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
oldPortsData
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext httpError
ReceiveDeleteFloatingIp uuid ->
Rest.Neutron.receiveDeleteFloatingIp model project uuid
ReceiveAssignFloatingIp floatingIp ->
-- TODO update servers so that new assignment is reflected in the UI
let
newProject =
processNewFloatingIp model.clientCurrentTime project floatingIp
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
ReceiveUnassignFloatingIp floatingIp ->
-- TODO update servers so that unassignment is reflected in the UI
let
newProject =
processNewFloatingIp model.clientCurrentTime project floatingIp
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
ReceiveSecurityGroups groups ->
Rest.Neutron.receiveSecurityGroupsAndEnsureExoGroup model project groups
ReceiveCreateExoSecurityGroup group ->
Rest.Neutron.receiveCreateExoSecurityGroupAndRequestCreateRules model project group
ReceiveCreateVolume ->
{- Should we add new volume to model now? -}
ViewStateHelpers.setProjectView project (ListProjectVolumes Defaults.volumeListViewParams) model
ReceiveVolumes volumes ->
let
-- Look for any server backing volumes that were created with no name, and give them a reasonable name
updateVolNameCmds : List (Cmd Msg)
updateVolNameCmds =
RDPP.withDefault [] project.servers
-- List of tuples containing server and Maybe boot vol
|> List.map
(\s ->
( s
, Helpers.getBootVol
(RemoteData.withDefault
[]
project.volumes
)
s.osProps.uuid
)
)
-- We only care about servers created by exosphere
|> List.filter
(\t ->
case Tuple.first t |> .exoProps |> .serverOrigin of
ServerFromExo _ ->
True
ServerNotFromExo ->
False
)
-- We only care about servers created as current OpenStack user
|> List.filter
(\t ->
(Tuple.first t).osProps.details.userUuid
== project.auth.user.uuid
)
-- We only care about servers with a non-empty name
|> List.filter
(\t ->
Tuple.first t
|> .osProps
|> .name
|> String.isEmpty
|> not
)
-- We only care about volume-backed servers
|> List.filterMap
(\t ->
case t of
( server, Just vol ) ->
-- Flatten second part of tuple
Just ( server, vol )
_ ->
Nothing
)
-- We only care about unnamed backing volumes
|> List.filter
(\t ->
Tuple.second t
|> .name
|> String.isEmpty
)
|> List.map
(\t ->
OSVolumes.requestUpdateVolumeName
project
(t |> Tuple.second |> .uuid)
("boot-vol-"
++ (t |> Tuple.first |> .osProps |> .name)
)
)
newProject =
{ project | volumes = RemoteData.succeed volumes }
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.batch updateVolNameCmds )
ReceiveDeleteVolume ->
( model, OSVolumes.requestVolumes project )
ReceiveUpdateVolumeName ->
( model, OSVolumes.requestVolumes project )
ReceiveAttachVolume attachment ->
ViewStateHelpers.setProjectView project (MountVolInstructions attachment) model
ReceiveDetachVolume ->
ViewStateHelpers.setProjectView project (ListProjectVolumes Defaults.volumeListViewParams) model
ReceiveAppCredential appCredential ->
let
newProject =
{ project | secret = ApplicationCredential appCredential }
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
ReceiveComputeQuota quota ->
let
newProject =
{ project | computeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
ReceiveVolumeQuota quota ->
let
newProject =
{ project | volumeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
processServerSpecificMsg : Model -> Project -> Server -> ServerSpecificMsgConstructor -> ( Model, Cmd Msg )
processServerSpecificMsg model project server serverMsgConstructor =
case serverMsgConstructor of
RequestServer ->
ApiModelHelpers.requestServer project.auth.project.uuid server.osProps.uuid model
RequestDeleteServer retainFloatingIps ->
let
( newProject, cmd ) =
requestDeleteServer project server.osProps.uuid retainFloatingIps
in
( GetterSetters.modelUpdateProject model newProject, cmd )
RequestAttachVolume volumeUuid ->
( model, OSSvrVols.requestAttachVolume project server.osProps.uuid volumeUuid )
RequestCreateServerImage imageName ->
let
newViewState =
ProjectView
project.auth.project.uuid
{ createPopup = False }
<|
AllResources
Defaults.allResourcesListViewParams
createImageCmd =
Rest.Nova.requestCreateServerImage project server.osProps.uuid imageName
in
( model, createImageCmd )
|> Helpers.pipelineCmd
(ViewStateHelpers.modelUpdateViewState newViewState)
RequestSetServerName newServerName ->
( model, Rest.Nova.requestSetServerName project server.osProps.uuid newServerName )
ReceiveServerEvents _ result ->
case result of
Ok serverEvents ->
let
newServer =
{ server | events = RemoteData.Success serverEvents }
newProject =
GetterSetters.projectUpdateServer project newServer
in
( GetterSetters.modelUpdateProject model newProject
, Cmd.none
)
Err _ ->
-- Dropping this on the floor for now, someday we may want to do something different
( model, Cmd.none )
ReceiveConsoleUrl url ->
Rest.Nova.receiveConsoleUrl model project server url
ReceiveDeleteServer ->
let
( serverDeletedModel, urlCmd ) =
let
newViewState =
case model.viewState of
ProjectView projectId viewParams (ServerDetail viewServerUuid _) ->
if viewServerUuid == server.osProps.uuid then
ProjectView
projectId
viewParams
(AllResources
Defaults.allResourcesListViewParams
)
else
model.viewState
_ ->
model.viewState
newProject =
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | deletionAttempted = True }
newServer =
{ server | exoProps = newExoProps }
in
GetterSetters.projectUpdateServer project newServer
modelUpdatedProject =
GetterSetters.modelUpdateProject model newProject
in
ViewStateHelpers.modelUpdateViewState newViewState modelUpdatedProject
in
( serverDeletedModel, urlCmd )
ReceiveCreateFloatingIp errorContext result ->
case result of
Ok ip ->
Rest.Neutron.receiveCreateFloatingIp model project server ip
Err httpErrorWithBody ->
let
newErrorContext =
if GetterSetters.serverPresentNotDeleting model server.osProps.uuid then
errorContext
else
{ errorContext | level = ErrorDebug }
in
State.Error.processSynchronousApiError model newErrorContext httpErrorWithBody
ReceiveServerPassword password ->
if String.isEmpty password then
( model, Cmd.none )
else
let
tag =
"exoPw:" ++ password
cmd =
case server.exoProps.serverOrigin of
ServerNotFromExo ->
Cmd.none
ServerFromExo serverFromExoProps ->
if serverFromExoProps.exoServerVersion >= 1 then
Cmd.batch
[ OSServerTags.requestCreateServerTag project server.osProps.uuid tag
, OSServerPassword.requestClearServerPassword project server.osProps.uuid
]
else
Cmd.none
in
( model, cmd )
ReceiveSetServerName _ errorContext result ->
case result of
Err e ->
State.Error.processSynchronousApiError model errorContext e
Ok actualNewServerName ->
let
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | name = actualNewServerName }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
modelWithUpdatedProject =
GetterSetters.modelUpdateProject model newProject
-- Only update the view if we are on the server details view for the server we're interested in
updatedView =
case model.viewState of
ProjectView projectIdentifier projectViewParams (ServerDetail serverUuid_ serverDetailViewParams) ->
if server.osProps.uuid == serverUuid_ then
let
newServerDetailsViewParams =
{ serverDetailViewParams
| serverNamePendingConfirmation = Nothing
}
in
ProjectView projectIdentifier
projectViewParams
(ServerDetail serverUuid_ newServerDetailsViewParams)
else
model.viewState
_ ->
model.viewState
-- Later, maybe: Check that newServerName == actualNewServerName
in
ViewStateHelpers.modelUpdateViewState updatedView modelWithUpdatedProject
ReceiveSetServerMetadata intendedMetadataItem errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError model errorContext e
Ok newServerMetadata ->
-- Update the model after ensuring the intended metadata item was actually added
if List.member intendedMetadataItem newServerMetadata then
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = newServerMetadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
else
-- This is bonkers, throw an error
State.Error.processStringError
model
errorContext
"The metadata items returned by OpenStack did not include the metadata item that we tried to set."
ReceiveDeleteServerMetadata metadataKey errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError model errorContext e
Ok _ ->
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = List.filter (\i -> i.key /= metadataKey) oldServerDetails.metadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
ReceiveGuacamoleAuthToken result ->
let
errorContext =
ErrorContext
"Receive a response from Guacamole auth token API"
ErrorDebug
Nothing
modelUpdateGuacProps : ServerFromExoProps -> GuacTypes.LaunchedWithGuacProps -> Model
modelUpdateGuacProps exoOriginProps guacProps =
let
newOriginProps =
{ exoOriginProps | guacamoleStatus = GuacTypes.LaunchedWithGuacamole guacProps }
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
newModel
in
case server.exoProps.serverOrigin of
ServerFromExo exoOriginProps ->
case exoOriginProps.guacamoleStatus of
GuacTypes.LaunchedWithGuacamole oldGuacProps ->
let
newGuacProps =
case result of
Ok tokenValue ->
if server.osProps.details.openstackStatus == OSTypes.ServerActive then
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
tokenValue
model.clientCurrentTime
)
(RDPP.NotLoading Nothing)
}
else
-- Server is not active, this token won't work, so we don't store it
{ oldGuacProps
| authToken =
RDPP.empty
}
Err e ->
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
oldGuacProps.authToken.data
(RDPP.NotLoading (Just ( e, model.clientCurrentTime )))
}
in
( modelUpdateGuacProps
exoOriginProps
newGuacProps
, Cmd.none
)
GuacTypes.NotLaunchedWithGuacamole ->
State.Error.processStringError
model
errorContext
"Server does not appear to have been launched with Guacamole support"
ServerNotFromExo ->
State.Error.processStringError
model
errorContext
"Server does not appear to have been launched from Exosphere"
RequestServerAction func targetStatuses ->
let
oldExoProps =
server.exoProps
newServer =
Server server.osProps { oldExoProps | targetOpenstackStatus = targetStatuses } server.events
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, func newProject newServer )
ReceiveConsoleLog errorContext result ->
case server.exoProps.serverOrigin of
ServerNotFromExo ->
( model, Cmd.none )
ServerFromExo exoOriginProps ->
let
oldExoSetupStatus =
case exoOriginProps.exoSetupStatus.data of
RDPP.DontHave ->
ExoSetupUnknown
RDPP.DoHave s _ ->
s
( newExoSetupStatusRDPP, exoSetupStatusMetadataCmd ) =
case result of
Err httpError ->
( RDPP.RemoteDataPlusPlus
exoOriginProps.exoSetupStatus.data
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
, Cmd.none
)
Ok consoleLog ->
let
newExoSetupStatus =
Helpers.ExoSetupStatus.parseConsoleLogExoSetupStatus
oldExoSetupStatus
consoleLog
server.osProps.details.created
model.clientCurrentTime
cmd =
if newExoSetupStatus == oldExoSetupStatus then
Cmd.none
else
let
value =
Helpers.ExoSetupStatus.exoSetupStatusToStr newExoSetupStatus
metadataItem =
OSTypes.MetadataItem
"exoSetup"
value
in
Rest.Nova.requestSetServerMetadata project server.osProps.uuid metadataItem
in
( RDPP.RemoteDataPlusPlus
(RDPP.DoHave
newExoSetupStatus
model.clientCurrentTime
)
(RDPP.NotLoading Nothing)
, cmd
)
newResourceUsage =
case result of
Err httpError ->
RDPP.RemoteDataPlusPlus
exoOriginProps.resourceUsage.data
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
Ok consoleLog ->
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
(Helpers.ServerResourceUsage.parseConsoleLog
consoleLog
(RDPP.withDefault
Types.ServerResourceUsage.emptyResourceUsageHistory
exoOriginProps.resourceUsage
)
)
model.clientCurrentTime
)
(RDPP.NotLoading Nothing)
newOriginProps =
{ exoOriginProps
| resourceUsage = newResourceUsage
, exoSetupStatus = newExoSetupStatusRDPP
}
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
case result of
Err httpError ->
State.Error.processSynchronousApiError newModel errorContext httpError
Ok _ ->
( newModel, exoSetupStatusMetadataCmd )
processNewFloatingIp : Time.Posix -> Project -> OSTypes.FloatingIp -> Project
processNewFloatingIp time project floatingIp =
let
otherIps =
project.floatingIps
|> RDPP.withDefault []
|> List.filter (\i -> i.uuid /= floatingIp.uuid)
newIps =
floatingIp :: otherIps
in
{ project
| floatingIps =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave newIps time)
(RDPP.NotLoading Nothing)
}
createProject : Model -> OSTypes.ScopedAuthToken -> Endpoints -> ( Model, Cmd Msg )
createProject model authToken endpoints =
let
newProject =
{ secret = NoProjectSecret
, auth = authToken
-- Maybe todo, eliminate parallel data structures in auth and endpoints?
, endpoints = endpoints
, images = []
, servers = RDPP.RemoteDataPlusPlus RDPP.DontHave RDPP.Loading
, flavors = []
, keypairs = RemoteData.NotAsked
, volumes = RemoteData.NotAsked
, networks = RDPP.empty
, autoAllocatedNetworkUuid = RDPP.empty
, floatingIps = RDPP.empty
, ports = RDPP.empty
, securityGroups = []
, computeQuota = RemoteData.NotAsked
, volumeQuota = RemoteData.NotAsked
, pendingCredentialedRequests = []
}
newProjects =
newProject :: model.projects
newViewStateFunc =
-- If the user is selecting projects from an unscoped provider then don't interrupt them
case model.viewState of
NonProjectView (SelectProjects _ _) ->
\model_ -> ( model_, Cmd.none )
NonProjectView _ ->
ViewStateHelpers.setProjectView newProject <|
AllResources Defaults.allResourcesListViewParams
ProjectView _ _ _ ->
ViewStateHelpers.setProjectView newProject <|
AllResources Defaults.allResourcesListViewParams
newModel =
{ model
| projects = newProjects
}
in
( newModel
, [ Rest.Nova.requestServers
, Rest.Neutron.requestSecurityGroups
, Rest.Keystone.requestAppCredential model.clientUuid model.clientCurrentTime
]
|> List.map (\x -> x newProject)
|> Cmd.batch
)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestFloatingIps newProject.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts newProject.auth.project.uuid)
|> Helpers.pipelineCmd newViewStateFunc
createUnscopedProvider : Model -> OSTypes.UnscopedAuthToken -> HelperTypes.Url -> ( Model, Cmd Msg )
createUnscopedProvider model authToken authUrl =
let
newProvider =
{ authUrl = authUrl
, token = <PASSWORD>Token
, projectsAvailable = RemoteData.Loading
}
newProviders =
newProvider :: model.unscopedProviders
in
( { model | unscopedProviders = newProviders }
, Rest.Keystone.requestUnscopedProjects newProvider model.cloudCorsProxyUrl
)
requestDeleteServer : Project -> OSTypes.ServerUuid -> Bool -> ( Project, Cmd Msg )
requestDeleteServer project serverUuid retainFloatingIps =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server likely deleted already, do nothing
( project, Cmd.none )
Just server ->
let
oldExoProps =
server.exoProps
newServer =
{ server | exoProps = { oldExoProps | deletionAttempted = True } }
deleteFloatingIpCmds =
if retainFloatingIps then
[]
else
GetterSetters.getServerFloatingIps project server.osProps.uuid
|> List.map .uuid
|> List.map (Rest.Neutron.requestDeleteFloatingIp project)
newProject =
GetterSetters.projectUpdateServer project newServer
in
( newProject
, Cmd.batch
[ Rest.Nova.requestDeleteServer newProject newServer
, Cmd.batch deleteFloatingIpCmds
]
)
| true | module State.State exposing (update)
import AppUrl.Builder
import AppUrl.Parser
import Browser.Navigation
import Helpers.ExoSetupStatus
import Helpers.GetterSetters as GetterSetters
import Helpers.Helpers as Helpers
import Helpers.RemoteDataPlusPlus as RDPP
import Helpers.ServerResourceUsage
import Helpers.Url as UrlHelpers
import Http
import LocalStorage.LocalStorage as LocalStorage
import Maybe
import OpenStack.ServerPassword as OSServerPassword
import OpenStack.ServerTags as OSServerTags
import OpenStack.ServerVolumes as OSSvrVols
import OpenStack.Types as OSTypes
import OpenStack.Volumes as OSVolumes
import Orchestration.Orchestration as Orchestration
import Ports
import RemoteData
import Rest.ApiModelHelpers as ApiModelHelpers
import Rest.Glance
import Rest.Keystone
import Rest.Neutron
import Rest.Nova
import State.Auth
import State.Error
import State.ViewState as ViewStateHelpers
import Style.Toast
import Style.Widgets.NumericTextInput.NumericTextInput
import Task
import Time
import Toasty
import Types.Defaults as Defaults
import Types.Error as Error exposing (ErrorContext, ErrorLevel(..))
import Types.Guacamole as GuacTypes
import Types.HelperTypes as HelperTypes
import Types.ServerResourceUsage
import Types.Types
exposing
( Endpoints
, ExoSetupStatus(..)
, HttpRequestMethod(..)
, LoginView(..)
, Model
, Msg(..)
, NewServerNetworkOptions(..)
, NonProjectViewConstructor(..)
, OpenstackLoginFormEntryType(..)
, OpenstackLoginViewParams
, Project
, ProjectSecret(..)
, ProjectSpecificMsgConstructor(..)
, ProjectViewConstructor(..)
, Server
, ServerFromExoProps
, ServerOrigin(..)
, ServerSpecificMsgConstructor(..)
, TickInterval
, UnscopedProviderProject
, ViewState(..)
, currentExoServerVersion
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
{- We want to `setStorage` on every update. This function adds the setStorage
command for every step of the update function.
-}
let
( newModel, cmds ) =
updateUnderlying msg model
orchestrationTimeCmd =
-- Each trip through the runtime, we get the time and feed it to orchestration module
case msg of
DoOrchestration _ ->
Cmd.none
Tick _ _ ->
Cmd.none
_ ->
Task.perform (\posix -> DoOrchestration posix) Time.now
in
( newModel
, Cmd.batch
[ Ports.setStorage (LocalStorage.generateStoredState newModel)
, orchestrationTimeCmd
, cmds
]
)
updateUnderlying : Msg -> Model -> ( Model, Cmd Msg )
updateUnderlying msg model =
case msg of
ToastyMsg subMsg ->
Toasty.update Style.Toast.toastConfig ToastyMsg subMsg model
MsgChangeWindowSize x y ->
( { model | windowSize = { width = x, height = y } }, Cmd.none )
Tick interval time ->
processTick model interval time
DoOrchestration posixTime ->
Orchestration.orchModel model posixTime
SetNonProjectView nonProjectViewConstructor ->
ViewStateHelpers.setNonProjectView nonProjectViewConstructor model
HandleApiErrorWithBody errorContext error ->
State.Error.processSynchronousApiError model errorContext error
RequestUnscopedToken openstackLoginUnscoped ->
let
creds =
-- Ensure auth URL includes port number and version
{ openstackLoginUnscoped
| authUrl =
State.Auth.authUrlWithPortAndVersion openstackLoginUnscoped.authUrl
}
in
( model, Rest.Keystone.requestUnscopedAuthToken model.cloudCorsProxyUrl creds )
JetstreamLogin jetstreamCreds ->
let
openstackCredsList =
State.Auth.jetstreamToOpenstackCreds jetstreamCreds
cmds =
List.map
(\creds -> Rest.Keystone.requestUnscopedAuthToken model.cloudCorsProxyUrl creds)
openstackCredsList
in
( model, Cmd.batch cmds )
ReceiveScopedAuthToken ( metadata, response ) ->
case Rest.Keystone.decodeScopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
model
(ErrorContext
"decode scoped auth token"
ErrorCrit
Nothing
)
error
Ok authToken ->
case Helpers.serviceCatalogToEndpoints authToken.catalog of
Err e ->
State.Error.processStringError
model
(ErrorContext
"Decode project endpoints"
ErrorCrit
(Just "Please check with your cloud administrator or the Exosphere developers.")
)
e
Ok endpoints ->
let
projectId =
authToken.project.uuid
in
-- If we don't have a project with same name + authUrl then create one, if we do then update its OSTypes.AuthToken
-- This code ensures we don't end up with duplicate projects on the same provider in our model.
case
GetterSetters.projectLookup model <| projectId
of
Nothing ->
createProject model authToken endpoints
Just project ->
-- If we don't have an application credential for this project yet, then get one
let
appCredCmd =
case project.secret of
ApplicationCredential _ ->
Cmd.none
_ ->
Rest.Keystone.requestAppCredential
model.clientUuid
model.clientCurrentTime
project
( newModel, updateTokenCmd ) =
State.Auth.projectUpdateAuthToken model project authToken
in
( newModel, Cmd.batch [ appCredCmd, updateTokenCmd ] )
ReceiveUnscopedAuthToken keystoneUrl ( metadata, response ) ->
case Rest.Keystone.decodeUnscopedAuthToken <| Http.GoodStatus_ metadata response of
Err error ->
State.Error.processStringError
model
(ErrorContext
"decode scoped auth token"
ErrorCrit
Nothing
)
error
Ok authToken ->
case
GetterSetters.providerLookup model keystoneUrl
of
Just unscopedProvider ->
-- We already have an unscoped provider in the model with the same auth URL, update its token
State.Auth.unscopedProviderUpdateAuthToken
model
unscopedProvider
authToken
Nothing ->
-- We don't have an unscoped provider with the same auth URL, create it
createUnscopedProvider model authToken keystoneUrl
ReceiveUnscopedProjects keystoneUrl unscopedProjects ->
case
GetterSetters.providerLookup model keystoneUrl
of
Just provider ->
let
newProvider =
{ provider | projectsAvailable = RemoteData.Success unscopedProjects }
newModel =
GetterSetters.modelUpdateUnscopedProvider model newProvider
in
-- If we are not already on a SelectProjects view, then go there
case newModel.viewState of
NonProjectView (SelectProjects _ _) ->
( newModel, Cmd.none )
_ ->
ViewStateHelpers.modelUpdateViewState
(NonProjectView <|
SelectProjects newProvider.authUrl []
)
newModel
Nothing ->
-- Provider not found, may have been removed, nothing to do
( model, Cmd.none )
RequestProjectLoginFromProvider keystoneUrl desiredProjects ->
case GetterSetters.providerLookup model keystoneUrl of
Just provider ->
let
buildLoginRequest : UnscopedProviderProject -> Cmd Msg
buildLoginRequest project =
Rest.Keystone.requestScopedAuthToken
model.cloudCorsProxyUrl
<|
OSTypes.TokenCreds
keystoneUrl
provider.token
project.project.uuid
loginRequests =
List.map buildLoginRequest desiredProjects
|> Cmd.batch
-- Remove unscoped provider from model now that we have selected projects from it
newUnscopedProviders =
List.filter
(\p -> p.authUrl /= keystoneUrl)
model.unscopedProviders
-- If we still have at least one unscoped provider in the model then ask the user to choose projects from it
newViewStateFunc =
case List.head newUnscopedProviders of
Just unscopedProvider ->
ViewStateHelpers.setNonProjectView
(SelectProjects unscopedProvider.authUrl [])
Nothing ->
-- If we have at least one project then show it, else show the login page
case List.head model.projects of
Just project ->
ViewStateHelpers.setProjectView
project
<|
AllResources Defaults.allResourcesListViewParams
Nothing ->
ViewStateHelpers.setNonProjectView
LoginPicker
modelUpdatedUnscopedProviders =
{ model | unscopedProviders = newUnscopedProviders }
in
( modelUpdatedUnscopedProviders, loginRequests )
|> Helpers.pipelineCmd newViewStateFunc
Nothing ->
State.Error.processStringError
model
(ErrorContext
("look for OpenStack provider with Keystone URL " ++ keystoneUrl)
ErrorCrit
Nothing
)
"Provider could not found in Exosphere's list of Providers."
ProjectMsg projectIdentifier innerMsg ->
case GetterSetters.projectLookup model projectIdentifier of
Nothing ->
-- Project not found, may have been removed, nothing to do
( model, Cmd.none )
Just project ->
processProjectSpecificMsg model project innerMsg
{- Form inputs -}
SubmitOpenRc openstackCreds openRc ->
let
newCreds =
State.Auth.processOpenRc openstackCreds openRc
newViewState =
NonProjectView <| Login <| LoginOpenstack <| OpenstackLoginViewParams newCreds openRc LoginViewCredsEntry
in
ViewStateHelpers.modelUpdateViewState newViewState model
OpenNewWindow url ->
( model, Ports.openNewWindow url )
NavigateToUrl url ->
( model, Browser.Navigation.load url )
UrlChange url ->
-- This handles presses of the browser back/forward button
let
exoJustSetThisUrl =
-- If this is a URL that Exosphere just set via StateHelpers.updateViewState, then ignore it
UrlHelpers.urlPathQueryMatches url model.prevUrl
in
if exoJustSetThisUrl then
( model, Cmd.none )
else
case
AppUrl.Parser.urlToViewState
model.urlPathPrefix
(ViewStateHelpers.defaultViewState model)
url
of
Just newViewState ->
( { model
| viewState = newViewState
, prevUrl = AppUrl.Builder.viewStateToUrl model.urlPathPrefix newViewState
}
, Cmd.none
)
Nothing ->
( { model
| viewState = NonProjectView PageNotFound
}
, Cmd.none
)
SetStyle styleMode ->
let
oldStyle =
model.style
newStyle =
{ oldStyle | styleMode = styleMode }
in
( { model | style = newStyle }, Cmd.none )
NoOp ->
( model, Cmd.none )
processTick : Model -> TickInterval -> Time.Posix -> ( Model, Cmd Msg )
processTick model interval time =
let
serverVolsNeedFrequentPoll : Project -> Server -> Bool
serverVolsNeedFrequentPoll project server =
GetterSetters.getVolsAttachedToServer project server
|> List.any volNeedsFrequentPoll
volNeedsFrequentPoll volume =
not <|
List.member
volume.status
[ OSTypes.Available
, OSTypes.Maintenance
, OSTypes.InUse
, OSTypes.Error
, OSTypes.ErrorDeleting
, OSTypes.ErrorBackingUp
, OSTypes.ErrorRestoring
, OSTypes.ErrorExtending
]
viewIndependentCmd =
if interval == 5 then
Task.perform (\posix -> DoOrchestration posix) Time.now
else
Cmd.none
( viewDependentModel, viewDependentCmd ) =
{- TODO move some of this to Orchestration? -}
case model.viewState of
NonProjectView _ ->
( model, Cmd.none )
ProjectView projectName _ projectViewState ->
case GetterSetters.projectLookup model projectName of
Nothing ->
{- Should this throw an error? -}
( model, Cmd.none )
Just project ->
let
pollVolumes : ( Model, Cmd Msg )
pollVolumes =
( model
, case interval of
5 ->
if List.any volNeedsFrequentPoll (RemoteData.withDefault [] project.volumes) then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
in
case projectViewState of
AllResources _ ->
pollVolumes
ServerDetail serverUuid _ ->
let
volCmd =
OSVolumes.requestVolumes project
in
case interval of
5 ->
case GetterSetters.serverLookup project serverUuid of
Just server ->
( model
, if serverVolsNeedFrequentPoll project server then
volCmd
else
Cmd.none
)
Nothing ->
( model, Cmd.none )
300 ->
( model, volCmd )
_ ->
( model, Cmd.none )
ListProjectVolumes _ ->
pollVolumes
VolumeDetail volumeUuid _ ->
( model
, case interval of
5 ->
case GetterSetters.volumeLookup project volumeUuid of
Nothing ->
Cmd.none
Just volume ->
if volNeedsFrequentPoll volume then
OSVolumes.requestVolumes project
else
Cmd.none
60 ->
OSVolumes.requestVolumes project
_ ->
Cmd.none
)
_ ->
( model, Cmd.none )
in
( { viewDependentModel | clientCurrentTime = time }
, Cmd.batch
[ viewDependentCmd
, viewIndependentCmd
]
)
processProjectSpecificMsg : Model -> Project -> ProjectSpecificMsgConstructor -> ( Model, Cmd Msg )
processProjectSpecificMsg model project msg =
case msg of
SetProjectView projectViewConstructor ->
ViewStateHelpers.setProjectView project projectViewConstructor model
PrepareCredentialedRequest requestProto posixTime ->
let
-- Add proxy URL
requestNeedingToken =
requestProto model.cloudCorsProxyUrl
currentTimeMillis =
posixTime |> Time.posixToMillis
tokenExpireTimeMillis =
project.auth.expiresAt |> Time.posixToMillis
tokenExpired =
-- Token expiring within 5 minutes
tokenExpireTimeMillis < currentTimeMillis + 300000
in
if not tokenExpired then
-- Token still valid, fire the request with current token
( model, requestNeedingToken project.auth.tokenValue )
else
-- Token is expired (or nearly expired) so we add request to list of pending requests and refresh that token
let
newPQRs =
requestNeedingToken :: project.pendingCredentialedRequests
newProject =
{ project | pendingCredentialedRequests = newPQRs }
newModel =
GetterSetters.modelUpdateProject model newProject
cmdResult =
State.Auth.requestAuthToken newModel newProject
in
case cmdResult of
Err e ->
let
errorContext =
ErrorContext
("Refresh authentication token for project " ++ project.auth.project.name)
ErrorCrit
(Just "Please remove this project from Exosphere and add it again.")
in
State.Error.processStringError newModel errorContext e
Ok cmd ->
( newModel, cmd )
ToggleCreatePopup ->
case model.viewState of
ProjectView projectId viewParams viewConstructor ->
let
newViewState =
ProjectView
projectId
{ viewParams
| createPopup = not viewParams.createPopup
}
viewConstructor
in
ViewStateHelpers.modelUpdateViewState newViewState model
_ ->
( model, Cmd.none )
RemoveProject ->
let
newProjects =
List.filter (\p -> p.auth.project.uuid /= project.auth.project.uuid) model.projects
newViewState =
case model.viewState of
NonProjectView _ ->
-- If we are not in a project-specific view then stay there
model.viewState
ProjectView _ _ _ ->
-- If we have any projects switch to the first one in the list, otherwise switch to login view
case List.head newProjects of
Just p ->
ProjectView
p.auth.project.uuid
Defaults.projectViewParams
<|
AllResources
Defaults.allResourcesListViewParams
Nothing ->
NonProjectView <| LoginPicker
modelUpdatedProjects =
{ model | projects = newProjects }
in
ViewStateHelpers.modelUpdateViewState newViewState modelUpdatedProjects
ServerMsg serverUuid serverMsgConstructor ->
case GetterSetters.serverLookup project serverUuid of
Nothing ->
let
errorContext =
ErrorContext
"receive results of API call for a specific server"
ErrorDebug
Nothing
in
State.Error.processStringError
model
errorContext
(String.join " "
[ "Instance"
, serverUuid
, "does not exist in the model, it may have been deleted."
]
)
Just server ->
processServerSpecificMsg model project server serverMsgConstructor
RequestServers ->
ApiModelHelpers.requestServers project.auth.project.uuid model
RequestCreateServer viewParams networkUuid ->
let
createServerRequest =
{ name = viewParams.serverName
, count = viewParams.count
, imageUuid = viewParams.imageUuid
, flavorUuid = viewParams.flavorUuid
, volBackedSizeGb =
viewParams.volSizeTextInput
|> Maybe.andThen Style.Widgets.NumericTextInput.NumericTextInput.toMaybe
, networkUuid = networkUuid
, keypairName = viewParams.keypairName
, userData =
Helpers.renderUserDataTemplate
project
viewParams.userDataTemplate
viewParams.keypairName
(viewParams.deployGuacamole |> Maybe.withDefault False)
viewParams.deployDesktopEnvironment
viewParams.installOperatingSystemUpdates
model.instanceConfigMgtRepoUrl
model.instanceConfigMgtRepoCheckout
, metadata =
Helpers.newServerMetadata
currentExoServerVersion
model.clientUuid
(viewParams.deployGuacamole |> Maybe.withDefault False)
viewParams.deployDesktopEnvironment
project.auth.user.name
viewParams.floatingIpCreationOption
}
in
( model, Rest.Nova.requestCreateServer project createServerRequest )
RequestCreateVolume name size ->
let
createVolumeRequest =
{ name = name
, size = size
}
in
( model, OSVolumes.requestCreateVolume project createVolumeRequest )
RequestDeleteVolume volumeUuid ->
( model, OSVolumes.requestDeleteVolume project volumeUuid )
RequestDetachVolume volumeUuid ->
let
maybeVolume =
OSVolumes.volumeLookup project volumeUuid
maybeServerUuid =
maybeVolume
|> Maybe.map (GetterSetters.getServersWithVolAttached project)
|> Maybe.andThen List.head
in
case maybeServerUuid of
Just serverUuid ->
( model, OSSvrVols.requestDetachVolume project serverUuid volumeUuid )
Nothing ->
State.Error.processStringError
model
(ErrorContext
("look for server UUID with attached volume " ++ volumeUuid)
ErrorCrit
Nothing
)
"Could not determine server attached to this volume."
RequestDeleteFloatingIp floatingIpAddress ->
( model, Rest.Neutron.requestDeleteFloatingIp project floatingIpAddress )
RequestAssignFloatingIp port_ floatingIpUuid ->
let
( newModel, setViewCmd ) =
ViewStateHelpers.setProjectView project (ListFloatingIps Defaults.floatingIpListViewParams) model
in
( newModel
, Cmd.batch
[ setViewCmd
, Rest.Neutron.requestAssignFloatingIp project port_ floatingIpUuid
]
)
RequestUnassignFloatingIp floatingIpUuid ->
( model, Rest.Neutron.requestUnassignFloatingIp project floatingIpUuid )
ReceiveImages images ->
Rest.Glance.receiveImages model project images
RequestDeleteServers serverUuidsToDelete ->
let
applyDelete : OSTypes.ServerUuid -> ( Project, Cmd Msg ) -> ( Project, Cmd Msg )
applyDelete serverUuid projCmdTuple =
let
( delServerProj, delServerCmd ) =
requestDeleteServer (Tuple.first projCmdTuple) serverUuid False
in
( delServerProj, Cmd.batch [ Tuple.second projCmdTuple, delServerCmd ] )
( newProject, cmd ) =
List.foldl
applyDelete
( project, Cmd.none )
serverUuidsToDelete
in
( GetterSetters.modelUpdateProject model newProject
, cmd
)
ReceiveServers errorContext result ->
case result of
Ok servers ->
Rest.Nova.receiveServers model project servers
Err e ->
let
oldServersData =
project.servers.data
newProject =
{ project
| servers =
RDPP.RemoteDataPlusPlus
oldServersData
(RDPP.NotLoading (Just ( e, model.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext e
ReceiveServer serverUuid errorContext result ->
case result of
Ok server ->
Rest.Nova.receiveServer model project server
Err httpErrorWithBody ->
let
httpError =
httpErrorWithBody.error
non404 =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server not in project, may have been deleted, ignoring this error
( model, Cmd.none )
Just server ->
-- Reset receivedTime and loadingSeparately
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps
| receivedTime = Nothing
, loadingSeparately = False
}
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext httpErrorWithBody
in
case httpError of
Http.BadStatus code ->
if code == 404 then
let
newErrorContext =
{ errorContext
| level = Error.ErrorDebug
, actionContext =
errorContext.actionContext
++ " -- 404 means server may have been deleted"
}
newProject =
GetterSetters.projectDeleteServer project serverUuid
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel newErrorContext httpErrorWithBody
else
non404
_ ->
non404
ReceiveFlavors flavors ->
Rest.Nova.receiveFlavors model project flavors
RequestKeypairs ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success _ ->
project.keypairs
_ ->
RemoteData.Loading
newProject =
{ project | keypairs = newKeypairs }
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel
, Rest.Nova.requestKeypairs newProject
)
ReceiveKeypairs keypairs ->
Rest.Nova.receiveKeypairs model project keypairs
RequestCreateKeypair keypairName publicKey ->
( model, Rest.Nova.requestCreateKeypair project keypairName publicKey )
ReceiveCreateKeypair keypair ->
let
newProject =
GetterSetters.projectUpdateKeypair project keypair
newModel =
GetterSetters.modelUpdateProject model newProject
in
ViewStateHelpers.setProjectView newProject (ListKeypairs Defaults.keypairListViewParams) newModel
RequestDeleteKeypair keypairName ->
( model, Rest.Nova.requestDeleteKeypair project keypairName )
ReceiveDeleteKeypair errorContext keypairName result ->
case result of
Err httpError ->
State.Error.processStringError model errorContext (Helpers.httpErrorToString httpError)
Ok () ->
let
newKeypairs =
case project.keypairs of
RemoteData.Success keypairs ->
keypairs
|> List.filter (\k -> k.name /= keypairName)
|> RemoteData.Success
_ ->
project.keypairs
newProject =
{ project | keypairs = newKeypairs }
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
ReceiveCreateServer _ ->
let
newViewState =
ProjectView
project.auth.project.uuid
Defaults.projectViewParams
<|
AllResources
Defaults.allResourcesListViewParams
in
( model, Cmd.none )
|> Helpers.pipelineCmd
(ApiModelHelpers.requestServers project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestNetworks project.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts project.auth.project.uuid)
|> Helpers.pipelineCmd
(ViewStateHelpers.modelUpdateViewState newViewState)
ReceiveNetworks errorContext result ->
case result of
Ok networks ->
Rest.Neutron.receiveNetworks model project networks
Err httpError ->
let
oldNetworksData =
project.networks.data
newProject =
{ project
| networks =
RDPP.RemoteDataPlusPlus
oldNetworksData
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext httpError
ReceiveAutoAllocatedNetwork errorContext result ->
let
newProject =
case result of
Ok netUuid ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave netUuid model.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
Err httpError ->
{ project
| autoAllocatedNetworkUuid =
RDPP.RemoteDataPlusPlus
project.autoAllocatedNetworkUuid.data
(RDPP.NotLoading
(Just
( httpError
, model.clientCurrentTime
)
)
)
}
newViewState =
case model.viewState of
ProjectView _ viewParams projectViewConstructor ->
case projectViewConstructor of
CreateServer createServerViewParams ->
if createServerViewParams.networkUuid == Nothing then
case Helpers.newServerNetworkOptions newProject of
AutoSelectedNetwork netUuid ->
ProjectView
project.auth.project.uuid
viewParams
(CreateServer
{ createServerViewParams
| networkUuid = Just netUuid
}
)
_ ->
model.viewState
else
model.viewState
_ ->
model.viewState
_ ->
model.viewState
newModel =
GetterSetters.modelUpdateProject
{ model | viewState = newViewState }
newProject
in
case result of
Ok _ ->
ApiModelHelpers.requestNetworks project.auth.project.uuid newModel
Err httpError ->
State.Error.processSynchronousApiError newModel errorContext httpError
|> Helpers.pipelineCmd (ApiModelHelpers.requestNetworks project.auth.project.uuid)
ReceiveFloatingIps ips ->
Rest.Neutron.receiveFloatingIps model project ips
ReceivePorts errorContext result ->
case result of
Ok ports ->
let
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave ports model.clientCurrentTime)
(RDPP.NotLoading Nothing)
}
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
Err httpError ->
let
oldPortsData =
project.ports.data
newProject =
{ project
| ports =
RDPP.RemoteDataPlusPlus
oldPortsData
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
}
newModel =
GetterSetters.modelUpdateProject model newProject
in
State.Error.processSynchronousApiError newModel errorContext httpError
ReceiveDeleteFloatingIp uuid ->
Rest.Neutron.receiveDeleteFloatingIp model project uuid
ReceiveAssignFloatingIp floatingIp ->
-- TODO update servers so that new assignment is reflected in the UI
let
newProject =
processNewFloatingIp model.clientCurrentTime project floatingIp
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
ReceiveUnassignFloatingIp floatingIp ->
-- TODO update servers so that unassignment is reflected in the UI
let
newProject =
processNewFloatingIp model.clientCurrentTime project floatingIp
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
ReceiveSecurityGroups groups ->
Rest.Neutron.receiveSecurityGroupsAndEnsureExoGroup model project groups
ReceiveCreateExoSecurityGroup group ->
Rest.Neutron.receiveCreateExoSecurityGroupAndRequestCreateRules model project group
ReceiveCreateVolume ->
{- Should we add new volume to model now? -}
ViewStateHelpers.setProjectView project (ListProjectVolumes Defaults.volumeListViewParams) model
ReceiveVolumes volumes ->
let
-- Look for any server backing volumes that were created with no name, and give them a reasonable name
updateVolNameCmds : List (Cmd Msg)
updateVolNameCmds =
RDPP.withDefault [] project.servers
-- List of tuples containing server and Maybe boot vol
|> List.map
(\s ->
( s
, Helpers.getBootVol
(RemoteData.withDefault
[]
project.volumes
)
s.osProps.uuid
)
)
-- We only care about servers created by exosphere
|> List.filter
(\t ->
case Tuple.first t |> .exoProps |> .serverOrigin of
ServerFromExo _ ->
True
ServerNotFromExo ->
False
)
-- We only care about servers created as current OpenStack user
|> List.filter
(\t ->
(Tuple.first t).osProps.details.userUuid
== project.auth.user.uuid
)
-- We only care about servers with a non-empty name
|> List.filter
(\t ->
Tuple.first t
|> .osProps
|> .name
|> String.isEmpty
|> not
)
-- We only care about volume-backed servers
|> List.filterMap
(\t ->
case t of
( server, Just vol ) ->
-- Flatten second part of tuple
Just ( server, vol )
_ ->
Nothing
)
-- We only care about unnamed backing volumes
|> List.filter
(\t ->
Tuple.second t
|> .name
|> String.isEmpty
)
|> List.map
(\t ->
OSVolumes.requestUpdateVolumeName
project
(t |> Tuple.second |> .uuid)
("boot-vol-"
++ (t |> Tuple.first |> .osProps |> .name)
)
)
newProject =
{ project | volumes = RemoteData.succeed volumes }
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.batch updateVolNameCmds )
ReceiveDeleteVolume ->
( model, OSVolumes.requestVolumes project )
ReceiveUpdateVolumeName ->
( model, OSVolumes.requestVolumes project )
ReceiveAttachVolume attachment ->
ViewStateHelpers.setProjectView project (MountVolInstructions attachment) model
ReceiveDetachVolume ->
ViewStateHelpers.setProjectView project (ListProjectVolumes Defaults.volumeListViewParams) model
ReceiveAppCredential appCredential ->
let
newProject =
{ project | secret = ApplicationCredential appCredential }
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
ReceiveComputeQuota quota ->
let
newProject =
{ project | computeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
ReceiveVolumeQuota quota ->
let
newProject =
{ project | volumeQuota = RemoteData.Success quota }
in
( GetterSetters.modelUpdateProject model newProject, Cmd.none )
processServerSpecificMsg : Model -> Project -> Server -> ServerSpecificMsgConstructor -> ( Model, Cmd Msg )
processServerSpecificMsg model project server serverMsgConstructor =
case serverMsgConstructor of
RequestServer ->
ApiModelHelpers.requestServer project.auth.project.uuid server.osProps.uuid model
RequestDeleteServer retainFloatingIps ->
let
( newProject, cmd ) =
requestDeleteServer project server.osProps.uuid retainFloatingIps
in
( GetterSetters.modelUpdateProject model newProject, cmd )
RequestAttachVolume volumeUuid ->
( model, OSSvrVols.requestAttachVolume project server.osProps.uuid volumeUuid )
RequestCreateServerImage imageName ->
let
newViewState =
ProjectView
project.auth.project.uuid
{ createPopup = False }
<|
AllResources
Defaults.allResourcesListViewParams
createImageCmd =
Rest.Nova.requestCreateServerImage project server.osProps.uuid imageName
in
( model, createImageCmd )
|> Helpers.pipelineCmd
(ViewStateHelpers.modelUpdateViewState newViewState)
RequestSetServerName newServerName ->
( model, Rest.Nova.requestSetServerName project server.osProps.uuid newServerName )
ReceiveServerEvents _ result ->
case result of
Ok serverEvents ->
let
newServer =
{ server | events = RemoteData.Success serverEvents }
newProject =
GetterSetters.projectUpdateServer project newServer
in
( GetterSetters.modelUpdateProject model newProject
, Cmd.none
)
Err _ ->
-- Dropping this on the floor for now, someday we may want to do something different
( model, Cmd.none )
ReceiveConsoleUrl url ->
Rest.Nova.receiveConsoleUrl model project server url
ReceiveDeleteServer ->
let
( serverDeletedModel, urlCmd ) =
let
newViewState =
case model.viewState of
ProjectView projectId viewParams (ServerDetail viewServerUuid _) ->
if viewServerUuid == server.osProps.uuid then
ProjectView
projectId
viewParams
(AllResources
Defaults.allResourcesListViewParams
)
else
model.viewState
_ ->
model.viewState
newProject =
let
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | deletionAttempted = True }
newServer =
{ server | exoProps = newExoProps }
in
GetterSetters.projectUpdateServer project newServer
modelUpdatedProject =
GetterSetters.modelUpdateProject model newProject
in
ViewStateHelpers.modelUpdateViewState newViewState modelUpdatedProject
in
( serverDeletedModel, urlCmd )
ReceiveCreateFloatingIp errorContext result ->
case result of
Ok ip ->
Rest.Neutron.receiveCreateFloatingIp model project server ip
Err httpErrorWithBody ->
let
newErrorContext =
if GetterSetters.serverPresentNotDeleting model server.osProps.uuid then
errorContext
else
{ errorContext | level = ErrorDebug }
in
State.Error.processSynchronousApiError model newErrorContext httpErrorWithBody
ReceiveServerPassword password ->
if String.isEmpty password then
( model, Cmd.none )
else
let
tag =
"exoPw:" ++ password
cmd =
case server.exoProps.serverOrigin of
ServerNotFromExo ->
Cmd.none
ServerFromExo serverFromExoProps ->
if serverFromExoProps.exoServerVersion >= 1 then
Cmd.batch
[ OSServerTags.requestCreateServerTag project server.osProps.uuid tag
, OSServerPassword.requestClearServerPassword project server.osProps.uuid
]
else
Cmd.none
in
( model, cmd )
ReceiveSetServerName _ errorContext result ->
case result of
Err e ->
State.Error.processSynchronousApiError model errorContext e
Ok actualNewServerName ->
let
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | name = actualNewServerName }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
modelWithUpdatedProject =
GetterSetters.modelUpdateProject model newProject
-- Only update the view if we are on the server details view for the server we're interested in
updatedView =
case model.viewState of
ProjectView projectIdentifier projectViewParams (ServerDetail serverUuid_ serverDetailViewParams) ->
if server.osProps.uuid == serverUuid_ then
let
newServerDetailsViewParams =
{ serverDetailViewParams
| serverNamePendingConfirmation = Nothing
}
in
ProjectView projectIdentifier
projectViewParams
(ServerDetail serverUuid_ newServerDetailsViewParams)
else
model.viewState
_ ->
model.viewState
-- Later, maybe: Check that newServerName == actualNewServerName
in
ViewStateHelpers.modelUpdateViewState updatedView modelWithUpdatedProject
ReceiveSetServerMetadata intendedMetadataItem errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError model errorContext e
Ok newServerMetadata ->
-- Update the model after ensuring the intended metadata item was actually added
if List.member intendedMetadataItem newServerMetadata then
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = newServerMetadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
else
-- This is bonkers, throw an error
State.Error.processStringError
model
errorContext
"The metadata items returned by OpenStack did not include the metadata item that we tried to set."
ReceiveDeleteServerMetadata metadataKey errorContext result ->
case result of
Err e ->
-- Error from API
State.Error.processSynchronousApiError model errorContext e
Ok _ ->
let
oldServerDetails =
server.osProps.details
newServerDetails =
{ oldServerDetails | metadata = List.filter (\i -> i.key /= metadataKey) oldServerDetails.metadata }
oldOsProps =
server.osProps
newOsProps =
{ oldOsProps | details = newServerDetails }
newServer =
{ server | osProps = newOsProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, Cmd.none )
ReceiveGuacamoleAuthToken result ->
let
errorContext =
ErrorContext
"Receive a response from Guacamole auth token API"
ErrorDebug
Nothing
modelUpdateGuacProps : ServerFromExoProps -> GuacTypes.LaunchedWithGuacProps -> Model
modelUpdateGuacProps exoOriginProps guacProps =
let
newOriginProps =
{ exoOriginProps | guacamoleStatus = GuacTypes.LaunchedWithGuacamole guacProps }
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
newModel
in
case server.exoProps.serverOrigin of
ServerFromExo exoOriginProps ->
case exoOriginProps.guacamoleStatus of
GuacTypes.LaunchedWithGuacamole oldGuacProps ->
let
newGuacProps =
case result of
Ok tokenValue ->
if server.osProps.details.openstackStatus == OSTypes.ServerActive then
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
tokenValue
model.clientCurrentTime
)
(RDPP.NotLoading Nothing)
}
else
-- Server is not active, this token won't work, so we don't store it
{ oldGuacProps
| authToken =
RDPP.empty
}
Err e ->
{ oldGuacProps
| authToken =
RDPP.RemoteDataPlusPlus
oldGuacProps.authToken.data
(RDPP.NotLoading (Just ( e, model.clientCurrentTime )))
}
in
( modelUpdateGuacProps
exoOriginProps
newGuacProps
, Cmd.none
)
GuacTypes.NotLaunchedWithGuacamole ->
State.Error.processStringError
model
errorContext
"Server does not appear to have been launched with Guacamole support"
ServerNotFromExo ->
State.Error.processStringError
model
errorContext
"Server does not appear to have been launched from Exosphere"
RequestServerAction func targetStatuses ->
let
oldExoProps =
server.exoProps
newServer =
Server server.osProps { oldExoProps | targetOpenstackStatus = targetStatuses } server.events
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
( newModel, func newProject newServer )
ReceiveConsoleLog errorContext result ->
case server.exoProps.serverOrigin of
ServerNotFromExo ->
( model, Cmd.none )
ServerFromExo exoOriginProps ->
let
oldExoSetupStatus =
case exoOriginProps.exoSetupStatus.data of
RDPP.DontHave ->
ExoSetupUnknown
RDPP.DoHave s _ ->
s
( newExoSetupStatusRDPP, exoSetupStatusMetadataCmd ) =
case result of
Err httpError ->
( RDPP.RemoteDataPlusPlus
exoOriginProps.exoSetupStatus.data
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
, Cmd.none
)
Ok consoleLog ->
let
newExoSetupStatus =
Helpers.ExoSetupStatus.parseConsoleLogExoSetupStatus
oldExoSetupStatus
consoleLog
server.osProps.details.created
model.clientCurrentTime
cmd =
if newExoSetupStatus == oldExoSetupStatus then
Cmd.none
else
let
value =
Helpers.ExoSetupStatus.exoSetupStatusToStr newExoSetupStatus
metadataItem =
OSTypes.MetadataItem
"exoSetup"
value
in
Rest.Nova.requestSetServerMetadata project server.osProps.uuid metadataItem
in
( RDPP.RemoteDataPlusPlus
(RDPP.DoHave
newExoSetupStatus
model.clientCurrentTime
)
(RDPP.NotLoading Nothing)
, cmd
)
newResourceUsage =
case result of
Err httpError ->
RDPP.RemoteDataPlusPlus
exoOriginProps.resourceUsage.data
(RDPP.NotLoading (Just ( httpError, model.clientCurrentTime )))
Ok consoleLog ->
RDPP.RemoteDataPlusPlus
(RDPP.DoHave
(Helpers.ServerResourceUsage.parseConsoleLog
consoleLog
(RDPP.withDefault
Types.ServerResourceUsage.emptyResourceUsageHistory
exoOriginProps.resourceUsage
)
)
model.clientCurrentTime
)
(RDPP.NotLoading Nothing)
newOriginProps =
{ exoOriginProps
| resourceUsage = newResourceUsage
, exoSetupStatus = newExoSetupStatusRDPP
}
oldExoProps =
server.exoProps
newExoProps =
{ oldExoProps | serverOrigin = ServerFromExo newOriginProps }
newServer =
{ server | exoProps = newExoProps }
newProject =
GetterSetters.projectUpdateServer project newServer
newModel =
GetterSetters.modelUpdateProject model newProject
in
case result of
Err httpError ->
State.Error.processSynchronousApiError newModel errorContext httpError
Ok _ ->
( newModel, exoSetupStatusMetadataCmd )
processNewFloatingIp : Time.Posix -> Project -> OSTypes.FloatingIp -> Project
processNewFloatingIp time project floatingIp =
let
otherIps =
project.floatingIps
|> RDPP.withDefault []
|> List.filter (\i -> i.uuid /= floatingIp.uuid)
newIps =
floatingIp :: otherIps
in
{ project
| floatingIps =
RDPP.RemoteDataPlusPlus
(RDPP.DoHave newIps time)
(RDPP.NotLoading Nothing)
}
createProject : Model -> OSTypes.ScopedAuthToken -> Endpoints -> ( Model, Cmd Msg )
createProject model authToken endpoints =
let
newProject =
{ secret = NoProjectSecret
, auth = authToken
-- Maybe todo, eliminate parallel data structures in auth and endpoints?
, endpoints = endpoints
, images = []
, servers = RDPP.RemoteDataPlusPlus RDPP.DontHave RDPP.Loading
, flavors = []
, keypairs = RemoteData.NotAsked
, volumes = RemoteData.NotAsked
, networks = RDPP.empty
, autoAllocatedNetworkUuid = RDPP.empty
, floatingIps = RDPP.empty
, ports = RDPP.empty
, securityGroups = []
, computeQuota = RemoteData.NotAsked
, volumeQuota = RemoteData.NotAsked
, pendingCredentialedRequests = []
}
newProjects =
newProject :: model.projects
newViewStateFunc =
-- If the user is selecting projects from an unscoped provider then don't interrupt them
case model.viewState of
NonProjectView (SelectProjects _ _) ->
\model_ -> ( model_, Cmd.none )
NonProjectView _ ->
ViewStateHelpers.setProjectView newProject <|
AllResources Defaults.allResourcesListViewParams
ProjectView _ _ _ ->
ViewStateHelpers.setProjectView newProject <|
AllResources Defaults.allResourcesListViewParams
newModel =
{ model
| projects = newProjects
}
in
( newModel
, [ Rest.Nova.requestServers
, Rest.Neutron.requestSecurityGroups
, Rest.Keystone.requestAppCredential model.clientUuid model.clientCurrentTime
]
|> List.map (\x -> x newProject)
|> Cmd.batch
)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestFloatingIps newProject.auth.project.uuid)
|> Helpers.pipelineCmd
(ApiModelHelpers.requestPorts newProject.auth.project.uuid)
|> Helpers.pipelineCmd newViewStateFunc
createUnscopedProvider : Model -> OSTypes.UnscopedAuthToken -> HelperTypes.Url -> ( Model, Cmd Msg )
createUnscopedProvider model authToken authUrl =
let
newProvider =
{ authUrl = authUrl
, token = PI:PASSWORD:<PASSWORD>END_PIToken
, projectsAvailable = RemoteData.Loading
}
newProviders =
newProvider :: model.unscopedProviders
in
( { model | unscopedProviders = newProviders }
, Rest.Keystone.requestUnscopedProjects newProvider model.cloudCorsProxyUrl
)
requestDeleteServer : Project -> OSTypes.ServerUuid -> Bool -> ( Project, Cmd Msg )
requestDeleteServer project serverUuid retainFloatingIps =
case GetterSetters.serverLookup project serverUuid of
Nothing ->
-- Server likely deleted already, do nothing
( project, Cmd.none )
Just server ->
let
oldExoProps =
server.exoProps
newServer =
{ server | exoProps = { oldExoProps | deletionAttempted = True } }
deleteFloatingIpCmds =
if retainFloatingIps then
[]
else
GetterSetters.getServerFloatingIps project server.osProps.uuid
|> List.map .uuid
|> List.map (Rest.Neutron.requestDeleteFloatingIp project)
newProject =
GetterSetters.projectUpdateServer project newServer
in
( newProject
, Cmd.batch
[ Rest.Nova.requestDeleteServer newProject newServer
, Cmd.batch deleteFloatingIpCmds
]
)
| elm |
[
{
"context": "e by \"\n , a [ href \"https://github.com/it6c65\" ] [ text \"Luis Ilarraza\" ]\n , br [] [",
"end": 4191,
"score": 0.9996515512,
"start": 4185,
"tag": "USERNAME",
"value": "it6c65"
},
{
"context": " , a [ href \"https://github.com/it6c65\" ] [ text \"Luis Ilarraza\" ]\n , br [] []\n , text \"Thi",
"end": 4216,
"score": 0.9998935461,
"start": 4203,
"tag": "NAME",
"value": "Luis Ilarraza"
},
{
"context": " the \"\n , a [ href \"https://github.com/JamelHammoud/hextime\" ] [ text \"HexTime\" ]\n , br []",
"end": 4433,
"score": 0.9996573329,
"start": 4421,
"tag": "USERNAME",
"value": "JamelHammoud"
},
{
"context": " [] []\n , a [ href \"https://github.com/it6c65/hextime-elm\" ] [ text \"CODE HERE\" ]\n ]",
"end": 4667,
"score": 0.999464035,
"start": 4661,
"tag": "USERNAME",
"value": "it6c65"
}
] | src/Main.elm | it6c65/hextime-elm | 0 | module Main exposing (main)
--
-- Show the current time in Hexadecimals
--
import Browser
import Dict exposing (Dict)
import Html exposing (Html, a, br, div, footer, h1, text)
import Html.Attributes exposing (class, href, style)
import Http
import Json.Decode as JD
import Task
import Time
import Url.Builder as UB
-- MAIN
main : Program () Model Msg
main =
Browser.document
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ zone : Time.Zone
, time : Time.Posix
, backgroundImage : Maybe UrlAddress
, color : Maybe Color
}
type alias Color =
{ red : String
, green : String
, blue : String
, hex : String
}
init : () -> ( Model, Cmd Msg )
init _ =
( Model Time.utc (Time.millisToPosix 0) Nothing Nothing
, Task.perform AdjustTimeZone Time.here
)
-- UPDATE
type Msg
= Tick Time.Posix
| AdjustTimeZone Time.Zone
| GetBackground (Result Http.Error UrlAddress)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Tick newTime ->
let
currentColor =
defineColor model.color
newColor =
changeRed model currentColor
|> changeGreen model
|> changeBlue model
|> toHex
newColorUrl =
defineColor newColor
finalUrl =
UB.crossOrigin "https://php-noise.com" [ "noise.php" ] [ UB.string "hex" (String.dropLeft 1 newColorUrl.hex), UB.string "json" "" ]
in
( { model
| time = newTime
, color = newColor
}
, fetchBackground finalUrl
)
AdjustTimeZone newZone ->
( { model | zone = newZone }
, Cmd.none
)
GetBackground bg ->
( { model | backgroundImage = Result.toMaybe bg }, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every 1000 Tick
-- Helper Functions
addLeftZero : String -> String
addLeftZero time =
if (String.toInt time |> Maybe.withDefault 0) < 10 then
"0" ++ time
else
time
changeRed : Model -> Color -> Color
changeRed model currentColor =
{ currentColor | red = addLeftZero (String.fromInt (Time.toHour model.zone model.time)) }
changeGreen : Model -> Color -> Color
changeGreen model currentColor =
{ currentColor | green = addLeftZero (String.fromInt (Time.toMinute model.zone model.time)) }
changeBlue : Model -> Color -> Color
changeBlue model currentColor =
{ currentColor | blue = addLeftZero (String.fromInt (Time.toSecond model.zone model.time)) }
toHex : Color -> Maybe Color
toHex currentColor =
Just { currentColor | hex = "#" ++ currentColor.red ++ currentColor.green ++ currentColor.blue }
emptyColor : Color
emptyColor =
Color "" "" "" "#000000"
defineColor : Maybe Color -> Color
defineColor color =
case color of
Just colorDefined ->
colorDefined
Nothing ->
emptyColor
viewBackgroundImage : Maybe UrlAddress -> Html.Attribute Msg
viewBackgroundImage bgUrl =
case bgUrl of
Just bg ->
let
address_image =
"url(" ++ bg.uri ++ ")"
in
style "background-image" address_image
Nothing ->
style "background-image" "none"
-- VIEW
view : Model -> Browser.Document Msg
view model =
Browser.Document "Hex Time"
(display model)
display : Model -> List (Html Msg)
display model =
let
currentColor =
defineColor model.color
hexcolor =
currentColor.hex
in
[ div
[ class "page"
, style "background-color" hexcolor
, viewBackgroundImage model.backgroundImage
]
[ h1 [] [ text hexcolor ]
, footer [ class "description" ]
[ text "Made by "
, a [ href "https://github.com/it6c65" ] [ text "Luis Ilarraza" ]
, br [] []
, text "This is the "
, a [ href "https://elm-lang.org" ] [ text "Elm version" ]
, text " of the "
, a [ href "https://github.com/JamelHammoud/hextime" ] [ text "HexTime" ]
, br [] []
, text "Now integrated with "
, a [ href "https://php-noise.com" ] [ text "Noise" ]
, br [] []
, a [ href "https://github.com/it6c65/hextime-elm" ] [ text "CODE HERE" ]
]
]
]
-- Fetch backgrounds from Api
type alias UrlAddress =
{ uri : String
}
bgUrlDecoder : JD.Decoder UrlAddress
bgUrlDecoder =
JD.map UrlAddress (JD.field "uri" JD.string)
fetchBackground : String -> Cmd Msg
fetchBackground address =
Http.get
{ url = address
, expect = Http.expectJson GetBackground bgUrlDecoder
}
| 26352 | module Main exposing (main)
--
-- Show the current time in Hexadecimals
--
import Browser
import Dict exposing (Dict)
import Html exposing (Html, a, br, div, footer, h1, text)
import Html.Attributes exposing (class, href, style)
import Http
import Json.Decode as JD
import Task
import Time
import Url.Builder as UB
-- MAIN
main : Program () Model Msg
main =
Browser.document
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ zone : Time.Zone
, time : Time.Posix
, backgroundImage : Maybe UrlAddress
, color : Maybe Color
}
type alias Color =
{ red : String
, green : String
, blue : String
, hex : String
}
init : () -> ( Model, Cmd Msg )
init _ =
( Model Time.utc (Time.millisToPosix 0) Nothing Nothing
, Task.perform AdjustTimeZone Time.here
)
-- UPDATE
type Msg
= Tick Time.Posix
| AdjustTimeZone Time.Zone
| GetBackground (Result Http.Error UrlAddress)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Tick newTime ->
let
currentColor =
defineColor model.color
newColor =
changeRed model currentColor
|> changeGreen model
|> changeBlue model
|> toHex
newColorUrl =
defineColor newColor
finalUrl =
UB.crossOrigin "https://php-noise.com" [ "noise.php" ] [ UB.string "hex" (String.dropLeft 1 newColorUrl.hex), UB.string "json" "" ]
in
( { model
| time = newTime
, color = newColor
}
, fetchBackground finalUrl
)
AdjustTimeZone newZone ->
( { model | zone = newZone }
, Cmd.none
)
GetBackground bg ->
( { model | backgroundImage = Result.toMaybe bg }, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every 1000 Tick
-- Helper Functions
addLeftZero : String -> String
addLeftZero time =
if (String.toInt time |> Maybe.withDefault 0) < 10 then
"0" ++ time
else
time
changeRed : Model -> Color -> Color
changeRed model currentColor =
{ currentColor | red = addLeftZero (String.fromInt (Time.toHour model.zone model.time)) }
changeGreen : Model -> Color -> Color
changeGreen model currentColor =
{ currentColor | green = addLeftZero (String.fromInt (Time.toMinute model.zone model.time)) }
changeBlue : Model -> Color -> Color
changeBlue model currentColor =
{ currentColor | blue = addLeftZero (String.fromInt (Time.toSecond model.zone model.time)) }
toHex : Color -> Maybe Color
toHex currentColor =
Just { currentColor | hex = "#" ++ currentColor.red ++ currentColor.green ++ currentColor.blue }
emptyColor : Color
emptyColor =
Color "" "" "" "#000000"
defineColor : Maybe Color -> Color
defineColor color =
case color of
Just colorDefined ->
colorDefined
Nothing ->
emptyColor
viewBackgroundImage : Maybe UrlAddress -> Html.Attribute Msg
viewBackgroundImage bgUrl =
case bgUrl of
Just bg ->
let
address_image =
"url(" ++ bg.uri ++ ")"
in
style "background-image" address_image
Nothing ->
style "background-image" "none"
-- VIEW
view : Model -> Browser.Document Msg
view model =
Browser.Document "Hex Time"
(display model)
display : Model -> List (Html Msg)
display model =
let
currentColor =
defineColor model.color
hexcolor =
currentColor.hex
in
[ div
[ class "page"
, style "background-color" hexcolor
, viewBackgroundImage model.backgroundImage
]
[ h1 [] [ text hexcolor ]
, footer [ class "description" ]
[ text "Made by "
, a [ href "https://github.com/it6c65" ] [ text "<NAME>" ]
, br [] []
, text "This is the "
, a [ href "https://elm-lang.org" ] [ text "Elm version" ]
, text " of the "
, a [ href "https://github.com/JamelHammoud/hextime" ] [ text "HexTime" ]
, br [] []
, text "Now integrated with "
, a [ href "https://php-noise.com" ] [ text "Noise" ]
, br [] []
, a [ href "https://github.com/it6c65/hextime-elm" ] [ text "CODE HERE" ]
]
]
]
-- Fetch backgrounds from Api
type alias UrlAddress =
{ uri : String
}
bgUrlDecoder : JD.Decoder UrlAddress
bgUrlDecoder =
JD.map UrlAddress (JD.field "uri" JD.string)
fetchBackground : String -> Cmd Msg
fetchBackground address =
Http.get
{ url = address
, expect = Http.expectJson GetBackground bgUrlDecoder
}
| true | module Main exposing (main)
--
-- Show the current time in Hexadecimals
--
import Browser
import Dict exposing (Dict)
import Html exposing (Html, a, br, div, footer, h1, text)
import Html.Attributes exposing (class, href, style)
import Http
import Json.Decode as JD
import Task
import Time
import Url.Builder as UB
-- MAIN
main : Program () Model Msg
main =
Browser.document
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ zone : Time.Zone
, time : Time.Posix
, backgroundImage : Maybe UrlAddress
, color : Maybe Color
}
type alias Color =
{ red : String
, green : String
, blue : String
, hex : String
}
init : () -> ( Model, Cmd Msg )
init _ =
( Model Time.utc (Time.millisToPosix 0) Nothing Nothing
, Task.perform AdjustTimeZone Time.here
)
-- UPDATE
type Msg
= Tick Time.Posix
| AdjustTimeZone Time.Zone
| GetBackground (Result Http.Error UrlAddress)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Tick newTime ->
let
currentColor =
defineColor model.color
newColor =
changeRed model currentColor
|> changeGreen model
|> changeBlue model
|> toHex
newColorUrl =
defineColor newColor
finalUrl =
UB.crossOrigin "https://php-noise.com" [ "noise.php" ] [ UB.string "hex" (String.dropLeft 1 newColorUrl.hex), UB.string "json" "" ]
in
( { model
| time = newTime
, color = newColor
}
, fetchBackground finalUrl
)
AdjustTimeZone newZone ->
( { model | zone = newZone }
, Cmd.none
)
GetBackground bg ->
( { model | backgroundImage = Result.toMaybe bg }, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every 1000 Tick
-- Helper Functions
addLeftZero : String -> String
addLeftZero time =
if (String.toInt time |> Maybe.withDefault 0) < 10 then
"0" ++ time
else
time
changeRed : Model -> Color -> Color
changeRed model currentColor =
{ currentColor | red = addLeftZero (String.fromInt (Time.toHour model.zone model.time)) }
changeGreen : Model -> Color -> Color
changeGreen model currentColor =
{ currentColor | green = addLeftZero (String.fromInt (Time.toMinute model.zone model.time)) }
changeBlue : Model -> Color -> Color
changeBlue model currentColor =
{ currentColor | blue = addLeftZero (String.fromInt (Time.toSecond model.zone model.time)) }
toHex : Color -> Maybe Color
toHex currentColor =
Just { currentColor | hex = "#" ++ currentColor.red ++ currentColor.green ++ currentColor.blue }
emptyColor : Color
emptyColor =
Color "" "" "" "#000000"
defineColor : Maybe Color -> Color
defineColor color =
case color of
Just colorDefined ->
colorDefined
Nothing ->
emptyColor
viewBackgroundImage : Maybe UrlAddress -> Html.Attribute Msg
viewBackgroundImage bgUrl =
case bgUrl of
Just bg ->
let
address_image =
"url(" ++ bg.uri ++ ")"
in
style "background-image" address_image
Nothing ->
style "background-image" "none"
-- VIEW
view : Model -> Browser.Document Msg
view model =
Browser.Document "Hex Time"
(display model)
display : Model -> List (Html Msg)
display model =
let
currentColor =
defineColor model.color
hexcolor =
currentColor.hex
in
[ div
[ class "page"
, style "background-color" hexcolor
, viewBackgroundImage model.backgroundImage
]
[ h1 [] [ text hexcolor ]
, footer [ class "description" ]
[ text "Made by "
, a [ href "https://github.com/it6c65" ] [ text "PI:NAME:<NAME>END_PI" ]
, br [] []
, text "This is the "
, a [ href "https://elm-lang.org" ] [ text "Elm version" ]
, text " of the "
, a [ href "https://github.com/JamelHammoud/hextime" ] [ text "HexTime" ]
, br [] []
, text "Now integrated with "
, a [ href "https://php-noise.com" ] [ text "Noise" ]
, br [] []
, a [ href "https://github.com/it6c65/hextime-elm" ] [ text "CODE HERE" ]
]
]
]
-- Fetch backgrounds from Api
type alias UrlAddress =
{ uri : String
}
bgUrlDecoder : JD.Decoder UrlAddress
bgUrlDecoder =
JD.map UrlAddress (JD.field "uri" JD.string)
fetchBackground : String -> Cmd Msg
fetchBackground address =
Http.get
{ url = address
, expect = Http.expectJson GetBackground bgUrlDecoder
}
| elm |
[
{
"context": "s \"poem-author\" ] [ text \"Auguries of Innocence by William Blake\"]\r\n ]\r\n",
"end": 1037,
"score": 0.999745369,
"start": 1024,
"tag": "NAME",
"value": "William Blake"
}
] | src/elm/Components/DialogTwo.elm | ondrej-tucek/elm-dialogs | 0 | module Components.DialogTwo exposing (myDialogTwo, contentDialogTwo)
import Html exposing (..)
import Material.Options as Options exposing (..)
import Model exposing (..)
dialogSettings : DialogSettings
dialogSettings =
{ viewCs = "dialog-two__view"
, titleCs = "dialog-two__title"
, contentCs = "dialog-two__content"
, actionsCs = "dialog-two__actions"
}
myDialogTwo : ModalDialog
myDialogTwo =
{ dialogSettings = dialogSettings
, dialogTitleText = "Dialog Two"
, dialogBtnText = "Close Dialog 2"
}
contentDialogTwo : Html Msg
contentDialogTwo =
Options.div []
[ Options.div [ cs "poem" ]
[ p [] [ text "To see a world in a grain of sand," ]
, p [] [ text "and a heaven in a wild flower," ]
, p [] [ text "to hold infinity in the palm of your hand," ]
, p [] [ text "and Eternity in an hour." ]
]
, Options.div [ cs "poem-author" ] [ text "Auguries of Innocence by William Blake"]
]
| 57745 | module Components.DialogTwo exposing (myDialogTwo, contentDialogTwo)
import Html exposing (..)
import Material.Options as Options exposing (..)
import Model exposing (..)
dialogSettings : DialogSettings
dialogSettings =
{ viewCs = "dialog-two__view"
, titleCs = "dialog-two__title"
, contentCs = "dialog-two__content"
, actionsCs = "dialog-two__actions"
}
myDialogTwo : ModalDialog
myDialogTwo =
{ dialogSettings = dialogSettings
, dialogTitleText = "Dialog Two"
, dialogBtnText = "Close Dialog 2"
}
contentDialogTwo : Html Msg
contentDialogTwo =
Options.div []
[ Options.div [ cs "poem" ]
[ p [] [ text "To see a world in a grain of sand," ]
, p [] [ text "and a heaven in a wild flower," ]
, p [] [ text "to hold infinity in the palm of your hand," ]
, p [] [ text "and Eternity in an hour." ]
]
, Options.div [ cs "poem-author" ] [ text "Auguries of Innocence by <NAME>"]
]
| true | module Components.DialogTwo exposing (myDialogTwo, contentDialogTwo)
import Html exposing (..)
import Material.Options as Options exposing (..)
import Model exposing (..)
dialogSettings : DialogSettings
dialogSettings =
{ viewCs = "dialog-two__view"
, titleCs = "dialog-two__title"
, contentCs = "dialog-two__content"
, actionsCs = "dialog-two__actions"
}
myDialogTwo : ModalDialog
myDialogTwo =
{ dialogSettings = dialogSettings
, dialogTitleText = "Dialog Two"
, dialogBtnText = "Close Dialog 2"
}
contentDialogTwo : Html Msg
contentDialogTwo =
Options.div []
[ Options.div [ cs "poem" ]
[ p [] [ text "To see a world in a grain of sand," ]
, p [] [ text "and a heaven in a wild flower," ]
, p [] [ text "to hold infinity in the palm of your hand," ]
, p [] [ text "and Eternity in an hour." ]
]
, Options.div [ cs "poem-author" ] [ text "Auguries of Innocence by PI:NAME:<NAME>END_PI"]
]
| elm |
[
{
"context": " class Styles.cite ]\n [ text \"―Stanley Morison\" ]\n ]\n ]\n ]\n",
"end": 949,
"score": 0.9994837046,
"start": 934,
"tag": "NAME",
"value": "Stanley Morison"
}
] | src/Quote/LeftBorder/View.elm | paulfioravanti/tachyons-components | 0 | module Quote.LeftBorder.View exposing (view)
import Html exposing (Html, blockquote, cite, div, p, text)
import Html.Attributes exposing (attribute, class)
import Quote.LeftBorder.Styles as Styles
view : Html msg
view =
let
copy =
"""
Discipline in typography is a prime virtue. Individuality must be
secured by means that are rational. Distinction needs to be won by
simplicity and restraint. It is equally true that these qualities
need to be infused wiht a certain spirit and vitality, or they
degenerate into dullness and mediocrity.
"""
in
div [ attribute "data-name" "component" ]
[ div [ class Styles.quote ]
[ blockquote [ class Styles.blockquote ]
[ p [ class Styles.copy ]
[ text copy ]
, cite [ class Styles.cite ]
[ text "―Stanley Morison" ]
]
]
]
| 3669 | module Quote.LeftBorder.View exposing (view)
import Html exposing (Html, blockquote, cite, div, p, text)
import Html.Attributes exposing (attribute, class)
import Quote.LeftBorder.Styles as Styles
view : Html msg
view =
let
copy =
"""
Discipline in typography is a prime virtue. Individuality must be
secured by means that are rational. Distinction needs to be won by
simplicity and restraint. It is equally true that these qualities
need to be infused wiht a certain spirit and vitality, or they
degenerate into dullness and mediocrity.
"""
in
div [ attribute "data-name" "component" ]
[ div [ class Styles.quote ]
[ blockquote [ class Styles.blockquote ]
[ p [ class Styles.copy ]
[ text copy ]
, cite [ class Styles.cite ]
[ text "―<NAME>" ]
]
]
]
| true | module Quote.LeftBorder.View exposing (view)
import Html exposing (Html, blockquote, cite, div, p, text)
import Html.Attributes exposing (attribute, class)
import Quote.LeftBorder.Styles as Styles
view : Html msg
view =
let
copy =
"""
Discipline in typography is a prime virtue. Individuality must be
secured by means that are rational. Distinction needs to be won by
simplicity and restraint. It is equally true that these qualities
need to be infused wiht a certain spirit and vitality, or they
degenerate into dullness and mediocrity.
"""
in
div [ attribute "data-name" "component" ]
[ div [ class Styles.quote ]
[ blockquote [ class Styles.blockquote ]
[ p [ class Styles.copy ]
[ text copy ]
, cite [ class Styles.cite ]
[ text "―PI:NAME:<NAME>END_PI" ]
]
]
]
| elm |
[
{
"context": "object\n [ ( \"name\", Encode.string \"Dummy\" )\n , ( \"nickname\", Encode.string ",
"end": 1863,
"score": 0.8317671418,
"start": 1858,
"tag": "NAME",
"value": "Dummy"
},
{
"context": "]\n )\n , ( \"token\", Encode.string \"SiM_0L{vErI0\" )\n ]\n",
"end": 2121,
"score": 0.9809831381,
"start": 2115,
"tag": "PASSWORD",
"value": "SiM_0L"
}
] | elm/Paack/Auth/Simulator.elm | PaackEng/frontend-elm-kit | 7 | module Paack.Auth.Simulator exposing (simulator)
import Iso8601
import Json.Encode as Encode
import Paack.Auth.Main as Auth exposing (Config, Effect(..))
import Paack.Auth.Result as AuthResult
import ProgramTest exposing (SimulatedEffect)
import SimulatedEffect.Cmd as SimulatedCmd
import SimulatedEffect.Navigation as Nav
import SimulatedEffect.Task as SimulatedTask
import Time
simulator : Config msg -> Effect -> SimulatedEffect msg
simulator config effect =
case effect of
NoneEffect ->
SimulatedCmd.none
PortCheckSession ->
authResult config mockLogin
PortLogin ->
portLogin config
PortLogout ->
portLogout config
loop : msg -> SimulatedEffect msg
loop msg =
SimulatedTask.perform identity <| SimulatedTask.succeed msg
authResult : Config msg -> Encode.Value -> SimulatedEffect msg
authResult config value =
SimulatedCmd.batch
[ loop <| Auth.mockResult config value
, case config.onLoginResult of
Just msg ->
loop <| msg <| AuthResult.decode value
Nothing ->
SimulatedCmd.none
]
portLogin : Config msg -> SimulatedEffect msg
portLogin config =
SimulatedCmd.batch
[ Nav.pushUrl "/?code=SOME_CODE&state=SOME_STATE"
, authResult config mockLogin
]
portLogout : Config msg -> SimulatedEffect msg
portLogout config =
SimulatedCmd.batch
[ Nav.pushUrl "/"
, authResult config mockLogout
]
mockLogout : Encode.Value
mockLogout =
Encode.object
[ ( "error", Encode.string "LOGOUT" )
, ( "errorDescription", Encode.string "Mocked Logout" )
]
mockLogin : Encode.Value
mockLogin =
Encode.object
[ ( "userData"
, Encode.object
[ ( "name", Encode.string "Dummy" )
, ( "nickname", Encode.string "Dummy" )
, ( "sub", Encode.string "dummy" )
, ( "updated_at", Iso8601.encode <| Time.millisToPosix 0 )
]
)
, ( "token", Encode.string "SiM_0L{vErI0" )
]
| 42162 | module Paack.Auth.Simulator exposing (simulator)
import Iso8601
import Json.Encode as Encode
import Paack.Auth.Main as Auth exposing (Config, Effect(..))
import Paack.Auth.Result as AuthResult
import ProgramTest exposing (SimulatedEffect)
import SimulatedEffect.Cmd as SimulatedCmd
import SimulatedEffect.Navigation as Nav
import SimulatedEffect.Task as SimulatedTask
import Time
simulator : Config msg -> Effect -> SimulatedEffect msg
simulator config effect =
case effect of
NoneEffect ->
SimulatedCmd.none
PortCheckSession ->
authResult config mockLogin
PortLogin ->
portLogin config
PortLogout ->
portLogout config
loop : msg -> SimulatedEffect msg
loop msg =
SimulatedTask.perform identity <| SimulatedTask.succeed msg
authResult : Config msg -> Encode.Value -> SimulatedEffect msg
authResult config value =
SimulatedCmd.batch
[ loop <| Auth.mockResult config value
, case config.onLoginResult of
Just msg ->
loop <| msg <| AuthResult.decode value
Nothing ->
SimulatedCmd.none
]
portLogin : Config msg -> SimulatedEffect msg
portLogin config =
SimulatedCmd.batch
[ Nav.pushUrl "/?code=SOME_CODE&state=SOME_STATE"
, authResult config mockLogin
]
portLogout : Config msg -> SimulatedEffect msg
portLogout config =
SimulatedCmd.batch
[ Nav.pushUrl "/"
, authResult config mockLogout
]
mockLogout : Encode.Value
mockLogout =
Encode.object
[ ( "error", Encode.string "LOGOUT" )
, ( "errorDescription", Encode.string "Mocked Logout" )
]
mockLogin : Encode.Value
mockLogin =
Encode.object
[ ( "userData"
, Encode.object
[ ( "name", Encode.string "<NAME>" )
, ( "nickname", Encode.string "Dummy" )
, ( "sub", Encode.string "dummy" )
, ( "updated_at", Iso8601.encode <| Time.millisToPosix 0 )
]
)
, ( "token", Encode.string "<PASSWORD>{vErI0" )
]
| true | module Paack.Auth.Simulator exposing (simulator)
import Iso8601
import Json.Encode as Encode
import Paack.Auth.Main as Auth exposing (Config, Effect(..))
import Paack.Auth.Result as AuthResult
import ProgramTest exposing (SimulatedEffect)
import SimulatedEffect.Cmd as SimulatedCmd
import SimulatedEffect.Navigation as Nav
import SimulatedEffect.Task as SimulatedTask
import Time
simulator : Config msg -> Effect -> SimulatedEffect msg
simulator config effect =
case effect of
NoneEffect ->
SimulatedCmd.none
PortCheckSession ->
authResult config mockLogin
PortLogin ->
portLogin config
PortLogout ->
portLogout config
loop : msg -> SimulatedEffect msg
loop msg =
SimulatedTask.perform identity <| SimulatedTask.succeed msg
authResult : Config msg -> Encode.Value -> SimulatedEffect msg
authResult config value =
SimulatedCmd.batch
[ loop <| Auth.mockResult config value
, case config.onLoginResult of
Just msg ->
loop <| msg <| AuthResult.decode value
Nothing ->
SimulatedCmd.none
]
portLogin : Config msg -> SimulatedEffect msg
portLogin config =
SimulatedCmd.batch
[ Nav.pushUrl "/?code=SOME_CODE&state=SOME_STATE"
, authResult config mockLogin
]
portLogout : Config msg -> SimulatedEffect msg
portLogout config =
SimulatedCmd.batch
[ Nav.pushUrl "/"
, authResult config mockLogout
]
mockLogout : Encode.Value
mockLogout =
Encode.object
[ ( "error", Encode.string "LOGOUT" )
, ( "errorDescription", Encode.string "Mocked Logout" )
]
mockLogin : Encode.Value
mockLogin =
Encode.object
[ ( "userData"
, Encode.object
[ ( "name", Encode.string "PI:NAME:<NAME>END_PI" )
, ( "nickname", Encode.string "Dummy" )
, ( "sub", Encode.string "dummy" )
, ( "updated_at", Iso8601.encode <| Time.millisToPosix 0 )
]
)
, ( "token", Encode.string "PI:PASSWORD:<PASSWORD>END_PI{vErI0" )
]
| elm |
[
{
"context": " { id : PersonId\n , avatar : Bool\n , name : PersonName\n , shortTitle : Maybe ShortTitle\n , longTit",
"end": 1453,
"score": 0.9512507915,
"start": 1443,
"tag": "NAME",
"value": "PersonName"
}
] | elm/src/Data/People.elm | tuturto/deep-sky | 5 | module Data.People exposing
( Age(..)
, DemesneShortInfo(..)
, DynastyLink
, Gender(..)
, OnPlanetData
, OnUnitData
, OpinionFeeling(..)
, OpinionIntel(..)
, OpinionReason(..)
, OpinionReport(..)
, OpinionScore(..)
, Person
, PersonIntel(..)
, PersonLocation(..)
, PetType(..)
, PlanetDemesneReportShort
, RelationLink
, RelationType(..)
, RelationVisibility(..)
, Sex(..)
, StarSystemDemesneReportShort
, StatValue(..)
, StatValues
, Trait
, TraitDescription(..)
, TraitName(..)
, TraitType(..)
, age
, formalName
, personIntelToString
, petTypeToString
, relationTypeOrdering
, relationTypeToString
, traitNameOrdering
, traitOrdering
, unAge
, unOpinionReason
, unOpinionScore
, unStatValue
, unTraitDescription
, unTraitName
, unTraitType
)
import Data.Common
exposing
( DemesneName
, DynastyId
, DynastyName
, PersonId
, PlanetId
, PlanetName
, StarDate
, StarSystemId
, StarSystemName
, UnitId
, unStarDate
)
import Data.PersonNames exposing (LongTitle(..), PersonName(..), ShortTitle(..))
import Data.Vehicles exposing (CrewPosition(..), UnitName(..))
import Ordering exposing (Ordering)
type alias Person =
{ id : PersonId
, avatar : Bool
, name : PersonName
, shortTitle : Maybe ShortTitle
, longTitle : Maybe LongTitle
, stats : Maybe StatValues
, sex : Sex
, gender : Gender
, age : Age
, relations : List RelationLink
, intelTypes : List PersonIntel
, dynasty : Maybe DynastyLink
, traits : Maybe (List Trait)
, avatarOpinion : OpinionReport
, opinionOfAvatar : OpinionReport
, location : PersonLocation
}
type StatValue
= StatValue Int
unStatValue : StatValue -> Int
unStatValue (StatValue n) =
n
type alias StatValues =
{ diplomacy : StatValue
, learning : StatValue
, martial : StatValue
, intrique : StatValue
, stewardship : StatValue
}
type Sex
= Male
| Female
| Intersex
type Gender
= Man
| Woman
| Agender
| Nonbinary
type Age
= Age Int
unAge : Age -> Int
unAge (Age n) =
n
{-| Age (time difference between two points in time) in full star years
-}
age : StarDate -> StarDate -> Age
age old new =
let
diff =
unStarDate old - unStarDate new
fullYears =
diff // 10
in
Age fullYears
{-| Short form demesne report, listing only ID and Name
-}
type DemesneShortInfo
= PlanetDemesneShort PlanetDemesneReportShort
| StarSystemDemesneShort StarSystemDemesneReportShort
type alias PlanetDemesneReportShort =
{ planetId : PlanetId
, starSystemId : StarSystemId
, name : PlanetName
, formalName : DemesneName
, date : StarDate
}
type alias StarSystemDemesneReportShort =
{ starSystemId : StarSystemId
, name : StarSystemName
, formalName : DemesneName
, date : StarDate
}
formalName : DemesneShortInfo -> DemesneName
formalName info =
case info of
PlanetDemesneShort report ->
report.formalName
StarSystemDemesneShort report ->
report.formalName
type alias RelationLink =
{ id : PersonId
, name : PersonName
, shortTitle : Maybe ShortTitle
, longTitle : Maybe LongTitle
, types : List RelationType
, opinion : OpinionReport
}
type RelationType
= Parent
| Child
| Sibling
| StepParent
| StepChild
| StepSibling
| Spouse
| ExSpouse
| Lover
| ExLover
| Friend
| Rival
{-| Arbitrary ordering for relation types
-}
relationTypeOrdering : Ordering RelationType
relationTypeOrdering =
Ordering.explicit
[ Parent
, StepParent
, Sibling
, StepSibling
, Spouse
, ExSpouse
, Child
, StepChild
, Lover
, ExLover
, Friend
, Rival
]
relationTypeToString : RelationType -> String
relationTypeToString r =
case r of
Parent ->
"Parent"
Child ->
"Child"
Sibling ->
"Sibling"
StepParent ->
"Stepparent"
StepChild ->
"Stepchild"
StepSibling ->
"Stepsibling"
Spouse ->
"Spouse"
ExSpouse ->
"Ex-spouse"
Lover ->
"Lover"
ExLover ->
"Ex-lover"
Friend ->
"Friend"
Rival ->
"Rival"
type PersonIntel
= Stats
| Demesne
| FamilyRelations
| SecretRelations
| Opinions OpinionIntel
| Traits
| Location
| Activity
type OpinionIntel
= BaseOpinionIntel RelationVisibility
| ReasonsForOpinions RelationVisibility
| DetailedOpinions RelationVisibility
type RelationVisibility
= SecretRelation
| FamilyRelation
| PublicRelation
personIntelToString : PersonIntel -> String
personIntelToString intel =
case intel of
Stats ->
"Stats"
Demesne ->
"Demesne"
FamilyRelations ->
"Family relations"
SecretRelations ->
"Secret relations"
Opinions _ ->
"Opinions"
Traits ->
"Traits"
Location ->
"Location"
Activity ->
"Activity"
type alias DynastyLink =
{ id : DynastyId
, name : DynastyName
}
type alias Trait =
{ name : TraitName
, traitType : TraitType
, description : TraitDescription
, validUntil : Maybe StarDate
}
type TraitName
= TraitName String
unTraitName : TraitName -> String
unTraitName (TraitName s) =
s
type TraitType
= TraitType String
unTraitType : TraitType -> String
unTraitType (TraitType t) =
t
type TraitDescription
= TraitDescription String
unTraitDescription : TraitDescription -> String
unTraitDescription (TraitDescription s) =
s
traitNameOrdering : Ordering TraitName
traitNameOrdering =
Ordering.byField unTraitName
traitOrdering : Ordering Trait
traitOrdering =
Ordering.byFieldWith traitNameOrdering .name
type OpinionReport
= BaseOpinionReport OpinionFeeling
| OpinionReasonReport OpinionFeeling (List OpinionReason)
| DetailedOpinionReport OpinionScore (List OpinionReason)
type OpinionFeeling
= PositiveFeeling
| NeutralFeeling
| NegativeFeeling
type OpinionReason
= OpinionReason String
unOpinionReason : OpinionReason -> String
unOpinionReason (OpinionReason s) =
s
type OpinionScore
= OpinionScore Int
unOpinionScore : OpinionScore -> Int
unOpinionScore (OpinionScore n) =
n
type PetType
= Cat
| Rat
petTypeToString : PetType -> String
petTypeToString pType =
case pType of
Cat ->
"cat"
Rat ->
"rat"
type PersonLocation
= OnPlanet OnPlanetData
| OnUnit OnUnitData
| UnknownLocation
type alias OnPlanetData =
{ planetId : PlanetId
, starSystemId : StarSystemId
, planetName : PlanetName
}
type alias OnUnitData =
{ unitId : UnitId
, unitName : UnitName
, position : Maybe CrewPosition
}
| 17530 | module Data.People exposing
( Age(..)
, DemesneShortInfo(..)
, DynastyLink
, Gender(..)
, OnPlanetData
, OnUnitData
, OpinionFeeling(..)
, OpinionIntel(..)
, OpinionReason(..)
, OpinionReport(..)
, OpinionScore(..)
, Person
, PersonIntel(..)
, PersonLocation(..)
, PetType(..)
, PlanetDemesneReportShort
, RelationLink
, RelationType(..)
, RelationVisibility(..)
, Sex(..)
, StarSystemDemesneReportShort
, StatValue(..)
, StatValues
, Trait
, TraitDescription(..)
, TraitName(..)
, TraitType(..)
, age
, formalName
, personIntelToString
, petTypeToString
, relationTypeOrdering
, relationTypeToString
, traitNameOrdering
, traitOrdering
, unAge
, unOpinionReason
, unOpinionScore
, unStatValue
, unTraitDescription
, unTraitName
, unTraitType
)
import Data.Common
exposing
( DemesneName
, DynastyId
, DynastyName
, PersonId
, PlanetId
, PlanetName
, StarDate
, StarSystemId
, StarSystemName
, UnitId
, unStarDate
)
import Data.PersonNames exposing (LongTitle(..), PersonName(..), ShortTitle(..))
import Data.Vehicles exposing (CrewPosition(..), UnitName(..))
import Ordering exposing (Ordering)
type alias Person =
{ id : PersonId
, avatar : Bool
, name : <NAME>
, shortTitle : Maybe ShortTitle
, longTitle : Maybe LongTitle
, stats : Maybe StatValues
, sex : Sex
, gender : Gender
, age : Age
, relations : List RelationLink
, intelTypes : List PersonIntel
, dynasty : Maybe DynastyLink
, traits : Maybe (List Trait)
, avatarOpinion : OpinionReport
, opinionOfAvatar : OpinionReport
, location : PersonLocation
}
type StatValue
= StatValue Int
unStatValue : StatValue -> Int
unStatValue (StatValue n) =
n
type alias StatValues =
{ diplomacy : StatValue
, learning : StatValue
, martial : StatValue
, intrique : StatValue
, stewardship : StatValue
}
type Sex
= Male
| Female
| Intersex
type Gender
= Man
| Woman
| Agender
| Nonbinary
type Age
= Age Int
unAge : Age -> Int
unAge (Age n) =
n
{-| Age (time difference between two points in time) in full star years
-}
age : StarDate -> StarDate -> Age
age old new =
let
diff =
unStarDate old - unStarDate new
fullYears =
diff // 10
in
Age fullYears
{-| Short form demesne report, listing only ID and Name
-}
type DemesneShortInfo
= PlanetDemesneShort PlanetDemesneReportShort
| StarSystemDemesneShort StarSystemDemesneReportShort
type alias PlanetDemesneReportShort =
{ planetId : PlanetId
, starSystemId : StarSystemId
, name : PlanetName
, formalName : DemesneName
, date : StarDate
}
type alias StarSystemDemesneReportShort =
{ starSystemId : StarSystemId
, name : StarSystemName
, formalName : DemesneName
, date : StarDate
}
formalName : DemesneShortInfo -> DemesneName
formalName info =
case info of
PlanetDemesneShort report ->
report.formalName
StarSystemDemesneShort report ->
report.formalName
type alias RelationLink =
{ id : PersonId
, name : PersonName
, shortTitle : Maybe ShortTitle
, longTitle : Maybe LongTitle
, types : List RelationType
, opinion : OpinionReport
}
type RelationType
= Parent
| Child
| Sibling
| StepParent
| StepChild
| StepSibling
| Spouse
| ExSpouse
| Lover
| ExLover
| Friend
| Rival
{-| Arbitrary ordering for relation types
-}
relationTypeOrdering : Ordering RelationType
relationTypeOrdering =
Ordering.explicit
[ Parent
, StepParent
, Sibling
, StepSibling
, Spouse
, ExSpouse
, Child
, StepChild
, Lover
, ExLover
, Friend
, Rival
]
relationTypeToString : RelationType -> String
relationTypeToString r =
case r of
Parent ->
"Parent"
Child ->
"Child"
Sibling ->
"Sibling"
StepParent ->
"Stepparent"
StepChild ->
"Stepchild"
StepSibling ->
"Stepsibling"
Spouse ->
"Spouse"
ExSpouse ->
"Ex-spouse"
Lover ->
"Lover"
ExLover ->
"Ex-lover"
Friend ->
"Friend"
Rival ->
"Rival"
type PersonIntel
= Stats
| Demesne
| FamilyRelations
| SecretRelations
| Opinions OpinionIntel
| Traits
| Location
| Activity
type OpinionIntel
= BaseOpinionIntel RelationVisibility
| ReasonsForOpinions RelationVisibility
| DetailedOpinions RelationVisibility
type RelationVisibility
= SecretRelation
| FamilyRelation
| PublicRelation
personIntelToString : PersonIntel -> String
personIntelToString intel =
case intel of
Stats ->
"Stats"
Demesne ->
"Demesne"
FamilyRelations ->
"Family relations"
SecretRelations ->
"Secret relations"
Opinions _ ->
"Opinions"
Traits ->
"Traits"
Location ->
"Location"
Activity ->
"Activity"
type alias DynastyLink =
{ id : DynastyId
, name : DynastyName
}
type alias Trait =
{ name : TraitName
, traitType : TraitType
, description : TraitDescription
, validUntil : Maybe StarDate
}
type TraitName
= TraitName String
unTraitName : TraitName -> String
unTraitName (TraitName s) =
s
type TraitType
= TraitType String
unTraitType : TraitType -> String
unTraitType (TraitType t) =
t
type TraitDescription
= TraitDescription String
unTraitDescription : TraitDescription -> String
unTraitDescription (TraitDescription s) =
s
traitNameOrdering : Ordering TraitName
traitNameOrdering =
Ordering.byField unTraitName
traitOrdering : Ordering Trait
traitOrdering =
Ordering.byFieldWith traitNameOrdering .name
type OpinionReport
= BaseOpinionReport OpinionFeeling
| OpinionReasonReport OpinionFeeling (List OpinionReason)
| DetailedOpinionReport OpinionScore (List OpinionReason)
type OpinionFeeling
= PositiveFeeling
| NeutralFeeling
| NegativeFeeling
type OpinionReason
= OpinionReason String
unOpinionReason : OpinionReason -> String
unOpinionReason (OpinionReason s) =
s
type OpinionScore
= OpinionScore Int
unOpinionScore : OpinionScore -> Int
unOpinionScore (OpinionScore n) =
n
type PetType
= Cat
| Rat
petTypeToString : PetType -> String
petTypeToString pType =
case pType of
Cat ->
"cat"
Rat ->
"rat"
type PersonLocation
= OnPlanet OnPlanetData
| OnUnit OnUnitData
| UnknownLocation
type alias OnPlanetData =
{ planetId : PlanetId
, starSystemId : StarSystemId
, planetName : PlanetName
}
type alias OnUnitData =
{ unitId : UnitId
, unitName : UnitName
, position : Maybe CrewPosition
}
| true | module Data.People exposing
( Age(..)
, DemesneShortInfo(..)
, DynastyLink
, Gender(..)
, OnPlanetData
, OnUnitData
, OpinionFeeling(..)
, OpinionIntel(..)
, OpinionReason(..)
, OpinionReport(..)
, OpinionScore(..)
, Person
, PersonIntel(..)
, PersonLocation(..)
, PetType(..)
, PlanetDemesneReportShort
, RelationLink
, RelationType(..)
, RelationVisibility(..)
, Sex(..)
, StarSystemDemesneReportShort
, StatValue(..)
, StatValues
, Trait
, TraitDescription(..)
, TraitName(..)
, TraitType(..)
, age
, formalName
, personIntelToString
, petTypeToString
, relationTypeOrdering
, relationTypeToString
, traitNameOrdering
, traitOrdering
, unAge
, unOpinionReason
, unOpinionScore
, unStatValue
, unTraitDescription
, unTraitName
, unTraitType
)
import Data.Common
exposing
( DemesneName
, DynastyId
, DynastyName
, PersonId
, PlanetId
, PlanetName
, StarDate
, StarSystemId
, StarSystemName
, UnitId
, unStarDate
)
import Data.PersonNames exposing (LongTitle(..), PersonName(..), ShortTitle(..))
import Data.Vehicles exposing (CrewPosition(..), UnitName(..))
import Ordering exposing (Ordering)
type alias Person =
{ id : PersonId
, avatar : Bool
, name : PI:NAME:<NAME>END_PI
, shortTitle : Maybe ShortTitle
, longTitle : Maybe LongTitle
, stats : Maybe StatValues
, sex : Sex
, gender : Gender
, age : Age
, relations : List RelationLink
, intelTypes : List PersonIntel
, dynasty : Maybe DynastyLink
, traits : Maybe (List Trait)
, avatarOpinion : OpinionReport
, opinionOfAvatar : OpinionReport
, location : PersonLocation
}
type StatValue
= StatValue Int
unStatValue : StatValue -> Int
unStatValue (StatValue n) =
n
type alias StatValues =
{ diplomacy : StatValue
, learning : StatValue
, martial : StatValue
, intrique : StatValue
, stewardship : StatValue
}
type Sex
= Male
| Female
| Intersex
type Gender
= Man
| Woman
| Agender
| Nonbinary
type Age
= Age Int
unAge : Age -> Int
unAge (Age n) =
n
{-| Age (time difference between two points in time) in full star years
-}
age : StarDate -> StarDate -> Age
age old new =
let
diff =
unStarDate old - unStarDate new
fullYears =
diff // 10
in
Age fullYears
{-| Short form demesne report, listing only ID and Name
-}
type DemesneShortInfo
= PlanetDemesneShort PlanetDemesneReportShort
| StarSystemDemesneShort StarSystemDemesneReportShort
type alias PlanetDemesneReportShort =
{ planetId : PlanetId
, starSystemId : StarSystemId
, name : PlanetName
, formalName : DemesneName
, date : StarDate
}
type alias StarSystemDemesneReportShort =
{ starSystemId : StarSystemId
, name : StarSystemName
, formalName : DemesneName
, date : StarDate
}
formalName : DemesneShortInfo -> DemesneName
formalName info =
case info of
PlanetDemesneShort report ->
report.formalName
StarSystemDemesneShort report ->
report.formalName
type alias RelationLink =
{ id : PersonId
, name : PersonName
, shortTitle : Maybe ShortTitle
, longTitle : Maybe LongTitle
, types : List RelationType
, opinion : OpinionReport
}
type RelationType
= Parent
| Child
| Sibling
| StepParent
| StepChild
| StepSibling
| Spouse
| ExSpouse
| Lover
| ExLover
| Friend
| Rival
{-| Arbitrary ordering for relation types
-}
relationTypeOrdering : Ordering RelationType
relationTypeOrdering =
Ordering.explicit
[ Parent
, StepParent
, Sibling
, StepSibling
, Spouse
, ExSpouse
, Child
, StepChild
, Lover
, ExLover
, Friend
, Rival
]
relationTypeToString : RelationType -> String
relationTypeToString r =
case r of
Parent ->
"Parent"
Child ->
"Child"
Sibling ->
"Sibling"
StepParent ->
"Stepparent"
StepChild ->
"Stepchild"
StepSibling ->
"Stepsibling"
Spouse ->
"Spouse"
ExSpouse ->
"Ex-spouse"
Lover ->
"Lover"
ExLover ->
"Ex-lover"
Friend ->
"Friend"
Rival ->
"Rival"
type PersonIntel
= Stats
| Demesne
| FamilyRelations
| SecretRelations
| Opinions OpinionIntel
| Traits
| Location
| Activity
type OpinionIntel
= BaseOpinionIntel RelationVisibility
| ReasonsForOpinions RelationVisibility
| DetailedOpinions RelationVisibility
type RelationVisibility
= SecretRelation
| FamilyRelation
| PublicRelation
personIntelToString : PersonIntel -> String
personIntelToString intel =
case intel of
Stats ->
"Stats"
Demesne ->
"Demesne"
FamilyRelations ->
"Family relations"
SecretRelations ->
"Secret relations"
Opinions _ ->
"Opinions"
Traits ->
"Traits"
Location ->
"Location"
Activity ->
"Activity"
type alias DynastyLink =
{ id : DynastyId
, name : DynastyName
}
type alias Trait =
{ name : TraitName
, traitType : TraitType
, description : TraitDescription
, validUntil : Maybe StarDate
}
type TraitName
= TraitName String
unTraitName : TraitName -> String
unTraitName (TraitName s) =
s
type TraitType
= TraitType String
unTraitType : TraitType -> String
unTraitType (TraitType t) =
t
type TraitDescription
= TraitDescription String
unTraitDescription : TraitDescription -> String
unTraitDescription (TraitDescription s) =
s
traitNameOrdering : Ordering TraitName
traitNameOrdering =
Ordering.byField unTraitName
traitOrdering : Ordering Trait
traitOrdering =
Ordering.byFieldWith traitNameOrdering .name
type OpinionReport
= BaseOpinionReport OpinionFeeling
| OpinionReasonReport OpinionFeeling (List OpinionReason)
| DetailedOpinionReport OpinionScore (List OpinionReason)
type OpinionFeeling
= PositiveFeeling
| NeutralFeeling
| NegativeFeeling
type OpinionReason
= OpinionReason String
unOpinionReason : OpinionReason -> String
unOpinionReason (OpinionReason s) =
s
type OpinionScore
= OpinionScore Int
unOpinionScore : OpinionScore -> Int
unOpinionScore (OpinionScore n) =
n
type PetType
= Cat
| Rat
petTypeToString : PetType -> String
petTypeToString pType =
case pType of
Cat ->
"cat"
Rat ->
"rat"
type PersonLocation
= OnPlanet OnPlanetData
| OnUnit OnUnitData
| UnknownLocation
type alias OnPlanetData =
{ planetId : PlanetId
, starSystemId : StarSystemId
, planetName : PlanetName
}
type alias OnUnitData =
{ unitId : UnitId
, unitName : UnitName
, position : Maybe CrewPosition
}
| elm |
[
{
"context": " gitlabUrl = \"\"\n , gitlabToken = \"yourtoken\"\n , projectId = \"1\"}\n , build",
"end": 379,
"score": 0.9791288376,
"start": 370,
"tag": "PASSWORD",
"value": "yourtoken"
}
] | src/Models.elm | Snorremd/builds-dashboard-gitlab | 0 |
module Models exposing (..)
import Builds.Models exposing (Build)
import Settings.Models exposing (Settings)
import Routing
type alias Model =
{ route : Routing.Route
, settings : Settings
, builds : List Build }
initialModel : Routing.Route -> Model
initialModel route =
{ route = route
, settings = { gitlabUrl = ""
, gitlabToken = "yourtoken"
, projectId = "1"}
, builds = []
} | 24391 |
module Models exposing (..)
import Builds.Models exposing (Build)
import Settings.Models exposing (Settings)
import Routing
type alias Model =
{ route : Routing.Route
, settings : Settings
, builds : List Build }
initialModel : Routing.Route -> Model
initialModel route =
{ route = route
, settings = { gitlabUrl = ""
, gitlabToken = "<PASSWORD>"
, projectId = "1"}
, builds = []
} | true |
module Models exposing (..)
import Builds.Models exposing (Build)
import Settings.Models exposing (Settings)
import Routing
type alias Model =
{ route : Routing.Route
, settings : Settings
, builds : List Build }
initialModel : Routing.Route -> Model
initialModel route =
{ route = route
, settings = { gitlabUrl = ""
, gitlabToken = "PI:PASSWORD:<PASSWORD>END_PI"
, projectId = "1"}
, builds = []
} | elm |
[
{
"context": "baseUrl = \"https://example.com\"\n , key = Just \"thefutureishere\"\n }\n\n { baseUrl = \"https://example.com/thum",
"end": 1433,
"score": 0.998852551,
"start": 1418,
"tag": "KEY",
"value": "thefutureishere"
},
{
"context": "= \"https://example.com/thumbor\"\n , key = Just \"thefutureishere\"\n }\n\n { baseUrl = \"https://example.com:1138",
"end": 1521,
"score": 0.9989632368,
"start": 1506,
"tag": "KEY",
"value": "thefutureishere"
},
{
"context": "tps://example.com:1138/thumbor\"\n , key = Just \"thefutureishere\"\n }\n\n-}\ntype alias Config =\n { baseUrl : St",
"end": 1614,
"score": 0.99900949,
"start": 1599,
"tag": "KEY",
"value": "thefutureishere"
},
{
"context": "tps://example.com:1138\"\n , key = Just \"thefutureishere\"\n }\n\n -- Prepare a common configura",
"end": 2612,
"score": 0.9952531457,
"start": 2597,
"tag": "KEY",
"value": "thefutureishere"
}
] | src/Thumbor.elm | itravel-de/elm-thumbor | 0 | module Thumbor exposing
( url
, Config
, Attribute
, size, sizeFixed, Size(..)
, manualCrop, horizontalAlign, HorizontalAlign(..), verticalAlign, VerticalAlign(..)
, trim, trimSimple, TrimSource(..)
, fitIn, FitInMode(..)
, filters, smart
)
{-|
# Core Functionality
@docs url
# Configuration
@docs Config
# Attributes
@docs Attribute
## Sizing
@docs size, sizeFixed, Size
## Cropping
@docs manualCrop, horizontalAlign, HorizontalAlign, verticalAlign, VerticalAlign
## Trimming
@docs trim, trimSimple, TrimSource
## Fitting
@docs fitIn, FitInMode
## Miscellaneous
@docs filters, smart
-}
import HmacSha1
import Thumbor.Filter exposing (Filter)
import Url.Builder
import Util
{-| Thumbor server configuration. The `baseUrl` configures the base URL your Thumbor instance is hosted on. It must contain at least an URL schema and host and can contain a custom port or path.
`key` contains your key for [URL signing](https://thumbor.readthedocs.io/en/latest/security.html#security). If `Nothing` is provided, URL signing will be disabled.
**Important Security Notice:** Since Elm is mostly used in front-end code, **your key will be exposed in clear-text to all clients**, nullifying the effect of this security measure.
**Make sure you have an alternate concept to stop URL tampering!**
Examples:
{ baseUrl = "https://example.com"
, key = Just "thefutureishere"
}
{ baseUrl = "https://example.com/thumbor"
, key = Just "thefutureishere"
}
{ baseUrl = "https://example.com:1138/thumbor"
, key = Just "thefutureishere"
}
-}
type alias Config =
{ baseUrl : String
, key : Maybe String
}
{-| -}
type FitInMode
= NormalFitIn
| AdaptiveFitIn
| FullFitIn
{-| -}
type TrimSource
= TopLeft
| BottomRight
{-| -}
type HorizontalAlign
= Left
| Center
| Right
{-| -}
type VerticalAlign
= Top
| Middle
| Bottom
{-| -}
type Size
= Fixed Int
| Proportional
| Original
{-| Creates a new image URL based on the given [`Config`](#Config), [`Attributes`](#Attribute) and original image URL.
Attributes can occur in any order. If an attribute is specified multiple times, the last occurrence wins - very much
like how [`elm/html`](https://package.elm-lang.org/packages/elm/html/latest/) attributes work.
You might want to use currying to ease usage of this package:
thumbor : List Thumbor.Attribute -> String -> String
thumbor =
Thumbor.url
{ host = "https://example.com:1138"
, key = Just "thefutureishere"
}
-- Prepare a common configuration for teaser images
prepareTeaserImage : String -> String
prepareTeaserImage =
thumbor [ Thumbor.scale 200 300 ]
-- Actually use this package to create a modified image
view : Model -> Html msg
view model =
img [ src (prepareTeaserImage "https://example.com/image.jpg") ] []
-}
url : Config -> List Attribute -> String -> String
url { baseUrl, key } attributes imageUrl =
let
pathSegments =
Url.Builder.relative (generatePathSegments attributes ++ [ imageUrl ]) []
hmacSignature =
case key of
Just value ->
HmacSha1.digest value pathSegments
|> HmacSha1.toBase64
|> Result.toMaybe
-- This case should never happen, base64 encode itself cannot fail. We have to investigate why
-- the HMAC library returns a Maybe here. Fallback is an unsafe Thumbor URL.
|> Maybe.withDefault "unsafe"
|> String.replace "+" "-"
|> String.replace "/" "_"
Nothing ->
"unsafe"
in
Url.Builder.crossOrigin baseUrl [ hmacSignature, pathSegments ] []
{-| Represents a Thumbor attribute, controlling how images are processed. See below for a list of available attribute constructors.
-}
type Attribute
= Size Size Size
| Filters (List Filter)
| FitIn FitInMode
| Trim TrimSource Int
| ManualCrop { left : Int, top : Int, right : Int, bottom : Int }
| HAlign HorizontalAlign
| VAlign VerticalAlign
| Smart
{-| Specifies the size of the image that will be returned by the service.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#image-size>
-}
size : Size -> Size -> Attribute
size =
Size
{-| Same as [size](#size), but always uses `Fixed` sizing for convenience.
-}
sizeFixed : Int -> Int -> Attribute
sizeFixed width height =
Size (Fixed width) (Fixed height)
{-| Specifies that the image should **not** be auto-cropped and auto-resized to be **exactly** the specified size, and
should be fit in an imaginary box (given by the [sizing](#sizing) argument) instead.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#fit-in>
-}
fitIn : FitInMode -> Attribute
fitIn =
FitIn
{-| Sets a list of filters as a chain to be used. See [Thumbor.Filter](Thumbor-Filter) for available filters and their usage.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#filters>
-}
filters : List Filter -> Attribute
filters =
Filters
{-| Removes surrounding space in images based on its color. You can pass in the source where the color should be sampled
with a [TrimSource](#TrimSource). In addition, you can specify a color tolerance with the second parameter. The tolerance
value will be clamped between `0` and `442`.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#trim>
-}
trim : TrimSource -> Int -> Attribute
trim =
Trim
{-| Same as [trim](#trim), but always uses `TopLeft` source and `0` tolerance.
-}
trimSimple : Attribute
trimSimple =
Trim TopLeft 0
{-| Useful for applications that provide custom real-time cropping capabilities.
This crop is performed before the rest of the operations, so it can be used as a prepare step _before_ resizing and smart-cropping.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#manual-crop>
-}
manualCrop : { left : Int, top : Int, right : Int, bottom : Int } -> Attribute
manualCrop =
ManualCrop
{-| Controls where the cropping will occur if some width needs to be trimmed. The default is `Center`.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#horizontal-align>
-}
horizontalAlign : HorizontalAlign -> Attribute
horizontalAlign =
HAlign
{-| Controls where the cropping will occur if some height needs to be trimmed. The default is `Middle`.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#vertical-align>
-}
verticalAlign : VerticalAlign -> Attribute
verticalAlign =
VAlign
{-| Thumbor uses some advanced techniques for obtaining important points of the image, called focal points.
If you use this attribute, smart cropping will be performed and will override both horizontal and vertical alignments
if it finds any focal points.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#smart-cropping>
-}
smart : Attribute
smart =
Smart
-- Internal
generatePathSegments : List Attribute -> List String
generatePathSegments attributes =
List.filterMap (\f -> f attributes)
[ findTrimPathSegment
, findManualCropPathSegment
, findFitInSegment
, findSizePathSegment
, findHorizontalAlignSegment
, findVerticalAlignSegment
, findSmartSegment
, findFiltersPathSegment
]
findHorizontalAlignSegment : List Attribute -> Maybe String
findHorizontalAlignSegment =
List.foldl
(\item acc ->
case item of
HAlign Left ->
Just "left"
HAlign Right ->
Just "right"
HAlign Center ->
Nothing
_ ->
acc
)
Nothing
findVerticalAlignSegment : List Attribute -> Maybe String
findVerticalAlignSegment =
List.foldl
(\item acc ->
case item of
VAlign Top ->
Just "top"
VAlign Bottom ->
Just "bottom"
VAlign Middle ->
Nothing
_ ->
acc
)
Nothing
findSmartSegment : List Attribute -> Maybe String
findSmartSegment =
List.foldl
(\item acc ->
case item of
Smart ->
Just "smart"
_ ->
acc
)
Nothing
sizeToString : Size -> String
sizeToString value =
case value of
Fixed i ->
String.fromInt i
Proportional ->
"0"
Original ->
"orig"
findSizePathSegment : List Attribute -> Maybe String
findSizePathSegment =
List.foldl
(\item acc ->
case item of
Size width height ->
Just (sizeToString width ++ "x" ++ sizeToString height)
_ ->
acc
)
Nothing
findFitInSegment : List Attribute -> Maybe String
findFitInSegment =
List.foldl
(\item acc ->
case item of
FitIn NormalFitIn ->
Just "fit-in"
FitIn FullFitIn ->
Just "full-fit-in"
FitIn AdaptiveFitIn ->
Just "adaptive-fit-in"
_ ->
acc
)
Nothing
findFiltersPathSegment : List Attribute -> Maybe String
findFiltersPathSegment =
List.foldl
(\item acc ->
case item of
Filters filters_ ->
filters_
|> List.map Thumbor.Filter.toString
|> String.join ":"
|> (++) "filters:"
|> Just
_ ->
acc
)
Nothing
findManualCropPathSegment : List Attribute -> Maybe String
findManualCropPathSegment =
List.foldl
(\item acc ->
case item of
ManualCrop { left, top, right, bottom } ->
let
leftString =
String.fromInt left
topString =
String.fromInt top
rightString =
String.fromInt right
bottomString =
String.fromInt bottom
in
Just (leftString ++ "x" ++ topString ++ ":" ++ rightString ++ "x" ++ bottomString)
_ ->
acc
)
Nothing
findTrimPathSegment : List Attribute -> Maybe String
findTrimPathSegment =
List.foldl
(\item acc ->
case item of
Trim source tolerance ->
let
normalizedTolerance =
clamp 0 442 tolerance
sourceString =
case source of
TopLeft ->
"top-left"
BottomRight ->
"bottom-right"
in
if source == BottomRight || normalizedTolerance > 0 then
Just ("trim:" ++ sourceString ++ ":" ++ String.fromInt normalizedTolerance)
else
Just "trim"
_ ->
acc
)
Nothing
| 49980 | module Thumbor exposing
( url
, Config
, Attribute
, size, sizeFixed, Size(..)
, manualCrop, horizontalAlign, HorizontalAlign(..), verticalAlign, VerticalAlign(..)
, trim, trimSimple, TrimSource(..)
, fitIn, FitInMode(..)
, filters, smart
)
{-|
# Core Functionality
@docs url
# Configuration
@docs Config
# Attributes
@docs Attribute
## Sizing
@docs size, sizeFixed, Size
## Cropping
@docs manualCrop, horizontalAlign, HorizontalAlign, verticalAlign, VerticalAlign
## Trimming
@docs trim, trimSimple, TrimSource
## Fitting
@docs fitIn, FitInMode
## Miscellaneous
@docs filters, smart
-}
import HmacSha1
import Thumbor.Filter exposing (Filter)
import Url.Builder
import Util
{-| Thumbor server configuration. The `baseUrl` configures the base URL your Thumbor instance is hosted on. It must contain at least an URL schema and host and can contain a custom port or path.
`key` contains your key for [URL signing](https://thumbor.readthedocs.io/en/latest/security.html#security). If `Nothing` is provided, URL signing will be disabled.
**Important Security Notice:** Since Elm is mostly used in front-end code, **your key will be exposed in clear-text to all clients**, nullifying the effect of this security measure.
**Make sure you have an alternate concept to stop URL tampering!**
Examples:
{ baseUrl = "https://example.com"
, key = Just "<KEY>"
}
{ baseUrl = "https://example.com/thumbor"
, key = Just "<KEY>"
}
{ baseUrl = "https://example.com:1138/thumbor"
, key = Just "<KEY>"
}
-}
type alias Config =
{ baseUrl : String
, key : Maybe String
}
{-| -}
type FitInMode
= NormalFitIn
| AdaptiveFitIn
| FullFitIn
{-| -}
type TrimSource
= TopLeft
| BottomRight
{-| -}
type HorizontalAlign
= Left
| Center
| Right
{-| -}
type VerticalAlign
= Top
| Middle
| Bottom
{-| -}
type Size
= Fixed Int
| Proportional
| Original
{-| Creates a new image URL based on the given [`Config`](#Config), [`Attributes`](#Attribute) and original image URL.
Attributes can occur in any order. If an attribute is specified multiple times, the last occurrence wins - very much
like how [`elm/html`](https://package.elm-lang.org/packages/elm/html/latest/) attributes work.
You might want to use currying to ease usage of this package:
thumbor : List Thumbor.Attribute -> String -> String
thumbor =
Thumbor.url
{ host = "https://example.com:1138"
, key = Just "<KEY>"
}
-- Prepare a common configuration for teaser images
prepareTeaserImage : String -> String
prepareTeaserImage =
thumbor [ Thumbor.scale 200 300 ]
-- Actually use this package to create a modified image
view : Model -> Html msg
view model =
img [ src (prepareTeaserImage "https://example.com/image.jpg") ] []
-}
url : Config -> List Attribute -> String -> String
url { baseUrl, key } attributes imageUrl =
let
pathSegments =
Url.Builder.relative (generatePathSegments attributes ++ [ imageUrl ]) []
hmacSignature =
case key of
Just value ->
HmacSha1.digest value pathSegments
|> HmacSha1.toBase64
|> Result.toMaybe
-- This case should never happen, base64 encode itself cannot fail. We have to investigate why
-- the HMAC library returns a Maybe here. Fallback is an unsafe Thumbor URL.
|> Maybe.withDefault "unsafe"
|> String.replace "+" "-"
|> String.replace "/" "_"
Nothing ->
"unsafe"
in
Url.Builder.crossOrigin baseUrl [ hmacSignature, pathSegments ] []
{-| Represents a Thumbor attribute, controlling how images are processed. See below for a list of available attribute constructors.
-}
type Attribute
= Size Size Size
| Filters (List Filter)
| FitIn FitInMode
| Trim TrimSource Int
| ManualCrop { left : Int, top : Int, right : Int, bottom : Int }
| HAlign HorizontalAlign
| VAlign VerticalAlign
| Smart
{-| Specifies the size of the image that will be returned by the service.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#image-size>
-}
size : Size -> Size -> Attribute
size =
Size
{-| Same as [size](#size), but always uses `Fixed` sizing for convenience.
-}
sizeFixed : Int -> Int -> Attribute
sizeFixed width height =
Size (Fixed width) (Fixed height)
{-| Specifies that the image should **not** be auto-cropped and auto-resized to be **exactly** the specified size, and
should be fit in an imaginary box (given by the [sizing](#sizing) argument) instead.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#fit-in>
-}
fitIn : FitInMode -> Attribute
fitIn =
FitIn
{-| Sets a list of filters as a chain to be used. See [Thumbor.Filter](Thumbor-Filter) for available filters and their usage.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#filters>
-}
filters : List Filter -> Attribute
filters =
Filters
{-| Removes surrounding space in images based on its color. You can pass in the source where the color should be sampled
with a [TrimSource](#TrimSource). In addition, you can specify a color tolerance with the second parameter. The tolerance
value will be clamped between `0` and `442`.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#trim>
-}
trim : TrimSource -> Int -> Attribute
trim =
Trim
{-| Same as [trim](#trim), but always uses `TopLeft` source and `0` tolerance.
-}
trimSimple : Attribute
trimSimple =
Trim TopLeft 0
{-| Useful for applications that provide custom real-time cropping capabilities.
This crop is performed before the rest of the operations, so it can be used as a prepare step _before_ resizing and smart-cropping.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#manual-crop>
-}
manualCrop : { left : Int, top : Int, right : Int, bottom : Int } -> Attribute
manualCrop =
ManualCrop
{-| Controls where the cropping will occur if some width needs to be trimmed. The default is `Center`.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#horizontal-align>
-}
horizontalAlign : HorizontalAlign -> Attribute
horizontalAlign =
HAlign
{-| Controls where the cropping will occur if some height needs to be trimmed. The default is `Middle`.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#vertical-align>
-}
verticalAlign : VerticalAlign -> Attribute
verticalAlign =
VAlign
{-| Thumbor uses some advanced techniques for obtaining important points of the image, called focal points.
If you use this attribute, smart cropping will be performed and will override both horizontal and vertical alignments
if it finds any focal points.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#smart-cropping>
-}
smart : Attribute
smart =
Smart
-- Internal
generatePathSegments : List Attribute -> List String
generatePathSegments attributes =
List.filterMap (\f -> f attributes)
[ findTrimPathSegment
, findManualCropPathSegment
, findFitInSegment
, findSizePathSegment
, findHorizontalAlignSegment
, findVerticalAlignSegment
, findSmartSegment
, findFiltersPathSegment
]
findHorizontalAlignSegment : List Attribute -> Maybe String
findHorizontalAlignSegment =
List.foldl
(\item acc ->
case item of
HAlign Left ->
Just "left"
HAlign Right ->
Just "right"
HAlign Center ->
Nothing
_ ->
acc
)
Nothing
findVerticalAlignSegment : List Attribute -> Maybe String
findVerticalAlignSegment =
List.foldl
(\item acc ->
case item of
VAlign Top ->
Just "top"
VAlign Bottom ->
Just "bottom"
VAlign Middle ->
Nothing
_ ->
acc
)
Nothing
findSmartSegment : List Attribute -> Maybe String
findSmartSegment =
List.foldl
(\item acc ->
case item of
Smart ->
Just "smart"
_ ->
acc
)
Nothing
sizeToString : Size -> String
sizeToString value =
case value of
Fixed i ->
String.fromInt i
Proportional ->
"0"
Original ->
"orig"
findSizePathSegment : List Attribute -> Maybe String
findSizePathSegment =
List.foldl
(\item acc ->
case item of
Size width height ->
Just (sizeToString width ++ "x" ++ sizeToString height)
_ ->
acc
)
Nothing
findFitInSegment : List Attribute -> Maybe String
findFitInSegment =
List.foldl
(\item acc ->
case item of
FitIn NormalFitIn ->
Just "fit-in"
FitIn FullFitIn ->
Just "full-fit-in"
FitIn AdaptiveFitIn ->
Just "adaptive-fit-in"
_ ->
acc
)
Nothing
findFiltersPathSegment : List Attribute -> Maybe String
findFiltersPathSegment =
List.foldl
(\item acc ->
case item of
Filters filters_ ->
filters_
|> List.map Thumbor.Filter.toString
|> String.join ":"
|> (++) "filters:"
|> Just
_ ->
acc
)
Nothing
findManualCropPathSegment : List Attribute -> Maybe String
findManualCropPathSegment =
List.foldl
(\item acc ->
case item of
ManualCrop { left, top, right, bottom } ->
let
leftString =
String.fromInt left
topString =
String.fromInt top
rightString =
String.fromInt right
bottomString =
String.fromInt bottom
in
Just (leftString ++ "x" ++ topString ++ ":" ++ rightString ++ "x" ++ bottomString)
_ ->
acc
)
Nothing
findTrimPathSegment : List Attribute -> Maybe String
findTrimPathSegment =
List.foldl
(\item acc ->
case item of
Trim source tolerance ->
let
normalizedTolerance =
clamp 0 442 tolerance
sourceString =
case source of
TopLeft ->
"top-left"
BottomRight ->
"bottom-right"
in
if source == BottomRight || normalizedTolerance > 0 then
Just ("trim:" ++ sourceString ++ ":" ++ String.fromInt normalizedTolerance)
else
Just "trim"
_ ->
acc
)
Nothing
| true | module Thumbor exposing
( url
, Config
, Attribute
, size, sizeFixed, Size(..)
, manualCrop, horizontalAlign, HorizontalAlign(..), verticalAlign, VerticalAlign(..)
, trim, trimSimple, TrimSource(..)
, fitIn, FitInMode(..)
, filters, smart
)
{-|
# Core Functionality
@docs url
# Configuration
@docs Config
# Attributes
@docs Attribute
## Sizing
@docs size, sizeFixed, Size
## Cropping
@docs manualCrop, horizontalAlign, HorizontalAlign, verticalAlign, VerticalAlign
## Trimming
@docs trim, trimSimple, TrimSource
## Fitting
@docs fitIn, FitInMode
## Miscellaneous
@docs filters, smart
-}
import HmacSha1
import Thumbor.Filter exposing (Filter)
import Url.Builder
import Util
{-| Thumbor server configuration. The `baseUrl` configures the base URL your Thumbor instance is hosted on. It must contain at least an URL schema and host and can contain a custom port or path.
`key` contains your key for [URL signing](https://thumbor.readthedocs.io/en/latest/security.html#security). If `Nothing` is provided, URL signing will be disabled.
**Important Security Notice:** Since Elm is mostly used in front-end code, **your key will be exposed in clear-text to all clients**, nullifying the effect of this security measure.
**Make sure you have an alternate concept to stop URL tampering!**
Examples:
{ baseUrl = "https://example.com"
, key = Just "PI:KEY:<KEY>END_PI"
}
{ baseUrl = "https://example.com/thumbor"
, key = Just "PI:KEY:<KEY>END_PI"
}
{ baseUrl = "https://example.com:1138/thumbor"
, key = Just "PI:KEY:<KEY>END_PI"
}
-}
type alias Config =
{ baseUrl : String
, key : Maybe String
}
{-| -}
type FitInMode
= NormalFitIn
| AdaptiveFitIn
| FullFitIn
{-| -}
type TrimSource
= TopLeft
| BottomRight
{-| -}
type HorizontalAlign
= Left
| Center
| Right
{-| -}
type VerticalAlign
= Top
| Middle
| Bottom
{-| -}
type Size
= Fixed Int
| Proportional
| Original
{-| Creates a new image URL based on the given [`Config`](#Config), [`Attributes`](#Attribute) and original image URL.
Attributes can occur in any order. If an attribute is specified multiple times, the last occurrence wins - very much
like how [`elm/html`](https://package.elm-lang.org/packages/elm/html/latest/) attributes work.
You might want to use currying to ease usage of this package:
thumbor : List Thumbor.Attribute -> String -> String
thumbor =
Thumbor.url
{ host = "https://example.com:1138"
, key = Just "PI:KEY:<KEY>END_PI"
}
-- Prepare a common configuration for teaser images
prepareTeaserImage : String -> String
prepareTeaserImage =
thumbor [ Thumbor.scale 200 300 ]
-- Actually use this package to create a modified image
view : Model -> Html msg
view model =
img [ src (prepareTeaserImage "https://example.com/image.jpg") ] []
-}
url : Config -> List Attribute -> String -> String
url { baseUrl, key } attributes imageUrl =
let
pathSegments =
Url.Builder.relative (generatePathSegments attributes ++ [ imageUrl ]) []
hmacSignature =
case key of
Just value ->
HmacSha1.digest value pathSegments
|> HmacSha1.toBase64
|> Result.toMaybe
-- This case should never happen, base64 encode itself cannot fail. We have to investigate why
-- the HMAC library returns a Maybe here. Fallback is an unsafe Thumbor URL.
|> Maybe.withDefault "unsafe"
|> String.replace "+" "-"
|> String.replace "/" "_"
Nothing ->
"unsafe"
in
Url.Builder.crossOrigin baseUrl [ hmacSignature, pathSegments ] []
{-| Represents a Thumbor attribute, controlling how images are processed. See below for a list of available attribute constructors.
-}
type Attribute
= Size Size Size
| Filters (List Filter)
| FitIn FitInMode
| Trim TrimSource Int
| ManualCrop { left : Int, top : Int, right : Int, bottom : Int }
| HAlign HorizontalAlign
| VAlign VerticalAlign
| Smart
{-| Specifies the size of the image that will be returned by the service.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#image-size>
-}
size : Size -> Size -> Attribute
size =
Size
{-| Same as [size](#size), but always uses `Fixed` sizing for convenience.
-}
sizeFixed : Int -> Int -> Attribute
sizeFixed width height =
Size (Fixed width) (Fixed height)
{-| Specifies that the image should **not** be auto-cropped and auto-resized to be **exactly** the specified size, and
should be fit in an imaginary box (given by the [sizing](#sizing) argument) instead.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#fit-in>
-}
fitIn : FitInMode -> Attribute
fitIn =
FitIn
{-| Sets a list of filters as a chain to be used. See [Thumbor.Filter](Thumbor-Filter) for available filters and their usage.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#filters>
-}
filters : List Filter -> Attribute
filters =
Filters
{-| Removes surrounding space in images based on its color. You can pass in the source where the color should be sampled
with a [TrimSource](#TrimSource). In addition, you can specify a color tolerance with the second parameter. The tolerance
value will be clamped between `0` and `442`.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#trim>
-}
trim : TrimSource -> Int -> Attribute
trim =
Trim
{-| Same as [trim](#trim), but always uses `TopLeft` source and `0` tolerance.
-}
trimSimple : Attribute
trimSimple =
Trim TopLeft 0
{-| Useful for applications that provide custom real-time cropping capabilities.
This crop is performed before the rest of the operations, so it can be used as a prepare step _before_ resizing and smart-cropping.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#manual-crop>
-}
manualCrop : { left : Int, top : Int, right : Int, bottom : Int } -> Attribute
manualCrop =
ManualCrop
{-| Controls where the cropping will occur if some width needs to be trimmed. The default is `Center`.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#horizontal-align>
-}
horizontalAlign : HorizontalAlign -> Attribute
horizontalAlign =
HAlign
{-| Controls where the cropping will occur if some height needs to be trimmed. The default is `Middle`.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#vertical-align>
-}
verticalAlign : VerticalAlign -> Attribute
verticalAlign =
VAlign
{-| Thumbor uses some advanced techniques for obtaining important points of the image, called focal points.
If you use this attribute, smart cropping will be performed and will override both horizontal and vertical alignments
if it finds any focal points.
Thumbor docs: <https://thumbor.readthedocs.io/en/latest/usage.html#smart-cropping>
-}
smart : Attribute
smart =
Smart
-- Internal
generatePathSegments : List Attribute -> List String
generatePathSegments attributes =
List.filterMap (\f -> f attributes)
[ findTrimPathSegment
, findManualCropPathSegment
, findFitInSegment
, findSizePathSegment
, findHorizontalAlignSegment
, findVerticalAlignSegment
, findSmartSegment
, findFiltersPathSegment
]
findHorizontalAlignSegment : List Attribute -> Maybe String
findHorizontalAlignSegment =
List.foldl
(\item acc ->
case item of
HAlign Left ->
Just "left"
HAlign Right ->
Just "right"
HAlign Center ->
Nothing
_ ->
acc
)
Nothing
findVerticalAlignSegment : List Attribute -> Maybe String
findVerticalAlignSegment =
List.foldl
(\item acc ->
case item of
VAlign Top ->
Just "top"
VAlign Bottom ->
Just "bottom"
VAlign Middle ->
Nothing
_ ->
acc
)
Nothing
findSmartSegment : List Attribute -> Maybe String
findSmartSegment =
List.foldl
(\item acc ->
case item of
Smart ->
Just "smart"
_ ->
acc
)
Nothing
sizeToString : Size -> String
sizeToString value =
case value of
Fixed i ->
String.fromInt i
Proportional ->
"0"
Original ->
"orig"
findSizePathSegment : List Attribute -> Maybe String
findSizePathSegment =
List.foldl
(\item acc ->
case item of
Size width height ->
Just (sizeToString width ++ "x" ++ sizeToString height)
_ ->
acc
)
Nothing
findFitInSegment : List Attribute -> Maybe String
findFitInSegment =
List.foldl
(\item acc ->
case item of
FitIn NormalFitIn ->
Just "fit-in"
FitIn FullFitIn ->
Just "full-fit-in"
FitIn AdaptiveFitIn ->
Just "adaptive-fit-in"
_ ->
acc
)
Nothing
findFiltersPathSegment : List Attribute -> Maybe String
findFiltersPathSegment =
List.foldl
(\item acc ->
case item of
Filters filters_ ->
filters_
|> List.map Thumbor.Filter.toString
|> String.join ":"
|> (++) "filters:"
|> Just
_ ->
acc
)
Nothing
findManualCropPathSegment : List Attribute -> Maybe String
findManualCropPathSegment =
List.foldl
(\item acc ->
case item of
ManualCrop { left, top, right, bottom } ->
let
leftString =
String.fromInt left
topString =
String.fromInt top
rightString =
String.fromInt right
bottomString =
String.fromInt bottom
in
Just (leftString ++ "x" ++ topString ++ ":" ++ rightString ++ "x" ++ bottomString)
_ ->
acc
)
Nothing
findTrimPathSegment : List Attribute -> Maybe String
findTrimPathSegment =
List.foldl
(\item acc ->
case item of
Trim source tolerance ->
let
normalizedTolerance =
clamp 0 442 tolerance
sourceString =
case source of
TopLeft ->
"top-left"
BottomRight ->
"bottom-right"
in
if source == BottomRight || normalizedTolerance > 0 then
Just ("trim:" ++ sourceString ++ ":" ++ String.fromInt normalizedTolerance)
else
Just "trim"
_ ->
acc
)
Nothing
| elm |
[
{
"context": "{-\n Copyright 2020 Morgan Stanley\n\n Licensed under the Apache License, Version 2.",
"end": 35,
"score": 0.9997974634,
"start": 21,
"tag": "NAME",
"value": "Morgan Stanley"
}
] | src/Morphir/IR/Path/CodecV1.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.Path.CodecV1 exposing (..)
{-| Encode a path to JSON.
-}
import Json.Decode as Decode
import Json.Encode as Encode
import Morphir.IR.Name.CodecV1 exposing (decodeName, encodeName)
import Morphir.IR.Path as Path exposing (Path)
encodePath : Path -> Encode.Value
encodePath path =
path
|> Path.toList
|> Encode.list encodeName
{-| Decode a path from JSON.
-}
decodePath : Decode.Decoder Path
decodePath =
Decode.list decodeName
|> Decode.map Path.fromList
| 8135 | {-
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.Path.CodecV1 exposing (..)
{-| Encode a path to JSON.
-}
import Json.Decode as Decode
import Json.Encode as Encode
import Morphir.IR.Name.CodecV1 exposing (decodeName, encodeName)
import Morphir.IR.Path as Path exposing (Path)
encodePath : Path -> Encode.Value
encodePath path =
path
|> Path.toList
|> Encode.list encodeName
{-| Decode a path from JSON.
-}
decodePath : Decode.Decoder Path
decodePath =
Decode.list decodeName
|> Decode.map Path.fromList
| 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.Path.CodecV1 exposing (..)
{-| Encode a path to JSON.
-}
import Json.Decode as Decode
import Json.Encode as Encode
import Morphir.IR.Name.CodecV1 exposing (decodeName, encodeName)
import Morphir.IR.Path as Path exposing (Path)
encodePath : Path -> Encode.Value
encodePath path =
path
|> Path.toList
|> Encode.list encodeName
{-| Decode a path from JSON.
-}
decodePath : Decode.Decoder Path
decodePath =
Decode.list decodeName
|> Decode.map Path.fromList
| elm |
[
{
"context": "ame\n@docs dayOfMonthWithSuffix\n\nCopyright (c) 2017 Yosuke Torii\n\n-}\n\nimport Date exposing (Day(..), Month(..))\n\n\n",
"end": 213,
"score": 0.9998582006,
"start": 201,
"tag": "NAME",
"value": "Yosuke Torii"
}
] | src/Date/Extra/I18n/I_ja_jp.elm | AdrianRibao/elm-date-extra | 81 | module Date.Extra.I18n.I_ja_jp exposing (..)
{-| Japanese values for day and month names.
@docs dayShort
@docs dayName
@docs monthShort
@docs monthName
@docs dayOfMonthWithSuffix
Copyright (c) 2017 Yosuke Torii
-}
import Date exposing (Day(..), Month(..))
{-| Day short name.
-}
dayShort : Day -> String
dayShort day =
case day of
Mon ->
"月"
Tue ->
"火"
Wed ->
"水"
Thu ->
"木"
Fri ->
"金"
Sat ->
"土"
Sun ->
"日"
{-| Day full name.
-}
dayName : Day -> String
dayName day =
case day of
Mon ->
"月曜日"
Tue ->
"火曜日"
Wed ->
"水曜日"
Thu ->
"木曜日"
Fri ->
"金曜日"
Sat ->
"土曜日"
Sun ->
"日曜日"
{-| Month short name.
-}
monthShort : Month -> String
monthShort 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"
{-| Month full name.
-}
monthName : Month -> String
monthName 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月"
{-| No suffixes for Japanese
-}
dayOfMonthWithSuffix : Bool -> Int -> String
dayOfMonthWithSuffix pad day =
case day of
_ ->
toString day
| 1753 | module Date.Extra.I18n.I_ja_jp exposing (..)
{-| Japanese values for day and month names.
@docs dayShort
@docs dayName
@docs monthShort
@docs monthName
@docs dayOfMonthWithSuffix
Copyright (c) 2017 <NAME>
-}
import Date exposing (Day(..), Month(..))
{-| Day short name.
-}
dayShort : Day -> String
dayShort day =
case day of
Mon ->
"月"
Tue ->
"火"
Wed ->
"水"
Thu ->
"木"
Fri ->
"金"
Sat ->
"土"
Sun ->
"日"
{-| Day full name.
-}
dayName : Day -> String
dayName day =
case day of
Mon ->
"月曜日"
Tue ->
"火曜日"
Wed ->
"水曜日"
Thu ->
"木曜日"
Fri ->
"金曜日"
Sat ->
"土曜日"
Sun ->
"日曜日"
{-| Month short name.
-}
monthShort : Month -> String
monthShort 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"
{-| Month full name.
-}
monthName : Month -> String
monthName 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月"
{-| No suffixes for Japanese
-}
dayOfMonthWithSuffix : Bool -> Int -> String
dayOfMonthWithSuffix pad day =
case day of
_ ->
toString day
| true | module Date.Extra.I18n.I_ja_jp exposing (..)
{-| Japanese values for day and month names.
@docs dayShort
@docs dayName
@docs monthShort
@docs monthName
@docs dayOfMonthWithSuffix
Copyright (c) 2017 PI:NAME:<NAME>END_PI
-}
import Date exposing (Day(..), Month(..))
{-| Day short name.
-}
dayShort : Day -> String
dayShort day =
case day of
Mon ->
"月"
Tue ->
"火"
Wed ->
"水"
Thu ->
"木"
Fri ->
"金"
Sat ->
"土"
Sun ->
"日"
{-| Day full name.
-}
dayName : Day -> String
dayName day =
case day of
Mon ->
"月曜日"
Tue ->
"火曜日"
Wed ->
"水曜日"
Thu ->
"木曜日"
Fri ->
"金曜日"
Sat ->
"土曜日"
Sun ->
"日曜日"
{-| Month short name.
-}
monthShort : Month -> String
monthShort 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"
{-| Month full name.
-}
monthName : Month -> String
monthName 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月"
{-| No suffixes for Japanese
-}
dayOfMonthWithSuffix : Bool -> Int -> String
dayOfMonthWithSuffix pad day =
case day of
_ ->
toString day
| elm |
[
{
"context": " ( { model\n | password = password\n , confirmPassword =\n ",
"end": 1936,
"score": 0.9891083837,
"start": 1928,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "model\n | email = email\n , password = password\n , confirmPassword = confirmPassword\n ",
"end": 8450,
"score": 0.9982444048,
"start": 8442,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " , password = password\n , confirmPassword = confirmPassword\n , acceptPolicy = acceptPolicy\n }\n\n\nsub",
"end": 8494,
"score": 0.9970964193,
"start": 8479,
"tag": "PASSWORD",
"value": "confirmPassword"
}
] | example/Main.elm | elm-review-bot/elm-validate | 2 | module Main exposing (main)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onBlur, onCheck, onClick, onInput, onSubmit)
import Http
import Json.Decode as Decode
import Json.Encode as Encode
import Validation exposing (..)
import Validators exposing (..)
main : Program () Model Msg
main =
Browser.element
{ init = always ( initModel, Cmd.none )
, view = view
, update = update
, subscriptions = \model -> Sub.none
}
type alias Model =
{ email : Field String String
, password : Field String String
, confirmPassword : Field String String
, acceptPolicy : Field Bool Bool
, status : SubmissionStatus
}
initModel : Model
initModel =
{ email = field ""
, password = field ""
, confirmPassword = field ""
, acceptPolicy = field False
, status = NotSubmitted
}
type Msg
= InputEmail String
| BlurEmail
| InputPassword String
| BlurPassword
| InputConfirmPassword String
| BlurConfirmPassword
| CheckAcceptPolicy Bool
| Submit
| SubmitResponse (Result Http.Error ())
-- Update
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
InputEmail e ->
( { model
| email =
model.email
|> validate (OnChange e) emailValidation
}
, Cmd.none
)
BlurEmail ->
( { model
| email =
model.email
|> validate OnBlur emailValidation
}
, Cmd.none
)
InputPassword p ->
let
password =
model.password
|> validate (OnChange p) passwordValidation
in
( { model
| password = password
, confirmPassword =
model.confirmPassword
|> validate OnRelatedChange (confirmPasswordValidation password)
}
, Cmd.none
)
BlurPassword ->
( { model
| password =
model.password
|> validate OnBlur passwordValidation
}
, Cmd.none
)
InputConfirmPassword p ->
( { model
| confirmPassword =
model.confirmPassword
|> validate (OnChange p) (confirmPasswordValidation model.password)
}
, Cmd.none
)
BlurConfirmPassword ->
( { model
| confirmPassword =
model.confirmPassword
|> validate OnBlur (confirmPasswordValidation model.password)
}
, Cmd.none
)
CheckAcceptPolicy a ->
( { model
| acceptPolicy = field a
}
, Cmd.none
)
Submit ->
model |> validateModel |> submitIfValid
SubmitResponse (Ok ()) ->
( { initModel
| status = Succeeded
}
, Cmd.none
)
SubmitResponse (Err _) ->
( { model
| status = Failed
}
, Cmd.none
)
-- View
view : Model -> Html Msg
view model =
div [ class "container" ]
[ Html.form
[ class "form"
, onSubmit Submit
, novalidate True
]
[ header model
, body model
, footer model
]
, div [ class "model-form" ]
(modelForm model)
]
header : Model -> Html Msg
header model =
div [ class "header" ]
[ h1 [] [ text "Register" ]
, renderStatus model.status
]
renderStatus : SubmissionStatus -> Html Msg
renderStatus status =
case status of
NotSubmitted ->
div [] []
InProcess ->
div [] [ text "Your request is being sent." ]
Succeeded ->
div [] [ text "Your request has been received." ]
Failed ->
div [ class "msg--error" ]
[ text "There was an error, please try again." ]
body : Model -> Html Msg
body model =
div [ class "content" ]
[ div []
[ input
[ placeholder "Your email *"
, type_ "email"
, required True
, value (model.email |> rawValue)
, onInput InputEmail
, onBlur BlurEmail
]
[]
, errorLabel model.email
]
, div []
[ input
[ placeholder "Your password *"
, type_ "password"
, required True
, value (model.password |> rawValue)
, onInput InputPassword
, onBlur BlurPassword
]
[]
, errorLabel model.password
]
, div []
[ input
[ placeholder "Your confirm password *"
, type_ "password"
, required True
, value (model.confirmPassword |> rawValue)
, onInput InputConfirmPassword
, onBlur BlurConfirmPassword
]
[]
, errorLabel model.confirmPassword
]
, div []
[ input
[ type_ "checkbox"
, id "terms"
, value (model.acceptPolicy |> rawValue |> Debug.toString)
, onCheck CheckAcceptPolicy
]
[]
, label [ for "terms" ]
[ text "I accept the privacy policy" ]
]
, div []
[ errorLabel model.acceptPolicy ]
]
errorLabel : Field raw a -> Html Msg
errorLabel fieldErrLbl =
div [ class "msg msg--error" ]
[ fieldErrLbl
|> extractError
|> Maybe.withDefault ""
|> text
]
footer : Model -> Html Msg
footer model =
div []
[ button
[ class "btn__submit"
, type_ "submit"
, disabled (model.status == InProcess)
]
[ text "Submit" ]
]
modelForm : Model -> List (Html msg)
modelForm model =
[ div [ class "header" ]
[ h1 [] [ text "Model state" ] ]
, div []
[ text "{ email ="
, p [ class "model__el" ]
[ model.email |> Debug.toString |> text ]
]
, div []
[ text ", password ="
, p [ class "model__el" ]
[ model.password |> Debug.toString |> text ]
]
, div []
[ text ", confirmPassword ="
, p [ class "model__el" ]
[ model.confirmPassword |> Debug.toString |> text ]
]
, div []
[ text ", acceptPolicy ="
, p [ class "model__el" ]
[ model.acceptPolicy |> Debug.toString |> text ]
]
, div []
[ text ", status ="
, div [ class "model__el" ]
[ model.status |> Debug.toString |> text ]
, text "}"
]
]
-- Validation
emailValidation : Validator String String
emailValidation =
composite (isNotEmpty "An email is required.") (isEmail "Please ensure this is a valid email.")
passwordValidation : Validator String String
passwordValidation =
isNotEmpty "Please enter a password."
confirmPasswordValidation : Field raw String -> Validator String String
confirmPasswordValidation password =
composite (isNotEmpty "Please enter a password.") (isEqualTo password "The passwords don't match.")
validateModel : Model -> Model
validateModel model =
let
email =
model.email |> validate OnSubmit emailValidation
password =
model.password |> validate OnSubmit passwordValidation
confirmPassword =
model.confirmPassword
|> validate OnSubmit (confirmPasswordValidation password)
acceptPolicy =
model.acceptPolicy
|> validate OnSubmit (isTrue "You must accept the policy.")
in
{ model
| email = email
, password = password
, confirmPassword = confirmPassword
, acceptPolicy = acceptPolicy
}
submitIfValid : Model -> ( Model, Cmd Msg )
submitIfValid model =
let
submissionResult =
Valid submit
|> applyValidity (validity model.email)
|> applyValidity (validity model.password)
|> applyValidity (validity model.confirmPassword)
|> applyValidity (validity model.acceptPolicy)
in
case submissionResult of
Valid cmd ->
( { model | status = InProcess }
, cmd
)
_ ->
( model, Cmd.none )
-- Send request
submit : String -> String -> String -> Bool -> Cmd Msg
submit email password _ _ =
let
url =
"http://localhost:8080/api/register"
json =
Encode.object
[ ( "email", Encode.string email )
, ( "password", Encode.string password )
]
decoder =
Decode.string |> Decode.map (always ())
request =
Http.post url (Http.jsonBody json) decoder
in
request
|> Http.send SubmitResponse
| 39566 | module Main exposing (main)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onBlur, onCheck, onClick, onInput, onSubmit)
import Http
import Json.Decode as Decode
import Json.Encode as Encode
import Validation exposing (..)
import Validators exposing (..)
main : Program () Model Msg
main =
Browser.element
{ init = always ( initModel, Cmd.none )
, view = view
, update = update
, subscriptions = \model -> Sub.none
}
type alias Model =
{ email : Field String String
, password : Field String String
, confirmPassword : Field String String
, acceptPolicy : Field Bool Bool
, status : SubmissionStatus
}
initModel : Model
initModel =
{ email = field ""
, password = field ""
, confirmPassword = field ""
, acceptPolicy = field False
, status = NotSubmitted
}
type Msg
= InputEmail String
| BlurEmail
| InputPassword String
| BlurPassword
| InputConfirmPassword String
| BlurConfirmPassword
| CheckAcceptPolicy Bool
| Submit
| SubmitResponse (Result Http.Error ())
-- Update
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
InputEmail e ->
( { model
| email =
model.email
|> validate (OnChange e) emailValidation
}
, Cmd.none
)
BlurEmail ->
( { model
| email =
model.email
|> validate OnBlur emailValidation
}
, Cmd.none
)
InputPassword p ->
let
password =
model.password
|> validate (OnChange p) passwordValidation
in
( { model
| password = <PASSWORD>
, confirmPassword =
model.confirmPassword
|> validate OnRelatedChange (confirmPasswordValidation password)
}
, Cmd.none
)
BlurPassword ->
( { model
| password =
model.password
|> validate OnBlur passwordValidation
}
, Cmd.none
)
InputConfirmPassword p ->
( { model
| confirmPassword =
model.confirmPassword
|> validate (OnChange p) (confirmPasswordValidation model.password)
}
, Cmd.none
)
BlurConfirmPassword ->
( { model
| confirmPassword =
model.confirmPassword
|> validate OnBlur (confirmPasswordValidation model.password)
}
, Cmd.none
)
CheckAcceptPolicy a ->
( { model
| acceptPolicy = field a
}
, Cmd.none
)
Submit ->
model |> validateModel |> submitIfValid
SubmitResponse (Ok ()) ->
( { initModel
| status = Succeeded
}
, Cmd.none
)
SubmitResponse (Err _) ->
( { model
| status = Failed
}
, Cmd.none
)
-- View
view : Model -> Html Msg
view model =
div [ class "container" ]
[ Html.form
[ class "form"
, onSubmit Submit
, novalidate True
]
[ header model
, body model
, footer model
]
, div [ class "model-form" ]
(modelForm model)
]
header : Model -> Html Msg
header model =
div [ class "header" ]
[ h1 [] [ text "Register" ]
, renderStatus model.status
]
renderStatus : SubmissionStatus -> Html Msg
renderStatus status =
case status of
NotSubmitted ->
div [] []
InProcess ->
div [] [ text "Your request is being sent." ]
Succeeded ->
div [] [ text "Your request has been received." ]
Failed ->
div [ class "msg--error" ]
[ text "There was an error, please try again." ]
body : Model -> Html Msg
body model =
div [ class "content" ]
[ div []
[ input
[ placeholder "Your email *"
, type_ "email"
, required True
, value (model.email |> rawValue)
, onInput InputEmail
, onBlur BlurEmail
]
[]
, errorLabel model.email
]
, div []
[ input
[ placeholder "Your password *"
, type_ "password"
, required True
, value (model.password |> rawValue)
, onInput InputPassword
, onBlur BlurPassword
]
[]
, errorLabel model.password
]
, div []
[ input
[ placeholder "Your confirm password *"
, type_ "password"
, required True
, value (model.confirmPassword |> rawValue)
, onInput InputConfirmPassword
, onBlur BlurConfirmPassword
]
[]
, errorLabel model.confirmPassword
]
, div []
[ input
[ type_ "checkbox"
, id "terms"
, value (model.acceptPolicy |> rawValue |> Debug.toString)
, onCheck CheckAcceptPolicy
]
[]
, label [ for "terms" ]
[ text "I accept the privacy policy" ]
]
, div []
[ errorLabel model.acceptPolicy ]
]
errorLabel : Field raw a -> Html Msg
errorLabel fieldErrLbl =
div [ class "msg msg--error" ]
[ fieldErrLbl
|> extractError
|> Maybe.withDefault ""
|> text
]
footer : Model -> Html Msg
footer model =
div []
[ button
[ class "btn__submit"
, type_ "submit"
, disabled (model.status == InProcess)
]
[ text "Submit" ]
]
modelForm : Model -> List (Html msg)
modelForm model =
[ div [ class "header" ]
[ h1 [] [ text "Model state" ] ]
, div []
[ text "{ email ="
, p [ class "model__el" ]
[ model.email |> Debug.toString |> text ]
]
, div []
[ text ", password ="
, p [ class "model__el" ]
[ model.password |> Debug.toString |> text ]
]
, div []
[ text ", confirmPassword ="
, p [ class "model__el" ]
[ model.confirmPassword |> Debug.toString |> text ]
]
, div []
[ text ", acceptPolicy ="
, p [ class "model__el" ]
[ model.acceptPolicy |> Debug.toString |> text ]
]
, div []
[ text ", status ="
, div [ class "model__el" ]
[ model.status |> Debug.toString |> text ]
, text "}"
]
]
-- Validation
emailValidation : Validator String String
emailValidation =
composite (isNotEmpty "An email is required.") (isEmail "Please ensure this is a valid email.")
passwordValidation : Validator String String
passwordValidation =
isNotEmpty "Please enter a password."
confirmPasswordValidation : Field raw String -> Validator String String
confirmPasswordValidation password =
composite (isNotEmpty "Please enter a password.") (isEqualTo password "The passwords don't match.")
validateModel : Model -> Model
validateModel model =
let
email =
model.email |> validate OnSubmit emailValidation
password =
model.password |> validate OnSubmit passwordValidation
confirmPassword =
model.confirmPassword
|> validate OnSubmit (confirmPasswordValidation password)
acceptPolicy =
model.acceptPolicy
|> validate OnSubmit (isTrue "You must accept the policy.")
in
{ model
| email = email
, password = <PASSWORD>
, confirmPassword = <PASSWORD>
, acceptPolicy = acceptPolicy
}
submitIfValid : Model -> ( Model, Cmd Msg )
submitIfValid model =
let
submissionResult =
Valid submit
|> applyValidity (validity model.email)
|> applyValidity (validity model.password)
|> applyValidity (validity model.confirmPassword)
|> applyValidity (validity model.acceptPolicy)
in
case submissionResult of
Valid cmd ->
( { model | status = InProcess }
, cmd
)
_ ->
( model, Cmd.none )
-- Send request
submit : String -> String -> String -> Bool -> Cmd Msg
submit email password _ _ =
let
url =
"http://localhost:8080/api/register"
json =
Encode.object
[ ( "email", Encode.string email )
, ( "password", Encode.string password )
]
decoder =
Decode.string |> Decode.map (always ())
request =
Http.post url (Http.jsonBody json) decoder
in
request
|> Http.send SubmitResponse
| true | module Main exposing (main)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onBlur, onCheck, onClick, onInput, onSubmit)
import Http
import Json.Decode as Decode
import Json.Encode as Encode
import Validation exposing (..)
import Validators exposing (..)
main : Program () Model Msg
main =
Browser.element
{ init = always ( initModel, Cmd.none )
, view = view
, update = update
, subscriptions = \model -> Sub.none
}
type alias Model =
{ email : Field String String
, password : Field String String
, confirmPassword : Field String String
, acceptPolicy : Field Bool Bool
, status : SubmissionStatus
}
initModel : Model
initModel =
{ email = field ""
, password = field ""
, confirmPassword = field ""
, acceptPolicy = field False
, status = NotSubmitted
}
type Msg
= InputEmail String
| BlurEmail
| InputPassword String
| BlurPassword
| InputConfirmPassword String
| BlurConfirmPassword
| CheckAcceptPolicy Bool
| Submit
| SubmitResponse (Result Http.Error ())
-- Update
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
InputEmail e ->
( { model
| email =
model.email
|> validate (OnChange e) emailValidation
}
, Cmd.none
)
BlurEmail ->
( { model
| email =
model.email
|> validate OnBlur emailValidation
}
, Cmd.none
)
InputPassword p ->
let
password =
model.password
|> validate (OnChange p) passwordValidation
in
( { model
| password = PI:PASSWORD:<PASSWORD>END_PI
, confirmPassword =
model.confirmPassword
|> validate OnRelatedChange (confirmPasswordValidation password)
}
, Cmd.none
)
BlurPassword ->
( { model
| password =
model.password
|> validate OnBlur passwordValidation
}
, Cmd.none
)
InputConfirmPassword p ->
( { model
| confirmPassword =
model.confirmPassword
|> validate (OnChange p) (confirmPasswordValidation model.password)
}
, Cmd.none
)
BlurConfirmPassword ->
( { model
| confirmPassword =
model.confirmPassword
|> validate OnBlur (confirmPasswordValidation model.password)
}
, Cmd.none
)
CheckAcceptPolicy a ->
( { model
| acceptPolicy = field a
}
, Cmd.none
)
Submit ->
model |> validateModel |> submitIfValid
SubmitResponse (Ok ()) ->
( { initModel
| status = Succeeded
}
, Cmd.none
)
SubmitResponse (Err _) ->
( { model
| status = Failed
}
, Cmd.none
)
-- View
view : Model -> Html Msg
view model =
div [ class "container" ]
[ Html.form
[ class "form"
, onSubmit Submit
, novalidate True
]
[ header model
, body model
, footer model
]
, div [ class "model-form" ]
(modelForm model)
]
header : Model -> Html Msg
header model =
div [ class "header" ]
[ h1 [] [ text "Register" ]
, renderStatus model.status
]
renderStatus : SubmissionStatus -> Html Msg
renderStatus status =
case status of
NotSubmitted ->
div [] []
InProcess ->
div [] [ text "Your request is being sent." ]
Succeeded ->
div [] [ text "Your request has been received." ]
Failed ->
div [ class "msg--error" ]
[ text "There was an error, please try again." ]
body : Model -> Html Msg
body model =
div [ class "content" ]
[ div []
[ input
[ placeholder "Your email *"
, type_ "email"
, required True
, value (model.email |> rawValue)
, onInput InputEmail
, onBlur BlurEmail
]
[]
, errorLabel model.email
]
, div []
[ input
[ placeholder "Your password *"
, type_ "password"
, required True
, value (model.password |> rawValue)
, onInput InputPassword
, onBlur BlurPassword
]
[]
, errorLabel model.password
]
, div []
[ input
[ placeholder "Your confirm password *"
, type_ "password"
, required True
, value (model.confirmPassword |> rawValue)
, onInput InputConfirmPassword
, onBlur BlurConfirmPassword
]
[]
, errorLabel model.confirmPassword
]
, div []
[ input
[ type_ "checkbox"
, id "terms"
, value (model.acceptPolicy |> rawValue |> Debug.toString)
, onCheck CheckAcceptPolicy
]
[]
, label [ for "terms" ]
[ text "I accept the privacy policy" ]
]
, div []
[ errorLabel model.acceptPolicy ]
]
errorLabel : Field raw a -> Html Msg
errorLabel fieldErrLbl =
div [ class "msg msg--error" ]
[ fieldErrLbl
|> extractError
|> Maybe.withDefault ""
|> text
]
footer : Model -> Html Msg
footer model =
div []
[ button
[ class "btn__submit"
, type_ "submit"
, disabled (model.status == InProcess)
]
[ text "Submit" ]
]
modelForm : Model -> List (Html msg)
modelForm model =
[ div [ class "header" ]
[ h1 [] [ text "Model state" ] ]
, div []
[ text "{ email ="
, p [ class "model__el" ]
[ model.email |> Debug.toString |> text ]
]
, div []
[ text ", password ="
, p [ class "model__el" ]
[ model.password |> Debug.toString |> text ]
]
, div []
[ text ", confirmPassword ="
, p [ class "model__el" ]
[ model.confirmPassword |> Debug.toString |> text ]
]
, div []
[ text ", acceptPolicy ="
, p [ class "model__el" ]
[ model.acceptPolicy |> Debug.toString |> text ]
]
, div []
[ text ", status ="
, div [ class "model__el" ]
[ model.status |> Debug.toString |> text ]
, text "}"
]
]
-- Validation
emailValidation : Validator String String
emailValidation =
composite (isNotEmpty "An email is required.") (isEmail "Please ensure this is a valid email.")
passwordValidation : Validator String String
passwordValidation =
isNotEmpty "Please enter a password."
confirmPasswordValidation : Field raw String -> Validator String String
confirmPasswordValidation password =
composite (isNotEmpty "Please enter a password.") (isEqualTo password "The passwords don't match.")
validateModel : Model -> Model
validateModel model =
let
email =
model.email |> validate OnSubmit emailValidation
password =
model.password |> validate OnSubmit passwordValidation
confirmPassword =
model.confirmPassword
|> validate OnSubmit (confirmPasswordValidation password)
acceptPolicy =
model.acceptPolicy
|> validate OnSubmit (isTrue "You must accept the policy.")
in
{ model
| email = email
, password = PI:PASSWORD:<PASSWORD>END_PI
, confirmPassword = PI:PASSWORD:<PASSWORD>END_PI
, acceptPolicy = acceptPolicy
}
submitIfValid : Model -> ( Model, Cmd Msg )
submitIfValid model =
let
submissionResult =
Valid submit
|> applyValidity (validity model.email)
|> applyValidity (validity model.password)
|> applyValidity (validity model.confirmPassword)
|> applyValidity (validity model.acceptPolicy)
in
case submissionResult of
Valid cmd ->
( { model | status = InProcess }
, cmd
)
_ ->
( model, Cmd.none )
-- Send request
submit : String -> String -> String -> Bool -> Cmd Msg
submit email password _ _ =
let
url =
"http://localhost:8080/api/register"
json =
Encode.object
[ ( "email", Encode.string email )
, ( "password", Encode.string password )
]
decoder =
Decode.string |> Decode.map (always ())
request =
Http.post url (Http.jsonBody json) decoder
in
request
|> Http.send SubmitResponse
| elm |
[
{
"context": "### Websites\n\n * [elm-todomvc](https://github.com/evancz/elm-todomvc) —\n todo list modelled on [To",
"end": 1972,
"score": 0.9941465855,
"start": 1966,
"tag": "USERNAME",
"value": "evancz"
},
{
"context": "odomvc.com/)\n * [elm-lang.org](https://github.com/elm-lang/elm-lang.org) —\n frontend and backend cod",
"end": 2095,
"score": 0.9835073352,
"start": 2087,
"tag": "USERNAME",
"value": "elm-lang"
},
{
"context": "site\n * [package.elm-lang.org](https://github.com/elm-lang/package.elm-lang.org) —\n frontend and bac",
"end": 2217,
"score": 0.9850907922,
"start": 2209,
"tag": "USERNAME",
"value": "elm-lang"
},
{
"context": "bsite\n * [Reddit Time Machine](https://github.com/Dobiasd/RedditTimeMachine) —\n Check out what was ",
"end": 2352,
"score": 0.979571104,
"start": 2345,
"tag": "USERNAME",
"value": "Dobiasd"
},
{
"context": "ut what was up on reddit days/weeks/months ago, by Tobias Hermann\n * [EAN/UPC-A Barcode Generator](https://github.c",
"end": 2455,
"score": 0.9035016894,
"start": 2441,
"tag": "NAME",
"value": "Tobias Hermann"
},
{
"context": " [EAN/UPC-A Barcode Generator](https://github.com/Dobiasd/Barcode-Generator) —\n with addon2/addon5 ",
"end": 2515,
"score": 0.8196282387,
"start": 2508,
"tag": "USERNAME",
"value": "Dobiasd"
},
{
"context": "sh;\n with addon2/addon5 and real-time output, by Tobias Hermann\n\n#### Games\n\n * [Tetris](https://github.com/jcoll",
"end": 2604,
"score": 0.9904005527,
"start": 2590,
"tag": "NAME",
"value": "Tobias Hermann"
},
{
"context": "rmann\n\n#### Games\n\n * [Tetris](https://github.com/jcollard/elmtris) —\n by Joe Collard\n * [Breakout](",
"end": 2657,
"score": 0.9884402156,
"start": 2649,
"tag": "USERNAME",
"value": "jcollard"
},
{
"context": "https://github.com/jcollard/elmtris) —\n by Joe Collard\n * [Breakout](https://github.com/Dobiasd/Breakout",
"end": 2692,
"score": 0.9995666146,
"start": 2681,
"tag": "NAME",
"value": "Joe Collard"
},
{
"context": " by Joe Collard\n * [Breakout](https://github.com/Dobiasd/Breakout#breakout--play-it) —\n by Tobias ",
"end": 2733,
"score": 0.9214894772,
"start": 2726,
"tag": "USERNAME",
"value": "Dobiasd"
},
{
"context": "/Dobiasd/Breakout#breakout--play-it) —\n by Tobias Hermann\n * [Maze](https://github.com/Dobiasd/Maze#maze--p",
"end": 2790,
"score": 0.843214035,
"start": 2776,
"tag": "NAME",
"value": "Tobias Hermann"
},
{
"context": " by Tobias Hermann\n * [Maze](https://github.com/Dobiasd/Maze#maze--play-it) —\n by Tobias Hermann\n",
"end": 2827,
"score": 0.9129081964,
"start": 2820,
"tag": "USERNAME",
"value": "Dobiasd"
},
{
"context": "thub.com/Dobiasd/Maze#maze--play-it) —\n by Tobias Hermann\n * [Demoscene-Concentration](https://github.com/D",
"end": 2876,
"score": 0.990939796,
"start": 2862,
"tag": "NAME",
"value": "Tobias Hermann"
},
{
"context": "n\n * [Demoscene-Concentration](https://github.com/Dobiasd/Demoscene-Concentration) —\n the classical",
"end": 2932,
"score": 0.9305956364,
"start": 2925,
"tag": "USERNAME",
"value": "Dobiasd"
},
{
"context": "ame with (simple) old-school demoscene effects, by Tobias Hermann\n * [Froggy](https://github.com/thSoft/froggy) &md",
"end": 3056,
"score": 0.9465103149,
"start": 3042,
"tag": "NAME",
"value": "Tobias Hermann"
},
{
"context": " by Tobias Hermann\n * [Froggy](https://github.com/thSoft/froggy) — by Dénes Harmath\n\n\"\"\"\n\n\nintermedi",
"end": 3094,
"score": 0.9864213467,
"start": 3088,
"tag": "USERNAME",
"value": "thSoft"
},
{
"context": "oggy](https://github.com/thSoft/froggy) — by Dénes Harmath\n\n\"\"\"\n\n\nintermediates =\n let ex = List.map Tile",
"end": 3127,
"score": 0.9993641973,
"start": 3114,
"tag": "NAME",
"value": "Dénes Harmath"
},
{
"context": "t\", \"TextField\")\n , (\"Password\" , \"Password\")\n , (\"Checkbox\", \"CheckBox\")\n ",
"end": 6374,
"score": 0.9990310669,
"start": 6366,
"tag": "PASSWORD",
"value": "Password"
}
] | frontend/public/Examples.elm | arsatiki/elm-lang.org | 0 | import Graphics.Element (..)
import List
import List ((::))
import Markdown
import Signal
import Text
import Website.Skeleton (skeleton)
import Website.ColorScheme (accent4)
import Website.Tiles as Tile
import Website.Widgets (headerFaces)
import Window
port title : String
port title = "Examples"
main : Signal.Signal Element
main =
Signal.map (skeleton "Examples" body) Window.dimensions
body outer =
let b = flow down <| List.intersperse (spacer 20 20) content
in
container outer (heightOf b) middle b
content =
let w = 600
exs = [ ("Display",elements), ("React",reactive), ("Compute",functional) ]
in
width w words ::
List.map (subsection w) exs ++
[ width w intermediate
, Tile.examples w intermediates
, width w projects
]
words = Markdown.toElement """
# Examples
This page will help you *learn by example* as you read and modify
Elm code in the [online editor](/try). It is split into sections
that will help you grow from beginner to expert:
* [Basics](#basics) — small programs focused on showing one concept
* [Intermediate](#intermediate) — larger examples that combine basic concepts
* [Big Projects](#big-projects) — websites and games written in Elm
Remember to check the [Elm syntax reference][syntax] when you see new syntax!
See the [learning resources](/Learn.elm) if you want to learn the fundamentals
of the language *not* by example. The [library documentation](/Libraries.elm)
is a very information dense resource once you become familiar with Elm.
[syntax]: /learn/Syntax.elm "The Syntax of Elm"
<h2 id="basics">Basics</h2>
"""
intermediate = Markdown.toElement """
<h2 id="intermediate">Intermediate</h2>
"""
projects = Markdown.toElement """
<h2 id="big-projects">Big Projects</h2>
These are all larger projects created with Elm. Fork them and use them
as templates for your own project!
#### Websites
* [elm-todomvc](https://github.com/evancz/elm-todomvc) —
todo list modelled on [TodoMVC](http://todomvc.com/)
* [elm-lang.org](https://github.com/elm-lang/elm-lang.org) —
frontend and backend code for this website
* [package.elm-lang.org](https://github.com/elm-lang/package.elm-lang.org) —
frontend and backend code for the package website
* [Reddit Time Machine](https://github.com/Dobiasd/RedditTimeMachine) —
Check out what was up on reddit days/weeks/months ago, by Tobias Hermann
* [EAN/UPC-A Barcode Generator](https://github.com/Dobiasd/Barcode-Generator) —
with addon2/addon5 and real-time output, by Tobias Hermann
#### Games
* [Tetris](https://github.com/jcollard/elmtris) —
by Joe Collard
* [Breakout](https://github.com/Dobiasd/Breakout#breakout--play-it) —
by Tobias Hermann
* [Maze](https://github.com/Dobiasd/Maze#maze--play-it) —
by Tobias Hermann
* [Demoscene-Concentration](https://github.com/Dobiasd/Demoscene-Concentration) —
the classical memory game with (simple) old-school demoscene effects, by Tobias Hermann
* [Froggy](https://github.com/thSoft/froggy) — by Dénes Harmath
"""
intermediates =
let ex = List.map Tile.intermediate
gl = List.map Tile.webgl
in
[ ex [ "Mario", "Walk", "Pong", "Turtle" ]
, ex [ "TextReverse", "Calculator", "Form", "Flickr" ]
, ex [ "Clock", "Plot", "SlideShow", "PieChart" ]
, gl [ "Triangle", "Cube", "Thwomp", "FirstPerson" ]
, ex [ "Physics", "Stamps" ]
]
addFolder folder lst =
let add (x,y) = (x, folder ++ y ++ ".elm")
f (n,xs) = (n, List.map add xs)
in List.map f lst
elements = addFolder "Elements/"
[ ("Words",
[ ("Text", "HelloWorld")
, ("Markdown", "Markdown")
])
, ("Images",
[ ("Images", "Image")
, ("Fitted", "FittedImage")
, ("Cropped", "CroppedImage")
])
, ("Formatting",
[ ("Size" , "Size")
, ("Opacity" , "Opacity")
, ("Text" , "Text")
, ("Typeface", "Typeface")
])
, ("Layout",
[ ("Simple Flow", "FlowDown1a")
, ("Flow Down" , "FlowDown2")
, ("Layers" , "Layers")
])
, ("Positioning",
[ ("Containers", "Position")
, ("Spacers" , "Spacer")
])
, ("2D Shapes", [ ("Lines" , "Lines")
, ("Shapes" , "Shapes")
, ("Elements" , "ToForm")
, ("Transforms", "Transforms")
])
, ("2D Fills", [ ("Color" , "Color")
, ("Gradient", "LinearGradient")
, ("Radial Gradient", "RadialGradient")
, ("Texture" , "Texture")
])
]
functional = addFolder "Functional/"
[ ("Recursion",
[ ("Factorial" , "Factorial")
, ("List Length", "Length")
, ("Zip" , "Zip")
, ("Quick Sort" , "QuickSort")
])
, ("Functions",
[ ("Functions" , "Anonymous")
, ("Application", "Application")
, ("Composition", "Composition")
, ("Infix Ops" , "Infix")
])
, ("Higher-Order",
[ ("Map" , "Map")
, ("Fold" , "Sum")
, ("Filter" , "Filter")
])
, ("Union Types",
[ ("Maybe", "Maybe")
, ("Boolean Expressions", "BooleanExpressions")
, ("Tree", "Tree")
])
, ("Libraries",
[ ("Dict", "Dict")
, ("Set", "Set")
])
]
reactive = addFolder "Reactive/"
[ ("Mouse", [ ("Position", "Position")
, ("Presses" , "IsDown")
, ("Clicks" , "CountClicks")
, ("Yogi", "ResizeYogi")
, ("Track", "Transforms")
])
,("Keyboard",[ ("Arrows" , "Arrows")
, ("wasd" , "Wasd")
, ("Keys Down" , "KeysDown")
, ("Key Presses", "CharPressed")
])
, ("Touch", [ ("Raw", "Touches")
, ("Touches", "Touch")
, ("Taps", "Taps")
, ("Draw", "Draw")
])
, ("Window", [ ("Size", "ResizePaint")
, ("Centering", "Centering")
])
, ("Time", [ ("FPS" , "Fps")
, ("FPS when", "FpsWhen")
, ("Every" , "Every")
])
, ("Input", [ ("Text", "TextField")
, ("Password" , "Password")
, ("Checkbox", "CheckBox")
, ("Drop Down", "DropDown")
])
-- , ("Random", [ ("Randomize", "Randomize") ])
-- , ("Http", [ ("Zip Codes", "ZipCodes") ])
, ("Filters",[ ("Sample", "SampleOn")
, ("Numbers Only", "KeepIf")
])
, ("Ports", [ ("Logging","Log")
, ("Set Title","Title")
, ("Redirect","Redirect")
])
]
example (name, loc) = Text.link ("/edit/examples/" ++ loc) (Text.fromString name)
toLinks (title, links) =
flow right
[ width 150 (Text.plainText <| " " ++ title)
, Text.leftAligned << Text.join (Text.fromString ", ") <| List.map example links
]
subsection w (name,info) =
flow down << List.intersperse (spacer w 6) << List.map (width w) <|
(tag name << Text.leftAligned << Text.typeface headerFaces << Text.bold <| Text.fromString name) ::
spacer 0 0 ::
List.map toLinks info ++ [spacer w 12]
| 17795 | import Graphics.Element (..)
import List
import List ((::))
import Markdown
import Signal
import Text
import Website.Skeleton (skeleton)
import Website.ColorScheme (accent4)
import Website.Tiles as Tile
import Website.Widgets (headerFaces)
import Window
port title : String
port title = "Examples"
main : Signal.Signal Element
main =
Signal.map (skeleton "Examples" body) Window.dimensions
body outer =
let b = flow down <| List.intersperse (spacer 20 20) content
in
container outer (heightOf b) middle b
content =
let w = 600
exs = [ ("Display",elements), ("React",reactive), ("Compute",functional) ]
in
width w words ::
List.map (subsection w) exs ++
[ width w intermediate
, Tile.examples w intermediates
, width w projects
]
words = Markdown.toElement """
# Examples
This page will help you *learn by example* as you read and modify
Elm code in the [online editor](/try). It is split into sections
that will help you grow from beginner to expert:
* [Basics](#basics) — small programs focused on showing one concept
* [Intermediate](#intermediate) — larger examples that combine basic concepts
* [Big Projects](#big-projects) — websites and games written in Elm
Remember to check the [Elm syntax reference][syntax] when you see new syntax!
See the [learning resources](/Learn.elm) if you want to learn the fundamentals
of the language *not* by example. The [library documentation](/Libraries.elm)
is a very information dense resource once you become familiar with Elm.
[syntax]: /learn/Syntax.elm "The Syntax of Elm"
<h2 id="basics">Basics</h2>
"""
intermediate = Markdown.toElement """
<h2 id="intermediate">Intermediate</h2>
"""
projects = Markdown.toElement """
<h2 id="big-projects">Big Projects</h2>
These are all larger projects created with Elm. Fork them and use them
as templates for your own project!
#### Websites
* [elm-todomvc](https://github.com/evancz/elm-todomvc) —
todo list modelled on [TodoMVC](http://todomvc.com/)
* [elm-lang.org](https://github.com/elm-lang/elm-lang.org) —
frontend and backend code for this website
* [package.elm-lang.org](https://github.com/elm-lang/package.elm-lang.org) —
frontend and backend code for the package website
* [Reddit Time Machine](https://github.com/Dobiasd/RedditTimeMachine) —
Check out what was up on reddit days/weeks/months ago, by <NAME>
* [EAN/UPC-A Barcode Generator](https://github.com/Dobiasd/Barcode-Generator) —
with addon2/addon5 and real-time output, by <NAME>
#### Games
* [Tetris](https://github.com/jcollard/elmtris) —
by <NAME>
* [Breakout](https://github.com/Dobiasd/Breakout#breakout--play-it) —
by <NAME>
* [Maze](https://github.com/Dobiasd/Maze#maze--play-it) —
by <NAME>
* [Demoscene-Concentration](https://github.com/Dobiasd/Demoscene-Concentration) —
the classical memory game with (simple) old-school demoscene effects, by <NAME>
* [Froggy](https://github.com/thSoft/froggy) — by <NAME>
"""
intermediates =
let ex = List.map Tile.intermediate
gl = List.map Tile.webgl
in
[ ex [ "Mario", "Walk", "Pong", "Turtle" ]
, ex [ "TextReverse", "Calculator", "Form", "Flickr" ]
, ex [ "Clock", "Plot", "SlideShow", "PieChart" ]
, gl [ "Triangle", "Cube", "Thwomp", "FirstPerson" ]
, ex [ "Physics", "Stamps" ]
]
addFolder folder lst =
let add (x,y) = (x, folder ++ y ++ ".elm")
f (n,xs) = (n, List.map add xs)
in List.map f lst
elements = addFolder "Elements/"
[ ("Words",
[ ("Text", "HelloWorld")
, ("Markdown", "Markdown")
])
, ("Images",
[ ("Images", "Image")
, ("Fitted", "FittedImage")
, ("Cropped", "CroppedImage")
])
, ("Formatting",
[ ("Size" , "Size")
, ("Opacity" , "Opacity")
, ("Text" , "Text")
, ("Typeface", "Typeface")
])
, ("Layout",
[ ("Simple Flow", "FlowDown1a")
, ("Flow Down" , "FlowDown2")
, ("Layers" , "Layers")
])
, ("Positioning",
[ ("Containers", "Position")
, ("Spacers" , "Spacer")
])
, ("2D Shapes", [ ("Lines" , "Lines")
, ("Shapes" , "Shapes")
, ("Elements" , "ToForm")
, ("Transforms", "Transforms")
])
, ("2D Fills", [ ("Color" , "Color")
, ("Gradient", "LinearGradient")
, ("Radial Gradient", "RadialGradient")
, ("Texture" , "Texture")
])
]
functional = addFolder "Functional/"
[ ("Recursion",
[ ("Factorial" , "Factorial")
, ("List Length", "Length")
, ("Zip" , "Zip")
, ("Quick Sort" , "QuickSort")
])
, ("Functions",
[ ("Functions" , "Anonymous")
, ("Application", "Application")
, ("Composition", "Composition")
, ("Infix Ops" , "Infix")
])
, ("Higher-Order",
[ ("Map" , "Map")
, ("Fold" , "Sum")
, ("Filter" , "Filter")
])
, ("Union Types",
[ ("Maybe", "Maybe")
, ("Boolean Expressions", "BooleanExpressions")
, ("Tree", "Tree")
])
, ("Libraries",
[ ("Dict", "Dict")
, ("Set", "Set")
])
]
reactive = addFolder "Reactive/"
[ ("Mouse", [ ("Position", "Position")
, ("Presses" , "IsDown")
, ("Clicks" , "CountClicks")
, ("Yogi", "ResizeYogi")
, ("Track", "Transforms")
])
,("Keyboard",[ ("Arrows" , "Arrows")
, ("wasd" , "Wasd")
, ("Keys Down" , "KeysDown")
, ("Key Presses", "CharPressed")
])
, ("Touch", [ ("Raw", "Touches")
, ("Touches", "Touch")
, ("Taps", "Taps")
, ("Draw", "Draw")
])
, ("Window", [ ("Size", "ResizePaint")
, ("Centering", "Centering")
])
, ("Time", [ ("FPS" , "Fps")
, ("FPS when", "FpsWhen")
, ("Every" , "Every")
])
, ("Input", [ ("Text", "TextField")
, ("Password" , "<PASSWORD>")
, ("Checkbox", "CheckBox")
, ("Drop Down", "DropDown")
])
-- , ("Random", [ ("Randomize", "Randomize") ])
-- , ("Http", [ ("Zip Codes", "ZipCodes") ])
, ("Filters",[ ("Sample", "SampleOn")
, ("Numbers Only", "KeepIf")
])
, ("Ports", [ ("Logging","Log")
, ("Set Title","Title")
, ("Redirect","Redirect")
])
]
example (name, loc) = Text.link ("/edit/examples/" ++ loc) (Text.fromString name)
toLinks (title, links) =
flow right
[ width 150 (Text.plainText <| " " ++ title)
, Text.leftAligned << Text.join (Text.fromString ", ") <| List.map example links
]
subsection w (name,info) =
flow down << List.intersperse (spacer w 6) << List.map (width w) <|
(tag name << Text.leftAligned << Text.typeface headerFaces << Text.bold <| Text.fromString name) ::
spacer 0 0 ::
List.map toLinks info ++ [spacer w 12]
| true | import Graphics.Element (..)
import List
import List ((::))
import Markdown
import Signal
import Text
import Website.Skeleton (skeleton)
import Website.ColorScheme (accent4)
import Website.Tiles as Tile
import Website.Widgets (headerFaces)
import Window
port title : String
port title = "Examples"
main : Signal.Signal Element
main =
Signal.map (skeleton "Examples" body) Window.dimensions
body outer =
let b = flow down <| List.intersperse (spacer 20 20) content
in
container outer (heightOf b) middle b
content =
let w = 600
exs = [ ("Display",elements), ("React",reactive), ("Compute",functional) ]
in
width w words ::
List.map (subsection w) exs ++
[ width w intermediate
, Tile.examples w intermediates
, width w projects
]
words = Markdown.toElement """
# Examples
This page will help you *learn by example* as you read and modify
Elm code in the [online editor](/try). It is split into sections
that will help you grow from beginner to expert:
* [Basics](#basics) — small programs focused on showing one concept
* [Intermediate](#intermediate) — larger examples that combine basic concepts
* [Big Projects](#big-projects) — websites and games written in Elm
Remember to check the [Elm syntax reference][syntax] when you see new syntax!
See the [learning resources](/Learn.elm) if you want to learn the fundamentals
of the language *not* by example. The [library documentation](/Libraries.elm)
is a very information dense resource once you become familiar with Elm.
[syntax]: /learn/Syntax.elm "The Syntax of Elm"
<h2 id="basics">Basics</h2>
"""
intermediate = Markdown.toElement """
<h2 id="intermediate">Intermediate</h2>
"""
projects = Markdown.toElement """
<h2 id="big-projects">Big Projects</h2>
These are all larger projects created with Elm. Fork them and use them
as templates for your own project!
#### Websites
* [elm-todomvc](https://github.com/evancz/elm-todomvc) —
todo list modelled on [TodoMVC](http://todomvc.com/)
* [elm-lang.org](https://github.com/elm-lang/elm-lang.org) —
frontend and backend code for this website
* [package.elm-lang.org](https://github.com/elm-lang/package.elm-lang.org) —
frontend and backend code for the package website
* [Reddit Time Machine](https://github.com/Dobiasd/RedditTimeMachine) —
Check out what was up on reddit days/weeks/months ago, by PI:NAME:<NAME>END_PI
* [EAN/UPC-A Barcode Generator](https://github.com/Dobiasd/Barcode-Generator) —
with addon2/addon5 and real-time output, by PI:NAME:<NAME>END_PI
#### Games
* [Tetris](https://github.com/jcollard/elmtris) —
by PI:NAME:<NAME>END_PI
* [Breakout](https://github.com/Dobiasd/Breakout#breakout--play-it) —
by PI:NAME:<NAME>END_PI
* [Maze](https://github.com/Dobiasd/Maze#maze--play-it) —
by PI:NAME:<NAME>END_PI
* [Demoscene-Concentration](https://github.com/Dobiasd/Demoscene-Concentration) —
the classical memory game with (simple) old-school demoscene effects, by PI:NAME:<NAME>END_PI
* [Froggy](https://github.com/thSoft/froggy) — by PI:NAME:<NAME>END_PI
"""
intermediates =
let ex = List.map Tile.intermediate
gl = List.map Tile.webgl
in
[ ex [ "Mario", "Walk", "Pong", "Turtle" ]
, ex [ "TextReverse", "Calculator", "Form", "Flickr" ]
, ex [ "Clock", "Plot", "SlideShow", "PieChart" ]
, gl [ "Triangle", "Cube", "Thwomp", "FirstPerson" ]
, ex [ "Physics", "Stamps" ]
]
addFolder folder lst =
let add (x,y) = (x, folder ++ y ++ ".elm")
f (n,xs) = (n, List.map add xs)
in List.map f lst
elements = addFolder "Elements/"
[ ("Words",
[ ("Text", "HelloWorld")
, ("Markdown", "Markdown")
])
, ("Images",
[ ("Images", "Image")
, ("Fitted", "FittedImage")
, ("Cropped", "CroppedImage")
])
, ("Formatting",
[ ("Size" , "Size")
, ("Opacity" , "Opacity")
, ("Text" , "Text")
, ("Typeface", "Typeface")
])
, ("Layout",
[ ("Simple Flow", "FlowDown1a")
, ("Flow Down" , "FlowDown2")
, ("Layers" , "Layers")
])
, ("Positioning",
[ ("Containers", "Position")
, ("Spacers" , "Spacer")
])
, ("2D Shapes", [ ("Lines" , "Lines")
, ("Shapes" , "Shapes")
, ("Elements" , "ToForm")
, ("Transforms", "Transforms")
])
, ("2D Fills", [ ("Color" , "Color")
, ("Gradient", "LinearGradient")
, ("Radial Gradient", "RadialGradient")
, ("Texture" , "Texture")
])
]
functional = addFolder "Functional/"
[ ("Recursion",
[ ("Factorial" , "Factorial")
, ("List Length", "Length")
, ("Zip" , "Zip")
, ("Quick Sort" , "QuickSort")
])
, ("Functions",
[ ("Functions" , "Anonymous")
, ("Application", "Application")
, ("Composition", "Composition")
, ("Infix Ops" , "Infix")
])
, ("Higher-Order",
[ ("Map" , "Map")
, ("Fold" , "Sum")
, ("Filter" , "Filter")
])
, ("Union Types",
[ ("Maybe", "Maybe")
, ("Boolean Expressions", "BooleanExpressions")
, ("Tree", "Tree")
])
, ("Libraries",
[ ("Dict", "Dict")
, ("Set", "Set")
])
]
reactive = addFolder "Reactive/"
[ ("Mouse", [ ("Position", "Position")
, ("Presses" , "IsDown")
, ("Clicks" , "CountClicks")
, ("Yogi", "ResizeYogi")
, ("Track", "Transforms")
])
,("Keyboard",[ ("Arrows" , "Arrows")
, ("wasd" , "Wasd")
, ("Keys Down" , "KeysDown")
, ("Key Presses", "CharPressed")
])
, ("Touch", [ ("Raw", "Touches")
, ("Touches", "Touch")
, ("Taps", "Taps")
, ("Draw", "Draw")
])
, ("Window", [ ("Size", "ResizePaint")
, ("Centering", "Centering")
])
, ("Time", [ ("FPS" , "Fps")
, ("FPS when", "FpsWhen")
, ("Every" , "Every")
])
, ("Input", [ ("Text", "TextField")
, ("Password" , "PI:PASSWORD:<PASSWORD>END_PI")
, ("Checkbox", "CheckBox")
, ("Drop Down", "DropDown")
])
-- , ("Random", [ ("Randomize", "Randomize") ])
-- , ("Http", [ ("Zip Codes", "ZipCodes") ])
, ("Filters",[ ("Sample", "SampleOn")
, ("Numbers Only", "KeepIf")
])
, ("Ports", [ ("Logging","Log")
, ("Set Title","Title")
, ("Redirect","Redirect")
])
]
example (name, loc) = Text.link ("/edit/examples/" ++ loc) (Text.fromString name)
toLinks (title, links) =
flow right
[ width 150 (Text.plainText <| " " ++ title)
, Text.leftAligned << Text.join (Text.fromString ", ") <| List.map example links
]
subsection w (name,info) =
flow down << List.intersperse (spacer w 6) << List.map (width w) <|
(tag name << Text.leftAligned << Text.typeface headerFaces << Text.bold <| Text.fromString name) ::
spacer 0 0 ::
List.map toLinks info ++ [spacer w 12]
| elm |
[
{
"context": " \"rewardAmount\": 12463,\n \"bakerAccount\": \"3siDnxannkQYYjCTgwEUvE9WThEaHy1J3RjyMA4ZBQmrR9hw1K\"\n }\n ],\n \"finalizationData\":{\n \"finaliz",
"end": 754,
"score": 0.9997739196,
"start": 704,
"tag": "KEY",
"value": "3siDnxannkQYYjCTgwEUvE9WThEaHy1J3RjyMA4ZBQmrR9hw1K"
},
{
"context": "ec44266f044a230ad7bd9339a992418fbcd11a3217686f6854a1816cd\",\n \"sender\": null,\n \"cost\": 0,\n ",
"end": 1640,
"score": 0.5519854426,
"start": 1639,
"tag": "KEY",
"value": "a"
},
{
"context": "66f044a230ad7bd9339a992418fbcd11a3217686f6854a1816cd\",\n \"sender\": null,\n \"cost\": 0,\n \"e",
"end": 1646,
"score": 0.5741668344,
"start": 1644,
"tag": "KEY",
"value": "cd"
},
{
"context": "tag\": \"CredentialDeployed\",\n \"regId\": \"a65da3c626172056bfb0f6612bf76bd79acf80dee092b0394b93cfabaa500b727592af22f66fae834965d33fda8940f1\",\n \"account\": \"3ADz9qYiEzeui5ccMC7CCHr",
"end": 2063,
"score": 0.9991933107,
"start": 1967,
"tag": "KEY",
"value": "a65da3c626172056bfb0f6612bf76bd79acf80dee092b0394b93cfabaa500b727592af22f66fae834965d33fda8940f1"
},
{
"context": "66fae834965d33fda8940f1\",\n \"account\": \"3ADz9qYiEzeui5ccMC7CCHrdsWArV4T45ktGhyt2CnUK4BL4U6\"\n }\n ],\n \"outcome\": \"succe",
"end": 2140,
"score": 0.9996722341,
"start": 2090,
"tag": "KEY",
"value": "3ADz9qYiEzeui5ccMC7CCHrdsWArV4T45ktGhyt2CnUK4BL4U6"
},
{
"context": ",\n \"from\": {\n \"address\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"type\": \"AddressAccount\"\n ",
"end": 2815,
"score": 0.9399808645,
"start": 2765,
"tag": "KEY",
"value": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
},
{
"context": "8d4112e770ee7674e80751254d6f27\",\n \"sender\": \"39KavYmY7LRw1mV5wbmTKY8A38ktzrQ3eWCn7KPzDW3S4sJps9\",\n \"cost\": 59,\n \"energyCost\": 59,\n ",
"end": 3137,
"score": 0.8331364989,
"start": 3087,
"tag": "KEY",
"value": "39KavYmY7LRw1mV5wbmTKY8A38ktzrQ3eWCn7KPzDW3S4sJps9"
},
{
"context": "ents\": [\n {\n \"address\": \"39KavYmY7LRw1mV5wbmTKY8A38ktzrQ3eWCn7KPzDW3S4sJps9\",\n \"type\": \"AddressAccount\"\n ",
"end": 3404,
"score": 0.7907953262,
"start": 3355,
"tag": "KEY",
"value": "9KavYmY7LRw1mV5wbmTKY8A38ktzrQ3eWCn7KPzDW3S4sJps9"
},
{
"context": "d96215755884522798092bc179de5b\",\n \"sender\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"cost\": 265,\n \"energyCost\": 265,\n ",
"end": 3719,
"score": 0.9945323467,
"start": 3669,
"tag": "KEY",
"value": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
},
{
"context": " \"tag\": \"StakeDelegated\",\n \"account\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"baker\": 0\n ",
"end": 3907,
"score": 0.9981395602,
"start": 3877,
"tag": "KEY",
"value": "43TULx3kDPDeQy1C1iLwBbS5EEV96c"
},
{
"context": " \"account\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"baker\": 0\n ",
"end": 3911,
"score": 0.628744781,
"start": 3910,
"tag": "KEY",
"value": "5"
},
{
"context": " \"account\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"baker\": 0\n }\n ",
"end": 3918,
"score": 0.59808743,
"start": 3912,
"tag": "KEY",
"value": "RdA9Dm"
},
{
"context": "unt\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"baker\": 0\n }\n ",
"end": 3921,
"score": 0.5534973741,
"start": 3920,
"tag": "KEY",
"value": "2"
},
{
"context": "t\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"baker\": 0\n }\n ],\n",
"end": 3926,
"score": 0.5907021761,
"start": 3922,
"tag": "KEY",
"value": "hxGZ"
},
{
"context": "4610c45af1c2ca0481119d47c8a2bb\",\n \"sender\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"cost\": 265,\n \"energyCost\": 265,\n ",
"end": 4224,
"score": 0.77727139,
"start": 4174,
"tag": "KEY",
"value": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
},
{
"context": " \"tag\": \"StakeDelegated\",\n \"account\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"baker\": 0\n }\n ],\n ",
"end": 4432,
"score": 0.9996806979,
"start": 4382,
"tag": "KEY",
"value": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
},
{
"context": "05bf06e62737fa563ed75e20fcec27\",\n \"sender\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"cost\": 3167,\n \"energyCost\": 3167,\n ",
"end": 4729,
"score": 0.8856873512,
"start": 4679,
"tag": "KEY",
"value": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
},
{
"context": "089668af8e64bd6b978ef7cfac39c7\",\n \"sender\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"cost\": 265,\n \"energyCost\": 265,\n ",
"end": 5153,
"score": 0.9519330859,
"start": 5103,
"tag": "KEY",
"value": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
},
{
"context": "a725ebc418b6631abb49b5f808a07c\",\n \"sender\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"cost\": 166,\n \"energyCost\": 166,\n ",
"end": 5585,
"score": 0.9511351585,
"start": 5535,
"tag": "KEY",
"value": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
},
{
"context": "ba2efa2baaed3b1228601e25bc2bb2\",\n \"sender\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n \"cost\": 165,\n \"energyCost\": 165,\n ",
"end": 5963,
"score": 0.9610321522,
"start": 5913,
"tag": "KEY",
"value": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
},
{
"context": " {\n \"hash\": \"5257c01e5f42a0afcead07149a474162c2a193702de59177bff0d7b8812a4d09\",\n \"sender\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96c",
"end": 6271,
"score": 0.6026827097,
"start": 6238,
"tag": "KEY",
"value": "2c2a193702de59177bff0d7b8812a4d09"
},
{
"context": "a193702de59177bff0d7b8812a4d09\",\n \"sender\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\"",
"end": 6292,
"score": 0.7100309134,
"start": 6291,
"tag": "KEY",
"value": "4"
},
{
"context": "3702de59177bff0d7b8812a4d09\",\n \"sender\": \"43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt\",\n ",
"end": 6297,
"score": 0.5253270864,
"start": 6294,
"tag": "KEY",
"value": "ULx"
},
{
"context": "32d2a591060cdeab4a02790f7cf4ad\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"cost\": 2705,\n \"energyCost\": 2705,\n ",
"end": 6808,
"score": 0.9759405851,
"start": 6758,
"tag": "KEY",
"value": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": "6f3ad84e1cd5900d85d79e63919bd3\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"cost\": 1527,\n \"energyCost\": 1527,\n ",
"end": 7305,
"score": 0.9354666471,
"start": 7255,
"tag": "KEY",
"value": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": " \"outcome\": \"success\"\n },\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"type\": \"initContract\"\n },\n {\n ",
"end": 8249,
"score": 0.9865072966,
"start": 8199,
"tag": "KEY",
"value": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": "76e3c821bfac5cddee9850ce7bf9e\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"cost\": 464,\n \"energyCost\": 464,\n ",
"end": 8443,
"score": 0.8641552329,
"start": 8394,
"tag": "KEY",
"value": "LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": " \"instigator\": {\n \"address\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n ",
"end": 8659,
"score": 0.5540008545,
"start": 8657,
"tag": "KEY",
"value": "RT"
},
{
"context": "gator\": {\n \"address\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n ",
"end": 8666,
"score": 0.5230073333,
"start": 8664,
"tag": "KEY",
"value": "hy"
},
{
"context": "or\": {\n \"address\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"type\": \"AddressAccount\"\n ",
"end": 8700,
"score": 0.6614429355,
"start": 8667,
"tag": "KEY",
"value": "H5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": " \"rewardAmount\": 35984,\n \"bakerAccount\": \"4EbkxwtSCopq6U1d7FcRgugR4DvKin4Wyg2qW5wmDkvWYFmDca\"\n }\n ],\n \"transactionSummaries\": [\n {\n ",
"end": 9453,
"score": 0.9997653365,
"start": 9403,
"tag": "KEY",
"value": "4EbkxwtSCopq6U1d7FcRgugR4DvKin4Wyg2qW5wmDkvWYFmDca"
},
{
"context": "2d2a591060cdeab4a02790f7cf4ad\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"cost\": 2705,\n \"energyCost\": 2705,\n ",
"end": 9649,
"score": 0.9037568569,
"start": 9600,
"tag": "KEY",
"value": "LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": "d043689e6fd08023034d3a2e3d5168\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"cost\": 1558,\n \"energyCost\": 1558,\n ",
"end": 11140,
"score": 0.9949352145,
"start": 11090,
"tag": "KEY",
"value": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": "6d89c14d8ab1f69623f5ca05efce98\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"cost\": 4890,\n \"energyCost\": 4890,\n ",
"end": 11637,
"score": 0.99705863,
"start": 11587,
"tag": "KEY",
"value": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": "23629d553f384b1c9691470b7648fe\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"cost\": 657,\n \"energyCost\": 657,\n ",
"end": 12134,
"score": 0.9133000374,
"start": 12084,
"tag": "KEY",
"value": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": "56105e408ffb34c987c1781cc7bace\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"cost\": 1417,\n \"energyCost\": 1417,\n ",
"end": 12629,
"score": 0.8813001513,
"start": 12579,
"tag": "KEY",
"value": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": ": 6\n },\n {\n \"hash\": \"404311b6f25efff2320d5091651e13745a078898e465e2bc006b4cad1c9341b0\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX",
"end": 13056,
"score": 0.886508882,
"start": 13010,
"tag": "KEY",
"value": "0d5091651e13745a078898e465e2bc006b4cad1c9341b0"
},
{
"context": "078898e465e2bc006b4cad1c9341b0\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"cost\": 3055,\n \"energyCost\": 3055,\n ",
"end": 13126,
"score": 0.9923276305,
"start": 13076,
"tag": "KEY",
"value": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": "1f142197747dd5e470f22167641474\",\n \"sender\": \"3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ\",\n \"cost\": 3479,\n \"energyCost\": 3479,\n ",
"end": 13623,
"score": 0.9953939915,
"start": 13573,
"tag": "KEY",
"value": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ"
},
{
"context": " \"rewardAmount\": 1751,\n \"bakerAccount\": \"3fS4u95Sx9SKzU83kxxYP4SWaWirVix4T7P9bgswmceqvcs4vR\"\n }\n ],\n \"transactionSummaries\": [\n ",
"end": 14674,
"score": 0.999770999,
"start": 14624,
"tag": "KEY",
"value": "3fS4u95Sx9SKzU83kxxYP4SWaWirVix4T7P9bgswmceqvcs4vR"
},
{
"context": " \"rewardAmount\": 207,\n \"bakerAccount\": \"4c7SXWg5bD3YpWQ2mmS8DSQiFm9MRpTd7Novo4ESPb1QLSYrts\"\n }\n ],\n \"transactionSummaries\": [\n {\n ",
"end": 15418,
"score": 0.9997432828,
"start": 15368,
"tag": "KEY",
"value": "4c7SXWg5bD3YpWQ2mmS8DSQiFm9MRpTd7Novo4ESPb1QLSYrts"
},
{
"context": "tag\": \"CredentialDeployed\",\n \"regId\": \"ac64aac1da15afd90d185475705935fbe224d5f7ddc43988e7db511656c787b452820b5096a2b323cf7612f5609d4cfb\",\n \"account\": \"3P2Qsi8FeMB6AijMi3kpD9F",
"end": 15934,
"score": 0.9934193492,
"start": 15838,
"tag": "KEY",
"value": "ac64aac1da15afd90d185475705935fbe224d5f7ddc43988e7db511656c787b452820b5096a2b323cf7612f5609d4cfb"
},
{
"context": "6a2b323cf7612f5609d4cfb\",\n \"account\": \"3P2Qsi8FeMB6AijMi3kpD9FrcFfAkoHDMu8kf7Fbd3cYYJpk2s\"\n }\n ],\n \"outcome\": \"succe",
"end": 16011,
"score": 0.9997295737,
"start": 15961,
"tag": "KEY",
"value": "3P2Qsi8FeMB6AijMi3kpD9FrcFfAkoHDMu8kf7Fbd3cYYJpk2s"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 16528,
"score": 0.9547375441,
"start": 16478,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 16683,
"score": 0.9446781278,
"start": 16633,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "05b0722a74d0ac1fe1f6b15d1496a2\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 17011,
"score": 0.963839829,
"start": 16961,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 17239,
"score": 0.9588532448,
"start": 17189,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 17394,
"score": 0.9474824667,
"start": 17344,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "064bd5077b853e6b324c23683af7b\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 17722,
"score": 0.8923130631,
"start": 17673,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 17950,
"score": 0.7621251345,
"start": 17901,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 18105,
"score": 0.6999610066,
"start": 18056,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "fcd3cc453c1307a504ef937a4fe8b5\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 18433,
"score": 0.9528210163,
"start": 18383,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressContract\"\n ",
"end": 18661,
"score": 0.6679267883,
"start": 18612,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": " \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 18817,
"score": 0.6862080693,
"start": 18770,
"tag": "KEY",
"value": "JHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "4837255ac720565479afab81767c96\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 19145,
"score": 0.9592928886,
"start": 19095,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 19373,
"score": 0.8920499086,
"start": 19323,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressContract\"\n ",
"end": 19528,
"score": 0.8729809523,
"start": 19479,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d025655775254e7124ae031688d9d8\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 19857,
"score": 0.944367826,
"start": 19807,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 20085,
"score": 0.9044177532,
"start": 20035,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 20240,
"score": 0.88654989,
"start": 20190,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "da0047454c484be9c80b487cc142c5\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 20568,
"score": 0.9836633205,
"start": 20518,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 20796,
"score": 0.953630209,
"start": 20746,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 20951,
"score": 0.9664904475,
"start": 20901,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "08a7bfcca0ade9dd9f63ae8dac317d\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 21279,
"score": 0.9762437344,
"start": 21229,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 21507,
"score": 0.9588016272,
"start": 21457,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 21662,
"score": 0.9433823824,
"start": 21612,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "fd5440af0bb7bee4b330648669b164\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 21990,
"score": 0.9385247231,
"start": 21940,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 22218,
"score": 0.7961688638,
"start": 22169,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 22373,
"score": 0.7090946436,
"start": 22324,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "b3f523472b89c583fdac918e762560\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 22701,
"score": 0.9105616808,
"start": 22651,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 22928,
"score": 0.7244185209,
"start": 22880,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRob"
},
{
"context": "\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 23083,
"score": 0.7080067396,
"start": 23035,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRob"
},
{
"context": "5111315efbc062a9d0f9082d1d5e6f\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 23412,
"score": 0.8624002934,
"start": 23362,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 23639,
"score": 0.6340515018,
"start": 23593,
"tag": "KEY",
"value": "JHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRob"
},
{
"context": "\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 23794,
"score": 0.6571565866,
"start": 23746,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRob"
},
{
"context": "a37052be8204078f516583cb5320e\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 24123,
"score": 0.7038750052,
"start": 24074,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 24351,
"score": 0.8701195717,
"start": 24301,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "2cf66ba838897b8f527642fb7e552a\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 24834,
"score": 0.6984092593,
"start": 24784,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "689ee37b22382d9a4b931637ae7\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"e",
"end": 25544,
"score": 0.5867486596,
"start": 25498,
"tag": "KEY",
"value": "JHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRob"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 25773,
"score": 0.9623658657,
"start": 25723,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 25928,
"score": 0.9634350538,
"start": 25878,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "7f66b33f1527396f0af63b5b9a3e6c\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 26256,
"score": 0.9677963257,
"start": 26206,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 26484,
"score": 0.9601408243,
"start": 26434,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 26639,
"score": 0.9645053744,
"start": 26589,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "34574c172a90f1923188751fb6775a\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 26967,
"score": 0.9582726955,
"start": 26917,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 27195,
"score": 0.8728890419,
"start": 27145,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 27350,
"score": 0.8915253282,
"start": 27301,
"tag": "KEY",
"value": "KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "ece1b12c1ca0f8f5a2936c7e260722\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 27678,
"score": 0.866730392,
"start": 27628,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 27906,
"score": 0.8865581155,
"start": 27856,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 28061,
"score": 0.8983312845,
"start": 28011,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "r\"\n },\n {\n \"hash\": \"5a9c8dd2b90b7943a4891b1ab41cbe8ae13cefb7a91c7ef3d884201408352b04\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupE",
"end": 28319,
"score": 0.9609225392,
"start": 28274,
"tag": "KEY",
"value": "91b1ab41cbe8ae13cefb7a91c7ef3d884201408352b04"
},
{
"context": "3cefb7a91c7ef3d884201408352b04\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 28389,
"score": 0.9845856428,
"start": 28339,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 28617,
"score": 0.9695955515,
"start": 28567,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 28772,
"score": 0.9665808678,
"start": 28722,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "6edcdfedee6b9ce5f520b9aef78ea7\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 29100,
"score": 0.9729642868,
"start": 29050,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 29328,
"score": 0.9703330994,
"start": 29278,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 29483,
"score": 0.9678218961,
"start": 29433,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "382d8d2fed680202140fe97e91fe76\",\n \"sender\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"cost\": 10,\n \"result\": {\n \"ev",
"end": 29811,
"score": 0.977237463,
"start": 29761,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "d\",\n \"to\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 30039,
"score": 0.9387688637,
"start": 29989,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": ",\n \"from\": {\n \"address\": \"4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL\",\n \"type\": \"AddressAccount\"\n ",
"end": 30194,
"score": 0.9395938516,
"start": 30144,
"tag": "KEY",
"value": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL"
},
{
"context": "g\": \"Mint\",\n \"foundationAccount\": \"48RDnoQaCKwy8xteebgLCDdX8qACa3WB5GnfuGMpCDfB2UfdL4\",\n \"mintPlatformDevelopmentCharge\"",
"end": 32048,
"score": 0.9996712208,
"start": 31998,
"tag": "KEY",
"value": "48RDnoQaCKwy8xteebgLCDdX8qACa3WB5GnfuGMpCDfB2UfdL4"
},
{
"context": "nt\": \"79711\",\n \"address\": \"3c1hZst6hfxm5CMPYGmUw7LvMe3Mo1VwgkXrBAb59GSdLzPiSz\"\n },\n {\n ",
"end": 32508,
"score": 0.9622157812,
"start": 32458,
"tag": "KEY",
"value": "3c1hZst6hfxm5CMPYGmUw7LvMe3Mo1VwgkXrBAb59GSdLzPiSz"
},
{
"context": "nt\": \"79711\",\n \"address\": \"3uyRpq2NPSY4VJn8Qd1uWGcUQTGpCAarHTtqpneiSGqv36Uhna\"\n },\n {\n ",
"end": 32684,
"score": 0.9839420915,
"start": 32634,
"tag": "KEY",
"value": "3uyRpq2NPSY4VJn8Qd1uWGcUQTGpCAarHTtqpneiSGqv36Uhna"
},
{
"context": "nt\": \"79711\",\n \"address\": \"4AymJeLgpB7s7bSn6ARm22iAB15m5PpTHaXATBCktnzxvoBowJ\"\n },\n {\n ",
"end": 32860,
"score": 0.9819642305,
"start": 32810,
"tag": "KEY",
"value": "4AymJeLgpB7s7bSn6ARm22iAB15m5PpTHaXATBCktnzxvoBowJ"
},
{
"context": "unt\": \"7974\",\n \"address\": \"4C9vCCSLdeTB2DsUZZECReygdLbMR5AACoR1H7EfBfYem7bqLx\"\n },\n {\n ",
"end": 33035,
"score": 0.9261940718,
"start": 32985,
"tag": "KEY",
"value": "4C9vCCSLdeTB2DsUZZECReygdLbMR5AACoR1H7EfBfYem7bqLx"
},
{
"context": "nt\": \"79711\",\n \"address\": \"4ESt5DAQY3xi74Pj386otNf2S4fsohDG8Qxyv15hvqvbgFvYvC\"\n },\n {\n ",
"end": 33211,
"score": 0.8828941584,
"start": 33161,
"tag": "KEY",
"value": "4ESt5DAQY3xi74Pj386otNf2S4fsohDG8Qxyv15hvqvbgFvYvC"
},
{
"context": "unt\": \"7978\",\n \"address\": \"4LRhqFikMSWMzX6ZenkvRVn94H6Zu6HdxmHvap9cuHmMrPraV2\"\n },\n {\n ",
"end": 33386,
"score": 0.9085800052,
"start": 33336,
"tag": "KEY",
"value": "4LRhqFikMSWMzX6ZenkvRVn94H6Zu6HdxmHvap9cuHmMrPraV2"
},
{
"context": "nt\": \"79711\",\n \"address\": \"4M63wWygknpRd1hVuKoirtusZJbWE9wiFe3rXCrZcFgLzXYzh4\"\n }\n ]\n ",
"end": 33562,
"score": 0.996384263,
"start": 33512,
"tag": "KEY",
"value": "4M63wWygknpRd1hVuKoirtusZJbWE9wiFe3rXCrZcFgLzXYzh4"
},
{
"context": "ward\": \"41914\",\n \"newGASAccount\": \"42737\",\n \"baker\": \"4M63wWygknpRd1hVuKoir",
"end": 33750,
"score": 0.7106663585,
"start": 33745,
"tag": "KEY",
"value": "42737"
},
{
"context": "ewGASAccount\": \"42737\",\n \"baker\": \"4M63wWygknpRd1hVuKoirtusZJbWE9wiFe3rXCrZcFgLzXYzh4\",\n \"foundationAccount\": \"48RDnoQaC",
"end": 33829,
"score": 0.9996727705,
"start": 33779,
"tag": "KEY",
"value": "4M63wWygknpRd1hVuKoirtusZJbWE9wiFe3rXCrZcFgLzXYzh4"
},
{
"context": "FgLzXYzh4\",\n \"foundationAccount\": \"48RDnoQaCKwy8xteebgLCDdX8qACa3WB5GnfuGMpCDfB2UfdL4\",\n \"oldGASAccount\": \"1671\",\n ",
"end": 33920,
"score": 0.9997551441,
"start": 33870,
"tag": "KEY",
"value": "48RDnoQaCKwy8xteebgLCDdX8qACa3WB5GnfuGMpCDfB2UfdL4"
},
{
"context": "MpCDfB2UfdL4\",\n \"oldGASAccount\": \"1671\",\n \"foundationCharge\": \"9220\",\n ",
"end": 33961,
"score": 0.8061470985,
"start": 33958,
"tag": "KEY",
"value": "671"
},
{
"context": " {\n \"verifyKey\": \"e0b5fc074eef1178e41f6f2c494bde78b65bd3f21c36db4d41a1e6cb259c3a7d\",\n \"schemeId\": \"Ed2551",
"end": 35540,
"score": 0.9997653365,
"start": 35476,
"tag": "KEY",
"value": "e0b5fc074eef1178e41f6f2c494bde78b65bd3f21c36db4d41a1e6cb259c3a7d"
},
{
"context": " {\n \"verifyKey\": \"1f420ab84863a9ba0472bcb39bfe27a07727f84ace50a6c3f9d6d75e2519febc\",\n \"schemeId\": \"Ed2551",
"end": 35752,
"score": 0.9997680187,
"start": 35688,
"tag": "KEY",
"value": "1f420ab84863a9ba0472bcb39bfe27a07727f84ace50a6c3f9d6d75e2519febc"
},
{
"context": " {\n \"verifyKey\": \"95a5064980b5bc27f3ae96a4831f3c60be82c2c0ee36de3ff028137a99fe823f\",\n \"schemeId\": \"Ed2551",
"end": 35964,
"score": 0.9997691512,
"start": 35900,
"tag": "KEY",
"value": "95a5064980b5bc27f3ae96a4831f3c60be82c2c0ee36de3ff028137a99fe823f"
},
{
"context": " {\n \"verifyKey\": \"ef3e58b13c43a8439046a774290a8ef0b17d6fe516cea1f48de894a5aec669a4\",\n \"schemeId\": \"Ed2551",
"end": 36176,
"score": 0.9997629523,
"start": 36112,
"tag": "KEY",
"value": "ef3e58b13c43a8439046a774290a8ef0b17d6fe516cea1f48de894a5aec669a4"
},
{
"context": " {\n \"verifyKey\": \"830ac28b779ab09d0be9bd15ded7343be1f24df01ccf2e7cffd7d6359500f46c\",\n \"schemeId\": \"Ed2551",
"end": 36388,
"score": 0.9997423887,
"start": 36324,
"tag": "KEY",
"value": "830ac28b779ab09d0be9bd15ded7343be1f24df01ccf2e7cffd7d6359500f46c"
},
{
"context": " \"authorizedKeys\": [\n 42,\n 43,\n ",
"end": 38551,
"score": 0.6593182087,
"start": 38550,
"tag": "KEY",
"value": "2"
},
{
"context": " {\n \"verifyKey\": \"97e908ee3a4d8dff49830aacca6bf42997f68afc1851fb5b3d58ae143ba4e147\",\n \"schemeId\": \"Ed2551",
"end": 39546,
"score": 0.9997825623,
"start": 39482,
"tag": "KEY",
"value": "97e908ee3a4d8dff49830aacca6bf42997f68afc1851fb5b3d58ae143ba4e147"
},
{
"context": " {\n \"verifyKey\": \"f222cc7e2ec7bc1ba7abeca6f503a123abd244292809f04425ad8d72f6ef47ff\",\n \"schemeId\": \"Ed2551",
"end": 39758,
"score": 0.9985787272,
"start": 39694,
"tag": "KEY",
"value": "f222cc7e2ec7bc1ba7abeca6f503a123abd244292809f04425ad8d72f6ef47ff"
},
{
"context": " {\n \"verifyKey\": \"e098e1e55b13988b01e882a7fce5070fd12fa72d409eccebfbad0fb32d6ee057\",\n \"schemeId\": \"Ed2551",
"end": 39970,
"score": 0.999768734,
"start": 39906,
"tag": "KEY",
"value": "e098e1e55b13988b01e882a7fce5070fd12fa72d409eccebfbad0fb32d6ee057"
},
{
"context": " {\n \"verifyKey\": \"58f71ef93d95fd9466aa917d426970c96ff48f9cf1aafb52e4caf427cf6331c8\",\n \"schemeId\": \"Ed2551",
"end": 40182,
"score": 0.9997732639,
"start": 40118,
"tag": "KEY",
"value": "58f71ef93d95fd9466aa917d426970c96ff48f9cf1aafb52e4caf427cf6331c8"
},
{
"context": " {\n \"verifyKey\": \"9521707ac0ed5b577bc334c25154ab92336a1731bc9bcaefd14cd62bb42dcf96\",\n \"schemeId\": \"Ed2551",
"end": 40394,
"score": 0.999771595,
"start": 40330,
"tag": "KEY",
"value": "9521707ac0ed5b577bc334c25154ab92336a1731bc9bcaefd14cd62bb42dcf96"
},
{
"context": " {\n \"verifyKey\": \"38e5321fca15c1f87fe7c1e266f1e85f68a877e3eea11fa45063ad5e4b92e2fb\",\n \"schemeId\": \"Ed2551",
"end": 40606,
"score": 0.9997736216,
"start": 40542,
"tag": "KEY",
"value": "38e5321fca15c1f87fe7c1e266f1e85f68a877e3eea11fa45063ad5e4b92e2fb"
},
{
"context": " {\n \"verifyKey\": \"0aab1d7d1b81b7526163df81288f645249a0310f8ac84c5e8bc8f7a80be43df1\",\n \"schemeId\": \"Ed2551",
"end": 40818,
"score": 0.9997739792,
"start": 40754,
"tag": "KEY",
"value": "0aab1d7d1b81b7526163df81288f645249a0310f8ac84c5e8bc8f7a80be43df1"
},
{
"context": " {\n \"verifyKey\": \"74aa4e9dac2bdfea7db5b9fccf240be370746a172a6ae2775b9751d96226dc9d\",\n \"schemeId\": \"Ed2551",
"end": 41030,
"score": 0.9997717142,
"start": 40966,
"tag": "KEY",
"value": "74aa4e9dac2bdfea7db5b9fccf240be370746a172a6ae2775b9751d96226dc9d"
},
{
"context": " {\n \"verifyKey\": \"4a00ab5a36d4b402ddc4c3160df838f0aba805bb47843e85c8b14971a322f7b0\",\n \"schemeId\": \"Ed2551",
"end": 41242,
"score": 0.9997755289,
"start": 41178,
"tag": "KEY",
"value": "4a00ab5a36d4b402ddc4c3160df838f0aba805bb47843e85c8b14971a322f7b0"
},
{
"context": " {\n \"verifyKey\": \"a0b17ad7ab31a49168ab4ee479141a2a102d34ee50c1e5abb3b2e78e901760ae\",\n \"schemeId\": \"Ed2551",
"end": 41454,
"score": 0.9997630119,
"start": 41390,
"tag": "KEY",
"value": "a0b17ad7ab31a49168ab4ee479141a2a102d34ee50c1e5abb3b2e78e901760ae"
},
{
"context": " {\n \"verifyKey\": \"701376912e8820d404bd93e887d450e115e1dba9c53fdbe4e963ac3be92b508e\",\n \"schemeId\": \"Ed2551",
"end": 41666,
"score": 0.999770999,
"start": 41602,
"tag": "KEY",
"value": "701376912e8820d404bd93e887d450e115e1dba9c53fdbe4e963ac3be92b508e"
},
{
"context": " {\n \"verifyKey\": \"aa5dd0d777e21571ea6bca6fad39cf84e4655643913d83f6ba4da4552f07c3ec\",\n \"schemeId\": \"Ed2551",
"end": 41878,
"score": 0.9997743368,
"start": 41814,
"tag": "KEY",
"value": "aa5dd0d777e21571ea6bca6fad39cf84e4655643913d83f6ba4da4552f07c3ec"
},
{
"context": " {\n \"verifyKey\": \"88766292b604ec67298b817395bb41459575b7eebe22db49a3c87c6e664f67bd\",\n \"schemeId\": \"Ed2551",
"end": 42090,
"score": 0.9997755885,
"start": 42026,
"tag": "KEY",
"value": "88766292b604ec67298b817395bb41459575b7eebe22db49a3c87c6e664f67bd"
},
{
"context": " {\n \"verifyKey\": \"3f14ba2f24bbb5fb0ec906e7b5080dd104bc7b0ffbf183234db67ab0ccaeec26\",\n \"schemeId\": \"Ed2551",
"end": 42302,
"score": 0.9997749925,
"start": 42238,
"tag": "KEY",
"value": "3f14ba2f24bbb5fb0ec906e7b5080dd104bc7b0ffbf183234db67ab0ccaeec26"
},
{
"context": " {\n \"verifyKey\": \"c39edc29fbf11264c60439e202a0a7fa91047fd54808057be50307a12018a38c\",\n \"schemeId\": \"Ed2551",
"end": 42514,
"score": 0.9947448373,
"start": 42450,
"tag": "KEY",
"value": "c39edc29fbf11264c60439e202a0a7fa91047fd54808057be50307a12018a38c"
},
{
"context": " {\n \"verifyKey\": \"5b85a0fed564bab70b67d201f405fbdf2712498720e2c7de8aa81bce7258319a\",\n \"schemeId\": \"Ed2551",
"end": 42726,
"score": 0.9997791052,
"start": 42662,
"tag": "KEY",
"value": "5b85a0fed564bab70b67d201f405fbdf2712498720e2c7de8aa81bce7258319a"
},
{
"context": " {\n \"verifyKey\": \"dae562dbf3c082ff4ef58b3308b8858bb2fe105680ad863901776cc5f3131f3d\",\n \"schemeId\": \"Ed2551",
"end": 42938,
"score": 0.9997775555,
"start": 42874,
"tag": "KEY",
"value": "dae562dbf3c082ff4ef58b3308b8858bb2fe105680ad863901776cc5f3131f3d"
},
{
"context": " {\n \"verifyKey\": \"5f28823bd52e6bd86d760a8b104bbd4e3b50cf45dfb076f057ab0561756664a7\",\n \"schemeId\": \"Ed2551",
"end": 43150,
"score": 0.9997773767,
"start": 43086,
"tag": "KEY",
"value": "5f28823bd52e6bd86d760a8b104bbd4e3b50cf45dfb076f057ab0561756664a7"
},
{
"context": " {\n \"verifyKey\": \"d034a8912eeef4c473798e0f790a16612781fb93b286baf20f4553fd07d8e1ca\",\n \"schemeId\": \"Ed2551",
"end": 43362,
"score": 0.9997781515,
"start": 43298,
"tag": "KEY",
"value": "d034a8912eeef4c473798e0f790a16612781fb93b286baf20f4553fd07d8e1ca"
},
{
"context": " {\n \"verifyKey\": \"e68b20b846c2144d1719f09613ad927055420f7d03282be8c1f0ec32d0a0837e\",\n \"schemeId\": \"Ed2551",
"end": 43574,
"score": 0.9997782111,
"start": 43510,
"tag": "KEY",
"value": "e68b20b846c2144d1719f09613ad927055420f7d03282be8c1f0ec32d0a0837e"
},
{
"context": " {\n \"verifyKey\": \"bf0c98b711d4bc5f0f2b90d427656234d2d4dc12bca59ae4c931cd9fcd4f66c0\",\n \"schemeId\": \"Ed2551",
"end": 43786,
"score": 0.9997803569,
"start": 43722,
"tag": "KEY",
"value": "bf0c98b711d4bc5f0f2b90d427656234d2d4dc12bca59ae4c931cd9fcd4f66c0"
},
{
"context": " {\n \"verifyKey\": \"97e0c06300746dd211f7aa2c29f3628c53036eba3c16a9ad1e116d5b09176ae5\",\n \"schemeId\": \"Ed2551",
"end": 43998,
"score": 0.9997696877,
"start": 43934,
"tag": "KEY",
"value": "97e0c06300746dd211f7aa2c29f3628c53036eba3c16a9ad1e116d5b09176ae5"
},
{
"context": " {\n \"verifyKey\": \"10de8b005647c3fa2d528c21a1222ff8e2f7f10143e1d1f99f572016c150cdb5\",\n \"schemeId\": \"Ed2551",
"end": 44210,
"score": 0.9997684956,
"start": 44146,
"tag": "KEY",
"value": "10de8b005647c3fa2d528c21a1222ff8e2f7f10143e1d1f99f572016c150cdb5"
},
{
"context": " {\n \"verifyKey\": \"f8a6f0e1b60caddfdfad28f2ebbe20393a9961ac5a02dd5770dfb4bc2f633d07\",\n \"schemeId\": \"Ed2551",
"end": 44422,
"score": 0.9997666478,
"start": 44358,
"tag": "KEY",
"value": "f8a6f0e1b60caddfdfad28f2ebbe20393a9961ac5a02dd5770dfb4bc2f633d07"
},
{
"context": " {\n \"verifyKey\": \"17cb31e51c9197ba1b88231f75ece5b3d33df60898408fac57375971bb68dfad\",\n \"schemeId\": \"Ed2551",
"end": 44634,
"score": 0.9997675419,
"start": 44570,
"tag": "KEY",
"value": "17cb31e51c9197ba1b88231f75ece5b3d33df60898408fac57375971bb68dfad"
},
{
"context": " {\n \"verifyKey\": \"661cb015b7ac83ec349f5010d9f73a62f383d9bc14d3256600ba6d26f9042110\",\n \"schemeId\": \"Ed2551",
"end": 44846,
"score": 0.9997645617,
"start": 44782,
"tag": "KEY",
"value": "661cb015b7ac83ec349f5010d9f73a62f383d9bc14d3256600ba6d26f9042110"
},
{
"context": " {\n \"verifyKey\": \"840d332eae5d251094e443a5a0acce58b63c43e72c7ce60add97f211d9b8b198\",\n \"schemeId\": \"Ed2551",
"end": 45058,
"score": 0.9997678399,
"start": 44994,
"tag": "KEY",
"value": "840d332eae5d251094e443a5a0acce58b63c43e72c7ce60add97f211d9b8b198"
},
{
"context": " {\n \"verifyKey\": \"55e9a120150626468f029dd343c2b03eb97b8fb6228a5d8772028f8752ad40f2\",\n \"schemeId\": \"Ed2551",
"end": 45270,
"score": 0.9996914268,
"start": 45206,
"tag": "KEY",
"value": "55e9a120150626468f029dd343c2b03eb97b8fb6228a5d8772028f8752ad40f2"
},
{
"context": " {\n \"verifyKey\": \"4d60696102711d5e536c202a46f149ba8a959a49edf9be8da726a51d2f1185a7\",\n \"schemeId\": \"Ed2551",
"end": 45482,
"score": 0.9997701049,
"start": 45418,
"tag": "KEY",
"value": "4d60696102711d5e536c202a46f149ba8a959a49edf9be8da726a51d2f1185a7"
},
{
"context": " {\n \"verifyKey\": \"aa0f8e391f16bd7095b1a3c02ba513a111194d650a7104a627bcbbf6c63d82c1\",\n \"schemeId\": \"Ed2551",
"end": 45694,
"score": 0.9997755885,
"start": 45630,
"tag": "KEY",
"value": "aa0f8e391f16bd7095b1a3c02ba513a111194d650a7104a627bcbbf6c63d82c1"
},
{
"context": " {\n \"verifyKey\": \"8c335e4bc9b8751ac45b15f3b1afea9765051f22393e93f5ff1bfd436d59c4f7\",\n \"schemeId\": \"Ed2551",
"end": 45906,
"score": 0.9997752905,
"start": 45842,
"tag": "KEY",
"value": "8c335e4bc9b8751ac45b15f3b1afea9765051f22393e93f5ff1bfd436d59c4f7"
},
{
"context": " {\n \"verifyKey\": \"a5a77daa690591d7e44520303efc843ba359deddcfa89456ab1a7c5a26419696\",\n \"schemeId\": \"Ed2551",
"end": 46118,
"score": 0.9997759461,
"start": 46054,
"tag": "KEY",
"value": "a5a77daa690591d7e44520303efc843ba359deddcfa89456ab1a7c5a26419696"
},
{
"context": " {\n \"verifyKey\": \"e33274cbb31675f479ddff48a163924269cb46b99d814363d66948ccaf3d01f9\",\n \"schemeId\": \"Ed2551",
"end": 46330,
"score": 0.999776125,
"start": 46266,
"tag": "KEY",
"value": "e33274cbb31675f479ddff48a163924269cb46b99d814363d66948ccaf3d01f9"
},
{
"context": " {\n \"verifyKey\": \"f2eb7342f2dfccbbe15f5f91adda221286b25447a5af8a8db2170d842a5c1350\",\n \"schemeId\": \"Ed2551",
"end": 46542,
"score": 0.9996936321,
"start": 46478,
"tag": "KEY",
"value": "f2eb7342f2dfccbbe15f5f91adda221286b25447a5af8a8db2170d842a5c1350"
},
{
"context": " {\n \"verifyKey\": \"cb9b6265f58cafc94bb33210357ee2709f4535b1aab08852d6df7a2421d1cb94\",\n \"schemeId\": \"Ed2551",
"end": 46754,
"score": 0.9997764826,
"start": 46690,
"tag": "KEY",
"value": "cb9b6265f58cafc94bb33210357ee2709f4535b1aab08852d6df7a2421d1cb94"
},
{
"context": " {\n \"verifyKey\": \"e26018620b19e90ab8a1a34e6d9d87d851e3f6f9d75f5f5192a30d3aec22f812\",\n \"schemeId\": \"Ed2551",
"end": 46966,
"score": 0.999774158,
"start": 46902,
"tag": "KEY",
"value": "e26018620b19e90ab8a1a34e6d9d87d851e3f6f9d75f5f5192a30d3aec22f812"
},
{
"context": " {\n \"verifyKey\": \"ce2cf1c1082b082abdb4599e15f6303303cc00cb8fe6820c5cda66c443e4144d\",\n \"schemeId\": \"Ed2551",
"end": 47178,
"score": 0.9997745752,
"start": 47114,
"tag": "KEY",
"value": "ce2cf1c1082b082abdb4599e15f6303303cc00cb8fe6820c5cda66c443e4144d"
},
{
"context": " {\n \"verifyKey\": \"cd735b34b9ebd6d5dcb9cb56040b78e04a5a9449de2473a03887cf6dade2af60\",\n \"schemeId\": \"Ed2551",
"end": 47390,
"score": 0.999774456,
"start": 47326,
"tag": "KEY",
"value": "cd735b34b9ebd6d5dcb9cb56040b78e04a5a9449de2473a03887cf6dade2af60"
},
{
"context": " {\n \"verifyKey\": \"78f9eac5476dd188177ddf22793c73231ff0abe11614f8373f86f33a2e14fbe6\",\n \"schemeId\": \"Ed2551",
"end": 47602,
"score": 0.9997739196,
"start": 47538,
"tag": "KEY",
"value": "78f9eac5476dd188177ddf22793c73231ff0abe11614f8373f86f33a2e14fbe6"
},
{
"context": " {\n \"verifyKey\": \"802af182e7ba273d1c41441716c21db4773e4635fe1ea27760f33f3ad920eb0c\",\n \"schemeId\": \"Ed2551",
"end": 47814,
"score": 0.9997727871,
"start": 47750,
"tag": "KEY",
"value": "802af182e7ba273d1c41441716c21db4773e4635fe1ea27760f33f3ad920eb0c"
},
{
"context": " {\n \"verifyKey\": \"a264dd70a3eeac72397cde270806bb36651f25c1971d7a364a87b8d2184ebce0\",\n \"schemeId\": \"Ed2551",
"end": 48026,
"score": 0.9997757077,
"start": 47962,
"tag": "KEY",
"value": "a264dd70a3eeac72397cde270806bb36651f25c1971d7a364a87b8d2184ebce0"
},
{
"context": " {\n \"verifyKey\": \"951a1a3c5f3907f5706a9a587516cca3c13d8af21abceb4225df66d942d06f02\",\n \"schemeId\": \"Ed2551",
"end": 48238,
"score": 0.9997762442,
"start": 48174,
"tag": "KEY",
"value": "951a1a3c5f3907f5706a9a587516cca3c13d8af21abceb4225df66d942d06f02"
},
{
"context": " {\n \"verifyKey\": \"285568e67384368b0740309827a295a7c6044db1e7c96f6895c8fc7e2a5b4a38\",\n \"schemeId\": \"Ed2551",
"end": 48450,
"score": 0.9997743368,
"start": 48386,
"tag": "KEY",
"value": "285568e67384368b0740309827a295a7c6044db1e7c96f6895c8fc7e2a5b4a38"
},
{
"context": " {\n \"verifyKey\": \"bdb46f6cdcf24c5f0f183275c6325ea4034ce3bab1e7a362fce227d37c43e71f\",\n \"schemeId\": \"Ed2551",
"end": 48662,
"score": 0.99977386,
"start": 48598,
"tag": "KEY",
"value": "bdb46f6cdcf24c5f0f183275c6325ea4034ce3bab1e7a362fce227d37c43e71f"
},
{
"context": " {\n \"verifyKey\": \"9b86c0d98a295a23c3c92cb918a48d9b3cf3ab01d5d1d78a036e4a6b7d577c74\",\n \"schemeId\": \"Ed2551",
"end": 48874,
"score": 0.9997754693,
"start": 48810,
"tag": "KEY",
"value": "9b86c0d98a295a23c3c92cb918a48d9b3cf3ab01d5d1d78a036e4a6b7d577c74"
},
{
"context": " {\n \"verifyKey\": \"cb7ac7662b4dc4ea902e0d6116dd936ac4e1ace0a86e50059941aba6fd4aefc0\",\n \"schemeId\": \"Ed2551",
"end": 49086,
"score": 0.9997745752,
"start": 49022,
"tag": "KEY",
"value": "cb7ac7662b4dc4ea902e0d6116dd936ac4e1ace0a86e50059941aba6fd4aefc0"
},
{
"context": " {\n \"verifyKey\": \"f69e41a6d9d8417db5497ebe4688b734fb709ee16bed147ded80dfa2930d69db\",\n ",
"end": 49263,
"score": 0.9281015396,
"start": 49234,
"tag": "KEY",
"value": "f69e41a6d9d8417db5497ebe4688b"
},
{
"context": " \"verifyKey\": \"f69e41a6d9d8417db5497ebe4688b734fb709ee16bed147ded80dfa2930d69db\",\n \"schemeId\": \"Ed2551",
"end": 49298,
"score": 0.7214946151,
"start": 49264,
"tag": "KEY",
"value": "34fb709ee16bed147ded80dfa2930d69db"
},
{
"context": " 9,\n 10\n ]\n },\n",
"end": 49955,
"score": 0.6269760132,
"start": 49954,
"tag": "KEY",
"value": "0"
},
{
"context": " \"authorizedKeys\": [\n 8,\n 9,\n ",
"end": 50157,
"score": 0.5233992934,
"start": 50156,
"tag": "KEY",
"value": "8"
},
{
"context": " {\n \"verifyKey\": \"0d57ecfe1f7d941fbc1bc0d001b632052d549cbeab6a966f944e3ad2dac89f6d\",\n \"schemeId\": \"Ed2551",
"end": 50482,
"score": 0.9997777343,
"start": 50418,
"tag": "KEY",
"value": "0d57ecfe1f7d941fbc1bc0d001b632052d549cbeab6a966f944e3ad2dac89f6d"
},
{
"context": " {\n \"verifyKey\": \"d0d29ce95287f45da364cdd6db512a9eb2bc43704381fc4cf0ffe14540568edc\",\n \"schemeId\": \"Ed2551",
"end": 50694,
"score": 0.999776125,
"start": 50630,
"tag": "KEY",
"value": "d0d29ce95287f45da364cdd6db512a9eb2bc43704381fc4cf0ffe14540568edc"
},
{
"context": " {\n \"verifyKey\": \"94bec66e5b2f69ba94592c98a7facb78033d35c326beecaf263aef536d2a9c2f\",\n \"schemeId\": \"Ed2551",
"end": 50906,
"score": 0.9997775555,
"start": 50842,
"tag": "KEY",
"value": "94bec66e5b2f69ba94592c98a7facb78033d35c326beecaf263aef536d2a9c2f"
},
{
"context": " {\n \"verifyKey\": \"1d13c5e8ca89c4fc0ef7e56e3bcec776490eb364a687c0769540fe2d59fc1b2c\",\n \"schemeId\": \"Ed2551",
"end": 51118,
"score": 0.9997791648,
"start": 51054,
"tag": "KEY",
"value": "1d13c5e8ca89c4fc0ef7e56e3bcec776490eb364a687c0769540fe2d59fc1b2c"
},
{
"context": " {\n \"verifyKey\": \"e9f9715686673769091df75ed0579976b82e83f73cc3559748c2e9627014d6d8\",\n ",
"end": 51287,
"score": 0.9997571707,
"start": 51266,
"tag": "KEY",
"value": "e9f9715686673769091df"
},
{
"context": " \"address\": \"4PXJrvKGKb1YZt2Vua3mSDThqUU2EChweuydsFtVFtvDDr585H\",\n ",
"end": 54208,
"score": 0.5072327256,
"start": 54206,
"tag": "KEY",
"value": "ua"
},
{
"context": " \"address\": \"4PXJrvKGKb1YZt2Vua3mSDThqUU2EChweuydsFtVFtvDDr585H\",\n ",
"end": 54215,
"score": 0.5228452086,
"start": 54214,
"tag": "KEY",
"value": "q"
}
] | src/client/elm/Explorer/Stubs.elm | eulervoid/concordium-network-dashboard | 1 | module Explorer.Stubs exposing (..)
blockSummaryStubs =
[ ( "allTransactions: The most comprehensive transactions example we have, mostly generated by the `debugTestFullProvision` helper function in middleware, with some manual additional transaction types added. Includes example of finalization record."
, getBlockSummaryAllTransactionsStub
)
, ( "sc module deploys: example from the SC demo", getBlockSummaryContractDeploysStub )
, ( "failure", getBlockSummaryFailureStub )
, ( "rstub", getBlockSummaryResponseStub )
]
getBlockSummaryAllTransactionsStub =
"""
{
"specialEvents": [
{
"bakerId": 1,
"rewardAmount": 12463,
"bakerAccount": "3siDnxannkQYYjCTgwEUvE9WThEaHy1J3RjyMA4ZBQmrR9hw1K"
}
],
"finalizationData":{
"finalizationIndex":3,
"finalizers":[
{
"bakerId":0,
"signed":true,
"weight":1200000000135
},
{
"bakerId":1,
"signed":false,
"weight":800000000005
},
{
"bakerId":2,
"signed":false,
"weight":1200000000000
},
{
"bakerId":3,
"signed":true,
"weight":800000000000
},
{
"bakerId":4,
"signed":true,
"weight":1200000000000
}
],
"finalizationDelay":0,
"finalizationBlockPointer":"847e0c5037f8eedf3e5b5c932e4ebcb0b5ad9deaa986d83a165d8712594e0e1d"
},
"transactionSummaries": [
{
"hash": "d1aeaedec44266f044a230ad7bd9339a992418fbcd11a3217686f6854a1816cd",
"sender": null,
"cost": 0,
"energyCost": 35000,
"result": {
"events": [
{
"tag": "AccountCreated",
"contents": "3ADz9qYiEzeui5ccMC7CCHrdsWArV4T45ktGhyt2CnUK4BL4U6"
},
{
"tag": "CredentialDeployed",
"regId": "a65da3c626172056bfb0f6612bf76bd79acf80dee092b0394b93cfabaa500b727592af22f66fae834965d33fda8940f1",
"account": "3ADz9qYiEzeui5ccMC7CCHrdsWArV4T45ktGhyt2CnUK4BL4U6"
}
],
"outcome": "success"
},
"type": null,
"index": 0
},
{
"hash": "4b7e1b22ff9365e29c57d7f85a0fd7a7dd3c50245cb9d04c560c520298013c3f",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 165,
"energyCost": 165,
"result": {
"events": [
{
"amount": 1000000,
"tag": "Transferred",
"to": {
"address": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"type": "AddressAccount"
},
"from": {
"address": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"type": "transfer",
"index": 0
},
{
"hash": "5292c68df8787b3b22a61397edc3fc04858d4112e770ee7674e80751254d6f27",
"sender": "39KavYmY7LRw1mV5wbmTKY8A38ktzrQ3eWCn7KPzDW3S4sJps9",
"cost": 59,
"energyCost": 59,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "AmountTooLarge",
"contents": [
{
"address": "39KavYmY7LRw1mV5wbmTKY8A38ktzrQ3eWCn7KPzDW3S4sJps9",
"type": "AddressAccount"
},
200000000
]
}
},
"type": "transfer",
"index": 0
},
{
"hash": "15c2c8a0a9d496630dff603d4d404a6912d96215755884522798092bc179de5b",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 265,
"energyCost": 265,
"result": {
"events": [
{
"tag": "StakeDelegated",
"account": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"baker": 0
}
],
"outcome": "success"
},
"type": "delegateStake",
"index": 1
},
{
"hash": "ae13d5677cdcbd90fad54e9768f4f1f4c44610c45af1c2ca0481119d47c8a2bb",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 265,
"energyCost": 265,
"result": {
"events": [
{
"tag": "StakeDelegated",
"account": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"baker": 0
}
],
"outcome": "success"
},
"type": "delegateStake",
"index": 2
},
{
"hash": "73513777db8519ef5b71a0bd06a1b06bd705bf06e62737fa563ed75e20fcec27",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 3167,
"energyCost": 3167,
"result": {
"events": [
{
"tag": "BakerAdded",
"contents": 5
}
],
"outcome": "success"
},
"type": "addBaker",
"index": 3
},
{
"hash": "affc03c8211ea90cb72143e5c44eff7e55089668af8e64bd6b978ef7cfac39c7",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 265,
"energyCost": 265,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "InvalidStakeDelegationTarget",
"contents": 12312312312
}
},
"type": "delegateStake",
"index": 4
},
{
"hash": "2b40fc10934a371e9d23dead69435d834aa725ebc418b6631abb49b5f808a07c",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 166,
"energyCost": 166,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "SerializationFailure"
}
},
"type": null,
"index": 5
},
{
"hash": "8841d4dd1da2875b63d829be55fc5441adba2efa2baaed3b1228601e25bc2bb2",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 165,
"energyCost": 165,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "SerializationFailure"
}
},
"type": null,
"index": 6
},
{
"hash": "5257c01e5f42a0afcead07149a474162c2a193702de59177bff0d7b8812a4d09",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 165,
"energyCost": 165,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "InvalidBakerRemoveSource",
"contents": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
}
},
"type": "removeBaker",
"index": 7
},
{
"hash": "2a0a5ea99e9f091a3704c7fa8d163e971f32d2a591060cdeab4a02790f7cf4ad",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 2705,
"energyCost": 2705,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "69f895cec649178d771b016019912e84bbc659ef35e132585cb5a358b7f7ffb0"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 0
},
{
"hash": "0b04e5f0e2969ea2961cc0667d48cc17166f3ad84e1cd5900d85d79e63919bd3",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1527,
"energyCost": 1527,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "33f8832053c36b443084040537f11a66527bc1446a0aa41704ddf06e44093455"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 1
},
{
"cost": 3031,
"energyCost": 3031,
"hash": "0a75fdac33df28b8ae17fead28f837cb28ae23999cdb81bd5f9b7993e24cc204",
"index": 0,
"result": {
"events": [
{
"address": {
"index": 0,
"subindex": 0
},
"amount": 0,
"name": 200,
"ref": "7d6b63bde558564b77070bf1da85c56e7fd9f006ef8d0923d19689577614dd2d",
"tag": "ContractInitialized"
}
],
"outcome": "success"
},
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"type": "initContract"
},
{
"hash": "a633a418a26353989dec0e813353984892976e3c821bfac5cddee9850ce7bf9e",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 464,
"energyCost": 464,
"result": {
"events": [
{
"amount": 10,
"tag": "Updated",
"instigator": {
"address": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"type": "AddressAccount"
},
"address": {
"subindex": 0,
"index": 0
},
"message": "ExprMessage (Let (LetForeign (Imported 7d6b63bde558564b77070bf1da85c56e7fd9f006ef8d0923d19689577614dd2d (Name 130)) (Linked (Constructor (Name 130))) (Atom (BoundVar (Reference (-1))))) (Let (Constructor (Name 1)) (App (Reference 0) [BoundVar (Reference 1)])))"
}
],
"outcome": "success"
},
"type": "update",
"index": 0
}
]
}
"""
getBlockSummaryContractDeploysStub =
"""
{
"specialEvents": [
{
"bakerId": 3,
"rewardAmount": 35984,
"bakerAccount": "4EbkxwtSCopq6U1d7FcRgugR4DvKin4Wyg2qW5wmDkvWYFmDca"
}
],
"transactionSummaries": [
{
"hash": "2a0a5ea99e9f091a3704c7fa8d163e971f32d2a591060cdeab4a02790f7cf4ad",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 2705,
"energyCost": 2705,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "69f895cec649178d771b016019912e84bbc659ef35e132585cb5a358b7f7ffb0"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 0
},
{
"hash": "0b04e5f0e2969ea2961cc0667d48cc17166f3ad84e1cd5900d85d79e63919bd3",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1527,
"energyCost": 1527,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "33f8832053c36b443084040537f11a66527bc1446a0aa41704ddf06e44093455"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 1
},
{
"hash": "21585869b20629a5fb13eaa40e4d488e6c458d8609e994194b6c4c0cd78ded50",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1365,
"energyCost": 1365,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "73310b972c101c4ec69e6eb427ebc843d5483f4adb771d1dc711f8de5ebaced4"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 2
},
{
"hash": "b5fba16ba8bb959bab172beb8939700e28d043689e6fd08023034d3a2e3d5168",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1558,
"energyCost": 1558,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "73e1ebc954909b336a9c08443fff079e75956e7c0f314c4ad56b8bcfebaef8c4"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 3
},
{
"hash": "e91402ac563df428372a23ab83a26224696d89c14d8ab1f69623f5ca05efce98",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 4890,
"energyCost": 4890,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "3aa516e0b15327d7427b9acf7600c3e0376f65eeef7187975be38df70e0ab3e6"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 4
},
{
"hash": "bac1fb11f121a88431c146acf2b5514cb723629d553f384b1c9691470b7648fe",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 657,
"energyCost": 657,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "6a1ece5ea0d5a25bcf6e53f6e7bb4cf2b5a8cabaa8b58ba30a454e3582b26007"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 5
},
{
"hash": "7df554bb85448d8cc2cc9ed11b9eac348f56105e408ffb34c987c1781cc7bace",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1417,
"energyCost": 1417,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "ec79b0b4ab8f91247b271af307e8d0ae7f8c6cff7bcd9ca63d214116a01aa876"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 6
},
{
"hash": "404311b6f25efff2320d5091651e13745a078898e465e2bc006b4cad1c9341b0",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 3055,
"energyCost": 3055,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "7d6b63bde558564b77070bf1da85c56e7fd9f006ef8d0923d19689577614dd2d"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 7
},
{
"hash": "7c1dac909a4f49a74d80976467eecbbe641f142197747dd5e470f22167641474",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 3479,
"energyCost": 3479,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "1e4a518694fba2bd3edecec2aaac166edf2b65b59c0c6900e26637b73a7fbb2b"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 8
},
{
"hash": "4aa521cb1733ef27a78151d698a8c460c69af9f2a4d4619497b7cea73a11264f",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1775,
"energyCost": 1775,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "6e33fddc0a95324af4510964827c02c87cf403255cb8f7baae90786625133a3a"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 9
}
]
}
"""
getBlockSummaryFailureStub =
"""
{
"specialEvents": [
{
"bakerId": 2,
"rewardAmount": 1751,
"bakerAccount": "3fS4u95Sx9SKzU83kxxYP4SWaWirVix4T7P9bgswmceqvcs4vR"
}
],
"transactionSummaries": [
{
"hash": "0ada4e64558bb99a3607647c490f39083f44c709e654d689d8bf3fb343a95961",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 165,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "InvalidAccountReference",
"contents": "3Es2U5gMdKrqJdXSUVzgW4KUosJ91AxfsAuvKx5tKE9P2SvjVk"
}
},
"energyCost": 165,
"type": "transfer",
"index": 0
}
]
}
"""
getBlockSummaryResponseStub =
"""
{
"specialEvents": [
{
"bakerId": 4,
"rewardAmount": 207,
"bakerAccount": "4c7SXWg5bD3YpWQ2mmS8DSQiFm9MRpTd7Novo4ESPb1QLSYrts"
}
],
"transactionSummaries": [
{
"hash": "ae3154e1ee8a64d9e9718e57fbc979175be2ee8526b23fcddab2d626ebaeb72d",
"sender": null,
"cost": 0,
"result": {
"events": [
{
"tag": "AccountCreated",
"contents": "3P2Qsi8FeMB6AijMi3kpD9FrcFfAkoHDMu8kf7Fbd3cYYJpk2s"
},
{
"tag": "CredentialDeployed",
"regId": "ac64aac1da15afd90d185475705935fbe224d5f7ddc43988e7db511656c787b452820b5096a2b323cf7612f5609d4cfb",
"account": "3P2Qsi8FeMB6AijMi3kpD9FrcFfAkoHDMu8kf7Fbd3cYYJpk2s"
}
],
"outcome": "success"
},
"energyCost": 35000,
"type": null,
"index": 0
},
{
"hash": "2ecde309ea6b48cebfbb73eb1ee3364c4f10330955a4a13acb7d87076461ab2d",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "dba5e4bafc7d2201cc23d30f288e276b5305b0722a74d0ac1fe1f6b15d1496a2",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "f59897e5be69ecd5ed5843a10d74ee2b652064bd5077b853e6b324c23683af7b",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "f49899ac815b01a9f6e49c4d1fc926c511fcd3cc453c1307a504ef937a4fe8b5",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressContract"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "3ad7e0a0e3ed193bfba065c83704ae5bf84837255ac720565479afab81767c96",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressContract"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "d3b0cdeab57dc4d5e6b1faa1e4915ddfc2d025655775254e7124ae031688d9d8",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "bf6e33703977ce94caa918911f63b04654da0047454c484be9c80b487cc142c5",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "8781b249f4629f0ca9789fe143bfd4031208a7bfcca0ade9dd9f63ae8dac317d",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "41e6c23be80ab1151697ad16a4427268b0fd5440af0bb7bee4b330648669b164",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "71b1e81a467f038102b4028f62f1d75324b3f523472b89c583fdac918e762560",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "5298e7d571852da5c030c15b1513405c365111315efbc062a9d0f9082d1d5e6f",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "c7487dc3ee7cd097636badc9c21771d2a62a37052be8204078f516583cb5320e",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "dd6871001af51dc048bbae8ceb187c58fb2cf66ba838897b8f527642fb7e552a",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "fc2ee2cd1294f0dc8a0c738c25bc6f762edf2689ee37b22382d9a4b931637ae7",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "029681010cdc89383926d32017af7e51357f66b33f1527396f0af63b5b9a3e6c",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "64fbd260407f681292cc4931f8c3d7edb034574c172a90f1923188751fb6775a",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "5cc3ec13c9844456d8b65f0534dca943a4ece1b12c1ca0f8f5a2936c7e260722",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "5a9c8dd2b90b7943a4891b1ab41cbe8ae13cefb7a91c7ef3d884201408352b04",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "16672379084db2866db4564e0c42103d3f6edcdfedee6b9ce5f520b9aef78ea7",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "de7eecba63d94c7810126cc325d6cf43d9382d8d2fed680202140fe97e91fe76",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
}
]
}
"""
{-| This block summary response was used to test that unusally long words
in the transaction memo of an event are displayed correctly.
-}
getBlockSummaryLongMemoStub =
"""
{
"finalizationData": {
"finalizationIndex": 40851,
"finalizers": [
{
"bakerId": 0,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 1,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 2,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 3,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 4,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 15,
"signed": true,
"weight": 300292749406
},
{
"bakerId": 42,
"signed": false,
"weight": 300143881109
}
],
"finalizationDelay": 0,
"finalizationBlockPointer": "e784294b2393ceedc1f5c8d9169591bd99dedc0564b8362852a2990f0cebfe00"
},
"specialEvents": [
{
"tag": "Mint",
"foundationAccount": "48RDnoQaCKwy8xteebgLCDdX8qACa3WB5GnfuGMpCDfB2UfdL4",
"mintPlatformDevelopmentCharge": "138171",
"mintFinalizationReward": "414508",
"mintBakingReward": "829017"
},
{
"remainder": "5",
"tag": "FinalizationRewards",
"finalizationRewards": [
{
"amount": "79711",
"address": "3c1hZst6hfxm5CMPYGmUw7LvMe3Mo1VwgkXrBAb59GSdLzPiSz"
},
{
"amount": "79711",
"address": "3uyRpq2NPSY4VJn8Qd1uWGcUQTGpCAarHTtqpneiSGqv36Uhna"
},
{
"amount": "79711",
"address": "4AymJeLgpB7s7bSn6ARm22iAB15m5PpTHaXATBCktnzxvoBowJ"
},
{
"amount": "7974",
"address": "4C9vCCSLdeTB2DsUZZECReygdLbMR5AACoR1H7EfBfYem7bqLx"
},
{
"amount": "79711",
"address": "4ESt5DAQY3xi74Pj386otNf2S4fsohDG8Qxyv15hvqvbgFvYvC"
},
{
"amount": "7978",
"address": "4LRhqFikMSWMzX6ZenkvRVn94H6Zu6HdxmHvap9cuHmMrPraV2"
},
{
"amount": "79711",
"address": "4M63wWygknpRd1hVuKoirtusZJbWE9wiFe3rXCrZcFgLzXYzh4"
}
]
},
{
"tag": "BlockReward",
"bakerReward": "41914",
"newGASAccount": "42737",
"baker": "4M63wWygknpRd1hVuKoirtusZJbWE9wiFe3rXCrZcFgLzXYzh4",
"foundationAccount": "48RDnoQaCKwy8xteebgLCDdX8qACa3WB5GnfuGMpCDfB2UfdL4",
"oldGASAccount": "1671",
"foundationCharge": "9220",
"transactionFees": "92200"
}
],
"updates": {
"chainParameters": {
"minimumThresholdForBaking": "300000000000",
"rewardParameters": {
"mintDistribution": {
"mintPerSlot": 7.555665e-10,
"bakingReward": 0.6,
"finalizationReward": 0.3
},
"transactionFeeDistribution": {
"gasAccount": 0.45,
"baker": 0.45
},
"gASRewards": {
"chainUpdate": 5.0e-3,
"accountCreation": 2.0e-3,
"baker": 0.25,
"finalizationProof": 5.0e-3
}
},
"microGTUPerEuro": {
"denominator": 1,
"numerator": 100000000
},
"foundationAccountIndex": 5,
"accountCreationLimit": 10,
"bakerCooldownEpochs": 1,
"electionDifficulty": 2.5e-2,
"euroPerEnergy": {
"denominator": 1000000,
"numerator": 1
}
},
"keys": {
"rootKeys": {
"keys": [
{
"verifyKey": "e0b5fc074eef1178e41f6f2c494bde78b65bd3f21c36db4d41a1e6cb259c3a7d",
"schemeId": "Ed25519"
},
{
"verifyKey": "1f420ab84863a9ba0472bcb39bfe27a07727f84ace50a6c3f9d6d75e2519febc",
"schemeId": "Ed25519"
},
{
"verifyKey": "95a5064980b5bc27f3ae96a4831f3c60be82c2c0ee36de3ff028137a99fe823f",
"schemeId": "Ed25519"
},
{
"verifyKey": "ef3e58b13c43a8439046a774290a8ef0b17d6fe516cea1f48de894a5aec669a4",
"schemeId": "Ed25519"
},
{
"verifyKey": "830ac28b779ab09d0be9bd15ded7343be1f24df01ccf2e7cffd7d6359500f46c",
"schemeId": "Ed25519"
}
],
"threshold": 3
},
"level2Keys": {
"mintDistribution": {
"threshold": 3,
"authorizedKeys": [
17,
18,
19,
20,
21
]
},
"addAnonymityRevoker": {
"threshold": 3,
"authorizedKeys": [
37,
38,
39,
40,
41
]
},
"transactionFeeDistribution": {
"threshold": 3,
"authorizedKeys": [
22,
23,
24,
25,
26
]
},
"bakerStakeThreshold": {
"threshold": 3,
"authorizedKeys": [
32,
33,
34,
35,
36
]
},
"microGTUPerEuro": {
"threshold": 1,
"authorizedKeys": [
11
]
},
"protocol": {
"threshold": 2,
"authorizedKeys": [
5,
6,
7
]
},
"addIdentityProvider": {
"threshold": 3,
"authorizedKeys": [
42,
43,
44,
45,
46
]
},
"paramGASRewards": {
"threshold": 3,
"authorizedKeys": [
27,
28,
29,
30,
31
]
},
"emergency": {
"threshold": 3,
"authorizedKeys": [
0,
1,
2,
3,
4
]
},
"keys": [
{
"verifyKey": "97e908ee3a4d8dff49830aacca6bf42997f68afc1851fb5b3d58ae143ba4e147",
"schemeId": "Ed25519"
},
{
"verifyKey": "f222cc7e2ec7bc1ba7abeca6f503a123abd244292809f04425ad8d72f6ef47ff",
"schemeId": "Ed25519"
},
{
"verifyKey": "e098e1e55b13988b01e882a7fce5070fd12fa72d409eccebfbad0fb32d6ee057",
"schemeId": "Ed25519"
},
{
"verifyKey": "58f71ef93d95fd9466aa917d426970c96ff48f9cf1aafb52e4caf427cf6331c8",
"schemeId": "Ed25519"
},
{
"verifyKey": "9521707ac0ed5b577bc334c25154ab92336a1731bc9bcaefd14cd62bb42dcf96",
"schemeId": "Ed25519"
},
{
"verifyKey": "38e5321fca15c1f87fe7c1e266f1e85f68a877e3eea11fa45063ad5e4b92e2fb",
"schemeId": "Ed25519"
},
{
"verifyKey": "0aab1d7d1b81b7526163df81288f645249a0310f8ac84c5e8bc8f7a80be43df1",
"schemeId": "Ed25519"
},
{
"verifyKey": "74aa4e9dac2bdfea7db5b9fccf240be370746a172a6ae2775b9751d96226dc9d",
"schemeId": "Ed25519"
},
{
"verifyKey": "4a00ab5a36d4b402ddc4c3160df838f0aba805bb47843e85c8b14971a322f7b0",
"schemeId": "Ed25519"
},
{
"verifyKey": "a0b17ad7ab31a49168ab4ee479141a2a102d34ee50c1e5abb3b2e78e901760ae",
"schemeId": "Ed25519"
},
{
"verifyKey": "701376912e8820d404bd93e887d450e115e1dba9c53fdbe4e963ac3be92b508e",
"schemeId": "Ed25519"
},
{
"verifyKey": "aa5dd0d777e21571ea6bca6fad39cf84e4655643913d83f6ba4da4552f07c3ec",
"schemeId": "Ed25519"
},
{
"verifyKey": "88766292b604ec67298b817395bb41459575b7eebe22db49a3c87c6e664f67bd",
"schemeId": "Ed25519"
},
{
"verifyKey": "3f14ba2f24bbb5fb0ec906e7b5080dd104bc7b0ffbf183234db67ab0ccaeec26",
"schemeId": "Ed25519"
},
{
"verifyKey": "c39edc29fbf11264c60439e202a0a7fa91047fd54808057be50307a12018a38c",
"schemeId": "Ed25519"
},
{
"verifyKey": "5b85a0fed564bab70b67d201f405fbdf2712498720e2c7de8aa81bce7258319a",
"schemeId": "Ed25519"
},
{
"verifyKey": "dae562dbf3c082ff4ef58b3308b8858bb2fe105680ad863901776cc5f3131f3d",
"schemeId": "Ed25519"
},
{
"verifyKey": "5f28823bd52e6bd86d760a8b104bbd4e3b50cf45dfb076f057ab0561756664a7",
"schemeId": "Ed25519"
},
{
"verifyKey": "d034a8912eeef4c473798e0f790a16612781fb93b286baf20f4553fd07d8e1ca",
"schemeId": "Ed25519"
},
{
"verifyKey": "e68b20b846c2144d1719f09613ad927055420f7d03282be8c1f0ec32d0a0837e",
"schemeId": "Ed25519"
},
{
"verifyKey": "bf0c98b711d4bc5f0f2b90d427656234d2d4dc12bca59ae4c931cd9fcd4f66c0",
"schemeId": "Ed25519"
},
{
"verifyKey": "97e0c06300746dd211f7aa2c29f3628c53036eba3c16a9ad1e116d5b09176ae5",
"schemeId": "Ed25519"
},
{
"verifyKey": "10de8b005647c3fa2d528c21a1222ff8e2f7f10143e1d1f99f572016c150cdb5",
"schemeId": "Ed25519"
},
{
"verifyKey": "f8a6f0e1b60caddfdfad28f2ebbe20393a9961ac5a02dd5770dfb4bc2f633d07",
"schemeId": "Ed25519"
},
{
"verifyKey": "17cb31e51c9197ba1b88231f75ece5b3d33df60898408fac57375971bb68dfad",
"schemeId": "Ed25519"
},
{
"verifyKey": "661cb015b7ac83ec349f5010d9f73a62f383d9bc14d3256600ba6d26f9042110",
"schemeId": "Ed25519"
},
{
"verifyKey": "840d332eae5d251094e443a5a0acce58b63c43e72c7ce60add97f211d9b8b198",
"schemeId": "Ed25519"
},
{
"verifyKey": "55e9a120150626468f029dd343c2b03eb97b8fb6228a5d8772028f8752ad40f2",
"schemeId": "Ed25519"
},
{
"verifyKey": "4d60696102711d5e536c202a46f149ba8a959a49edf9be8da726a51d2f1185a7",
"schemeId": "Ed25519"
},
{
"verifyKey": "aa0f8e391f16bd7095b1a3c02ba513a111194d650a7104a627bcbbf6c63d82c1",
"schemeId": "Ed25519"
},
{
"verifyKey": "8c335e4bc9b8751ac45b15f3b1afea9765051f22393e93f5ff1bfd436d59c4f7",
"schemeId": "Ed25519"
},
{
"verifyKey": "a5a77daa690591d7e44520303efc843ba359deddcfa89456ab1a7c5a26419696",
"schemeId": "Ed25519"
},
{
"verifyKey": "e33274cbb31675f479ddff48a163924269cb46b99d814363d66948ccaf3d01f9",
"schemeId": "Ed25519"
},
{
"verifyKey": "f2eb7342f2dfccbbe15f5f91adda221286b25447a5af8a8db2170d842a5c1350",
"schemeId": "Ed25519"
},
{
"verifyKey": "cb9b6265f58cafc94bb33210357ee2709f4535b1aab08852d6df7a2421d1cb94",
"schemeId": "Ed25519"
},
{
"verifyKey": "e26018620b19e90ab8a1a34e6d9d87d851e3f6f9d75f5f5192a30d3aec22f812",
"schemeId": "Ed25519"
},
{
"verifyKey": "ce2cf1c1082b082abdb4599e15f6303303cc00cb8fe6820c5cda66c443e4144d",
"schemeId": "Ed25519"
},
{
"verifyKey": "cd735b34b9ebd6d5dcb9cb56040b78e04a5a9449de2473a03887cf6dade2af60",
"schemeId": "Ed25519"
},
{
"verifyKey": "78f9eac5476dd188177ddf22793c73231ff0abe11614f8373f86f33a2e14fbe6",
"schemeId": "Ed25519"
},
{
"verifyKey": "802af182e7ba273d1c41441716c21db4773e4635fe1ea27760f33f3ad920eb0c",
"schemeId": "Ed25519"
},
{
"verifyKey": "a264dd70a3eeac72397cde270806bb36651f25c1971d7a364a87b8d2184ebce0",
"schemeId": "Ed25519"
},
{
"verifyKey": "951a1a3c5f3907f5706a9a587516cca3c13d8af21abceb4225df66d942d06f02",
"schemeId": "Ed25519"
},
{
"verifyKey": "285568e67384368b0740309827a295a7c6044db1e7c96f6895c8fc7e2a5b4a38",
"schemeId": "Ed25519"
},
{
"verifyKey": "bdb46f6cdcf24c5f0f183275c6325ea4034ce3bab1e7a362fce227d37c43e71f",
"schemeId": "Ed25519"
},
{
"verifyKey": "9b86c0d98a295a23c3c92cb918a48d9b3cf3ab01d5d1d78a036e4a6b7d577c74",
"schemeId": "Ed25519"
},
{
"verifyKey": "cb7ac7662b4dc4ea902e0d6116dd936ac4e1ace0a86e50059941aba6fd4aefc0",
"schemeId": "Ed25519"
},
{
"verifyKey": "f69e41a6d9d8417db5497ebe4688b734fb709ee16bed147ded80dfa2930d69db",
"schemeId": "Ed25519"
}
],
"foundationAccount": {
"threshold": 3,
"authorizedKeys": [
12,
13,
14,
15,
16
]
},
"electionDifficulty": {
"threshold": 2,
"authorizedKeys": [
8,
9,
10
]
},
"euroPerEnergy": {
"threshold": 2,
"authorizedKeys": [
8,
9,
10
]
}
},
"level1Keys": {
"keys": [
{
"verifyKey": "0d57ecfe1f7d941fbc1bc0d001b632052d549cbeab6a966f944e3ad2dac89f6d",
"schemeId": "Ed25519"
},
{
"verifyKey": "d0d29ce95287f45da364cdd6db512a9eb2bc43704381fc4cf0ffe14540568edc",
"schemeId": "Ed25519"
},
{
"verifyKey": "94bec66e5b2f69ba94592c98a7facb78033d35c326beecaf263aef536d2a9c2f",
"schemeId": "Ed25519"
},
{
"verifyKey": "1d13c5e8ca89c4fc0ef7e56e3bcec776490eb364a687c0769540fe2d59fc1b2c",
"schemeId": "Ed25519"
},
{
"verifyKey": "e9f9715686673769091df75ed0579976b82e83f73cc3559748c2e9627014d6d8",
"schemeId": "Ed25519"
}
],
"threshold": 3
}
},
"updateQueues": {
"mintDistribution": {
"nextSequenceNumber": 1,
"queue": []
},
"rootKeys": {
"nextSequenceNumber": 1,
"queue": []
},
"addAnonymityRevoker": {
"nextSequenceNumber": 1,
"queue": []
},
"transactionFeeDistribution": {
"nextSequenceNumber": 1,
"queue": []
},
"bakerStakeThreshold": {
"nextSequenceNumber": 1,
"queue": []
},
"level2Keys": {
"nextSequenceNumber": 1,
"queue": []
},
"microGTUPerEuro": {
"nextSequenceNumber": 1,
"queue": []
},
"protocol": {
"nextSequenceNumber": 2,
"queue": []
},
"addIdentityProvider": {
"nextSequenceNumber": 1,
"queue": []
},
"gasRewards": {
"nextSequenceNumber": 1,
"queue": []
},
"foundationAccount": {
"nextSequenceNumber": 1,
"queue": []
},
"electionDifficulty": {
"nextSequenceNumber": 1,
"queue": []
},
"euroPerEnergy": {
"nextSequenceNumber": 1,
"queue": []
},
"level1Keys": {
"nextSequenceNumber": 1,
"queue": []
}
}
},
"transactionSummaries": [
{
"hash": "1623fb1b65720bbf34b7d9c47818af49e7c4610eaf6f1e241ba1208d1e5d94bb",
"sender": "4PXJrvKGKb1YZt2Vua3mSDThqUU2EChweuydsFtVFtvDDr585H",
"cost": "92200",
"energyCost": 922,
"result": {
"events": [
{
"amount": "1000000",
"tag": "Transferred",
"to": {
"address": "48RDnoQaCKwy8xteebgLCDdX8qACa3WB5GnfuGMpCDfB2UfdL4",
"type": "AddressAccount"
},
"from": {
"address": "4PXJrvKGKb1YZt2Vua3mSDThqUU2EChweuydsFtVFtvDDr585H",
"type": "AddressAccount"
}
},
{
"memo": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"tag": "TransferMemo"
}
],
"outcome": "success"
},
"type": {
"contents": "transferWithMemo",
"type": "accountTransaction"
},
"index": 0
}
]
}
"""
| 38020 | module Explorer.Stubs exposing (..)
blockSummaryStubs =
[ ( "allTransactions: The most comprehensive transactions example we have, mostly generated by the `debugTestFullProvision` helper function in middleware, with some manual additional transaction types added. Includes example of finalization record."
, getBlockSummaryAllTransactionsStub
)
, ( "sc module deploys: example from the SC demo", getBlockSummaryContractDeploysStub )
, ( "failure", getBlockSummaryFailureStub )
, ( "rstub", getBlockSummaryResponseStub )
]
getBlockSummaryAllTransactionsStub =
"""
{
"specialEvents": [
{
"bakerId": 1,
"rewardAmount": 12463,
"bakerAccount": "<KEY>"
}
],
"finalizationData":{
"finalizationIndex":3,
"finalizers":[
{
"bakerId":0,
"signed":true,
"weight":1200000000135
},
{
"bakerId":1,
"signed":false,
"weight":800000000005
},
{
"bakerId":2,
"signed":false,
"weight":1200000000000
},
{
"bakerId":3,
"signed":true,
"weight":800000000000
},
{
"bakerId":4,
"signed":true,
"weight":1200000000000
}
],
"finalizationDelay":0,
"finalizationBlockPointer":"847e0c5037f8eedf3e5b5c932e4ebcb0b5ad9deaa986d83a165d8712594e0e1d"
},
"transactionSummaries": [
{
"hash": "d1aeaedec44266f044a230ad7bd9339a992418fbcd11a3217686f6854<KEY>1816<KEY>",
"sender": null,
"cost": 0,
"energyCost": 35000,
"result": {
"events": [
{
"tag": "AccountCreated",
"contents": "3ADz9qYiEzeui5ccMC7CCHrdsWArV4T45ktGhyt2CnUK4BL4U6"
},
{
"tag": "CredentialDeployed",
"regId": "<KEY>",
"account": "<KEY>"
}
],
"outcome": "success"
},
"type": null,
"index": 0
},
{
"hash": "4b7e1b22ff9365e29c57d7f85a0fd7a7dd3c50245cb9d04c560c520298013c3f",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 165,
"energyCost": 165,
"result": {
"events": [
{
"amount": 1000000,
"tag": "Transferred",
"to": {
"address": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"type": "transfer",
"index": 0
},
{
"hash": "5292c68df8787b3b22a61397edc3fc04858d4112e770ee7674e80751254d6f27",
"sender": "<KEY>",
"cost": 59,
"energyCost": 59,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "AmountTooLarge",
"contents": [
{
"address": "3<KEY>",
"type": "AddressAccount"
},
200000000
]
}
},
"type": "transfer",
"index": 0
},
{
"hash": "15c2c8a0a9d496630dff603d4d404a6912d96215755884522798092bc179de5b",
"sender": "<KEY>",
"cost": 265,
"energyCost": 265,
"result": {
"events": [
{
"tag": "StakeDelegated",
"account": "<KEY>YPw<KEY>Z<KEY>4D<KEY>3<KEY>t",
"baker": 0
}
],
"outcome": "success"
},
"type": "delegateStake",
"index": 1
},
{
"hash": "ae13d5677cdcbd90fad54e9768f4f1f4c44610c45af1c2ca0481119d47c8a2bb",
"sender": "<KEY>",
"cost": 265,
"energyCost": 265,
"result": {
"events": [
{
"tag": "StakeDelegated",
"account": "<KEY>",
"baker": 0
}
],
"outcome": "success"
},
"type": "delegateStake",
"index": 2
},
{
"hash": "73513777db8519ef5b71a0bd06a1b06bd705bf06e62737fa563ed75e20fcec27",
"sender": "<KEY>",
"cost": 3167,
"energyCost": 3167,
"result": {
"events": [
{
"tag": "BakerAdded",
"contents": 5
}
],
"outcome": "success"
},
"type": "addBaker",
"index": 3
},
{
"hash": "affc03c8211ea90cb72143e5c44eff7e55089668af8e64bd6b978ef7cfac39c7",
"sender": "<KEY>",
"cost": 265,
"energyCost": 265,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "InvalidStakeDelegationTarget",
"contents": 12312312312
}
},
"type": "delegateStake",
"index": 4
},
{
"hash": "2b40fc10934a371e9d23dead69435d834aa725ebc418b6631abb49b5f808a07c",
"sender": "<KEY>",
"cost": 166,
"energyCost": 166,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "SerializationFailure"
}
},
"type": null,
"index": 5
},
{
"hash": "8841d4dd1da2875b63d829be55fc5441adba2efa2baaed3b1228601e25bc2bb2",
"sender": "<KEY>",
"cost": 165,
"energyCost": 165,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "SerializationFailure"
}
},
"type": null,
"index": 6
},
{
"hash": "5257c01e5f42a0afcead07149a47416<KEY>",
"sender": "<KEY>3T<KEY>3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 165,
"energyCost": 165,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "InvalidBakerRemoveSource",
"contents": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
}
},
"type": "removeBaker",
"index": 7
},
{
"hash": "2a0a5ea99e9f091a3704c7fa8d163e971f32d2a591060cdeab4a02790f7cf4ad",
"sender": "<KEY>",
"cost": 2705,
"energyCost": 2705,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "69f895cec649178d771b016019912e84bbc659ef35e132585cb5a358b7f7ffb0"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 0
},
{
"hash": "0b04e5f0e2969ea2961cc0667d48cc17166f3ad84e1cd5900d85d79e63919bd3",
"sender": "<KEY>",
"cost": 1527,
"energyCost": 1527,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "33f8832053c36b443084040537f11a66527bc1446a0aa41704ddf06e44093455"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 1
},
{
"cost": 3031,
"energyCost": 3031,
"hash": "0a75fdac33df28b8ae17fead28f837cb28ae23999cdb81bd5f9b7993e24cc204",
"index": 0,
"result": {
"events": [
{
"address": {
"index": 0,
"subindex": 0
},
"amount": 0,
"name": 200,
"ref": "7d6b63bde558564b77070bf1da85c56e7fd9f006ef8d0923d19689577614dd2d",
"tag": "ContractInitialized"
}
],
"outcome": "success"
},
"sender": "<KEY>",
"type": "initContract"
},
{
"hash": "a633a418a26353989dec0e813353984892976e3c821bfac5cddee9850ce7bf9e",
"sender": "3<KEY>",
"cost": 464,
"energyCost": 464,
"result": {
"events": [
{
"amount": 10,
"tag": "Updated",
"instigator": {
"address": "3Lqzxro<KEY>xGGBu<KEY>o<KEY>",
"type": "AddressAccount"
},
"address": {
"subindex": 0,
"index": 0
},
"message": "ExprMessage (Let (LetForeign (Imported 7d6b63bde558564b77070bf1da85c56e7fd9f006ef8d0923d19689577614dd2d (Name 130)) (Linked (Constructor (Name 130))) (Atom (BoundVar (Reference (-1))))) (Let (Constructor (Name 1)) (App (Reference 0) [BoundVar (Reference 1)])))"
}
],
"outcome": "success"
},
"type": "update",
"index": 0
}
]
}
"""
getBlockSummaryContractDeploysStub =
"""
{
"specialEvents": [
{
"bakerId": 3,
"rewardAmount": 35984,
"bakerAccount": "<KEY>"
}
],
"transactionSummaries": [
{
"hash": "2a0a5ea99e9f091a3704c7fa8d163e971f32d2a591060cdeab4a02790f7cf4ad",
"sender": "3<KEY>",
"cost": 2705,
"energyCost": 2705,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "69f895cec649178d771b016019912e84bbc659ef35e132585cb5a358b7f7ffb0"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 0
},
{
"hash": "0b04e5f0e2969ea2961cc0667d48cc17166f3ad84e1cd5900d85d79e63919bd3",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1527,
"energyCost": 1527,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "33f8832053c36b443084040537f11a66527bc1446a0aa41704ddf06e44093455"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 1
},
{
"hash": "21585869b20629a5fb13eaa40e4d488e6c458d8609e994194b6c4c0cd78ded50",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1365,
"energyCost": 1365,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "73310b972c101c4ec69e6eb427ebc843d5483f4adb771d1dc711f8de5ebaced4"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 2
},
{
"hash": "b5fba16ba8bb959bab172beb8939700e28d043689e6fd08023034d3a2e3d5168",
"sender": "<KEY>",
"cost": 1558,
"energyCost": 1558,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "73e1ebc954909b336a9c08443fff079e75956e7c0f314c4ad56b8bcfebaef8c4"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 3
},
{
"hash": "e91402ac563df428372a23ab83a26224696d89c14d8ab1f69623f5ca05efce98",
"sender": "<KEY>",
"cost": 4890,
"energyCost": 4890,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "3aa516e0b15327d7427b9acf7600c3e0376f65eeef7187975be38df70e0ab3e6"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 4
},
{
"hash": "bac1fb11f121a88431c146acf2b5514cb723629d553f384b1c9691470b7648fe",
"sender": "<KEY>",
"cost": 657,
"energyCost": 657,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "6a1ece5ea0d5a25bcf6e53f6e7bb4cf2b5a8cabaa8b58ba30a454e3582b26007"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 5
},
{
"hash": "7df554bb85448d8cc2cc9ed11b9eac348f56105e408ffb34c987c1781cc7bace",
"sender": "<KEY>",
"cost": 1417,
"energyCost": 1417,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "ec79b0b4ab8f91247b271af307e8d0ae7f8c6cff7bcd9ca63d214116a01aa876"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 6
},
{
"hash": "404311b6f25efff232<KEY>",
"sender": "<KEY>",
"cost": 3055,
"energyCost": 3055,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "7d6b63bde558564b77070bf1da85c56e7fd9f006ef8d0923d19689577614dd2d"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 7
},
{
"hash": "7c1dac909a4f49a74d80976467eecbbe641f142197747dd5e470f22167641474",
"sender": "<KEY>",
"cost": 3479,
"energyCost": 3479,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "1e4a518694fba2bd3edecec2aaac166edf2b65b59c0c6900e26637b73a7fbb2b"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 8
},
{
"hash": "4aa521cb1733ef27a78151d698a8c460c69af9f2a4d4619497b7cea73a11264f",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1775,
"energyCost": 1775,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "6e33fddc0a95324af4510964827c02c87cf403255cb8f7baae90786625133a3a"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 9
}
]
}
"""
getBlockSummaryFailureStub =
"""
{
"specialEvents": [
{
"bakerId": 2,
"rewardAmount": 1751,
"bakerAccount": "<KEY>"
}
],
"transactionSummaries": [
{
"hash": "0ada4e64558bb99a3607647c490f39083f44c709e654d689d8bf3fb343a95961",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 165,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "InvalidAccountReference",
"contents": "3Es2U5gMdKrqJdXSUVzgW4KUosJ91AxfsAuvKx5tKE9P2SvjVk"
}
},
"energyCost": 165,
"type": "transfer",
"index": 0
}
]
}
"""
getBlockSummaryResponseStub =
"""
{
"specialEvents": [
{
"bakerId": 4,
"rewardAmount": 207,
"bakerAccount": "<KEY>"
}
],
"transactionSummaries": [
{
"hash": "ae3154e1ee8a64d9e9718e57fbc979175be2ee8526b23fcddab2d626ebaeb72d",
"sender": null,
"cost": 0,
"result": {
"events": [
{
"tag": "AccountCreated",
"contents": "3P2Qsi8FeMB6AijMi3kpD9FrcFfAkoHDMu8kf7Fbd3cYYJpk2s"
},
{
"tag": "CredentialDeployed",
"regId": "<KEY>",
"account": "<KEY>"
}
],
"outcome": "success"
},
"energyCost": 35000,
"type": null,
"index": 0
},
{
"hash": "2ecde309ea6b48cebfbb73eb1ee3364c4f10330955a4a13acb7d87076461ab2d",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "dba5e4bafc7d2201cc23d30f288e276b5305b0722a74d0ac1fe1f6b15d1496a2",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "f59897e5be69ecd5ed5843a10d74ee2b652064bd5077b853e6b324c23683af7b",
"sender": "4<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "4<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "f49899ac815b01a9f6e49c4d1fc926c511fcd3cc453c1307a504ef937a4fe8b5",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4<KEY>",
"type": "AddressContract"
},
"from": {
"address": "4KY<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "3ad7e0a0e3ed193bfba065c83704ae5bf84837255ac720565479afab81767c96",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "4<KEY>",
"type": "AddressContract"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "d3b0cdeab57dc4d5e6b1faa1e4915ddfc2d025655775254e7124ae031688d9d8",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "bf6e33703977ce94caa918911f63b04654da0047454c484be9c80b487cc142c5",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "8781b249f4629f0ca9789fe143bfd4031208a7bfcca0ade9dd9f63ae8dac317d",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "41e6c23be80ab1151697ad16a4427268b0fd5440af0bb7bee4b330648669b164",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "4<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "71b1e81a467f038102b4028f62f1d75324b3f523472b89c583fdac918e762560",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4<KEY>L",
"type": "AddressAccount"
},
"from": {
"address": "4<KEY>L",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "5298e7d571852da5c030c15b1513405c365111315efbc062a9d0f9082d1d5e6f",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KY<KEY>L",
"type": "AddressAccount"
},
"from": {
"address": "4<KEY>L",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "c7487dc3ee7cd097636badc9c21771d2a62a37052be8204078f516583cb5320e",
"sender": "4<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "dd6871001af51dc048bbae8ceb187c58fb2cf66ba838897b8f527642fb7e552a",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "fc2ee2cd1294f0dc8a0c738c25bc6f762edf2689ee37b22382d9a4b931637ae7",
"sender": "4KY<KEY>L",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "029681010cdc89383926d32017af7e51357f66b33f1527396f0af63b5b9a3e6c",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "64fbd260407f681292cc4931f8c3d7edb034574c172a90f1923188751fb6775a",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "4<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "5cc3ec13c9844456d8b65f0534dca943a4ece1b12c1ca0f8f5a2936c7e260722",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "5a9c8dd2b90b7943a48<KEY>",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "16672379084db2866db4564e0c42103d3f6edcdfedee6b9ce5f520b9aef78ea7",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "de7eecba63d94c7810126cc325d6cf43d9382d8d2fed680202140fe97e91fe76",
"sender": "<KEY>",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "<KEY>",
"type": "AddressAccount"
},
"from": {
"address": "<KEY>",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
}
]
}
"""
{-| This block summary response was used to test that unusally long words
in the transaction memo of an event are displayed correctly.
-}
getBlockSummaryLongMemoStub =
"""
{
"finalizationData": {
"finalizationIndex": 40851,
"finalizers": [
{
"bakerId": 0,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 1,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 2,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 3,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 4,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 15,
"signed": true,
"weight": 300292749406
},
{
"bakerId": 42,
"signed": false,
"weight": 300143881109
}
],
"finalizationDelay": 0,
"finalizationBlockPointer": "e784294b2393ceedc1f5c8d9169591bd99dedc0564b8362852a2990f0cebfe00"
},
"specialEvents": [
{
"tag": "Mint",
"foundationAccount": "<KEY>",
"mintPlatformDevelopmentCharge": "138171",
"mintFinalizationReward": "414508",
"mintBakingReward": "829017"
},
{
"remainder": "5",
"tag": "FinalizationRewards",
"finalizationRewards": [
{
"amount": "79711",
"address": "<KEY>"
},
{
"amount": "79711",
"address": "<KEY>"
},
{
"amount": "79711",
"address": "<KEY>"
},
{
"amount": "7974",
"address": "<KEY>"
},
{
"amount": "79711",
"address": "<KEY>"
},
{
"amount": "7978",
"address": "<KEY>"
},
{
"amount": "79711",
"address": "<KEY>"
}
]
},
{
"tag": "BlockReward",
"bakerReward": "41914",
"newGASAccount": "<KEY>",
"baker": "<KEY>",
"foundationAccount": "<KEY>",
"oldGASAccount": "1<KEY>",
"foundationCharge": "9220",
"transactionFees": "92200"
}
],
"updates": {
"chainParameters": {
"minimumThresholdForBaking": "300000000000",
"rewardParameters": {
"mintDistribution": {
"mintPerSlot": 7.555665e-10,
"bakingReward": 0.6,
"finalizationReward": 0.3
},
"transactionFeeDistribution": {
"gasAccount": 0.45,
"baker": 0.45
},
"gASRewards": {
"chainUpdate": 5.0e-3,
"accountCreation": 2.0e-3,
"baker": 0.25,
"finalizationProof": 5.0e-3
}
},
"microGTUPerEuro": {
"denominator": 1,
"numerator": 100000000
},
"foundationAccountIndex": 5,
"accountCreationLimit": 10,
"bakerCooldownEpochs": 1,
"electionDifficulty": 2.5e-2,
"euroPerEnergy": {
"denominator": 1000000,
"numerator": 1
}
},
"keys": {
"rootKeys": {
"keys": [
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
}
],
"threshold": 3
},
"level2Keys": {
"mintDistribution": {
"threshold": 3,
"authorizedKeys": [
17,
18,
19,
20,
21
]
},
"addAnonymityRevoker": {
"threshold": 3,
"authorizedKeys": [
37,
38,
39,
40,
41
]
},
"transactionFeeDistribution": {
"threshold": 3,
"authorizedKeys": [
22,
23,
24,
25,
26
]
},
"bakerStakeThreshold": {
"threshold": 3,
"authorizedKeys": [
32,
33,
34,
35,
36
]
},
"microGTUPerEuro": {
"threshold": 1,
"authorizedKeys": [
11
]
},
"protocol": {
"threshold": 2,
"authorizedKeys": [
5,
6,
7
]
},
"addIdentityProvider": {
"threshold": 3,
"authorizedKeys": [
4<KEY>,
43,
44,
45,
46
]
},
"paramGASRewards": {
"threshold": 3,
"authorizedKeys": [
27,
28,
29,
30,
31
]
},
"emergency": {
"threshold": 3,
"authorizedKeys": [
0,
1,
2,
3,
4
]
},
"keys": [
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>7<KEY>",
"schemeId": "Ed25519"
}
],
"foundationAccount": {
"threshold": 3,
"authorizedKeys": [
12,
13,
14,
15,
16
]
},
"electionDifficulty": {
"threshold": 2,
"authorizedKeys": [
8,
9,
1<KEY>
]
},
"euroPerEnergy": {
"threshold": 2,
"authorizedKeys": [
<KEY>,
9,
10
]
}
},
"level1Keys": {
"keys": [
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>",
"schemeId": "Ed25519"
},
{
"verifyKey": "<KEY>75ed0579976b82e83f73cc3559748c2e9627014d6d8",
"schemeId": "Ed25519"
}
],
"threshold": 3
}
},
"updateQueues": {
"mintDistribution": {
"nextSequenceNumber": 1,
"queue": []
},
"rootKeys": {
"nextSequenceNumber": 1,
"queue": []
},
"addAnonymityRevoker": {
"nextSequenceNumber": 1,
"queue": []
},
"transactionFeeDistribution": {
"nextSequenceNumber": 1,
"queue": []
},
"bakerStakeThreshold": {
"nextSequenceNumber": 1,
"queue": []
},
"level2Keys": {
"nextSequenceNumber": 1,
"queue": []
},
"microGTUPerEuro": {
"nextSequenceNumber": 1,
"queue": []
},
"protocol": {
"nextSequenceNumber": 2,
"queue": []
},
"addIdentityProvider": {
"nextSequenceNumber": 1,
"queue": []
},
"gasRewards": {
"nextSequenceNumber": 1,
"queue": []
},
"foundationAccount": {
"nextSequenceNumber": 1,
"queue": []
},
"electionDifficulty": {
"nextSequenceNumber": 1,
"queue": []
},
"euroPerEnergy": {
"nextSequenceNumber": 1,
"queue": []
},
"level1Keys": {
"nextSequenceNumber": 1,
"queue": []
}
}
},
"transactionSummaries": [
{
"hash": "1623fb1b65720bbf34b7d9c47818af49e7c4610eaf6f1e241ba1208d1e5d94bb",
"sender": "4PXJrvKGKb1YZt2Vua3mSDThqUU2EChweuydsFtVFtvDDr585H",
"cost": "92200",
"energyCost": 922,
"result": {
"events": [
{
"amount": "1000000",
"tag": "Transferred",
"to": {
"address": "48RDnoQaCKwy8xteebgLCDdX8qACa3WB5GnfuGMpCDfB2UfdL4",
"type": "AddressAccount"
},
"from": {
"address": "4PXJrvKGKb1YZt2V<KEY>3mSDTh<KEY>UU2EChweuydsFtVFtvDDr585H",
"type": "AddressAccount"
}
},
{
"memo": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"tag": "TransferMemo"
}
],
"outcome": "success"
},
"type": {
"contents": "transferWithMemo",
"type": "accountTransaction"
},
"index": 0
}
]
}
"""
| true | module Explorer.Stubs exposing (..)
blockSummaryStubs =
[ ( "allTransactions: The most comprehensive transactions example we have, mostly generated by the `debugTestFullProvision` helper function in middleware, with some manual additional transaction types added. Includes example of finalization record."
, getBlockSummaryAllTransactionsStub
)
, ( "sc module deploys: example from the SC demo", getBlockSummaryContractDeploysStub )
, ( "failure", getBlockSummaryFailureStub )
, ( "rstub", getBlockSummaryResponseStub )
]
getBlockSummaryAllTransactionsStub =
"""
{
"specialEvents": [
{
"bakerId": 1,
"rewardAmount": 12463,
"bakerAccount": "PI:KEY:<KEY>END_PI"
}
],
"finalizationData":{
"finalizationIndex":3,
"finalizers":[
{
"bakerId":0,
"signed":true,
"weight":1200000000135
},
{
"bakerId":1,
"signed":false,
"weight":800000000005
},
{
"bakerId":2,
"signed":false,
"weight":1200000000000
},
{
"bakerId":3,
"signed":true,
"weight":800000000000
},
{
"bakerId":4,
"signed":true,
"weight":1200000000000
}
],
"finalizationDelay":0,
"finalizationBlockPointer":"847e0c5037f8eedf3e5b5c932e4ebcb0b5ad9deaa986d83a165d8712594e0e1d"
},
"transactionSummaries": [
{
"hash": "d1aeaedec44266f044a230ad7bd9339a992418fbcd11a3217686f6854PI:KEY:<KEY>END_PI1816PI:KEY:<KEY>END_PI",
"sender": null,
"cost": 0,
"energyCost": 35000,
"result": {
"events": [
{
"tag": "AccountCreated",
"contents": "3ADz9qYiEzeui5ccMC7CCHrdsWArV4T45ktGhyt2CnUK4BL4U6"
},
{
"tag": "CredentialDeployed",
"regId": "PI:KEY:<KEY>END_PI",
"account": "PI:KEY:<KEY>END_PI"
}
],
"outcome": "success"
},
"type": null,
"index": 0
},
{
"hash": "4b7e1b22ff9365e29c57d7f85a0fd7a7dd3c50245cb9d04c560c520298013c3f",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 165,
"energyCost": 165,
"result": {
"events": [
{
"amount": 1000000,
"tag": "Transferred",
"to": {
"address": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"type": "transfer",
"index": 0
},
{
"hash": "5292c68df8787b3b22a61397edc3fc04858d4112e770ee7674e80751254d6f27",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 59,
"energyCost": 59,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "AmountTooLarge",
"contents": [
{
"address": "3PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
200000000
]
}
},
"type": "transfer",
"index": 0
},
{
"hash": "15c2c8a0a9d496630dff603d4d404a6912d96215755884522798092bc179de5b",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 265,
"energyCost": 265,
"result": {
"events": [
{
"tag": "StakeDelegated",
"account": "PI:KEY:<KEY>END_PIYPwPI:KEY:<KEY>END_PIZPI:KEY:<KEY>END_PI4DPI:KEY:<KEY>END_PI3PI:KEY:<KEY>END_PIt",
"baker": 0
}
],
"outcome": "success"
},
"type": "delegateStake",
"index": 1
},
{
"hash": "ae13d5677cdcbd90fad54e9768f4f1f4c44610c45af1c2ca0481119d47c8a2bb",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 265,
"energyCost": 265,
"result": {
"events": [
{
"tag": "StakeDelegated",
"account": "PI:KEY:<KEY>END_PI",
"baker": 0
}
],
"outcome": "success"
},
"type": "delegateStake",
"index": 2
},
{
"hash": "73513777db8519ef5b71a0bd06a1b06bd705bf06e62737fa563ed75e20fcec27",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 3167,
"energyCost": 3167,
"result": {
"events": [
{
"tag": "BakerAdded",
"contents": 5
}
],
"outcome": "success"
},
"type": "addBaker",
"index": 3
},
{
"hash": "affc03c8211ea90cb72143e5c44eff7e55089668af8e64bd6b978ef7cfac39c7",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 265,
"energyCost": 265,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "InvalidStakeDelegationTarget",
"contents": 12312312312
}
},
"type": "delegateStake",
"index": 4
},
{
"hash": "2b40fc10934a371e9d23dead69435d834aa725ebc418b6631abb49b5f808a07c",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 166,
"energyCost": 166,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "SerializationFailure"
}
},
"type": null,
"index": 5
},
{
"hash": "8841d4dd1da2875b63d829be55fc5441adba2efa2baaed3b1228601e25bc2bb2",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 165,
"energyCost": 165,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "SerializationFailure"
}
},
"type": null,
"index": 6
},
{
"hash": "5257c01e5f42a0afcead07149a47416PI:KEY:<KEY>END_PI",
"sender": "PI:KEY:<KEY>END_PI3TPI:KEY:<KEY>END_PI3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 165,
"energyCost": 165,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "InvalidBakerRemoveSource",
"contents": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt"
}
},
"type": "removeBaker",
"index": 7
},
{
"hash": "2a0a5ea99e9f091a3704c7fa8d163e971f32d2a591060cdeab4a02790f7cf4ad",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 2705,
"energyCost": 2705,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "69f895cec649178d771b016019912e84bbc659ef35e132585cb5a358b7f7ffb0"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 0
},
{
"hash": "0b04e5f0e2969ea2961cc0667d48cc17166f3ad84e1cd5900d85d79e63919bd3",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 1527,
"energyCost": 1527,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "33f8832053c36b443084040537f11a66527bc1446a0aa41704ddf06e44093455"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 1
},
{
"cost": 3031,
"energyCost": 3031,
"hash": "0a75fdac33df28b8ae17fead28f837cb28ae23999cdb81bd5f9b7993e24cc204",
"index": 0,
"result": {
"events": [
{
"address": {
"index": 0,
"subindex": 0
},
"amount": 0,
"name": 200,
"ref": "7d6b63bde558564b77070bf1da85c56e7fd9f006ef8d0923d19689577614dd2d",
"tag": "ContractInitialized"
}
],
"outcome": "success"
},
"sender": "PI:KEY:<KEY>END_PI",
"type": "initContract"
},
{
"hash": "a633a418a26353989dec0e813353984892976e3c821bfac5cddee9850ce7bf9e",
"sender": "3PI:KEY:<KEY>END_PI",
"cost": 464,
"energyCost": 464,
"result": {
"events": [
{
"amount": 10,
"tag": "Updated",
"instigator": {
"address": "3LqzxroPI:KEY:<KEY>END_PIxGGBuPI:KEY:<KEY>END_PIoPI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"address": {
"subindex": 0,
"index": 0
},
"message": "ExprMessage (Let (LetForeign (Imported 7d6b63bde558564b77070bf1da85c56e7fd9f006ef8d0923d19689577614dd2d (Name 130)) (Linked (Constructor (Name 130))) (Atom (BoundVar (Reference (-1))))) (Let (Constructor (Name 1)) (App (Reference 0) [BoundVar (Reference 1)])))"
}
],
"outcome": "success"
},
"type": "update",
"index": 0
}
]
}
"""
getBlockSummaryContractDeploysStub =
"""
{
"specialEvents": [
{
"bakerId": 3,
"rewardAmount": 35984,
"bakerAccount": "PI:KEY:<KEY>END_PI"
}
],
"transactionSummaries": [
{
"hash": "2a0a5ea99e9f091a3704c7fa8d163e971f32d2a591060cdeab4a02790f7cf4ad",
"sender": "3PI:KEY:<KEY>END_PI",
"cost": 2705,
"energyCost": 2705,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "69f895cec649178d771b016019912e84bbc659ef35e132585cb5a358b7f7ffb0"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 0
},
{
"hash": "0b04e5f0e2969ea2961cc0667d48cc17166f3ad84e1cd5900d85d79e63919bd3",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1527,
"energyCost": 1527,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "33f8832053c36b443084040537f11a66527bc1446a0aa41704ddf06e44093455"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 1
},
{
"hash": "21585869b20629a5fb13eaa40e4d488e6c458d8609e994194b6c4c0cd78ded50",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1365,
"energyCost": 1365,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "73310b972c101c4ec69e6eb427ebc843d5483f4adb771d1dc711f8de5ebaced4"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 2
},
{
"hash": "b5fba16ba8bb959bab172beb8939700e28d043689e6fd08023034d3a2e3d5168",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 1558,
"energyCost": 1558,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "73e1ebc954909b336a9c08443fff079e75956e7c0f314c4ad56b8bcfebaef8c4"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 3
},
{
"hash": "e91402ac563df428372a23ab83a26224696d89c14d8ab1f69623f5ca05efce98",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 4890,
"energyCost": 4890,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "3aa516e0b15327d7427b9acf7600c3e0376f65eeef7187975be38df70e0ab3e6"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 4
},
{
"hash": "bac1fb11f121a88431c146acf2b5514cb723629d553f384b1c9691470b7648fe",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 657,
"energyCost": 657,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "6a1ece5ea0d5a25bcf6e53f6e7bb4cf2b5a8cabaa8b58ba30a454e3582b26007"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 5
},
{
"hash": "7df554bb85448d8cc2cc9ed11b9eac348f56105e408ffb34c987c1781cc7bace",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 1417,
"energyCost": 1417,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "ec79b0b4ab8f91247b271af307e8d0ae7f8c6cff7bcd9ca63d214116a01aa876"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 6
},
{
"hash": "404311b6f25efff232PI:KEY:<KEY>END_PI",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 3055,
"energyCost": 3055,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "7d6b63bde558564b77070bf1da85c56e7fd9f006ef8d0923d19689577614dd2d"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 7
},
{
"hash": "7c1dac909a4f49a74d80976467eecbbe641f142197747dd5e470f22167641474",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 3479,
"energyCost": 3479,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "1e4a518694fba2bd3edecec2aaac166edf2b65b59c0c6900e26637b73a7fbb2b"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 8
},
{
"hash": "4aa521cb1733ef27a78151d698a8c460c69af9f2a4d4619497b7cea73a11264f",
"sender": "3LqzxroRTxGGBuhyoH5CzSyUvrgvhX1tPPCLVZz8QQ9ZmbrmcZ",
"cost": 1775,
"energyCost": 1775,
"result": {
"events": [
{
"tag": "ModuleDeployed",
"contents": "6e33fddc0a95324af4510964827c02c87cf403255cb8f7baae90786625133a3a"
}
],
"outcome": "success"
},
"type": "deployModule",
"index": 9
}
]
}
"""
getBlockSummaryFailureStub =
"""
{
"specialEvents": [
{
"bakerId": 2,
"rewardAmount": 1751,
"bakerAccount": "PI:KEY:<KEY>END_PI"
}
],
"transactionSummaries": [
{
"hash": "0ada4e64558bb99a3607647c490f39083f44c709e654d689d8bf3fb343a95961",
"sender": "43TULx3kDPDeQy1C1iLwBbS5EEV96cYPw5ZRdA9Dm4D23hxGZt",
"cost": 165,
"result": {
"outcome": "reject",
"rejectReason": {
"tag": "InvalidAccountReference",
"contents": "3Es2U5gMdKrqJdXSUVzgW4KUosJ91AxfsAuvKx5tKE9P2SvjVk"
}
},
"energyCost": 165,
"type": "transfer",
"index": 0
}
]
}
"""
getBlockSummaryResponseStub =
"""
{
"specialEvents": [
{
"bakerId": 4,
"rewardAmount": 207,
"bakerAccount": "PI:KEY:<KEY>END_PI"
}
],
"transactionSummaries": [
{
"hash": "ae3154e1ee8a64d9e9718e57fbc979175be2ee8526b23fcddab2d626ebaeb72d",
"sender": null,
"cost": 0,
"result": {
"events": [
{
"tag": "AccountCreated",
"contents": "3P2Qsi8FeMB6AijMi3kpD9FrcFfAkoHDMu8kf7Fbd3cYYJpk2s"
},
{
"tag": "CredentialDeployed",
"regId": "PI:KEY:<KEY>END_PI",
"account": "PI:KEY:<KEY>END_PI"
}
],
"outcome": "success"
},
"energyCost": 35000,
"type": null,
"index": 0
},
{
"hash": "2ecde309ea6b48cebfbb73eb1ee3364c4f10330955a4a13acb7d87076461ab2d",
"sender": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "dba5e4bafc7d2201cc23d30f288e276b5305b0722a74d0ac1fe1f6b15d1496a2",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "f59897e5be69ecd5ed5843a10d74ee2b652064bd5077b853e6b324c23683af7b",
"sender": "4PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "4PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "f49899ac815b01a9f6e49c4d1fc926c511fcd3cc453c1307a504ef937a4fe8b5",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4PI:KEY:<KEY>END_PI",
"type": "AddressContract"
},
"from": {
"address": "4KYPI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "3ad7e0a0e3ed193bfba065c83704ae5bf84837255ac720565479afab81767c96",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "4PI:KEY:<KEY>END_PI",
"type": "AddressContract"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "d3b0cdeab57dc4d5e6b1faa1e4915ddfc2d025655775254e7124ae031688d9d8",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "bf6e33703977ce94caa918911f63b04654da0047454c484be9c80b487cc142c5",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "8781b249f4629f0ca9789fe143bfd4031208a7bfcca0ade9dd9f63ae8dac317d",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "41e6c23be80ab1151697ad16a4427268b0fd5440af0bb7bee4b330648669b164",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "4PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "71b1e81a467f038102b4028f62f1d75324b3f523472b89c583fdac918e762560",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4PI:KEY:<KEY>END_PIL",
"type": "AddressAccount"
},
"from": {
"address": "4PI:KEY:<KEY>END_PIL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "5298e7d571852da5c030c15b1513405c365111315efbc062a9d0f9082d1d5e6f",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYPI:KEY:<KEY>END_PIL",
"type": "AddressAccount"
},
"from": {
"address": "4PI:KEY:<KEY>END_PIL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "c7487dc3ee7cd097636badc9c21771d2a62a37052be8204078f516583cb5320e",
"sender": "4PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "dd6871001af51dc048bbae8ceb187c58fb2cf66ba838897b8f527642fb7e552a",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
},
"from": {
"address": "4KYJHs49FX7tPD2pFY2whbfZ8AjupEtX8yNSLwWMFQFUZgRobL",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "fc2ee2cd1294f0dc8a0c738c25bc6f762edf2689ee37b22382d9a4b931637ae7",
"sender": "4KYPI:KEY:<KEY>END_PIL",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "029681010cdc89383926d32017af7e51357f66b33f1527396f0af63b5b9a3e6c",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "64fbd260407f681292cc4931f8c3d7edb034574c172a90f1923188751fb6775a",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "4PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "5cc3ec13c9844456d8b65f0534dca943a4ece1b12c1ca0f8f5a2936c7e260722",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "5a9c8dd2b90b7943a48PI:KEY:<KEY>END_PI",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "16672379084db2866db4564e0c42103d3f6edcdfedee6b9ce5f520b9aef78ea7",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
},
{
"hash": "de7eecba63d94c7810126cc325d6cf43d9382d8d2fed680202140fe97e91fe76",
"sender": "PI:KEY:<KEY>END_PI",
"cost": 10,
"result": {
"events": [
{
"amount": 123,
"tag": "Transferred",
"to": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
},
"from": {
"address": "PI:KEY:<KEY>END_PI",
"type": "AddressAccount"
}
}
],
"outcome": "success"
},
"energyCost": 10,
"type": "transfer"
}
]
}
"""
{-| This block summary response was used to test that unusally long words
in the transaction memo of an event are displayed correctly.
-}
getBlockSummaryLongMemoStub =
"""
{
"finalizationData": {
"finalizationIndex": 40851,
"finalizers": [
{
"bakerId": 0,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 1,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 2,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 3,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 4,
"signed": true,
"weight": 3000000000000
},
{
"bakerId": 15,
"signed": true,
"weight": 300292749406
},
{
"bakerId": 42,
"signed": false,
"weight": 300143881109
}
],
"finalizationDelay": 0,
"finalizationBlockPointer": "e784294b2393ceedc1f5c8d9169591bd99dedc0564b8362852a2990f0cebfe00"
},
"specialEvents": [
{
"tag": "Mint",
"foundationAccount": "PI:KEY:<KEY>END_PI",
"mintPlatformDevelopmentCharge": "138171",
"mintFinalizationReward": "414508",
"mintBakingReward": "829017"
},
{
"remainder": "5",
"tag": "FinalizationRewards",
"finalizationRewards": [
{
"amount": "79711",
"address": "PI:KEY:<KEY>END_PI"
},
{
"amount": "79711",
"address": "PI:KEY:<KEY>END_PI"
},
{
"amount": "79711",
"address": "PI:KEY:<KEY>END_PI"
},
{
"amount": "7974",
"address": "PI:KEY:<KEY>END_PI"
},
{
"amount": "79711",
"address": "PI:KEY:<KEY>END_PI"
},
{
"amount": "7978",
"address": "PI:KEY:<KEY>END_PI"
},
{
"amount": "79711",
"address": "PI:KEY:<KEY>END_PI"
}
]
},
{
"tag": "BlockReward",
"bakerReward": "41914",
"newGASAccount": "PI:KEY:<KEY>END_PI",
"baker": "PI:KEY:<KEY>END_PI",
"foundationAccount": "PI:KEY:<KEY>END_PI",
"oldGASAccount": "1PI:KEY:<KEY>END_PI",
"foundationCharge": "9220",
"transactionFees": "92200"
}
],
"updates": {
"chainParameters": {
"minimumThresholdForBaking": "300000000000",
"rewardParameters": {
"mintDistribution": {
"mintPerSlot": 7.555665e-10,
"bakingReward": 0.6,
"finalizationReward": 0.3
},
"transactionFeeDistribution": {
"gasAccount": 0.45,
"baker": 0.45
},
"gASRewards": {
"chainUpdate": 5.0e-3,
"accountCreation": 2.0e-3,
"baker": 0.25,
"finalizationProof": 5.0e-3
}
},
"microGTUPerEuro": {
"denominator": 1,
"numerator": 100000000
},
"foundationAccountIndex": 5,
"accountCreationLimit": 10,
"bakerCooldownEpochs": 1,
"electionDifficulty": 2.5e-2,
"euroPerEnergy": {
"denominator": 1000000,
"numerator": 1
}
},
"keys": {
"rootKeys": {
"keys": [
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
}
],
"threshold": 3
},
"level2Keys": {
"mintDistribution": {
"threshold": 3,
"authorizedKeys": [
17,
18,
19,
20,
21
]
},
"addAnonymityRevoker": {
"threshold": 3,
"authorizedKeys": [
37,
38,
39,
40,
41
]
},
"transactionFeeDistribution": {
"threshold": 3,
"authorizedKeys": [
22,
23,
24,
25,
26
]
},
"bakerStakeThreshold": {
"threshold": 3,
"authorizedKeys": [
32,
33,
34,
35,
36
]
},
"microGTUPerEuro": {
"threshold": 1,
"authorizedKeys": [
11
]
},
"protocol": {
"threshold": 2,
"authorizedKeys": [
5,
6,
7
]
},
"addIdentityProvider": {
"threshold": 3,
"authorizedKeys": [
4PI:KEY:<KEY>END_PI,
43,
44,
45,
46
]
},
"paramGASRewards": {
"threshold": 3,
"authorizedKeys": [
27,
28,
29,
30,
31
]
},
"emergency": {
"threshold": 3,
"authorizedKeys": [
0,
1,
2,
3,
4
]
},
"keys": [
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
}
],
"foundationAccount": {
"threshold": 3,
"authorizedKeys": [
12,
13,
14,
15,
16
]
},
"electionDifficulty": {
"threshold": 2,
"authorizedKeys": [
8,
9,
1PI:KEY:<KEY>END_PI
]
},
"euroPerEnergy": {
"threshold": 2,
"authorizedKeys": [
PI:KEY:<KEY>END_PI,
9,
10
]
}
},
"level1Keys": {
"keys": [
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI",
"schemeId": "Ed25519"
},
{
"verifyKey": "PI:KEY:<KEY>END_PI75ed0579976b82e83f73cc3559748c2e9627014d6d8",
"schemeId": "Ed25519"
}
],
"threshold": 3
}
},
"updateQueues": {
"mintDistribution": {
"nextSequenceNumber": 1,
"queue": []
},
"rootKeys": {
"nextSequenceNumber": 1,
"queue": []
},
"addAnonymityRevoker": {
"nextSequenceNumber": 1,
"queue": []
},
"transactionFeeDistribution": {
"nextSequenceNumber": 1,
"queue": []
},
"bakerStakeThreshold": {
"nextSequenceNumber": 1,
"queue": []
},
"level2Keys": {
"nextSequenceNumber": 1,
"queue": []
},
"microGTUPerEuro": {
"nextSequenceNumber": 1,
"queue": []
},
"protocol": {
"nextSequenceNumber": 2,
"queue": []
},
"addIdentityProvider": {
"nextSequenceNumber": 1,
"queue": []
},
"gasRewards": {
"nextSequenceNumber": 1,
"queue": []
},
"foundationAccount": {
"nextSequenceNumber": 1,
"queue": []
},
"electionDifficulty": {
"nextSequenceNumber": 1,
"queue": []
},
"euroPerEnergy": {
"nextSequenceNumber": 1,
"queue": []
},
"level1Keys": {
"nextSequenceNumber": 1,
"queue": []
}
}
},
"transactionSummaries": [
{
"hash": "1623fb1b65720bbf34b7d9c47818af49e7c4610eaf6f1e241ba1208d1e5d94bb",
"sender": "4PXJrvKGKb1YZt2Vua3mSDThqUU2EChweuydsFtVFtvDDr585H",
"cost": "92200",
"energyCost": 922,
"result": {
"events": [
{
"amount": "1000000",
"tag": "Transferred",
"to": {
"address": "48RDnoQaCKwy8xteebgLCDdX8qACa3WB5GnfuGMpCDfB2UfdL4",
"type": "AddressAccount"
},
"from": {
"address": "4PXJrvKGKb1YZt2VPI:KEY:<KEY>END_PI3mSDThPI:KEY:<KEY>END_PIUU2EChweuydsFtVFtvDDr585H",
"type": "AddressAccount"
}
},
{
"memo": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"tag": "TransferMemo"
}
],
"outcome": "success"
},
"type": {
"contents": "transferWithMemo",
"type": "accountTransaction"
},
"index": 0
}
]
}
"""
| elm |
[
{
"context": " than 9 waypoints are truncated\"\n\n\nexample =\n \"St. Gallen - Zurich - Berne - Basel\"\n\n\n\n---- MODEL ----\n\n\nty",
"end": 637,
"score": 0.999792099,
"start": 627,
"tag": "NAME",
"value": "St. Gallen"
}
] | src/Main.elm | lroellin/directions-parser-elm | 0 | module Main exposing (..)
import Browser
import Html exposing (Html, a, button, div, form, h1, h2, img, label, li, p, text, textarea, ul)
import Html.Attributes exposing (for, href, id, rows, src, target, value, class)
import Html.Events exposing (onClick, onInput)
import Url.Builder exposing (crossOrigin, int, string)
import List.Extra exposing (last)
---- CONSTANTS ----
maxMobileWaypoints =
3
maxAbsoluteWaypoints =
9
mobileWaypointsMessage =
"Mobile browsers: more than 3 waypoints are truncated"
absoluteWaypointsMessage =
"All browsers: more than 9 waypoints are truncated"
example =
"St. Gallen - Zurich - Berne - Basel"
---- MODEL ----
type alias Model =
{ content : String
}
type WarningNeeded
= Yes (List String)
| No
init : ( Model, Cmd Msg )
init =
( { content = "" }, Cmd.none )
---- UPDATE ----
type Msg
= Change String
| LoadExample
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Change content ->
( { model | content = content }, Cmd.none )
LoadExample ->
( { model | content = example }, Cmd.none )
---- VIEW ----
view : Model -> Html Msg
view model =
div []
[ h1 [] [ text "Google Maps Direction Parser" ]
, p [] [ text "Enter a list of place names, each separated with a space and a hyphen." ]
, button [ onClick LoadExample ] [ text "Add example" ]
, form []
[ label [ for "content" ] [ text "Place List" ]
, textarea [ id "content", rows 5, onInput Change, value model.content ] [ ]
]
, link (splitter model)
, validation (warning model) model
]
validation : WarningNeeded -> Model -> Html msg
validation warningNeeded model =
case warningNeeded of
Yes list ->
div []
[ h1 [] [ text "Google API Limitation" ]
, p []
[ text "You have "
, text (String.fromInt (List.length (splitter model)))
, text " waypoints"
]
, ul [] (List.map (\l -> li [] [ text l ]) list)
]
No ->
text ""
link : List String -> Html msg
link list =
a [ class "button", href (linkTarget list), target "_blank" ] [ text "Go" ]
---- PROGRAM ----
splitter : Model -> List String
splitter model =
String.split " - " model.content
warning : Model -> WarningNeeded
warning model =
if List.length (splitter model) > maxMobileWaypoints then
if List.length (splitter model) > maxAbsoluteWaypoints then
Yes [ mobileWaypointsMessage, absoluteWaypointsMessage ]
else
Yes [ mobileWaypointsMessage ]
else
No
linkTarget : List String -> String
linkTarget list =
crossOrigin "https://www.google.com"
[ "maps", "dir", "" ]
[ int "api" 1
, linkOrigin list
, linkWaypoints list
, linkDestination list
]
linkOrigin : List String -> Url.Builder.QueryParameter
linkOrigin list =
case list of
[] ->
string "origin" ""
origin :: _ ->
string "origin" origin
linkWaypoints : List String -> Url.Builder.QueryParameter
linkWaypoints list =
case list of
[] ->
string "waypoints" ""
_ :: waypoints ->
case List.Extra.init (waypoints) of
Nothing -> string "waypoints" ""
Just waypointss ->
string "waypoints" (String.join "|" waypointss)
linkDestination : List String -> Url.Builder.QueryParameter
linkDestination list =
case (last list) of
Nothing ->
string "destination" ""
Just a ->
string "destination" a
main : Program () Model Msg
main =
Browser.element
{ view = view
, init = \_ -> init
, update = update
, subscriptions = always Sub.none
}
| 25452 | module Main exposing (..)
import Browser
import Html exposing (Html, a, button, div, form, h1, h2, img, label, li, p, text, textarea, ul)
import Html.Attributes exposing (for, href, id, rows, src, target, value, class)
import Html.Events exposing (onClick, onInput)
import Url.Builder exposing (crossOrigin, int, string)
import List.Extra exposing (last)
---- CONSTANTS ----
maxMobileWaypoints =
3
maxAbsoluteWaypoints =
9
mobileWaypointsMessage =
"Mobile browsers: more than 3 waypoints are truncated"
absoluteWaypointsMessage =
"All browsers: more than 9 waypoints are truncated"
example =
"<NAME> - Zurich - Berne - Basel"
---- MODEL ----
type alias Model =
{ content : String
}
type WarningNeeded
= Yes (List String)
| No
init : ( Model, Cmd Msg )
init =
( { content = "" }, Cmd.none )
---- UPDATE ----
type Msg
= Change String
| LoadExample
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Change content ->
( { model | content = content }, Cmd.none )
LoadExample ->
( { model | content = example }, Cmd.none )
---- VIEW ----
view : Model -> Html Msg
view model =
div []
[ h1 [] [ text "Google Maps Direction Parser" ]
, p [] [ text "Enter a list of place names, each separated with a space and a hyphen." ]
, button [ onClick LoadExample ] [ text "Add example" ]
, form []
[ label [ for "content" ] [ text "Place List" ]
, textarea [ id "content", rows 5, onInput Change, value model.content ] [ ]
]
, link (splitter model)
, validation (warning model) model
]
validation : WarningNeeded -> Model -> Html msg
validation warningNeeded model =
case warningNeeded of
Yes list ->
div []
[ h1 [] [ text "Google API Limitation" ]
, p []
[ text "You have "
, text (String.fromInt (List.length (splitter model)))
, text " waypoints"
]
, ul [] (List.map (\l -> li [] [ text l ]) list)
]
No ->
text ""
link : List String -> Html msg
link list =
a [ class "button", href (linkTarget list), target "_blank" ] [ text "Go" ]
---- PROGRAM ----
splitter : Model -> List String
splitter model =
String.split " - " model.content
warning : Model -> WarningNeeded
warning model =
if List.length (splitter model) > maxMobileWaypoints then
if List.length (splitter model) > maxAbsoluteWaypoints then
Yes [ mobileWaypointsMessage, absoluteWaypointsMessage ]
else
Yes [ mobileWaypointsMessage ]
else
No
linkTarget : List String -> String
linkTarget list =
crossOrigin "https://www.google.com"
[ "maps", "dir", "" ]
[ int "api" 1
, linkOrigin list
, linkWaypoints list
, linkDestination list
]
linkOrigin : List String -> Url.Builder.QueryParameter
linkOrigin list =
case list of
[] ->
string "origin" ""
origin :: _ ->
string "origin" origin
linkWaypoints : List String -> Url.Builder.QueryParameter
linkWaypoints list =
case list of
[] ->
string "waypoints" ""
_ :: waypoints ->
case List.Extra.init (waypoints) of
Nothing -> string "waypoints" ""
Just waypointss ->
string "waypoints" (String.join "|" waypointss)
linkDestination : List String -> Url.Builder.QueryParameter
linkDestination list =
case (last list) of
Nothing ->
string "destination" ""
Just a ->
string "destination" a
main : Program () Model Msg
main =
Browser.element
{ view = view
, init = \_ -> init
, update = update
, subscriptions = always Sub.none
}
| true | module Main exposing (..)
import Browser
import Html exposing (Html, a, button, div, form, h1, h2, img, label, li, p, text, textarea, ul)
import Html.Attributes exposing (for, href, id, rows, src, target, value, class)
import Html.Events exposing (onClick, onInput)
import Url.Builder exposing (crossOrigin, int, string)
import List.Extra exposing (last)
---- CONSTANTS ----
maxMobileWaypoints =
3
maxAbsoluteWaypoints =
9
mobileWaypointsMessage =
"Mobile browsers: more than 3 waypoints are truncated"
absoluteWaypointsMessage =
"All browsers: more than 9 waypoints are truncated"
example =
"PI:NAME:<NAME>END_PI - Zurich - Berne - Basel"
---- MODEL ----
type alias Model =
{ content : String
}
type WarningNeeded
= Yes (List String)
| No
init : ( Model, Cmd Msg )
init =
( { content = "" }, Cmd.none )
---- UPDATE ----
type Msg
= Change String
| LoadExample
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Change content ->
( { model | content = content }, Cmd.none )
LoadExample ->
( { model | content = example }, Cmd.none )
---- VIEW ----
view : Model -> Html Msg
view model =
div []
[ h1 [] [ text "Google Maps Direction Parser" ]
, p [] [ text "Enter a list of place names, each separated with a space and a hyphen." ]
, button [ onClick LoadExample ] [ text "Add example" ]
, form []
[ label [ for "content" ] [ text "Place List" ]
, textarea [ id "content", rows 5, onInput Change, value model.content ] [ ]
]
, link (splitter model)
, validation (warning model) model
]
validation : WarningNeeded -> Model -> Html msg
validation warningNeeded model =
case warningNeeded of
Yes list ->
div []
[ h1 [] [ text "Google API Limitation" ]
, p []
[ text "You have "
, text (String.fromInt (List.length (splitter model)))
, text " waypoints"
]
, ul [] (List.map (\l -> li [] [ text l ]) list)
]
No ->
text ""
link : List String -> Html msg
link list =
a [ class "button", href (linkTarget list), target "_blank" ] [ text "Go" ]
---- PROGRAM ----
splitter : Model -> List String
splitter model =
String.split " - " model.content
warning : Model -> WarningNeeded
warning model =
if List.length (splitter model) > maxMobileWaypoints then
if List.length (splitter model) > maxAbsoluteWaypoints then
Yes [ mobileWaypointsMessage, absoluteWaypointsMessage ]
else
Yes [ mobileWaypointsMessage ]
else
No
linkTarget : List String -> String
linkTarget list =
crossOrigin "https://www.google.com"
[ "maps", "dir", "" ]
[ int "api" 1
, linkOrigin list
, linkWaypoints list
, linkDestination list
]
linkOrigin : List String -> Url.Builder.QueryParameter
linkOrigin list =
case list of
[] ->
string "origin" ""
origin :: _ ->
string "origin" origin
linkWaypoints : List String -> Url.Builder.QueryParameter
linkWaypoints list =
case list of
[] ->
string "waypoints" ""
_ :: waypoints ->
case List.Extra.init (waypoints) of
Nothing -> string "waypoints" ""
Just waypointss ->
string "waypoints" (String.join "|" waypointss)
linkDestination : List String -> Url.Builder.QueryParameter
linkDestination list =
case (last list) of
Nothing ->
string "destination" ""
Just a ->
string "destination" a
main : Program () Model Msg
main =
Browser.element
{ view = view
, init = \_ -> init
, update = update
, subscriptions = always Sub.none
}
| elm |
[
{
"context": "ult (\"\n , a [ href \"https://github.com/jinjor/elm-xml-parser\" ] [ text \"Source\" ]\n ,",
"end": 1416,
"score": 0.9994317293,
"start": 1410,
"tag": "USERNAME",
"value": "jinjor"
},
{
"context": "tialText : String\ninitialText =\n \"\"\"<note>\n<to>Tove</to>\n<from>Jani</from>\n<heading>Reminder</heading",
"end": 1915,
"score": 0.8184492588,
"start": 1911,
"tag": "NAME",
"value": "Tove"
},
{
"context": "g\ninitialText =\n \"\"\"<note>\n<to>Tove</to>\n<from>Jani</from>\n<heading>Reminder</heading>\n<body>Don't fo",
"end": 1931,
"score": 0.9965288639,
"start": 1927,
"tag": "NAME",
"value": "Jani"
}
] | docs/Demo.elm | hgoes/elm-xml-parser | 20 | port module Demo exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import XmlParser exposing (..)
port init : (String -> msg) -> Sub msg
port input : (String -> msg) -> Sub msg
port parse : ({} -> msg) -> Sub msg
main : Program Never Model Msg
main =
program
{ init = initialModel ! []
, update = \msg model -> (update msg model) ! []
, view = view
, subscriptions =
\_ ->
Sub.batch
[ init Init
, input Input
, parse (always Show)
]
}
type alias Model =
{ src : String
, dest : String
}
initialModel : Model
initialModel =
{ src = ""
, dest = ""
}
type Msg
= Init String
| Input String
| Show
update : Msg -> Model -> Model
update msg model =
case msg of
Init s ->
{ model | src = s } |> show
Input s ->
{ model | src = s }
Show ->
model |> show
show : Model -> Model
show model =
{ model
| dest =
toString (XmlParser.parse model.src)
}
view : Model -> Html Msg
view model =
div []
[ h1 [ style [] ] [ text "XmlParser DEMO" ]
, p []
[ text "Press Ctrl+S to show result ("
, a [ href "https://github.com/jinjor/elm-xml-parser" ] [ text "Source" ]
, text ")"
]
, div [ style [ ( "display", "flex" ) ] ]
[ div [ id "editor", style [ ( "height", "500px" ), ( "width", "40%" ), ( "border", "solid 1px #aaa" ) ] ] [ text initialText ]
, div [ style [ ( "min-height", "500px" ), ( "width", "60%" ), ( "flex-grow", "1" ), ( "border", "solid 1px #aaa" ) ] ] [ text model.dest ]
]
]
initialText : String
initialText =
"""<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
"""
| 53871 | port module Demo exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import XmlParser exposing (..)
port init : (String -> msg) -> Sub msg
port input : (String -> msg) -> Sub msg
port parse : ({} -> msg) -> Sub msg
main : Program Never Model Msg
main =
program
{ init = initialModel ! []
, update = \msg model -> (update msg model) ! []
, view = view
, subscriptions =
\_ ->
Sub.batch
[ init Init
, input Input
, parse (always Show)
]
}
type alias Model =
{ src : String
, dest : String
}
initialModel : Model
initialModel =
{ src = ""
, dest = ""
}
type Msg
= Init String
| Input String
| Show
update : Msg -> Model -> Model
update msg model =
case msg of
Init s ->
{ model | src = s } |> show
Input s ->
{ model | src = s }
Show ->
model |> show
show : Model -> Model
show model =
{ model
| dest =
toString (XmlParser.parse model.src)
}
view : Model -> Html Msg
view model =
div []
[ h1 [ style [] ] [ text "XmlParser DEMO" ]
, p []
[ text "Press Ctrl+S to show result ("
, a [ href "https://github.com/jinjor/elm-xml-parser" ] [ text "Source" ]
, text ")"
]
, div [ style [ ( "display", "flex" ) ] ]
[ div [ id "editor", style [ ( "height", "500px" ), ( "width", "40%" ), ( "border", "solid 1px #aaa" ) ] ] [ text initialText ]
, div [ style [ ( "min-height", "500px" ), ( "width", "60%" ), ( "flex-grow", "1" ), ( "border", "solid 1px #aaa" ) ] ] [ text model.dest ]
]
]
initialText : String
initialText =
"""<note>
<to><NAME></to>
<from><NAME></from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
"""
| true | port module Demo exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import XmlParser exposing (..)
port init : (String -> msg) -> Sub msg
port input : (String -> msg) -> Sub msg
port parse : ({} -> msg) -> Sub msg
main : Program Never Model Msg
main =
program
{ init = initialModel ! []
, update = \msg model -> (update msg model) ! []
, view = view
, subscriptions =
\_ ->
Sub.batch
[ init Init
, input Input
, parse (always Show)
]
}
type alias Model =
{ src : String
, dest : String
}
initialModel : Model
initialModel =
{ src = ""
, dest = ""
}
type Msg
= Init String
| Input String
| Show
update : Msg -> Model -> Model
update msg model =
case msg of
Init s ->
{ model | src = s } |> show
Input s ->
{ model | src = s }
Show ->
model |> show
show : Model -> Model
show model =
{ model
| dest =
toString (XmlParser.parse model.src)
}
view : Model -> Html Msg
view model =
div []
[ h1 [ style [] ] [ text "XmlParser DEMO" ]
, p []
[ text "Press Ctrl+S to show result ("
, a [ href "https://github.com/jinjor/elm-xml-parser" ] [ text "Source" ]
, text ")"
]
, div [ style [ ( "display", "flex" ) ] ]
[ div [ id "editor", style [ ( "height", "500px" ), ( "width", "40%" ), ( "border", "solid 1px #aaa" ) ] ] [ text initialText ]
, div [ style [ ( "min-height", "500px" ), ( "width", "60%" ), ( "flex-grow", "1" ), ( "border", "solid 1px #aaa" ) ] ] [ text model.dest ]
]
]
initialText : String
initialText =
"""<note>
<to>PI:NAME:<NAME>END_PI</to>
<from>PI:NAME:<NAME>END_PI</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
"""
| elm |
[
{
"context": "iv [ class \"navigation\" ]\n [ h1 [] [ text \"HRAFNAR\" ]\n , ul []\n [ li [] [ a [",
"end": 3657,
"score": 0.696374774,
"start": 3655,
"tag": "NAME",
"value": "HR"
}
] | client/Main.elm | realglobe-Inc/hrafnar | 0 | module Main exposing (main)
import Browser exposing (Document, UrlRequest)
import Browser.Navigation as Nav exposing (Key)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Maybe
import Page.Index as Index
import Page.Project as Project
import Url exposing (Url)
import Url.Parser as UP exposing ((</>), Parser)
main : Program () Model Msg
main =
Browser.application
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
, onUrlRequest = Link
, onUrlChange = UrlChanged
}
type alias Model =
{ key : Key
, route : Route
, language : Language
}
type Route
= Index Index.Model
| Project Project.Model
| NotFound
type Language
= Japanese
| English
type Msg
= Link UrlRequest
| UrlChanged Url
| IndexMsg Index.Msg
| ProjectMsg Project.Msg
| NoOp
init : () -> Url -> Key -> ( Model, Cmd Msg )
init _ url k =
stepUrl url
{ key = k
, route = NotFound
, language = Japanese
}
stepUrl : Url -> Model -> ( Model, Cmd Msg )
stepUrl url model =
let
parser =
UP.oneOf
[ UP.map (stepIndex model <| Index.init) UP.top
, UP.map (stepProject model <| Project.init) (UP.s "project")
]
in
UP.parse parser url
|> Maybe.withDefault ( { model | route = NotFound }, Cmd.none )
stepIndex : Model -> ( Index.Model, Cmd Index.Msg ) -> ( Model, Cmd Msg )
stepIndex model ( model_, cmd ) =
( { model | route = Index model_ }, Cmd.map IndexMsg cmd )
stepProject : Model -> ( Project.Model, Cmd Project.Msg ) -> ( Model, Cmd Msg )
stepProject model ( model_, cmd ) =
( { model | route = Project model_ }, Cmd.map ProjectMsg cmd )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case ( msg, model.route ) of
( Link req, _ ) ->
case req of
Browser.Internal url ->
( model
, Nav.pushUrl model.key (Url.toString url)
)
Browser.External url ->
( model
, Nav.load url
)
( UrlChanged url, _ ) ->
stepUrl url model
( IndexMsg msg_, Index model_ ) ->
stepIndex model <| Index.update model_ msg_
( ProjectMsg msg_, Project model_ ) ->
stepProject model <| Project.update model_ msg_
_ ->
( model
, Cmd.none
)
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
view : Model -> Document Msg
view model =
{ title = "Hrafnar"
, body =
[ div [ classList [ ("container", True)
, ("ravens-are-in-odins-service", True)
]
]
[ navigation model
, div [ class "content" ]
<| case model.route of
Index model_ ->
[ h1 [] [ text "Dashboard" ]
, Html.map IndexMsg <| Index.view model_
]
Project model_ ->
[ h1 [] [ text "Project" ]
, Html.map ProjectMsg <| Project.view model_
]
NotFound ->
[ notFound model ]
]
]
}
navigation : Model -> Html Msg
navigation model =
div [ class "navigation" ]
[ h1 [] [ text "HRAFNAR" ]
, ul []
[ li [] [ a [ href "/" ] [ text "Dashboard" ] ]
, li [] [ a [ href "/project" ] [ text "Project" ] ]
, li [] [ a [ href "/process" ] [ text "Process" ] ]
, li [] [ a [ href "/settings" ] [ text "Settings" ] ]
]
]
notFound : Model -> Html Msg
notFound model =
text "nyaan..."
| 55590 | module Main exposing (main)
import Browser exposing (Document, UrlRequest)
import Browser.Navigation as Nav exposing (Key)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Maybe
import Page.Index as Index
import Page.Project as Project
import Url exposing (Url)
import Url.Parser as UP exposing ((</>), Parser)
main : Program () Model Msg
main =
Browser.application
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
, onUrlRequest = Link
, onUrlChange = UrlChanged
}
type alias Model =
{ key : Key
, route : Route
, language : Language
}
type Route
= Index Index.Model
| Project Project.Model
| NotFound
type Language
= Japanese
| English
type Msg
= Link UrlRequest
| UrlChanged Url
| IndexMsg Index.Msg
| ProjectMsg Project.Msg
| NoOp
init : () -> Url -> Key -> ( Model, Cmd Msg )
init _ url k =
stepUrl url
{ key = k
, route = NotFound
, language = Japanese
}
stepUrl : Url -> Model -> ( Model, Cmd Msg )
stepUrl url model =
let
parser =
UP.oneOf
[ UP.map (stepIndex model <| Index.init) UP.top
, UP.map (stepProject model <| Project.init) (UP.s "project")
]
in
UP.parse parser url
|> Maybe.withDefault ( { model | route = NotFound }, Cmd.none )
stepIndex : Model -> ( Index.Model, Cmd Index.Msg ) -> ( Model, Cmd Msg )
stepIndex model ( model_, cmd ) =
( { model | route = Index model_ }, Cmd.map IndexMsg cmd )
stepProject : Model -> ( Project.Model, Cmd Project.Msg ) -> ( Model, Cmd Msg )
stepProject model ( model_, cmd ) =
( { model | route = Project model_ }, Cmd.map ProjectMsg cmd )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case ( msg, model.route ) of
( Link req, _ ) ->
case req of
Browser.Internal url ->
( model
, Nav.pushUrl model.key (Url.toString url)
)
Browser.External url ->
( model
, Nav.load url
)
( UrlChanged url, _ ) ->
stepUrl url model
( IndexMsg msg_, Index model_ ) ->
stepIndex model <| Index.update model_ msg_
( ProjectMsg msg_, Project model_ ) ->
stepProject model <| Project.update model_ msg_
_ ->
( model
, Cmd.none
)
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
view : Model -> Document Msg
view model =
{ title = "Hrafnar"
, body =
[ div [ classList [ ("container", True)
, ("ravens-are-in-odins-service", True)
]
]
[ navigation model
, div [ class "content" ]
<| case model.route of
Index model_ ->
[ h1 [] [ text "Dashboard" ]
, Html.map IndexMsg <| Index.view model_
]
Project model_ ->
[ h1 [] [ text "Project" ]
, Html.map ProjectMsg <| Project.view model_
]
NotFound ->
[ notFound model ]
]
]
}
navigation : Model -> Html Msg
navigation model =
div [ class "navigation" ]
[ h1 [] [ text "<NAME>AFNAR" ]
, ul []
[ li [] [ a [ href "/" ] [ text "Dashboard" ] ]
, li [] [ a [ href "/project" ] [ text "Project" ] ]
, li [] [ a [ href "/process" ] [ text "Process" ] ]
, li [] [ a [ href "/settings" ] [ text "Settings" ] ]
]
]
notFound : Model -> Html Msg
notFound model =
text "nyaan..."
| true | module Main exposing (main)
import Browser exposing (Document, UrlRequest)
import Browser.Navigation as Nav exposing (Key)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Maybe
import Page.Index as Index
import Page.Project as Project
import Url exposing (Url)
import Url.Parser as UP exposing ((</>), Parser)
main : Program () Model Msg
main =
Browser.application
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
, onUrlRequest = Link
, onUrlChange = UrlChanged
}
type alias Model =
{ key : Key
, route : Route
, language : Language
}
type Route
= Index Index.Model
| Project Project.Model
| NotFound
type Language
= Japanese
| English
type Msg
= Link UrlRequest
| UrlChanged Url
| IndexMsg Index.Msg
| ProjectMsg Project.Msg
| NoOp
init : () -> Url -> Key -> ( Model, Cmd Msg )
init _ url k =
stepUrl url
{ key = k
, route = NotFound
, language = Japanese
}
stepUrl : Url -> Model -> ( Model, Cmd Msg )
stepUrl url model =
let
parser =
UP.oneOf
[ UP.map (stepIndex model <| Index.init) UP.top
, UP.map (stepProject model <| Project.init) (UP.s "project")
]
in
UP.parse parser url
|> Maybe.withDefault ( { model | route = NotFound }, Cmd.none )
stepIndex : Model -> ( Index.Model, Cmd Index.Msg ) -> ( Model, Cmd Msg )
stepIndex model ( model_, cmd ) =
( { model | route = Index model_ }, Cmd.map IndexMsg cmd )
stepProject : Model -> ( Project.Model, Cmd Project.Msg ) -> ( Model, Cmd Msg )
stepProject model ( model_, cmd ) =
( { model | route = Project model_ }, Cmd.map ProjectMsg cmd )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case ( msg, model.route ) of
( Link req, _ ) ->
case req of
Browser.Internal url ->
( model
, Nav.pushUrl model.key (Url.toString url)
)
Browser.External url ->
( model
, Nav.load url
)
( UrlChanged url, _ ) ->
stepUrl url model
( IndexMsg msg_, Index model_ ) ->
stepIndex model <| Index.update model_ msg_
( ProjectMsg msg_, Project model_ ) ->
stepProject model <| Project.update model_ msg_
_ ->
( model
, Cmd.none
)
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
view : Model -> Document Msg
view model =
{ title = "Hrafnar"
, body =
[ div [ classList [ ("container", True)
, ("ravens-are-in-odins-service", True)
]
]
[ navigation model
, div [ class "content" ]
<| case model.route of
Index model_ ->
[ h1 [] [ text "Dashboard" ]
, Html.map IndexMsg <| Index.view model_
]
Project model_ ->
[ h1 [] [ text "Project" ]
, Html.map ProjectMsg <| Project.view model_
]
NotFound ->
[ notFound model ]
]
]
}
navigation : Model -> Html Msg
navigation model =
div [ class "navigation" ]
[ h1 [] [ text "PI:NAME:<NAME>END_PIAFNAR" ]
, ul []
[ li [] [ a [ href "/" ] [ text "Dashboard" ] ]
, li [] [ a [ href "/project" ] [ text "Project" ] ]
, li [] [ a [ href "/process" ] [ text "Process" ] ]
, li [] [ a [ href "/settings" ] [ text "Settings" ] ]
]
]
notFound : Model -> Html Msg
notFound model =
text "nyaan..."
| elm |
[
{
"context": "\nallCards =\n [ { id = CardId 1\n , name = \"Barracks\"\n , cost = [ ( Build, 2 ) ]\n , effects ",
"end": 184,
"score": 0.9966874123,
"start": 176,
"tag": "NAME",
"value": "Barracks"
},
{
"context": " ]\n }\n , { id = CardId 2\n , name = \"Laboratory\"\n , cost = [ ( Build, 3 ) ]\n , effects ",
"end": 342,
"score": 0.6570978165,
"start": 332,
"tag": "NAME",
"value": "Laboratory"
},
{
"context": " ]\n }\n , { id = CardId 3\n , name = \"Cavern\"\n , cost = [ ( Build, 2 ) ]\n , effects ",
"end": 494,
"score": 0.9967426658,
"start": 488,
"tag": "NAME",
"value": "Cavern"
},
{
"context": " ]\n }\n , { id = CardId 4\n , name = \"Quarry\"\n , cost = [ ( Build, 1 ) ]\n , effects ",
"end": 648,
"score": 0.9883297682,
"start": 642,
"tag": "NAME",
"value": "Quarry"
},
{
"context": " ]\n }\n , { id = CardId 5\n , name = \"Mine\"\n , cost = [ ( Build, 3 ) ]\n , effects ",
"end": 798,
"score": 0.7535479069,
"start": 794,
"tag": "NAME",
"value": "Mine"
},
{
"context": " ]\n }\n , { id = CardId 7\n , name = footman.name\n , cost = [ ( Command, 1 ) ]\n ,",
"end": 1153,
"score": 0.5067421198,
"start": 1149,
"tag": "NAME",
"value": "foot"
},
{
"context": " ]\n }\n , { id = CardId 9\n , name = golem.name\n , cost = [ ( Build, 1 ), ( Command,",
"end": 1496,
"score": 0.6909374595,
"start": 1494,
"tag": "NAME",
"value": "go"
}
] | src/Data/Cards.elm | mpajunen/cottage | 0 | module Data.Cards exposing (allCards)
import Data.Common exposing (..)
import Data.Creatures exposing (..)
allCards : Cards
allCards =
[ { id = CardId 1
, name = "Barracks"
, cost = [ ( Build, 2 ) ]
, effects =
[ (Gain ( Command, 1 ))
]
}
, { id = CardId 2
, name = "Laboratory"
, cost = [ ( Build, 3 ) ]
, effects =
[ (Gain ( Magic, 1 ))
]
}
, { id = CardId 3
, name = "Cavern"
, cost = [ ( Build, 2 ) ]
, effects =
[ (Gain ( Command, 2 ))
]
}
, { id = CardId 4
, name = "Quarry"
, cost = [ ( Build, 1 ) ]
, effects =
[ (Gain ( Build, 1 ))
]
}
, { id = CardId 5
, name = "Mine"
, cost = [ ( Build, 3 ) ]
, effects =
[ (Gain ( Build, 2 ))
]
}
, { id = CardId 6
, name = "Experimental laboratory"
, cost = [ ( Build, 5 ) ]
, effects =
[ (Gain ( Magic, 3 ))
, (Gain ( Command, -1 ))
]
}
, { id = CardId 7
, name = footman.name
, cost = [ ( Command, 1 ) ]
, effects =
[ (Summon footman)
]
}
, { id = CardId 8
, name = knight.name
, cost = [ ( Command, 3 ) ]
, effects =
[ (Summon knight)
, (Gain ( Command, -1 ))
]
}
, { id = CardId 9
, name = golem.name
, cost = [ ( Build, 1 ), ( Command, 1 ), ( Magic, 2 ) ]
, effects =
[ (Summon golem)
, (Gain ( Magic, -1 ))
]
}
]
| 49565 | module Data.Cards exposing (allCards)
import Data.Common exposing (..)
import Data.Creatures exposing (..)
allCards : Cards
allCards =
[ { id = CardId 1
, name = "<NAME>"
, cost = [ ( Build, 2 ) ]
, effects =
[ (Gain ( Command, 1 ))
]
}
, { id = CardId 2
, name = "<NAME>"
, cost = [ ( Build, 3 ) ]
, effects =
[ (Gain ( Magic, 1 ))
]
}
, { id = CardId 3
, name = "<NAME>"
, cost = [ ( Build, 2 ) ]
, effects =
[ (Gain ( Command, 2 ))
]
}
, { id = CardId 4
, name = "<NAME>"
, cost = [ ( Build, 1 ) ]
, effects =
[ (Gain ( Build, 1 ))
]
}
, { id = CardId 5
, name = "<NAME>"
, cost = [ ( Build, 3 ) ]
, effects =
[ (Gain ( Build, 2 ))
]
}
, { id = CardId 6
, name = "Experimental laboratory"
, cost = [ ( Build, 5 ) ]
, effects =
[ (Gain ( Magic, 3 ))
, (Gain ( Command, -1 ))
]
}
, { id = CardId 7
, name = <NAME>man.name
, cost = [ ( Command, 1 ) ]
, effects =
[ (Summon footman)
]
}
, { id = CardId 8
, name = knight.name
, cost = [ ( Command, 3 ) ]
, effects =
[ (Summon knight)
, (Gain ( Command, -1 ))
]
}
, { id = CardId 9
, name = <NAME>lem.name
, cost = [ ( Build, 1 ), ( Command, 1 ), ( Magic, 2 ) ]
, effects =
[ (Summon golem)
, (Gain ( Magic, -1 ))
]
}
]
| true | module Data.Cards exposing (allCards)
import Data.Common exposing (..)
import Data.Creatures exposing (..)
allCards : Cards
allCards =
[ { id = CardId 1
, name = "PI:NAME:<NAME>END_PI"
, cost = [ ( Build, 2 ) ]
, effects =
[ (Gain ( Command, 1 ))
]
}
, { id = CardId 2
, name = "PI:NAME:<NAME>END_PI"
, cost = [ ( Build, 3 ) ]
, effects =
[ (Gain ( Magic, 1 ))
]
}
, { id = CardId 3
, name = "PI:NAME:<NAME>END_PI"
, cost = [ ( Build, 2 ) ]
, effects =
[ (Gain ( Command, 2 ))
]
}
, { id = CardId 4
, name = "PI:NAME:<NAME>END_PI"
, cost = [ ( Build, 1 ) ]
, effects =
[ (Gain ( Build, 1 ))
]
}
, { id = CardId 5
, name = "PI:NAME:<NAME>END_PI"
, cost = [ ( Build, 3 ) ]
, effects =
[ (Gain ( Build, 2 ))
]
}
, { id = CardId 6
, name = "Experimental laboratory"
, cost = [ ( Build, 5 ) ]
, effects =
[ (Gain ( Magic, 3 ))
, (Gain ( Command, -1 ))
]
}
, { id = CardId 7
, name = PI:NAME:<NAME>END_PIman.name
, cost = [ ( Command, 1 ) ]
, effects =
[ (Summon footman)
]
}
, { id = CardId 8
, name = knight.name
, cost = [ ( Command, 3 ) ]
, effects =
[ (Summon knight)
, (Gain ( Command, -1 ))
]
}
, { id = CardId 9
, name = PI:NAME:<NAME>END_PIlem.name
, cost = [ ( Build, 1 ), ( Command, 1 ), ( Magic, 2 ) ]
, effects =
[ (Summon golem)
, (Gain ( Magic, -1 ))
]
}
]
| elm |
[
{
"context": "ting dates.\n\n@docs config\n\nCopyright (c) 2016-2017 Bruno Girin\n\n-}\n\nimport Date\nimport Date.Extra.Config as Conf",
"end": 155,
"score": 0.9998726845,
"start": 144,
"tag": "NAME",
"value": "Bruno Girin"
}
] | src/Date/Extra/Config/Config_fr_fr.elm | AdrianRibao/elm-date-extra | 81 | module Date.Extra.Config.Config_fr_fr exposing (..)
{-| This is the French config for formatting dates.
@docs config
Copyright (c) 2016-2017 Bruno Girin
-}
import Date
import Date.Extra.Config as Config
import Date.Extra.I18n.I_default as Default
import Date.Extra.I18n.I_fr_fr as French
{-| Config for fr-fr.
-}
config : Config.Config
config =
{ i18n =
{ dayShort = French.dayShort
, dayName = French.dayName
, monthShort = French.monthShort
, monthName = French.monthName
, dayOfMonthWithSuffix = French.dayOfMonthWithSuffix
, twelveHourPeriod = Default.twelveHourPeriod
}
, format =
{ date = "%d/%m/%Y" -- dd/MM/yyyy
, longDate = "%A %-d %B %Y" -- dddd, d MMMM yyyy
, time = "%H:%M" -- h:mm (hours in 24)
, longTime = "%H:%M:%S" -- h:mm:ss (hours in 24)
, dateTime = "%-d/%m/%Y %H:%M" -- date + time (hours in 24)
, firstDayOfWeek = Date.Mon
}
}
| 39174 | module Date.Extra.Config.Config_fr_fr exposing (..)
{-| This is the French config for formatting dates.
@docs config
Copyright (c) 2016-2017 <NAME>
-}
import Date
import Date.Extra.Config as Config
import Date.Extra.I18n.I_default as Default
import Date.Extra.I18n.I_fr_fr as French
{-| Config for fr-fr.
-}
config : Config.Config
config =
{ i18n =
{ dayShort = French.dayShort
, dayName = French.dayName
, monthShort = French.monthShort
, monthName = French.monthName
, dayOfMonthWithSuffix = French.dayOfMonthWithSuffix
, twelveHourPeriod = Default.twelveHourPeriod
}
, format =
{ date = "%d/%m/%Y" -- dd/MM/yyyy
, longDate = "%A %-d %B %Y" -- dddd, d MMMM yyyy
, time = "%H:%M" -- h:mm (hours in 24)
, longTime = "%H:%M:%S" -- h:mm:ss (hours in 24)
, dateTime = "%-d/%m/%Y %H:%M" -- date + time (hours in 24)
, firstDayOfWeek = Date.Mon
}
}
| true | module Date.Extra.Config.Config_fr_fr exposing (..)
{-| This is the French config for formatting dates.
@docs config
Copyright (c) 2016-2017 PI:NAME:<NAME>END_PI
-}
import Date
import Date.Extra.Config as Config
import Date.Extra.I18n.I_default as Default
import Date.Extra.I18n.I_fr_fr as French
{-| Config for fr-fr.
-}
config : Config.Config
config =
{ i18n =
{ dayShort = French.dayShort
, dayName = French.dayName
, monthShort = French.monthShort
, monthName = French.monthName
, dayOfMonthWithSuffix = French.dayOfMonthWithSuffix
, twelveHourPeriod = Default.twelveHourPeriod
}
, format =
{ date = "%d/%m/%Y" -- dd/MM/yyyy
, longDate = "%A %-d %B %Y" -- dddd, d MMMM yyyy
, time = "%H:%M" -- h:mm (hours in 24)
, longTime = "%H:%M:%S" -- h:mm:ss (hours in 24)
, dateTime = "%-d/%m/%Y %H:%M" -- date + time (hours in 24)
, firstDayOfWeek = Date.Mon
}
}
| elm |
[
{
"context": ".AES to Crypto.Strings.Crypt\n-- Copyright (c) 2017 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n",
"end": 172,
"score": 0.9998731613,
"start": 158,
"tag": "NAME",
"value": "Bill St. Clair"
},
{
"context": "rings.Crypt\n-- Copyright (c) 2017 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n-- Distributed under th",
"end": 195,
"score": 0.9999296665,
"start": 174,
"tag": "EMAIL",
"value": "billstclair@gmail.com"
}
] | src/Crypto/Strings/BlockAes.elm | Zinggi/elm-crypto-string | 0 | ----------------------------------------------------------------------
--
-- BlockAes.elm
-- Connect Crypto.AES to Crypto.Strings.Crypt
-- Copyright (c) 2017 Bill St. Clair <billstclair@gmail.com>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
module Crypto.Strings.BlockAes exposing (Key, KeySize(..), encryption, setKeySize)
{-| Connect Crypto.AES to Crypto.Strings.Crypt
# Types
@docs Key, KeySize
# Functions
@docs encryption, setKeySize
-}
import Array exposing (Array)
import Crypto.AES as AES
import Crypto.Strings.Types exposing (Block, Encryption, KeyExpander)
{-| AES key type
-}
type alias Key =
AES.Keys
{-| AES encryption. 32-byte key size. Use `setKeySize` to change it.
-}
encryption : Encryption Key
encryption =
{ name = "AES"
, blockSize = 16
, keyExpander = keyExpander
, encryptor = encrypt
, decryptor = decrypt
}
keyExpander : KeyExpander AES.Keys
keyExpander =
{ keySize = 32
, expander = AES.expandKey
}
{-| An AES key size. 16, 24, or 32 bytes.
-}
type KeySize
= KeySize16
| KeySize24
| KeySize32
keySizeToInt : KeySize -> Int
keySizeToInt keySize =
case keySize of
KeySize16 ->
16
KeySize24 ->
24
KeySize32 ->
32
{-| Change the key size of the keyExpander inside an AES Encryption spec.
-}
setKeySize : KeySize -> Encryption Key -> Encryption Key
setKeySize keySize encryption =
let
expander =
encryption.keyExpander
in
{ encryption
| keyExpander = { expander | keySize = keySizeToInt keySize }
}
encrypt : AES.Keys -> Block -> Block
encrypt keys block =
AES.encrypt keys block
decrypt : AES.Keys -> Block -> Block
decrypt keys block =
AES.decrypt keys block
| 31116 | ----------------------------------------------------------------------
--
-- BlockAes.elm
-- Connect Crypto.AES to Crypto.Strings.Crypt
-- Copyright (c) 2017 <NAME> <<EMAIL>>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
module Crypto.Strings.BlockAes exposing (Key, KeySize(..), encryption, setKeySize)
{-| Connect Crypto.AES to Crypto.Strings.Crypt
# Types
@docs Key, KeySize
# Functions
@docs encryption, setKeySize
-}
import Array exposing (Array)
import Crypto.AES as AES
import Crypto.Strings.Types exposing (Block, Encryption, KeyExpander)
{-| AES key type
-}
type alias Key =
AES.Keys
{-| AES encryption. 32-byte key size. Use `setKeySize` to change it.
-}
encryption : Encryption Key
encryption =
{ name = "AES"
, blockSize = 16
, keyExpander = keyExpander
, encryptor = encrypt
, decryptor = decrypt
}
keyExpander : KeyExpander AES.Keys
keyExpander =
{ keySize = 32
, expander = AES.expandKey
}
{-| An AES key size. 16, 24, or 32 bytes.
-}
type KeySize
= KeySize16
| KeySize24
| KeySize32
keySizeToInt : KeySize -> Int
keySizeToInt keySize =
case keySize of
KeySize16 ->
16
KeySize24 ->
24
KeySize32 ->
32
{-| Change the key size of the keyExpander inside an AES Encryption spec.
-}
setKeySize : KeySize -> Encryption Key -> Encryption Key
setKeySize keySize encryption =
let
expander =
encryption.keyExpander
in
{ encryption
| keyExpander = { expander | keySize = keySizeToInt keySize }
}
encrypt : AES.Keys -> Block -> Block
encrypt keys block =
AES.encrypt keys block
decrypt : AES.Keys -> Block -> Block
decrypt keys block =
AES.decrypt keys block
| true | ----------------------------------------------------------------------
--
-- BlockAes.elm
-- Connect Crypto.AES to Crypto.Strings.Crypt
-- 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 Crypto.Strings.BlockAes exposing (Key, KeySize(..), encryption, setKeySize)
{-| Connect Crypto.AES to Crypto.Strings.Crypt
# Types
@docs Key, KeySize
# Functions
@docs encryption, setKeySize
-}
import Array exposing (Array)
import Crypto.AES as AES
import Crypto.Strings.Types exposing (Block, Encryption, KeyExpander)
{-| AES key type
-}
type alias Key =
AES.Keys
{-| AES encryption. 32-byte key size. Use `setKeySize` to change it.
-}
encryption : Encryption Key
encryption =
{ name = "AES"
, blockSize = 16
, keyExpander = keyExpander
, encryptor = encrypt
, decryptor = decrypt
}
keyExpander : KeyExpander AES.Keys
keyExpander =
{ keySize = 32
, expander = AES.expandKey
}
{-| An AES key size. 16, 24, or 32 bytes.
-}
type KeySize
= KeySize16
| KeySize24
| KeySize32
keySizeToInt : KeySize -> Int
keySizeToInt keySize =
case keySize of
KeySize16 ->
16
KeySize24 ->
24
KeySize32 ->
32
{-| Change the key size of the keyExpander inside an AES Encryption spec.
-}
setKeySize : KeySize -> Encryption Key -> Encryption Key
setKeySize keySize encryption =
let
expander =
encryption.keyExpander
in
{ encryption
| keyExpander = { expander | keySize = keySizeToInt keySize }
}
encrypt : AES.Keys -> Block -> Block
encrypt keys block =
AES.encrypt keys block
decrypt : AES.Keys -> Block -> Block
decrypt keys block =
AES.decrypt keys block
| elm |
[
{
"context": "{-\n Swaggy Jenkins\n Jenkins API clients generated from Swagger / O",
"end": 20,
"score": 0.9995701313,
"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.9999135733,
"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.9996570349,
"start": 240,
"tag": "USERNAME",
"value": "openapitools"
}
] | clients/elm/generated/src/Data/GithubRespositoryContainer.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.GithubRespositoryContainer exposing (GithubRespositoryContainer, githubRespositoryContainerDecoder, githubRespositoryContainerEncoder)
import Data.GithubRespositoryContainerlinks exposing (GithubRespositoryContainerlinks, githubRespositoryContainerlinksDecoder, githubRespositoryContainerlinksEncoder)
import Data.GithubRepositories exposing (GithubRepositories, githubRepositoriesDecoder, githubRepositoriesEncoder)
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 GithubRespositoryContainer =
{ class : Maybe String
, links : Maybe GithubRespositoryContainerlinks
, repositories : Maybe GithubRepositories
}
githubRespositoryContainerDecoder : Decoder GithubRespositoryContainer
githubRespositoryContainerDecoder =
decode GithubRespositoryContainer
|> optional "_class" (Decode.nullable Decode.string) Nothing
|> optional "_links" (Decode.nullable githubRespositoryContainerlinksDecoder) Nothing
|> optional "repositories" (Decode.nullable githubRepositoriesDecoder) Nothing
githubRespositoryContainerEncoder : GithubRespositoryContainer -> Encode.Value
githubRespositoryContainerEncoder model =
Encode.object
[ ( "_class", withDefault Encode.null (map Encode.string model.class) )
, ( "_links", withDefault Encode.null (map githubRespositoryContainerlinksEncoder model.links) )
, ( "repositories", withDefault Encode.null (map githubRepositoriesEncoder model.repositories) )
]
| 43048 | {-
<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.GithubRespositoryContainer exposing (GithubRespositoryContainer, githubRespositoryContainerDecoder, githubRespositoryContainerEncoder)
import Data.GithubRespositoryContainerlinks exposing (GithubRespositoryContainerlinks, githubRespositoryContainerlinksDecoder, githubRespositoryContainerlinksEncoder)
import Data.GithubRepositories exposing (GithubRepositories, githubRepositoriesDecoder, githubRepositoriesEncoder)
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 GithubRespositoryContainer =
{ class : Maybe String
, links : Maybe GithubRespositoryContainerlinks
, repositories : Maybe GithubRepositories
}
githubRespositoryContainerDecoder : Decoder GithubRespositoryContainer
githubRespositoryContainerDecoder =
decode GithubRespositoryContainer
|> optional "_class" (Decode.nullable Decode.string) Nothing
|> optional "_links" (Decode.nullable githubRespositoryContainerlinksDecoder) Nothing
|> optional "repositories" (Decode.nullable githubRepositoriesDecoder) Nothing
githubRespositoryContainerEncoder : GithubRespositoryContainer -> Encode.Value
githubRespositoryContainerEncoder model =
Encode.object
[ ( "_class", withDefault Encode.null (map Encode.string model.class) )
, ( "_links", withDefault Encode.null (map githubRespositoryContainerlinksEncoder model.links) )
, ( "repositories", withDefault Encode.null (map githubRepositoriesEncoder model.repositories) )
]
| 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.GithubRespositoryContainer exposing (GithubRespositoryContainer, githubRespositoryContainerDecoder, githubRespositoryContainerEncoder)
import Data.GithubRespositoryContainerlinks exposing (GithubRespositoryContainerlinks, githubRespositoryContainerlinksDecoder, githubRespositoryContainerlinksEncoder)
import Data.GithubRepositories exposing (GithubRepositories, githubRepositoriesDecoder, githubRepositoriesEncoder)
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 GithubRespositoryContainer =
{ class : Maybe String
, links : Maybe GithubRespositoryContainerlinks
, repositories : Maybe GithubRepositories
}
githubRespositoryContainerDecoder : Decoder GithubRespositoryContainer
githubRespositoryContainerDecoder =
decode GithubRespositoryContainer
|> optional "_class" (Decode.nullable Decode.string) Nothing
|> optional "_links" (Decode.nullable githubRespositoryContainerlinksDecoder) Nothing
|> optional "repositories" (Decode.nullable githubRepositoriesDecoder) Nothing
githubRespositoryContainerEncoder : GithubRespositoryContainer -> Encode.Value
githubRespositoryContainerEncoder model =
Encode.object
[ ( "_class", withDefault Encode.null (map Encode.string model.class) )
, ( "_links", withDefault Encode.null (map githubRespositoryContainerlinksEncoder model.links) )
, ( "repositories", withDefault Encode.null (map githubRepositoriesEncoder model.repositories) )
]
| elm |
[
{
"context": "he literal in braces:\n\n {\n \"MyNameIs\": \"Je m'appelle {name}\"\n }\n\nPluralization is implement",
"end": 487,
"score": 0.7007630467,
"start": 486,
"tag": "NAME",
"value": "m"
},
{
"context": "literal in braces:\n\n {\n \"MyNameIs\": \"Je m'appelle {name}\"\n }\n\nPluralization is implemented b",
"end": 491,
"score": 0.7270836234,
"start": 488,
"tag": "NAME",
"value": "app"
}
] | src/Translator.elm | ccapndave/elm-translator | 6 | module Translator exposing
( Translator, decoder, encode
, Literal, makeLiteral, makeLiteralWithOptions
, defaultTranslator, addTranslations, updateTranslations
, trans, text, placeholder
)
{-| This is package to provide type safe internationalisation, where translations can be loaded at
runtime. Default translations, substitutions and pluralization are supported.
Substitutions are implemented by surrounding the literal in braces:
{
"MyNameIs": "Je m'appelle {name}"
}
Pluralization is implemented by having the singular case on the left of the pipe symbol, and all
other cases on the right. The number can be substituted using `{count}`.
{
"MyAge": "I am only one year old|I'm {count} years old"
}
@docs Translator, decoder, encode
@docs Literal, makeLiteral, makeLiteralWithOptions
@docs defaultTranslator, addTranslations, updateTranslations
@docs trans, text, placeholder
-}
import Dict exposing (Dict)
import Html exposing (Attribute, Html)
import Html.Attributes
import Json.Decode as JD exposing (Decoder, field)
import Json.Encode as JE exposing (Value)
import Regex
import Translations exposing (Translations)
{-| This represents a literal that can be translated.
-}
type Literal
= Literal LiteralData
type alias LiteralData =
{ id : String
, default : Maybe String
, substitutions : Dict String String
, count : Maybe Int
}
{-| The translator contains the translation stack. This probably belongs in the model.
-}
type Translator
= Translator (List Translations)
{-| A Json decoder for a translator
-}
decoder : Decoder Translator
decoder =
JD.list Translations.decoder
|> JD.map Translator
{-| A Json encoder for a translator
-}
encode : Translator -> Value
encode (Translator translations) =
translations
|> JE.list Translations.encode
{-| An empty translator. The only translations this will be able to do are the defaults
specified in the literals (hence why it is called `defaultTranslator`).
-}
defaultTranslator : Translator
defaultTranslator =
Translator []
{-| Add a translation dictionary to a translator.
-}
addTranslations : Translations -> Translator -> Translator
addTranslations translations (Translator translationDicts) =
Translator (translations :: translationDicts)
{-| Update the translation dictionary at the head of the stack. If there are none
then set this as the only translation dictionary.
-}
updateTranslations : Translations -> Translator -> Translator
updateTranslations translations (Translator translationDicts) =
case translationDicts of
[] ->
Translator [ translations ]
firstTranslations :: xs ->
Translator (translations :: xs)
{-| Given the id of the literal in the translations, make a Literal that can be used
for doing a translation.
-}
makeLiteral : String -> Literal
makeLiteral id =
makeLiteralWithOptions id Nothing Dict.empty Nothing
{-| Given the id of the literal in the translations, make a Literal that can be used
for doing a translation. This also allows you to specify a default translation, substitutions
and a count for pluralisation.
-}
makeLiteralWithOptions : String -> Maybe String -> Dict String String -> Maybe Int -> Literal
makeLiteralWithOptions id default substitutions count =
Literal (LiteralData id default substitutions count)
findTranslation : Literal -> Translator -> String
findTranslation ((Literal { id, default }) as literal) (Translator translations) =
case translations of
[] ->
default |> Maybe.withDefault "..."
firstTranslationDict :: xs ->
case Dict.get id firstTranslationDict of
Just translation ->
translation
Nothing ->
findTranslation literal (Translator xs)
{-| Given a Literal, translate to a String. This can never fail, and in the event
of being unable to match in either the loaded or default literals this will fall back to "...".
This supports substitutions and pluralization.
-}
trans : Literal -> Translator -> String
trans ((Literal { id, default, substitutions, count }) as literal) translator =
findTranslation literal translator
|> substitute substitutions
|> pluralize count
{-| A translated version of Html.text for use directly in an Elm view
-}
text : Translator -> Literal -> Html msg
text translator literal =
translator
|> trans literal
|> Html.text
{-| A translated version of Html.Attributes.placeholder for use directly in an Elm view
-}
placeholder : Translator -> Literal -> Attribute msg
placeholder translator literal =
translator
|> trans literal
|> Html.Attributes.placeholder
{-| Apply any substitutions by replacing any `{key}`s in the translated string with their `value`s
-}
substitute : Dict String String -> String -> String
substitute substitutions translation =
let
substituteItem : String -> String -> String -> String
substituteItem key value str =
Regex.fromString ("{\\s*" ++ key ++ "\\s*}")
|> Maybe.map (\regex -> Regex.replace regex (\_ -> value) str)
|> Maybe.withDefault str
in
substitutions
|> Dict.foldl substituteItem translation
{-| Deal with pluralization based on the given count
-}
pluralize : Maybe Int -> String -> String
pluralize count translation =
let
( singularClause, pluralClause ) =
case String.split "|" translation of
[ s, p ] ->
( s, p )
otherwise ->
( "", "" )
in
case count of
Just 1 ->
singularClause |> substitute (Dict.fromList [ ( "count", "1" ) ])
Just n ->
pluralClause |> substitute (Dict.fromList [ ( "count", String.fromInt n ) ])
Nothing ->
translation
| 37495 | module Translator exposing
( Translator, decoder, encode
, Literal, makeLiteral, makeLiteralWithOptions
, defaultTranslator, addTranslations, updateTranslations
, trans, text, placeholder
)
{-| This is package to provide type safe internationalisation, where translations can be loaded at
runtime. Default translations, substitutions and pluralization are supported.
Substitutions are implemented by surrounding the literal in braces:
{
"MyNameIs": "Je <NAME>'<NAME>elle {name}"
}
Pluralization is implemented by having the singular case on the left of the pipe symbol, and all
other cases on the right. The number can be substituted using `{count}`.
{
"MyAge": "I am only one year old|I'm {count} years old"
}
@docs Translator, decoder, encode
@docs Literal, makeLiteral, makeLiteralWithOptions
@docs defaultTranslator, addTranslations, updateTranslations
@docs trans, text, placeholder
-}
import Dict exposing (Dict)
import Html exposing (Attribute, Html)
import Html.Attributes
import Json.Decode as JD exposing (Decoder, field)
import Json.Encode as JE exposing (Value)
import Regex
import Translations exposing (Translations)
{-| This represents a literal that can be translated.
-}
type Literal
= Literal LiteralData
type alias LiteralData =
{ id : String
, default : Maybe String
, substitutions : Dict String String
, count : Maybe Int
}
{-| The translator contains the translation stack. This probably belongs in the model.
-}
type Translator
= Translator (List Translations)
{-| A Json decoder for a translator
-}
decoder : Decoder Translator
decoder =
JD.list Translations.decoder
|> JD.map Translator
{-| A Json encoder for a translator
-}
encode : Translator -> Value
encode (Translator translations) =
translations
|> JE.list Translations.encode
{-| An empty translator. The only translations this will be able to do are the defaults
specified in the literals (hence why it is called `defaultTranslator`).
-}
defaultTranslator : Translator
defaultTranslator =
Translator []
{-| Add a translation dictionary to a translator.
-}
addTranslations : Translations -> Translator -> Translator
addTranslations translations (Translator translationDicts) =
Translator (translations :: translationDicts)
{-| Update the translation dictionary at the head of the stack. If there are none
then set this as the only translation dictionary.
-}
updateTranslations : Translations -> Translator -> Translator
updateTranslations translations (Translator translationDicts) =
case translationDicts of
[] ->
Translator [ translations ]
firstTranslations :: xs ->
Translator (translations :: xs)
{-| Given the id of the literal in the translations, make a Literal that can be used
for doing a translation.
-}
makeLiteral : String -> Literal
makeLiteral id =
makeLiteralWithOptions id Nothing Dict.empty Nothing
{-| Given the id of the literal in the translations, make a Literal that can be used
for doing a translation. This also allows you to specify a default translation, substitutions
and a count for pluralisation.
-}
makeLiteralWithOptions : String -> Maybe String -> Dict String String -> Maybe Int -> Literal
makeLiteralWithOptions id default substitutions count =
Literal (LiteralData id default substitutions count)
findTranslation : Literal -> Translator -> String
findTranslation ((Literal { id, default }) as literal) (Translator translations) =
case translations of
[] ->
default |> Maybe.withDefault "..."
firstTranslationDict :: xs ->
case Dict.get id firstTranslationDict of
Just translation ->
translation
Nothing ->
findTranslation literal (Translator xs)
{-| Given a Literal, translate to a String. This can never fail, and in the event
of being unable to match in either the loaded or default literals this will fall back to "...".
This supports substitutions and pluralization.
-}
trans : Literal -> Translator -> String
trans ((Literal { id, default, substitutions, count }) as literal) translator =
findTranslation literal translator
|> substitute substitutions
|> pluralize count
{-| A translated version of Html.text for use directly in an Elm view
-}
text : Translator -> Literal -> Html msg
text translator literal =
translator
|> trans literal
|> Html.text
{-| A translated version of Html.Attributes.placeholder for use directly in an Elm view
-}
placeholder : Translator -> Literal -> Attribute msg
placeholder translator literal =
translator
|> trans literal
|> Html.Attributes.placeholder
{-| Apply any substitutions by replacing any `{key}`s in the translated string with their `value`s
-}
substitute : Dict String String -> String -> String
substitute substitutions translation =
let
substituteItem : String -> String -> String -> String
substituteItem key value str =
Regex.fromString ("{\\s*" ++ key ++ "\\s*}")
|> Maybe.map (\regex -> Regex.replace regex (\_ -> value) str)
|> Maybe.withDefault str
in
substitutions
|> Dict.foldl substituteItem translation
{-| Deal with pluralization based on the given count
-}
pluralize : Maybe Int -> String -> String
pluralize count translation =
let
( singularClause, pluralClause ) =
case String.split "|" translation of
[ s, p ] ->
( s, p )
otherwise ->
( "", "" )
in
case count of
Just 1 ->
singularClause |> substitute (Dict.fromList [ ( "count", "1" ) ])
Just n ->
pluralClause |> substitute (Dict.fromList [ ( "count", String.fromInt n ) ])
Nothing ->
translation
| true | module Translator exposing
( Translator, decoder, encode
, Literal, makeLiteral, makeLiteralWithOptions
, defaultTranslator, addTranslations, updateTranslations
, trans, text, placeholder
)
{-| This is package to provide type safe internationalisation, where translations can be loaded at
runtime. Default translations, substitutions and pluralization are supported.
Substitutions are implemented by surrounding the literal in braces:
{
"MyNameIs": "Je PI:NAME:<NAME>END_PI'PI:NAME:<NAME>END_PIelle {name}"
}
Pluralization is implemented by having the singular case on the left of the pipe symbol, and all
other cases on the right. The number can be substituted using `{count}`.
{
"MyAge": "I am only one year old|I'm {count} years old"
}
@docs Translator, decoder, encode
@docs Literal, makeLiteral, makeLiteralWithOptions
@docs defaultTranslator, addTranslations, updateTranslations
@docs trans, text, placeholder
-}
import Dict exposing (Dict)
import Html exposing (Attribute, Html)
import Html.Attributes
import Json.Decode as JD exposing (Decoder, field)
import Json.Encode as JE exposing (Value)
import Regex
import Translations exposing (Translations)
{-| This represents a literal that can be translated.
-}
type Literal
= Literal LiteralData
type alias LiteralData =
{ id : String
, default : Maybe String
, substitutions : Dict String String
, count : Maybe Int
}
{-| The translator contains the translation stack. This probably belongs in the model.
-}
type Translator
= Translator (List Translations)
{-| A Json decoder for a translator
-}
decoder : Decoder Translator
decoder =
JD.list Translations.decoder
|> JD.map Translator
{-| A Json encoder for a translator
-}
encode : Translator -> Value
encode (Translator translations) =
translations
|> JE.list Translations.encode
{-| An empty translator. The only translations this will be able to do are the defaults
specified in the literals (hence why it is called `defaultTranslator`).
-}
defaultTranslator : Translator
defaultTranslator =
Translator []
{-| Add a translation dictionary to a translator.
-}
addTranslations : Translations -> Translator -> Translator
addTranslations translations (Translator translationDicts) =
Translator (translations :: translationDicts)
{-| Update the translation dictionary at the head of the stack. If there are none
then set this as the only translation dictionary.
-}
updateTranslations : Translations -> Translator -> Translator
updateTranslations translations (Translator translationDicts) =
case translationDicts of
[] ->
Translator [ translations ]
firstTranslations :: xs ->
Translator (translations :: xs)
{-| Given the id of the literal in the translations, make a Literal that can be used
for doing a translation.
-}
makeLiteral : String -> Literal
makeLiteral id =
makeLiteralWithOptions id Nothing Dict.empty Nothing
{-| Given the id of the literal in the translations, make a Literal that can be used
for doing a translation. This also allows you to specify a default translation, substitutions
and a count for pluralisation.
-}
makeLiteralWithOptions : String -> Maybe String -> Dict String String -> Maybe Int -> Literal
makeLiteralWithOptions id default substitutions count =
Literal (LiteralData id default substitutions count)
findTranslation : Literal -> Translator -> String
findTranslation ((Literal { id, default }) as literal) (Translator translations) =
case translations of
[] ->
default |> Maybe.withDefault "..."
firstTranslationDict :: xs ->
case Dict.get id firstTranslationDict of
Just translation ->
translation
Nothing ->
findTranslation literal (Translator xs)
{-| Given a Literal, translate to a String. This can never fail, and in the event
of being unable to match in either the loaded or default literals this will fall back to "...".
This supports substitutions and pluralization.
-}
trans : Literal -> Translator -> String
trans ((Literal { id, default, substitutions, count }) as literal) translator =
findTranslation literal translator
|> substitute substitutions
|> pluralize count
{-| A translated version of Html.text for use directly in an Elm view
-}
text : Translator -> Literal -> Html msg
text translator literal =
translator
|> trans literal
|> Html.text
{-| A translated version of Html.Attributes.placeholder for use directly in an Elm view
-}
placeholder : Translator -> Literal -> Attribute msg
placeholder translator literal =
translator
|> trans literal
|> Html.Attributes.placeholder
{-| Apply any substitutions by replacing any `{key}`s in the translated string with their `value`s
-}
substitute : Dict String String -> String -> String
substitute substitutions translation =
let
substituteItem : String -> String -> String -> String
substituteItem key value str =
Regex.fromString ("{\\s*" ++ key ++ "\\s*}")
|> Maybe.map (\regex -> Regex.replace regex (\_ -> value) str)
|> Maybe.withDefault str
in
substitutions
|> Dict.foldl substituteItem translation
{-| Deal with pluralization based on the given count
-}
pluralize : Maybe Int -> String -> String
pluralize count translation =
let
( singularClause, pluralClause ) =
case String.split "|" translation of
[ s, p ] ->
( s, p )
otherwise ->
( "", "" )
in
case count of
Just 1 ->
singularClause |> substitute (Dict.fromList [ ( "count", "1" ) ])
Just n ->
pluralClause |> substitute (Dict.fromList [ ( "count", String.fromInt n ) ])
Nothing ->
translation
| elm |
[
{
"context": "s not exposed to clients.\n\nCopyright (c) 2016-2018 Robin Luiten\n\n-}\n\nimport Date exposing (Date, Month(..))\nimpor",
"end": 122,
"score": 0.9998250008,
"start": 110,
"tag": "NAME",
"value": "Robin Luiten"
}
] | src/Date/Extra/Internal.elm | AdrianRibao/elm-date-extra | 81 | module Date.Extra.Internal exposing (..)
{-| This module is not exposed to clients.
Copyright (c) 2016-2018 Robin Luiten
-}
import Date exposing (Date, Month(..))
import Date.Extra.Period as Period
import Date.Extra.Internal2 as Internal2
import Date.Extra.TypeAlias exposing (DateFromFields)
{-| Adjust date as if it was in utc zone.
-}
hackDateAsUtc : Date -> Date
hackDateAsUtc date =
let
offset =
getTimezoneOffset date
oHours =
offset // Internal2.ticksAnHour
oMinutes =
(offset - (oHours * Internal2.ticksAnHour)) // Internal2.ticksAMinute
in
hackDateAsOffset offset date
{-| Adjust date for time zone offset in minutes.
-}
hackDateAsOffset : Int -> Date -> Date
hackDateAsOffset offsetMinutes date =
Internal2.toTime date
|> (+) (offsetMinutes * Internal2.ticksAMinute)
|> Internal2.fromTime
{-| Returns number of days since civil 1970-01-01. Negative values indicate
days prior to 1970-01-01.
Reference: <http://stackoverflow.com/questions/7960318/math-to-convert-seconds-since-1970-into-date-and-vice-versa>
Which references: <http://howardhinnant.github.io/date_algorithms.html>
-}
daysFromCivil : Int -> Int -> Int -> Int
daysFromCivil year month day =
let
y =
year
- if month <= 2 then
1
else
0
era =
(if y >= 0 then
y
else
y - 399
)
// 400
yoe =
y - (era * 400)
-- [0, 399]
doy =
(153
* (month
+ (if month > 2 then
-3
else
9
)
)
+ 2
)
// 5
+ day
- 1
-- [0, 365]
doe =
yoe * 365 + yoe // 4 - yoe // 100 + doy
-- [0, 146096]
in
era * 146097 + doe - 719468
{-| See comment in `Create.getTimezoneOffset`
-}
getTimezoneOffset : Date -> Int
getTimezoneOffset date =
let
dateTicks =
floor (Date.toTime date)
v1Ticks =
ticksFromDateFields date
in
(dateTicks - v1Ticks) // Internal2.ticksAMinute
ticksFromDateFields : Date -> Int
ticksFromDateFields date =
ticksFromFields
(Date.year date)
(Date.month date)
(Date.day date)
(Date.hour date)
(Date.minute date)
(Date.second date)
(Date.millisecond date)
ticksFromFieldsRecord : DateFromFields -> Int
ticksFromFieldsRecord { year, month, day, hour, minute, second, millisecond } =
ticksFromFields year month day hour minute second millisecond
ticksFromFields : Int -> Month -> Int -> Int -> Int -> Int -> Int -> Int
ticksFromFields year month day hour minute second millisecond =
let
clampYear =
if year < 0 then
0
else
year
monthInt =
Internal2.monthToInt month
clampDay =
clamp 1 (Internal2.daysInMonth clampYear month) day
dayCount =
daysFromCivil clampYear monthInt clampDay
in
Period.toTicks <|
Period.Delta
{ millisecond = (clamp 0 999 millisecond)
, second = (clamp 0 59 second)
, minute = (clamp 0 59 minute)
, hour = (clamp 0 23 hour)
, day = dayCount
, week = 0
}
| 28327 | module Date.Extra.Internal exposing (..)
{-| This module is not exposed to clients.
Copyright (c) 2016-2018 <NAME>
-}
import Date exposing (Date, Month(..))
import Date.Extra.Period as Period
import Date.Extra.Internal2 as Internal2
import Date.Extra.TypeAlias exposing (DateFromFields)
{-| Adjust date as if it was in utc zone.
-}
hackDateAsUtc : Date -> Date
hackDateAsUtc date =
let
offset =
getTimezoneOffset date
oHours =
offset // Internal2.ticksAnHour
oMinutes =
(offset - (oHours * Internal2.ticksAnHour)) // Internal2.ticksAMinute
in
hackDateAsOffset offset date
{-| Adjust date for time zone offset in minutes.
-}
hackDateAsOffset : Int -> Date -> Date
hackDateAsOffset offsetMinutes date =
Internal2.toTime date
|> (+) (offsetMinutes * Internal2.ticksAMinute)
|> Internal2.fromTime
{-| Returns number of days since civil 1970-01-01. Negative values indicate
days prior to 1970-01-01.
Reference: <http://stackoverflow.com/questions/7960318/math-to-convert-seconds-since-1970-into-date-and-vice-versa>
Which references: <http://howardhinnant.github.io/date_algorithms.html>
-}
daysFromCivil : Int -> Int -> Int -> Int
daysFromCivil year month day =
let
y =
year
- if month <= 2 then
1
else
0
era =
(if y >= 0 then
y
else
y - 399
)
// 400
yoe =
y - (era * 400)
-- [0, 399]
doy =
(153
* (month
+ (if month > 2 then
-3
else
9
)
)
+ 2
)
// 5
+ day
- 1
-- [0, 365]
doe =
yoe * 365 + yoe // 4 - yoe // 100 + doy
-- [0, 146096]
in
era * 146097 + doe - 719468
{-| See comment in `Create.getTimezoneOffset`
-}
getTimezoneOffset : Date -> Int
getTimezoneOffset date =
let
dateTicks =
floor (Date.toTime date)
v1Ticks =
ticksFromDateFields date
in
(dateTicks - v1Ticks) // Internal2.ticksAMinute
ticksFromDateFields : Date -> Int
ticksFromDateFields date =
ticksFromFields
(Date.year date)
(Date.month date)
(Date.day date)
(Date.hour date)
(Date.minute date)
(Date.second date)
(Date.millisecond date)
ticksFromFieldsRecord : DateFromFields -> Int
ticksFromFieldsRecord { year, month, day, hour, minute, second, millisecond } =
ticksFromFields year month day hour minute second millisecond
ticksFromFields : Int -> Month -> Int -> Int -> Int -> Int -> Int -> Int
ticksFromFields year month day hour minute second millisecond =
let
clampYear =
if year < 0 then
0
else
year
monthInt =
Internal2.monthToInt month
clampDay =
clamp 1 (Internal2.daysInMonth clampYear month) day
dayCount =
daysFromCivil clampYear monthInt clampDay
in
Period.toTicks <|
Period.Delta
{ millisecond = (clamp 0 999 millisecond)
, second = (clamp 0 59 second)
, minute = (clamp 0 59 minute)
, hour = (clamp 0 23 hour)
, day = dayCount
, week = 0
}
| true | module Date.Extra.Internal exposing (..)
{-| This module is not exposed to clients.
Copyright (c) 2016-2018 PI:NAME:<NAME>END_PI
-}
import Date exposing (Date, Month(..))
import Date.Extra.Period as Period
import Date.Extra.Internal2 as Internal2
import Date.Extra.TypeAlias exposing (DateFromFields)
{-| Adjust date as if it was in utc zone.
-}
hackDateAsUtc : Date -> Date
hackDateAsUtc date =
let
offset =
getTimezoneOffset date
oHours =
offset // Internal2.ticksAnHour
oMinutes =
(offset - (oHours * Internal2.ticksAnHour)) // Internal2.ticksAMinute
in
hackDateAsOffset offset date
{-| Adjust date for time zone offset in minutes.
-}
hackDateAsOffset : Int -> Date -> Date
hackDateAsOffset offsetMinutes date =
Internal2.toTime date
|> (+) (offsetMinutes * Internal2.ticksAMinute)
|> Internal2.fromTime
{-| Returns number of days since civil 1970-01-01. Negative values indicate
days prior to 1970-01-01.
Reference: <http://stackoverflow.com/questions/7960318/math-to-convert-seconds-since-1970-into-date-and-vice-versa>
Which references: <http://howardhinnant.github.io/date_algorithms.html>
-}
daysFromCivil : Int -> Int -> Int -> Int
daysFromCivil year month day =
let
y =
year
- if month <= 2 then
1
else
0
era =
(if y >= 0 then
y
else
y - 399
)
// 400
yoe =
y - (era * 400)
-- [0, 399]
doy =
(153
* (month
+ (if month > 2 then
-3
else
9
)
)
+ 2
)
// 5
+ day
- 1
-- [0, 365]
doe =
yoe * 365 + yoe // 4 - yoe // 100 + doy
-- [0, 146096]
in
era * 146097 + doe - 719468
{-| See comment in `Create.getTimezoneOffset`
-}
getTimezoneOffset : Date -> Int
getTimezoneOffset date =
let
dateTicks =
floor (Date.toTime date)
v1Ticks =
ticksFromDateFields date
in
(dateTicks - v1Ticks) // Internal2.ticksAMinute
ticksFromDateFields : Date -> Int
ticksFromDateFields date =
ticksFromFields
(Date.year date)
(Date.month date)
(Date.day date)
(Date.hour date)
(Date.minute date)
(Date.second date)
(Date.millisecond date)
ticksFromFieldsRecord : DateFromFields -> Int
ticksFromFieldsRecord { year, month, day, hour, minute, second, millisecond } =
ticksFromFields year month day hour minute second millisecond
ticksFromFields : Int -> Month -> Int -> Int -> Int -> Int -> Int -> Int
ticksFromFields year month day hour minute second millisecond =
let
clampYear =
if year < 0 then
0
else
year
monthInt =
Internal2.monthToInt month
clampDay =
clamp 1 (Internal2.daysInMonth clampYear month) day
dayCount =
daysFromCivil clampYear monthInt clampDay
in
Period.toTicks <|
Period.Delta
{ millisecond = (clamp 0 999 millisecond)
, second = (clamp 0 59 second)
, minute = (clamp 0 59 minute)
, hour = (clamp 0 23 hour)
, day = dayCount
, week = 0
}
| elm |
[
{
"context": " data\n --> Ok\n --> [ { id = 1, name = \"Atlas\", species = \"cat\" }\n --> , { id = 2, name ",
"end": 1950,
"score": 0.9984617829,
"start": 1945,
"tag": "NAME",
"value": "Atlas"
},
{
"context": "species = \"cat\" }\n --> , { id = 2, name = \"Axel\", species = \"puffin\" }\n --> ]\n\nYou can dec",
"end": 2007,
"score": 0.998644948,
"start": 2003,
"tag": "NAME",
"value": "Axel"
},
{
"context": " \"1\\tBrian\\n2\\tAtlas\"\n --> Ok [ ( 1, \"Brian\" ), ( 2, \"Atlas\" ) ]\n\n-}\ndecodeCustom : { fieldSe",
"end": 12776,
"score": 0.9993911982,
"start": 12771,
"tag": "NAME",
"value": "Brian"
},
{
"context": "n2\\tAtlas\"\n --> Ok [ ( 1, \"Brian\" ), ( 2, \"Atlas\" ) ]\n\n-}\ndecodeCustom : { fieldSeparator : Char }",
"end": 12792,
"score": 0.9904177785,
"start": 12787,
"tag": "NAME",
"value": "Atlas"
},
{
"context": ",1.37\"\n --> Ok\n --> [ { id = 1, name = \"Atlas\", species = \"cat\", weight = 14 }\n --> , { ",
"end": 23680,
"score": 0.7759777308,
"start": 23675,
"tag": "NAME",
"value": "Atlas"
},
{
"context": "t\", weight = 14 }\n --> , { id = 2, name = \"Axel\", species = \"puffin\", weight = 1.37 }\n --> ",
"end": 23750,
"score": 0.9623935223,
"start": 23746,
"tag": "NAME",
"value": "Axel"
},
{
"context": "you could parse a hexadecimal number with\n[`rtfeldman/elm-hex`](https://package.elm-lang.org/packages/r",
"end": 27118,
"score": 0.5303995609,
"start": 27115,
"tag": "USERNAME",
"value": "man"
},
{
"context": "lm-hex`](https://package.elm-lang.org/packages/rtfeldman/elm-hex/latest/):\n\n import Hex\n\n hex : Deco",
"end": 27176,
"score": 0.595417738,
"start": 27170,
"tag": "USERNAME",
"value": "eldman"
}
] | src/Csv/Decode.elm | jpagex/elm-csv | 23 | module Csv.Decode exposing
( Decoder, string, int, float, blank
, column, field
, FieldNames(..), decodeCsv, decodeCustom, Error(..), errorToString, Column(..), Problem(..)
, map, map2, map3, into, pipeline
, oneOf, andThen, succeed, fail, fromResult, fromMaybe
)
{-| Decode values from CSV. This package tries to be as
unsurprising as possible, imitating [`elm/json`][elm-json] and
[`NoRedInk/elm-json-decode-pipeline`][json-decode-pipeline] so that you can
apply whatever you already know about JSON decoders to a different data format.
[elm-json]: https://package.elm-lang.org/packages/elm/json/latest/
[json-decode-pipline]: https://package.elm-lang.org/packages/NoRedInk/elm-json-decode-pipeline/latest/
## A Crash Course on Constructing Decoders
Say you have a CSV like this:
ID,Name,Species
1,Atlas,cat
2,Axel,puffin
You want to get some data out of it, so you're looking through these docs.
Where do you begin?
The first thing you need to know is that decoders are designed to fit together
to match whatever data shapes are in your CSV. So to decode the ID (an `Int` in
the "ID" field), you'd combine [`int`](#int) and [`field`](#field) like this:
data : String
data =
-- \u{000D} is the carriage return
"ID,Name,Species\u{000D}\n1,Atlas,cat\u{000D}\n2,Axel,puffin"
decodeCsv FieldNamesFromFirstRow (field "ID" int) data
--> Ok [ 1, 2 ]
But this is probably not enough, so we'll need to combine a bunch of decoders
together using [`into`](#into):
decodeCsv FieldNamesFromFirstRow
(into
(\id name species ->
{ id = id
, name = name
, species = species
}
)
|> pipeline (field "ID" int)
|> pipeline (field "Name" string)
|> pipeline (field "Species" string)
)
data
--> Ok
--> [ { id = 1, name = "Atlas", species = "cat" }
--> , { id = 2, name = "Axel", species = "puffin" }
--> ]
You can decode as many things as you want by giving [`into`](#into) a function
that takes more arguments.
## Basic Decoders
@docs Decoder, string, int, float, blank
## Finding Values
@docs column, field
## Running Decoders
@docs FieldNames, decodeCsv, decodeCustom, Error, errorToString, Column, Problem
## Transforming Values
@docs map, map2, map3, into, pipeline
## Fancy Decoding
@docs oneOf, andThen, succeed, fail, fromResult, fromMaybe
-}
import Csv.Parser as Parser
import Dict exposing (Dict)
-- BASIC DECODERS
{-| A way to specify what kind of thing you want to decode into. For example,
if you have a `Pet` data type, you'd want a `Decoder Pet`.
-}
type Decoder a
= Decoder
(Location
-> Dict String Int
-> Int
-> List String
->
Result
{ row : Int
, column : Column
, problems : List Problem
}
a
)
fromString : (String -> Result Problem a) -> Decoder a
fromString convert =
Decoder <|
\location fieldNames rowNum row ->
case location of
Column_ colNum ->
case row |> List.drop colNum |> List.head of
Just value ->
case convert value of
Ok converted ->
Ok converted
Err problem ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ problem ]
}
Nothing ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ ColumnNotFound colNum ]
}
Field_ name ->
case Dict.get name fieldNames of
Just colNum ->
case row |> List.drop colNum |> List.head of
Just value ->
case convert value of
Ok converted ->
Ok converted
Err problem ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ problem ]
}
Nothing ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ FieldNotFound name ]
}
Nothing ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ FieldNotProvided name ]
}
OnlyColumn_ ->
case row of
[] ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ ColumnNotFound 0 ]
}
[ only ] ->
case convert only of
Ok converted ->
Ok converted
Err problem ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ problem ]
}
_ ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ ExpectedOneColumn (List.length row) ]
}
{-| Decode a string.
decodeCsv NoFieldNames string "a" --> Ok [ "a" ]
Unless you specify otherwise (e.g. with [`field`](#field)) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames string "a,b"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )
-}
string : Decoder String
string =
fromString Ok
{-| Decode an integer.
decodeCsv NoFieldNames int "1" --> Ok [ 1 ]
decodeCsv NoFieldNames int "volcano"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedInt "volcano" ]
--> }
--> ]
--> )
Unless you specify otherwise (e.g. with [`field`](#field)) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames int "1,2"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )
-}
int : Decoder Int
int =
fromString <|
\value ->
case String.toInt (String.trim value) of
Just parsed ->
Ok parsed
Nothing ->
Err (ExpectedInt value)
{-| Decode a floating-point number.
decodeCsv NoFieldNames float "3.14" --> Ok [ 3.14 ]
decodeCsv NoFieldNames float "mimesis"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedFloat "mimesis" ]
--> }
--> ]
--> )
Unless you specify otherwise (e.g. with [`field`](#field)) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames float "1.0,2.0"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )
-}
float : Decoder Float
float =
fromString <|
\value ->
case String.toFloat (String.trim value) of
Just parsed ->
Ok parsed
Nothing ->
Err (ExpectedFloat value)
{-| Handle blank fields by turning them into `Maybe`s. We consider a field
to be blank if it's empty or consists solely of whitespace characters.
decodeCsv NoFieldNames (blank int) "\r\n1"
--> Ok [ Nothing, Just 1 ]
-}
blank : Decoder a -> Decoder (Maybe a)
blank decoder =
andThen
(\maybeBlank ->
if String.isEmpty (String.trim maybeBlank) then
succeed Nothing
else
map Just decoder
)
string
-- LOCATIONS
type Location
= Column_ Int
| Field_ String
| OnlyColumn_
{-| Parse a value at a numbered column, starting from 0.
decodeCsv NoFieldNames (column 1 string) "a,b,c" --> Ok [ "b" ]
decodeCsv NoFieldNames (column 100 float) "3.14"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = Column 100
--> , problems = [ ColumnNotFound 100 ]
--> }
--> ]
--> )
-}
column : Int -> Decoder a -> Decoder a
column col (Decoder decoder) =
Decoder (\_ fieldNames row -> decoder (Column_ col) fieldNames row)
{-| Parse a value at a named column. There are a number of ways to provide
these names, see [`FieldNames`](#FieldNames)
decodeCsv
FieldNamesFromFirstRow
(field "Country" string)
"Country\r\nArgentina"
--> Ok [ "Argentina" ]
-}
field : String -> Decoder a -> Decoder a
field name (Decoder decoder) =
Decoder (\_ fieldNames row -> decoder (Field_ name) fieldNames row)
-- RUN DECODERS
{-| Where do we get names for use with [`field`](#field)?
- `NoFieldNames`: don't get field names at all. [`field`](#field) will
always fail.
- `CustomFieldNames`: use the provided field names in order (so `["Id", "Name"]`
will mean that "Id" is in column 0 and "Name" is in column 1.)
- `FieldNamesFromFirstRow`: use the first row of the CSV as the source of
field names.
-}
type FieldNames
= NoFieldNames
| CustomFieldNames (List String)
| FieldNamesFromFirstRow
getFieldNames : FieldNames -> List (List String) -> Result Error ( Dict String Int, Int, List (List String) )
getFieldNames headers rows =
let
fromList : List String -> Dict String Int
fromList names =
names
|> List.foldl
(\name ( soFar, i ) ->
( Dict.insert name i soFar
, i + 1
)
)
( Dict.empty, 0 )
|> Tuple.first
in
case headers of
NoFieldNames ->
Ok ( Dict.empty, 0, rows )
CustomFieldNames names ->
Ok ( fromList names, 0, rows )
FieldNamesFromFirstRow ->
case rows of
[] ->
Err NoFieldNamesOnFirstRow
first :: rest ->
Ok ( fromList (List.map String.trim first), 1, rest )
{-| Convert a CSV string into some type you care about using the
[`Decoder`](#Decoder)s in this module!
-}
decodeCsv : FieldNames -> Decoder a -> String -> Result Error (List a)
decodeCsv =
decodeCustom { fieldSeparator = ',' }
{-| Convert something shaped roughly like a CSV. For example, to decode
a TSV (_tab_-separated values) string:
decodeCustom { fieldSeparator = '\t' }
NoFieldNames
(map2 Tuple.pair
(column 0 int)
(column 1 string)
)
"1\tBrian\n2\tAtlas"
--> Ok [ ( 1, "Brian" ), ( 2, "Atlas" ) ]
-}
decodeCustom : { fieldSeparator : Char } -> FieldNames -> Decoder a -> String -> Result Error (List a)
decodeCustom config fieldNames decoder source =
Parser.parse config source
|> Result.mapError ParsingError
|> Result.andThen (applyDecoder fieldNames decoder)
applyDecoder : FieldNames -> Decoder a -> List (List String) -> Result Error (List a)
applyDecoder fieldNames (Decoder decode) allRows =
let
defaultLocation : Location
defaultLocation =
OnlyColumn_
in
Result.andThen
(\( resolvedNames, firstRowNumber, rows ) ->
rows
|> List.foldl
(\row ( soFar, rowNum ) ->
( case decode defaultLocation resolvedNames rowNum row of
Ok val ->
case soFar of
Ok values ->
Ok (val :: values)
Err errs ->
Err errs
Err err ->
case soFar of
Ok _ ->
Err [ err ]
Err errs ->
Err (err :: errs)
, rowNum + 1
)
)
( Ok [], firstRowNumber )
|> Tuple.first
|> Result.map List.reverse
|> Result.mapError (DecodingErrors << List.reverse)
)
(getFieldNames fieldNames allRows)
{-| Sometimes we cannot decode every row in a CSV. This is how we tell
you what went wrong. If you need to present this to someone, you can get a
human-readable version with [`errorToString`](#errorToString)
Some more detail:
- `ParsingError`: there was a problem parsing the CSV into rows and
columns. All these errors have to do with quoting issues. Check that
any quoted fields are closed and that quotes are escaped.
- `NoFieldNamesOnFirstRow`: we tried to get the field names from the first
row (using [`FieldNames`](#FieldNames)) but couldn't find any, probably
because the input was blank.
- `DecodingErrors`: we couldn't decode a value using the specified
decoder. See [`Problem`](#Problem) for more details.
-}
type Error
= ParsingError Parser.Problem
| NoFieldNamesOnFirstRow
| DecodingErrors
(List
{ row : Int
, column : Column
, problems : List Problem
}
)
{-| Where did the problem happen?
- `Column`: at the given column number
- `Field`: at the given named column (with optional column number if we were
able to look up what column we _should_ have found.)
- `OnlyColumn`: at the only column in the row
-}
type Column
= Column Int
| Field String (Maybe Int)
| OnlyColumn
locationToColumn : Dict String Int -> Location -> Column
locationToColumn fieldNames location =
case location of
Column_ i ->
Column i
Field_ name ->
Field name (Dict.get name fieldNames)
OnlyColumn_ ->
OnlyColumn
{-| Things that can go wrong while decoding:
- `ColumnNotFound Int` and `FieldNotFound String`: we looked for the
specified column, but couldn't find it. The argument specifies where we
tried to look.
- `FieldNotProvided String`: we looked for a specific field, but it wasn't
present in the first row or the provided field names (depending on your
configuration.)
- `ExpectedOneColumn Int`: basic decoders like [`string`](#string) and
[`int`](#int) expect to find a single column per row. If there are multiple
columns, and you don't specify which to use with [`column`](#column)
or [`field`](#field), you'll get this error. The argument says how many
columns we found.
- `ExpectedInt String` and `ExpectedFloat String`: we failed to parse a
string into a number. The argument specifies the string we got.
- `Failure`: we got a custom failure message from [`fail`](#fail).
-}
type Problem
= ColumnNotFound Int
| FieldNotFound String
| FieldNotProvided String
| ExpectedOneColumn Int
| ExpectedInt String
| ExpectedFloat String
| Failure String
{-| Produce a human-readable version of an [`Error`](#Error)?!
-}
errorToString : Error -> String
errorToString error =
case error of
ParsingError (Parser.SourceEndedWithoutClosingQuote row) ->
"The source ended on row " ++ String.fromInt row ++ " in a quoted field without a closing quote."
ParsingError (Parser.AdditionalCharactersAfterClosingQuote row) ->
"On row " ++ String.fromInt row ++ " in the source, there were additional characters in a field after a closing quote."
NoFieldNamesOnFirstRow ->
"I expected to see field names on the first row, but there were none."
DecodingErrors errs ->
let
problemString : Problem -> String
problemString problem =
case problem of
ColumnNotFound i ->
"I couldn't find column #" ++ String.fromInt i ++ "."
FieldNotFound name ->
"I couldn't find the `" ++ name ++ "` column."
FieldNotProvided name ->
"The `" ++ name ++ "` field wasn't provided in the field names."
ExpectedOneColumn howMany ->
"I expected exactly one column, but there were " ++ String.fromInt howMany ++ "."
ExpectedInt notInt ->
"I could not parse an int from `" ++ notInt ++ "`."
ExpectedFloat notFloat ->
"I could not parse a float from `" ++ notFloat ++ "`."
Failure custom ->
custom
rowAndColumnString : { a | row : Int, column : Column } -> String
rowAndColumnString err =
"row "
++ String.fromInt err.row
++ ", "
++ (case err.column of
Column col ->
"column " ++ String.fromInt col
Field name Nothing ->
"in the `" ++ name ++ "` field"
Field name (Just col) ->
"in the `" ++ name ++ "` field (column " ++ String.fromInt col ++ ")"
OnlyColumn ->
"column 0 (the only column present)"
)
errString : { row : Int, column : Column, problems : List Problem } -> String
errString err =
case List.map problemString err.problems of
[] ->
"There was an internal error while generating an error on "
++ rowAndColumnString err
++ " and I don't have any info about what went wrong. Please open an issue!"
[ only ] ->
"There was a problem on "
++ rowAndColumnString err
++ ": "
++ only
many ->
"There were some problems on "
++ rowAndColumnString err
++ ":\n\n"
++ String.join "\n" (List.map (\problem -> " - " ++ problem) many)
in
case errs of
[] ->
"Something went wrong, but I got an blank error list so I don't know what it was. Please open an issue!"
[ only ] ->
errString only
many ->
"I saw "
++ String.fromInt (List.length many)
++ " problems while decoding this CSV:\n\n"
++ String.join "\n\n" (List.map errString errs)
-- MAPPING
{-| Transform a decoded value.
decodeCsv NoFieldNames (map (\i -> i * 2) int) "15"
--> Ok [ 30 ]
decodeCsv NoFieldNames (map String.reverse string) "slap"
--> Ok [ "pals" ]
-}
map : (from -> to) -> Decoder from -> Decoder to
map transform (Decoder decoder) =
Decoder (\location fieldNames rowNum row -> decoder location fieldNames rowNum row |> Result.map transform)
{-| Combine two decoders to make something else.
decodeCsv NoFieldNames
(map2 Tuple.pair
(column 0 int)
(column 1 string)
)
"1,Atlas"
--> Ok [ (1, "Atlas") ]
-}
map2 : (a -> b -> c) -> Decoder a -> Decoder b -> Decoder c
map2 transform (Decoder decodeA) (Decoder decodeB) =
Decoder
(\location fieldNames rowNum row ->
Result.map2 transform
(decodeA location fieldNames rowNum row)
(decodeB location fieldNames rowNum row)
)
{-| Like [`map2`](#map2), but with three decoders. `map4` and beyond don't
exist in this package. Use [`into`](#into) to decode records instead!
decodeCsv NoFieldNames
(map3 (\r g b -> (r, g, b))
(column 0 int)
(column 1 int)
(column 2 int)
)
"255,255,0"
--> Ok [ (255, 255, 0) ]
-}
map3 : (a -> b -> c -> d) -> Decoder a -> Decoder b -> Decoder c -> Decoder d
map3 transform (Decoder decodeA) (Decoder decodeB) (Decoder decodeC) =
Decoder
(\location fieldNames rowNum row ->
Result.map3 transform
(decodeA location fieldNames rowNum row)
(decodeB location fieldNames rowNum row)
(decodeC location fieldNames rowNum row)
)
{-| Combine an arbitrary amount of fields. You provide a function that takes
as many arguments as you need, then send it values by providing decoders with
[`pipeline`](#pipeline).
type alias Pet =
{ id : Int
, name : String
, species : String
, weight : Float
}
petDecoder : Decoder Pet
petDecoder =
into Pet
|> pipeline (column 0 int)
|> pipeline (column 1 string)
|> pipeline (column 2 string)
|> pipeline (column 3 float)
Now you can decode pets like this:
decodeCsv NoFieldNames petDecoder "1,Atlas,cat,14\r\n2,Axel,puffin,1.37"
--> Ok
--> [ { id = 1, name = "Atlas", species = "cat", weight = 14 }
--> , { id = 2, name = "Axel", species = "puffin", weight = 1.37 }
--> ]
-}
into : (a -> b) -> Decoder (a -> b)
into =
succeed
{-| See [`into`](#into).
-}
pipeline : Decoder a -> Decoder (a -> b) -> Decoder b
pipeline =
map2 (\value fn -> fn value)
-- FANCY DECODING
{-| Try several possible decoders in sequence, committing to the first one
that passes.
decodeCsv NoFieldNames
(oneOf
(map Just int)
[ succeed Nothing ]
)
"1"
--> Ok [ Just 1 ]
decodeCsv NoFieldNames
(oneOf
(map Just int)
[ succeed Nothing ]
)
"a"
--> Ok [ Nothing ]
-}
oneOf : Decoder a -> List (Decoder a) -> Decoder a
oneOf first rest =
case rest of
[] ->
first
next :: others ->
recover first (oneOf next others)
recover : Decoder a -> Decoder a -> Decoder a
recover (Decoder first) (Decoder second) =
Decoder <|
\location fieldNames rowNum row ->
case first location fieldNames rowNum row of
Ok value ->
Ok value
Err err ->
case second location fieldNames rowNum row of
Ok value ->
Ok value
Err { problems } ->
Err { err | problems = err.problems ++ problems }
{-| Decode some value _and then_ make a decoding decision based on the
outcome. For example, if you wanted to reject negative numbers, you might
do something like this:
positiveInt : Decoder Int
positiveInt =
int
|> andThen
(\rawInt ->
if rawInt < 0 then
Decode.fail "Only positive numbers allowed!"
else
Decode.succeed rawInt
)
You could then use it like this:
decodeCsv NoFieldNames positiveInt "1" -- Ok [ 1 ]
decodeCsv NoFieldNames positiveInt "-1"
-- Err { row = 0, problem = Failure "Only positive numbers allowed!" }
-}
andThen : (a -> Decoder b) -> Decoder a -> Decoder b
andThen next (Decoder first) =
Decoder
(\location fieldNames rowNum row ->
first location fieldNames rowNum row
|> Result.andThen
(\nextValue ->
let
(Decoder final) =
next nextValue
in
final location fieldNames rowNum row
)
)
{-| Always succeed, no matter what. Mostly useful with [`andThen`](#andThen).
-}
succeed : a -> Decoder a
succeed value =
Decoder (\_ _ _ _ -> Ok value)
{-| Always fail with the given message, no matter what. Mostly useful with
[`andThen`](#andThen).
-}
fail : String -> Decoder a
fail message =
Decoder
(\location fieldNames rowNum _ ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ Failure message ]
}
)
{-| Make creating custom decoders a little easier. If you already have a
function that parses into something you care about, you can combine it with
this.
For example, here's how you could parse a hexadecimal number with
[`rtfeldman/elm-hex`](https://package.elm-lang.org/packages/rtfeldman/elm-hex/latest/):
import Hex
hex : Decoder Int
hex =
andThen
(\value -> fromResult (Hex.fromString value))
string
decodeCsv NoFieldNames hex "ff"
--> Ok [ 255 ]
-}
fromResult : Result String a -> Decoder a
fromResult result =
case result of
Ok great ->
succeed great
Err problem ->
fail problem
{-| Like [`fromResult`](#fromResult) but you have to specify the error
message since `Nothing` has no further information.
For example, you could implement something like [`int`](#int) using this:
myInt : Decoder Int
myInt =
andThen
(\value ->
fromMaybe "Expected an int"
(String.toInt value)
)
string
decodeCsv NoFieldNames myInt "123"
--> Ok [ 123 ]
(That said, you probably want to use [`int`](#int) instead... it has better
error messages and is more tolerant of unusual situations!)
-}
fromMaybe : String -> Maybe a -> Decoder a
fromMaybe problem maybe =
case maybe of
Just value ->
succeed value
Nothing ->
fail problem
| 35890 | module Csv.Decode exposing
( Decoder, string, int, float, blank
, column, field
, FieldNames(..), decodeCsv, decodeCustom, Error(..), errorToString, Column(..), Problem(..)
, map, map2, map3, into, pipeline
, oneOf, andThen, succeed, fail, fromResult, fromMaybe
)
{-| Decode values from CSV. This package tries to be as
unsurprising as possible, imitating [`elm/json`][elm-json] and
[`NoRedInk/elm-json-decode-pipeline`][json-decode-pipeline] so that you can
apply whatever you already know about JSON decoders to a different data format.
[elm-json]: https://package.elm-lang.org/packages/elm/json/latest/
[json-decode-pipline]: https://package.elm-lang.org/packages/NoRedInk/elm-json-decode-pipeline/latest/
## A Crash Course on Constructing Decoders
Say you have a CSV like this:
ID,Name,Species
1,Atlas,cat
2,Axel,puffin
You want to get some data out of it, so you're looking through these docs.
Where do you begin?
The first thing you need to know is that decoders are designed to fit together
to match whatever data shapes are in your CSV. So to decode the ID (an `Int` in
the "ID" field), you'd combine [`int`](#int) and [`field`](#field) like this:
data : String
data =
-- \u{000D} is the carriage return
"ID,Name,Species\u{000D}\n1,Atlas,cat\u{000D}\n2,Axel,puffin"
decodeCsv FieldNamesFromFirstRow (field "ID" int) data
--> Ok [ 1, 2 ]
But this is probably not enough, so we'll need to combine a bunch of decoders
together using [`into`](#into):
decodeCsv FieldNamesFromFirstRow
(into
(\id name species ->
{ id = id
, name = name
, species = species
}
)
|> pipeline (field "ID" int)
|> pipeline (field "Name" string)
|> pipeline (field "Species" string)
)
data
--> Ok
--> [ { id = 1, name = "<NAME>", species = "cat" }
--> , { id = 2, name = "<NAME>", species = "puffin" }
--> ]
You can decode as many things as you want by giving [`into`](#into) a function
that takes more arguments.
## Basic Decoders
@docs Decoder, string, int, float, blank
## Finding Values
@docs column, field
## Running Decoders
@docs FieldNames, decodeCsv, decodeCustom, Error, errorToString, Column, Problem
## Transforming Values
@docs map, map2, map3, into, pipeline
## Fancy Decoding
@docs oneOf, andThen, succeed, fail, fromResult, fromMaybe
-}
import Csv.Parser as Parser
import Dict exposing (Dict)
-- BASIC DECODERS
{-| A way to specify what kind of thing you want to decode into. For example,
if you have a `Pet` data type, you'd want a `Decoder Pet`.
-}
type Decoder a
= Decoder
(Location
-> Dict String Int
-> Int
-> List String
->
Result
{ row : Int
, column : Column
, problems : List Problem
}
a
)
fromString : (String -> Result Problem a) -> Decoder a
fromString convert =
Decoder <|
\location fieldNames rowNum row ->
case location of
Column_ colNum ->
case row |> List.drop colNum |> List.head of
Just value ->
case convert value of
Ok converted ->
Ok converted
Err problem ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ problem ]
}
Nothing ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ ColumnNotFound colNum ]
}
Field_ name ->
case Dict.get name fieldNames of
Just colNum ->
case row |> List.drop colNum |> List.head of
Just value ->
case convert value of
Ok converted ->
Ok converted
Err problem ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ problem ]
}
Nothing ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ FieldNotFound name ]
}
Nothing ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ FieldNotProvided name ]
}
OnlyColumn_ ->
case row of
[] ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ ColumnNotFound 0 ]
}
[ only ] ->
case convert only of
Ok converted ->
Ok converted
Err problem ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ problem ]
}
_ ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ ExpectedOneColumn (List.length row) ]
}
{-| Decode a string.
decodeCsv NoFieldNames string "a" --> Ok [ "a" ]
Unless you specify otherwise (e.g. with [`field`](#field)) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames string "a,b"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )
-}
string : Decoder String
string =
fromString Ok
{-| Decode an integer.
decodeCsv NoFieldNames int "1" --> Ok [ 1 ]
decodeCsv NoFieldNames int "volcano"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedInt "volcano" ]
--> }
--> ]
--> )
Unless you specify otherwise (e.g. with [`field`](#field)) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames int "1,2"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )
-}
int : Decoder Int
int =
fromString <|
\value ->
case String.toInt (String.trim value) of
Just parsed ->
Ok parsed
Nothing ->
Err (ExpectedInt value)
{-| Decode a floating-point number.
decodeCsv NoFieldNames float "3.14" --> Ok [ 3.14 ]
decodeCsv NoFieldNames float "mimesis"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedFloat "mimesis" ]
--> }
--> ]
--> )
Unless you specify otherwise (e.g. with [`field`](#field)) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames float "1.0,2.0"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )
-}
float : Decoder Float
float =
fromString <|
\value ->
case String.toFloat (String.trim value) of
Just parsed ->
Ok parsed
Nothing ->
Err (ExpectedFloat value)
{-| Handle blank fields by turning them into `Maybe`s. We consider a field
to be blank if it's empty or consists solely of whitespace characters.
decodeCsv NoFieldNames (blank int) "\r\n1"
--> Ok [ Nothing, Just 1 ]
-}
blank : Decoder a -> Decoder (Maybe a)
blank decoder =
andThen
(\maybeBlank ->
if String.isEmpty (String.trim maybeBlank) then
succeed Nothing
else
map Just decoder
)
string
-- LOCATIONS
type Location
= Column_ Int
| Field_ String
| OnlyColumn_
{-| Parse a value at a numbered column, starting from 0.
decodeCsv NoFieldNames (column 1 string) "a,b,c" --> Ok [ "b" ]
decodeCsv NoFieldNames (column 100 float) "3.14"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = Column 100
--> , problems = [ ColumnNotFound 100 ]
--> }
--> ]
--> )
-}
column : Int -> Decoder a -> Decoder a
column col (Decoder decoder) =
Decoder (\_ fieldNames row -> decoder (Column_ col) fieldNames row)
{-| Parse a value at a named column. There are a number of ways to provide
these names, see [`FieldNames`](#FieldNames)
decodeCsv
FieldNamesFromFirstRow
(field "Country" string)
"Country\r\nArgentina"
--> Ok [ "Argentina" ]
-}
field : String -> Decoder a -> Decoder a
field name (Decoder decoder) =
Decoder (\_ fieldNames row -> decoder (Field_ name) fieldNames row)
-- RUN DECODERS
{-| Where do we get names for use with [`field`](#field)?
- `NoFieldNames`: don't get field names at all. [`field`](#field) will
always fail.
- `CustomFieldNames`: use the provided field names in order (so `["Id", "Name"]`
will mean that "Id" is in column 0 and "Name" is in column 1.)
- `FieldNamesFromFirstRow`: use the first row of the CSV as the source of
field names.
-}
type FieldNames
= NoFieldNames
| CustomFieldNames (List String)
| FieldNamesFromFirstRow
getFieldNames : FieldNames -> List (List String) -> Result Error ( Dict String Int, Int, List (List String) )
getFieldNames headers rows =
let
fromList : List String -> Dict String Int
fromList names =
names
|> List.foldl
(\name ( soFar, i ) ->
( Dict.insert name i soFar
, i + 1
)
)
( Dict.empty, 0 )
|> Tuple.first
in
case headers of
NoFieldNames ->
Ok ( Dict.empty, 0, rows )
CustomFieldNames names ->
Ok ( fromList names, 0, rows )
FieldNamesFromFirstRow ->
case rows of
[] ->
Err NoFieldNamesOnFirstRow
first :: rest ->
Ok ( fromList (List.map String.trim first), 1, rest )
{-| Convert a CSV string into some type you care about using the
[`Decoder`](#Decoder)s in this module!
-}
decodeCsv : FieldNames -> Decoder a -> String -> Result Error (List a)
decodeCsv =
decodeCustom { fieldSeparator = ',' }
{-| Convert something shaped roughly like a CSV. For example, to decode
a TSV (_tab_-separated values) string:
decodeCustom { fieldSeparator = '\t' }
NoFieldNames
(map2 Tuple.pair
(column 0 int)
(column 1 string)
)
"1\tBrian\n2\tAtlas"
--> Ok [ ( 1, "<NAME>" ), ( 2, "<NAME>" ) ]
-}
decodeCustom : { fieldSeparator : Char } -> FieldNames -> Decoder a -> String -> Result Error (List a)
decodeCustom config fieldNames decoder source =
Parser.parse config source
|> Result.mapError ParsingError
|> Result.andThen (applyDecoder fieldNames decoder)
applyDecoder : FieldNames -> Decoder a -> List (List String) -> Result Error (List a)
applyDecoder fieldNames (Decoder decode) allRows =
let
defaultLocation : Location
defaultLocation =
OnlyColumn_
in
Result.andThen
(\( resolvedNames, firstRowNumber, rows ) ->
rows
|> List.foldl
(\row ( soFar, rowNum ) ->
( case decode defaultLocation resolvedNames rowNum row of
Ok val ->
case soFar of
Ok values ->
Ok (val :: values)
Err errs ->
Err errs
Err err ->
case soFar of
Ok _ ->
Err [ err ]
Err errs ->
Err (err :: errs)
, rowNum + 1
)
)
( Ok [], firstRowNumber )
|> Tuple.first
|> Result.map List.reverse
|> Result.mapError (DecodingErrors << List.reverse)
)
(getFieldNames fieldNames allRows)
{-| Sometimes we cannot decode every row in a CSV. This is how we tell
you what went wrong. If you need to present this to someone, you can get a
human-readable version with [`errorToString`](#errorToString)
Some more detail:
- `ParsingError`: there was a problem parsing the CSV into rows and
columns. All these errors have to do with quoting issues. Check that
any quoted fields are closed and that quotes are escaped.
- `NoFieldNamesOnFirstRow`: we tried to get the field names from the first
row (using [`FieldNames`](#FieldNames)) but couldn't find any, probably
because the input was blank.
- `DecodingErrors`: we couldn't decode a value using the specified
decoder. See [`Problem`](#Problem) for more details.
-}
type Error
= ParsingError Parser.Problem
| NoFieldNamesOnFirstRow
| DecodingErrors
(List
{ row : Int
, column : Column
, problems : List Problem
}
)
{-| Where did the problem happen?
- `Column`: at the given column number
- `Field`: at the given named column (with optional column number if we were
able to look up what column we _should_ have found.)
- `OnlyColumn`: at the only column in the row
-}
type Column
= Column Int
| Field String (Maybe Int)
| OnlyColumn
locationToColumn : Dict String Int -> Location -> Column
locationToColumn fieldNames location =
case location of
Column_ i ->
Column i
Field_ name ->
Field name (Dict.get name fieldNames)
OnlyColumn_ ->
OnlyColumn
{-| Things that can go wrong while decoding:
- `ColumnNotFound Int` and `FieldNotFound String`: we looked for the
specified column, but couldn't find it. The argument specifies where we
tried to look.
- `FieldNotProvided String`: we looked for a specific field, but it wasn't
present in the first row or the provided field names (depending on your
configuration.)
- `ExpectedOneColumn Int`: basic decoders like [`string`](#string) and
[`int`](#int) expect to find a single column per row. If there are multiple
columns, and you don't specify which to use with [`column`](#column)
or [`field`](#field), you'll get this error. The argument says how many
columns we found.
- `ExpectedInt String` and `ExpectedFloat String`: we failed to parse a
string into a number. The argument specifies the string we got.
- `Failure`: we got a custom failure message from [`fail`](#fail).
-}
type Problem
= ColumnNotFound Int
| FieldNotFound String
| FieldNotProvided String
| ExpectedOneColumn Int
| ExpectedInt String
| ExpectedFloat String
| Failure String
{-| Produce a human-readable version of an [`Error`](#Error)?!
-}
errorToString : Error -> String
errorToString error =
case error of
ParsingError (Parser.SourceEndedWithoutClosingQuote row) ->
"The source ended on row " ++ String.fromInt row ++ " in a quoted field without a closing quote."
ParsingError (Parser.AdditionalCharactersAfterClosingQuote row) ->
"On row " ++ String.fromInt row ++ " in the source, there were additional characters in a field after a closing quote."
NoFieldNamesOnFirstRow ->
"I expected to see field names on the first row, but there were none."
DecodingErrors errs ->
let
problemString : Problem -> String
problemString problem =
case problem of
ColumnNotFound i ->
"I couldn't find column #" ++ String.fromInt i ++ "."
FieldNotFound name ->
"I couldn't find the `" ++ name ++ "` column."
FieldNotProvided name ->
"The `" ++ name ++ "` field wasn't provided in the field names."
ExpectedOneColumn howMany ->
"I expected exactly one column, but there were " ++ String.fromInt howMany ++ "."
ExpectedInt notInt ->
"I could not parse an int from `" ++ notInt ++ "`."
ExpectedFloat notFloat ->
"I could not parse a float from `" ++ notFloat ++ "`."
Failure custom ->
custom
rowAndColumnString : { a | row : Int, column : Column } -> String
rowAndColumnString err =
"row "
++ String.fromInt err.row
++ ", "
++ (case err.column of
Column col ->
"column " ++ String.fromInt col
Field name Nothing ->
"in the `" ++ name ++ "` field"
Field name (Just col) ->
"in the `" ++ name ++ "` field (column " ++ String.fromInt col ++ ")"
OnlyColumn ->
"column 0 (the only column present)"
)
errString : { row : Int, column : Column, problems : List Problem } -> String
errString err =
case List.map problemString err.problems of
[] ->
"There was an internal error while generating an error on "
++ rowAndColumnString err
++ " and I don't have any info about what went wrong. Please open an issue!"
[ only ] ->
"There was a problem on "
++ rowAndColumnString err
++ ": "
++ only
many ->
"There were some problems on "
++ rowAndColumnString err
++ ":\n\n"
++ String.join "\n" (List.map (\problem -> " - " ++ problem) many)
in
case errs of
[] ->
"Something went wrong, but I got an blank error list so I don't know what it was. Please open an issue!"
[ only ] ->
errString only
many ->
"I saw "
++ String.fromInt (List.length many)
++ " problems while decoding this CSV:\n\n"
++ String.join "\n\n" (List.map errString errs)
-- MAPPING
{-| Transform a decoded value.
decodeCsv NoFieldNames (map (\i -> i * 2) int) "15"
--> Ok [ 30 ]
decodeCsv NoFieldNames (map String.reverse string) "slap"
--> Ok [ "pals" ]
-}
map : (from -> to) -> Decoder from -> Decoder to
map transform (Decoder decoder) =
Decoder (\location fieldNames rowNum row -> decoder location fieldNames rowNum row |> Result.map transform)
{-| Combine two decoders to make something else.
decodeCsv NoFieldNames
(map2 Tuple.pair
(column 0 int)
(column 1 string)
)
"1,Atlas"
--> Ok [ (1, "Atlas") ]
-}
map2 : (a -> b -> c) -> Decoder a -> Decoder b -> Decoder c
map2 transform (Decoder decodeA) (Decoder decodeB) =
Decoder
(\location fieldNames rowNum row ->
Result.map2 transform
(decodeA location fieldNames rowNum row)
(decodeB location fieldNames rowNum row)
)
{-| Like [`map2`](#map2), but with three decoders. `map4` and beyond don't
exist in this package. Use [`into`](#into) to decode records instead!
decodeCsv NoFieldNames
(map3 (\r g b -> (r, g, b))
(column 0 int)
(column 1 int)
(column 2 int)
)
"255,255,0"
--> Ok [ (255, 255, 0) ]
-}
map3 : (a -> b -> c -> d) -> Decoder a -> Decoder b -> Decoder c -> Decoder d
map3 transform (Decoder decodeA) (Decoder decodeB) (Decoder decodeC) =
Decoder
(\location fieldNames rowNum row ->
Result.map3 transform
(decodeA location fieldNames rowNum row)
(decodeB location fieldNames rowNum row)
(decodeC location fieldNames rowNum row)
)
{-| Combine an arbitrary amount of fields. You provide a function that takes
as many arguments as you need, then send it values by providing decoders with
[`pipeline`](#pipeline).
type alias Pet =
{ id : Int
, name : String
, species : String
, weight : Float
}
petDecoder : Decoder Pet
petDecoder =
into Pet
|> pipeline (column 0 int)
|> pipeline (column 1 string)
|> pipeline (column 2 string)
|> pipeline (column 3 float)
Now you can decode pets like this:
decodeCsv NoFieldNames petDecoder "1,Atlas,cat,14\r\n2,Axel,puffin,1.37"
--> Ok
--> [ { id = 1, name = "<NAME>", species = "cat", weight = 14 }
--> , { id = 2, name = "<NAME>", species = "puffin", weight = 1.37 }
--> ]
-}
into : (a -> b) -> Decoder (a -> b)
into =
succeed
{-| See [`into`](#into).
-}
pipeline : Decoder a -> Decoder (a -> b) -> Decoder b
pipeline =
map2 (\value fn -> fn value)
-- FANCY DECODING
{-| Try several possible decoders in sequence, committing to the first one
that passes.
decodeCsv NoFieldNames
(oneOf
(map Just int)
[ succeed Nothing ]
)
"1"
--> Ok [ Just 1 ]
decodeCsv NoFieldNames
(oneOf
(map Just int)
[ succeed Nothing ]
)
"a"
--> Ok [ Nothing ]
-}
oneOf : Decoder a -> List (Decoder a) -> Decoder a
oneOf first rest =
case rest of
[] ->
first
next :: others ->
recover first (oneOf next others)
recover : Decoder a -> Decoder a -> Decoder a
recover (Decoder first) (Decoder second) =
Decoder <|
\location fieldNames rowNum row ->
case first location fieldNames rowNum row of
Ok value ->
Ok value
Err err ->
case second location fieldNames rowNum row of
Ok value ->
Ok value
Err { problems } ->
Err { err | problems = err.problems ++ problems }
{-| Decode some value _and then_ make a decoding decision based on the
outcome. For example, if you wanted to reject negative numbers, you might
do something like this:
positiveInt : Decoder Int
positiveInt =
int
|> andThen
(\rawInt ->
if rawInt < 0 then
Decode.fail "Only positive numbers allowed!"
else
Decode.succeed rawInt
)
You could then use it like this:
decodeCsv NoFieldNames positiveInt "1" -- Ok [ 1 ]
decodeCsv NoFieldNames positiveInt "-1"
-- Err { row = 0, problem = Failure "Only positive numbers allowed!" }
-}
andThen : (a -> Decoder b) -> Decoder a -> Decoder b
andThen next (Decoder first) =
Decoder
(\location fieldNames rowNum row ->
first location fieldNames rowNum row
|> Result.andThen
(\nextValue ->
let
(Decoder final) =
next nextValue
in
final location fieldNames rowNum row
)
)
{-| Always succeed, no matter what. Mostly useful with [`andThen`](#andThen).
-}
succeed : a -> Decoder a
succeed value =
Decoder (\_ _ _ _ -> Ok value)
{-| Always fail with the given message, no matter what. Mostly useful with
[`andThen`](#andThen).
-}
fail : String -> Decoder a
fail message =
Decoder
(\location fieldNames rowNum _ ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ Failure message ]
}
)
{-| Make creating custom decoders a little easier. If you already have a
function that parses into something you care about, you can combine it with
this.
For example, here's how you could parse a hexadecimal number with
[`rtfeldman/elm-hex`](https://package.elm-lang.org/packages/rtfeldman/elm-hex/latest/):
import Hex
hex : Decoder Int
hex =
andThen
(\value -> fromResult (Hex.fromString value))
string
decodeCsv NoFieldNames hex "ff"
--> Ok [ 255 ]
-}
fromResult : Result String a -> Decoder a
fromResult result =
case result of
Ok great ->
succeed great
Err problem ->
fail problem
{-| Like [`fromResult`](#fromResult) but you have to specify the error
message since `Nothing` has no further information.
For example, you could implement something like [`int`](#int) using this:
myInt : Decoder Int
myInt =
andThen
(\value ->
fromMaybe "Expected an int"
(String.toInt value)
)
string
decodeCsv NoFieldNames myInt "123"
--> Ok [ 123 ]
(That said, you probably want to use [`int`](#int) instead... it has better
error messages and is more tolerant of unusual situations!)
-}
fromMaybe : String -> Maybe a -> Decoder a
fromMaybe problem maybe =
case maybe of
Just value ->
succeed value
Nothing ->
fail problem
| true | module Csv.Decode exposing
( Decoder, string, int, float, blank
, column, field
, FieldNames(..), decodeCsv, decodeCustom, Error(..), errorToString, Column(..), Problem(..)
, map, map2, map3, into, pipeline
, oneOf, andThen, succeed, fail, fromResult, fromMaybe
)
{-| Decode values from CSV. This package tries to be as
unsurprising as possible, imitating [`elm/json`][elm-json] and
[`NoRedInk/elm-json-decode-pipeline`][json-decode-pipeline] so that you can
apply whatever you already know about JSON decoders to a different data format.
[elm-json]: https://package.elm-lang.org/packages/elm/json/latest/
[json-decode-pipline]: https://package.elm-lang.org/packages/NoRedInk/elm-json-decode-pipeline/latest/
## A Crash Course on Constructing Decoders
Say you have a CSV like this:
ID,Name,Species
1,Atlas,cat
2,Axel,puffin
You want to get some data out of it, so you're looking through these docs.
Where do you begin?
The first thing you need to know is that decoders are designed to fit together
to match whatever data shapes are in your CSV. So to decode the ID (an `Int` in
the "ID" field), you'd combine [`int`](#int) and [`field`](#field) like this:
data : String
data =
-- \u{000D} is the carriage return
"ID,Name,Species\u{000D}\n1,Atlas,cat\u{000D}\n2,Axel,puffin"
decodeCsv FieldNamesFromFirstRow (field "ID" int) data
--> Ok [ 1, 2 ]
But this is probably not enough, so we'll need to combine a bunch of decoders
together using [`into`](#into):
decodeCsv FieldNamesFromFirstRow
(into
(\id name species ->
{ id = id
, name = name
, species = species
}
)
|> pipeline (field "ID" int)
|> pipeline (field "Name" string)
|> pipeline (field "Species" string)
)
data
--> Ok
--> [ { id = 1, name = "PI:NAME:<NAME>END_PI", species = "cat" }
--> , { id = 2, name = "PI:NAME:<NAME>END_PI", species = "puffin" }
--> ]
You can decode as many things as you want by giving [`into`](#into) a function
that takes more arguments.
## Basic Decoders
@docs Decoder, string, int, float, blank
## Finding Values
@docs column, field
## Running Decoders
@docs FieldNames, decodeCsv, decodeCustom, Error, errorToString, Column, Problem
## Transforming Values
@docs map, map2, map3, into, pipeline
## Fancy Decoding
@docs oneOf, andThen, succeed, fail, fromResult, fromMaybe
-}
import Csv.Parser as Parser
import Dict exposing (Dict)
-- BASIC DECODERS
{-| A way to specify what kind of thing you want to decode into. For example,
if you have a `Pet` data type, you'd want a `Decoder Pet`.
-}
type Decoder a
= Decoder
(Location
-> Dict String Int
-> Int
-> List String
->
Result
{ row : Int
, column : Column
, problems : List Problem
}
a
)
fromString : (String -> Result Problem a) -> Decoder a
fromString convert =
Decoder <|
\location fieldNames rowNum row ->
case location of
Column_ colNum ->
case row |> List.drop colNum |> List.head of
Just value ->
case convert value of
Ok converted ->
Ok converted
Err problem ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ problem ]
}
Nothing ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ ColumnNotFound colNum ]
}
Field_ name ->
case Dict.get name fieldNames of
Just colNum ->
case row |> List.drop colNum |> List.head of
Just value ->
case convert value of
Ok converted ->
Ok converted
Err problem ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ problem ]
}
Nothing ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ FieldNotFound name ]
}
Nothing ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ FieldNotProvided name ]
}
OnlyColumn_ ->
case row of
[] ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ ColumnNotFound 0 ]
}
[ only ] ->
case convert only of
Ok converted ->
Ok converted
Err problem ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ problem ]
}
_ ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ ExpectedOneColumn (List.length row) ]
}
{-| Decode a string.
decodeCsv NoFieldNames string "a" --> Ok [ "a" ]
Unless you specify otherwise (e.g. with [`field`](#field)) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames string "a,b"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )
-}
string : Decoder String
string =
fromString Ok
{-| Decode an integer.
decodeCsv NoFieldNames int "1" --> Ok [ 1 ]
decodeCsv NoFieldNames int "volcano"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedInt "volcano" ]
--> }
--> ]
--> )
Unless you specify otherwise (e.g. with [`field`](#field)) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames int "1,2"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )
-}
int : Decoder Int
int =
fromString <|
\value ->
case String.toInt (String.trim value) of
Just parsed ->
Ok parsed
Nothing ->
Err (ExpectedInt value)
{-| Decode a floating-point number.
decodeCsv NoFieldNames float "3.14" --> Ok [ 3.14 ]
decodeCsv NoFieldNames float "mimesis"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedFloat "mimesis" ]
--> }
--> ]
--> )
Unless you specify otherwise (e.g. with [`field`](#field)) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames float "1.0,2.0"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )
-}
float : Decoder Float
float =
fromString <|
\value ->
case String.toFloat (String.trim value) of
Just parsed ->
Ok parsed
Nothing ->
Err (ExpectedFloat value)
{-| Handle blank fields by turning them into `Maybe`s. We consider a field
to be blank if it's empty or consists solely of whitespace characters.
decodeCsv NoFieldNames (blank int) "\r\n1"
--> Ok [ Nothing, Just 1 ]
-}
blank : Decoder a -> Decoder (Maybe a)
blank decoder =
andThen
(\maybeBlank ->
if String.isEmpty (String.trim maybeBlank) then
succeed Nothing
else
map Just decoder
)
string
-- LOCATIONS
type Location
= Column_ Int
| Field_ String
| OnlyColumn_
{-| Parse a value at a numbered column, starting from 0.
decodeCsv NoFieldNames (column 1 string) "a,b,c" --> Ok [ "b" ]
decodeCsv NoFieldNames (column 100 float) "3.14"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = Column 100
--> , problems = [ ColumnNotFound 100 ]
--> }
--> ]
--> )
-}
column : Int -> Decoder a -> Decoder a
column col (Decoder decoder) =
Decoder (\_ fieldNames row -> decoder (Column_ col) fieldNames row)
{-| Parse a value at a named column. There are a number of ways to provide
these names, see [`FieldNames`](#FieldNames)
decodeCsv
FieldNamesFromFirstRow
(field "Country" string)
"Country\r\nArgentina"
--> Ok [ "Argentina" ]
-}
field : String -> Decoder a -> Decoder a
field name (Decoder decoder) =
Decoder (\_ fieldNames row -> decoder (Field_ name) fieldNames row)
-- RUN DECODERS
{-| Where do we get names for use with [`field`](#field)?
- `NoFieldNames`: don't get field names at all. [`field`](#field) will
always fail.
- `CustomFieldNames`: use the provided field names in order (so `["Id", "Name"]`
will mean that "Id" is in column 0 and "Name" is in column 1.)
- `FieldNamesFromFirstRow`: use the first row of the CSV as the source of
field names.
-}
type FieldNames
= NoFieldNames
| CustomFieldNames (List String)
| FieldNamesFromFirstRow
getFieldNames : FieldNames -> List (List String) -> Result Error ( Dict String Int, Int, List (List String) )
getFieldNames headers rows =
let
fromList : List String -> Dict String Int
fromList names =
names
|> List.foldl
(\name ( soFar, i ) ->
( Dict.insert name i soFar
, i + 1
)
)
( Dict.empty, 0 )
|> Tuple.first
in
case headers of
NoFieldNames ->
Ok ( Dict.empty, 0, rows )
CustomFieldNames names ->
Ok ( fromList names, 0, rows )
FieldNamesFromFirstRow ->
case rows of
[] ->
Err NoFieldNamesOnFirstRow
first :: rest ->
Ok ( fromList (List.map String.trim first), 1, rest )
{-| Convert a CSV string into some type you care about using the
[`Decoder`](#Decoder)s in this module!
-}
decodeCsv : FieldNames -> Decoder a -> String -> Result Error (List a)
decodeCsv =
decodeCustom { fieldSeparator = ',' }
{-| Convert something shaped roughly like a CSV. For example, to decode
a TSV (_tab_-separated values) string:
decodeCustom { fieldSeparator = '\t' }
NoFieldNames
(map2 Tuple.pair
(column 0 int)
(column 1 string)
)
"1\tBrian\n2\tAtlas"
--> Ok [ ( 1, "PI:NAME:<NAME>END_PI" ), ( 2, "PI:NAME:<NAME>END_PI" ) ]
-}
decodeCustom : { fieldSeparator : Char } -> FieldNames -> Decoder a -> String -> Result Error (List a)
decodeCustom config fieldNames decoder source =
Parser.parse config source
|> Result.mapError ParsingError
|> Result.andThen (applyDecoder fieldNames decoder)
applyDecoder : FieldNames -> Decoder a -> List (List String) -> Result Error (List a)
applyDecoder fieldNames (Decoder decode) allRows =
let
defaultLocation : Location
defaultLocation =
OnlyColumn_
in
Result.andThen
(\( resolvedNames, firstRowNumber, rows ) ->
rows
|> List.foldl
(\row ( soFar, rowNum ) ->
( case decode defaultLocation resolvedNames rowNum row of
Ok val ->
case soFar of
Ok values ->
Ok (val :: values)
Err errs ->
Err errs
Err err ->
case soFar of
Ok _ ->
Err [ err ]
Err errs ->
Err (err :: errs)
, rowNum + 1
)
)
( Ok [], firstRowNumber )
|> Tuple.first
|> Result.map List.reverse
|> Result.mapError (DecodingErrors << List.reverse)
)
(getFieldNames fieldNames allRows)
{-| Sometimes we cannot decode every row in a CSV. This is how we tell
you what went wrong. If you need to present this to someone, you can get a
human-readable version with [`errorToString`](#errorToString)
Some more detail:
- `ParsingError`: there was a problem parsing the CSV into rows and
columns. All these errors have to do with quoting issues. Check that
any quoted fields are closed and that quotes are escaped.
- `NoFieldNamesOnFirstRow`: we tried to get the field names from the first
row (using [`FieldNames`](#FieldNames)) but couldn't find any, probably
because the input was blank.
- `DecodingErrors`: we couldn't decode a value using the specified
decoder. See [`Problem`](#Problem) for more details.
-}
type Error
= ParsingError Parser.Problem
| NoFieldNamesOnFirstRow
| DecodingErrors
(List
{ row : Int
, column : Column
, problems : List Problem
}
)
{-| Where did the problem happen?
- `Column`: at the given column number
- `Field`: at the given named column (with optional column number if we were
able to look up what column we _should_ have found.)
- `OnlyColumn`: at the only column in the row
-}
type Column
= Column Int
| Field String (Maybe Int)
| OnlyColumn
locationToColumn : Dict String Int -> Location -> Column
locationToColumn fieldNames location =
case location of
Column_ i ->
Column i
Field_ name ->
Field name (Dict.get name fieldNames)
OnlyColumn_ ->
OnlyColumn
{-| Things that can go wrong while decoding:
- `ColumnNotFound Int` and `FieldNotFound String`: we looked for the
specified column, but couldn't find it. The argument specifies where we
tried to look.
- `FieldNotProvided String`: we looked for a specific field, but it wasn't
present in the first row or the provided field names (depending on your
configuration.)
- `ExpectedOneColumn Int`: basic decoders like [`string`](#string) and
[`int`](#int) expect to find a single column per row. If there are multiple
columns, and you don't specify which to use with [`column`](#column)
or [`field`](#field), you'll get this error. The argument says how many
columns we found.
- `ExpectedInt String` and `ExpectedFloat String`: we failed to parse a
string into a number. The argument specifies the string we got.
- `Failure`: we got a custom failure message from [`fail`](#fail).
-}
type Problem
= ColumnNotFound Int
| FieldNotFound String
| FieldNotProvided String
| ExpectedOneColumn Int
| ExpectedInt String
| ExpectedFloat String
| Failure String
{-| Produce a human-readable version of an [`Error`](#Error)?!
-}
errorToString : Error -> String
errorToString error =
case error of
ParsingError (Parser.SourceEndedWithoutClosingQuote row) ->
"The source ended on row " ++ String.fromInt row ++ " in a quoted field without a closing quote."
ParsingError (Parser.AdditionalCharactersAfterClosingQuote row) ->
"On row " ++ String.fromInt row ++ " in the source, there were additional characters in a field after a closing quote."
NoFieldNamesOnFirstRow ->
"I expected to see field names on the first row, but there were none."
DecodingErrors errs ->
let
problemString : Problem -> String
problemString problem =
case problem of
ColumnNotFound i ->
"I couldn't find column #" ++ String.fromInt i ++ "."
FieldNotFound name ->
"I couldn't find the `" ++ name ++ "` column."
FieldNotProvided name ->
"The `" ++ name ++ "` field wasn't provided in the field names."
ExpectedOneColumn howMany ->
"I expected exactly one column, but there were " ++ String.fromInt howMany ++ "."
ExpectedInt notInt ->
"I could not parse an int from `" ++ notInt ++ "`."
ExpectedFloat notFloat ->
"I could not parse a float from `" ++ notFloat ++ "`."
Failure custom ->
custom
rowAndColumnString : { a | row : Int, column : Column } -> String
rowAndColumnString err =
"row "
++ String.fromInt err.row
++ ", "
++ (case err.column of
Column col ->
"column " ++ String.fromInt col
Field name Nothing ->
"in the `" ++ name ++ "` field"
Field name (Just col) ->
"in the `" ++ name ++ "` field (column " ++ String.fromInt col ++ ")"
OnlyColumn ->
"column 0 (the only column present)"
)
errString : { row : Int, column : Column, problems : List Problem } -> String
errString err =
case List.map problemString err.problems of
[] ->
"There was an internal error while generating an error on "
++ rowAndColumnString err
++ " and I don't have any info about what went wrong. Please open an issue!"
[ only ] ->
"There was a problem on "
++ rowAndColumnString err
++ ": "
++ only
many ->
"There were some problems on "
++ rowAndColumnString err
++ ":\n\n"
++ String.join "\n" (List.map (\problem -> " - " ++ problem) many)
in
case errs of
[] ->
"Something went wrong, but I got an blank error list so I don't know what it was. Please open an issue!"
[ only ] ->
errString only
many ->
"I saw "
++ String.fromInt (List.length many)
++ " problems while decoding this CSV:\n\n"
++ String.join "\n\n" (List.map errString errs)
-- MAPPING
{-| Transform a decoded value.
decodeCsv NoFieldNames (map (\i -> i * 2) int) "15"
--> Ok [ 30 ]
decodeCsv NoFieldNames (map String.reverse string) "slap"
--> Ok [ "pals" ]
-}
map : (from -> to) -> Decoder from -> Decoder to
map transform (Decoder decoder) =
Decoder (\location fieldNames rowNum row -> decoder location fieldNames rowNum row |> Result.map transform)
{-| Combine two decoders to make something else.
decodeCsv NoFieldNames
(map2 Tuple.pair
(column 0 int)
(column 1 string)
)
"1,Atlas"
--> Ok [ (1, "Atlas") ]
-}
map2 : (a -> b -> c) -> Decoder a -> Decoder b -> Decoder c
map2 transform (Decoder decodeA) (Decoder decodeB) =
Decoder
(\location fieldNames rowNum row ->
Result.map2 transform
(decodeA location fieldNames rowNum row)
(decodeB location fieldNames rowNum row)
)
{-| Like [`map2`](#map2), but with three decoders. `map4` and beyond don't
exist in this package. Use [`into`](#into) to decode records instead!
decodeCsv NoFieldNames
(map3 (\r g b -> (r, g, b))
(column 0 int)
(column 1 int)
(column 2 int)
)
"255,255,0"
--> Ok [ (255, 255, 0) ]
-}
map3 : (a -> b -> c -> d) -> Decoder a -> Decoder b -> Decoder c -> Decoder d
map3 transform (Decoder decodeA) (Decoder decodeB) (Decoder decodeC) =
Decoder
(\location fieldNames rowNum row ->
Result.map3 transform
(decodeA location fieldNames rowNum row)
(decodeB location fieldNames rowNum row)
(decodeC location fieldNames rowNum row)
)
{-| Combine an arbitrary amount of fields. You provide a function that takes
as many arguments as you need, then send it values by providing decoders with
[`pipeline`](#pipeline).
type alias Pet =
{ id : Int
, name : String
, species : String
, weight : Float
}
petDecoder : Decoder Pet
petDecoder =
into Pet
|> pipeline (column 0 int)
|> pipeline (column 1 string)
|> pipeline (column 2 string)
|> pipeline (column 3 float)
Now you can decode pets like this:
decodeCsv NoFieldNames petDecoder "1,Atlas,cat,14\r\n2,Axel,puffin,1.37"
--> Ok
--> [ { id = 1, name = "PI:NAME:<NAME>END_PI", species = "cat", weight = 14 }
--> , { id = 2, name = "PI:NAME:<NAME>END_PI", species = "puffin", weight = 1.37 }
--> ]
-}
into : (a -> b) -> Decoder (a -> b)
into =
succeed
{-| See [`into`](#into).
-}
pipeline : Decoder a -> Decoder (a -> b) -> Decoder b
pipeline =
map2 (\value fn -> fn value)
-- FANCY DECODING
{-| Try several possible decoders in sequence, committing to the first one
that passes.
decodeCsv NoFieldNames
(oneOf
(map Just int)
[ succeed Nothing ]
)
"1"
--> Ok [ Just 1 ]
decodeCsv NoFieldNames
(oneOf
(map Just int)
[ succeed Nothing ]
)
"a"
--> Ok [ Nothing ]
-}
oneOf : Decoder a -> List (Decoder a) -> Decoder a
oneOf first rest =
case rest of
[] ->
first
next :: others ->
recover first (oneOf next others)
recover : Decoder a -> Decoder a -> Decoder a
recover (Decoder first) (Decoder second) =
Decoder <|
\location fieldNames rowNum row ->
case first location fieldNames rowNum row of
Ok value ->
Ok value
Err err ->
case second location fieldNames rowNum row of
Ok value ->
Ok value
Err { problems } ->
Err { err | problems = err.problems ++ problems }
{-| Decode some value _and then_ make a decoding decision based on the
outcome. For example, if you wanted to reject negative numbers, you might
do something like this:
positiveInt : Decoder Int
positiveInt =
int
|> andThen
(\rawInt ->
if rawInt < 0 then
Decode.fail "Only positive numbers allowed!"
else
Decode.succeed rawInt
)
You could then use it like this:
decodeCsv NoFieldNames positiveInt "1" -- Ok [ 1 ]
decodeCsv NoFieldNames positiveInt "-1"
-- Err { row = 0, problem = Failure "Only positive numbers allowed!" }
-}
andThen : (a -> Decoder b) -> Decoder a -> Decoder b
andThen next (Decoder first) =
Decoder
(\location fieldNames rowNum row ->
first location fieldNames rowNum row
|> Result.andThen
(\nextValue ->
let
(Decoder final) =
next nextValue
in
final location fieldNames rowNum row
)
)
{-| Always succeed, no matter what. Mostly useful with [`andThen`](#andThen).
-}
succeed : a -> Decoder a
succeed value =
Decoder (\_ _ _ _ -> Ok value)
{-| Always fail with the given message, no matter what. Mostly useful with
[`andThen`](#andThen).
-}
fail : String -> Decoder a
fail message =
Decoder
(\location fieldNames rowNum _ ->
Err
{ row = rowNum
, column = locationToColumn fieldNames location
, problems = [ Failure message ]
}
)
{-| Make creating custom decoders a little easier. If you already have a
function that parses into something you care about, you can combine it with
this.
For example, here's how you could parse a hexadecimal number with
[`rtfeldman/elm-hex`](https://package.elm-lang.org/packages/rtfeldman/elm-hex/latest/):
import Hex
hex : Decoder Int
hex =
andThen
(\value -> fromResult (Hex.fromString value))
string
decodeCsv NoFieldNames hex "ff"
--> Ok [ 255 ]
-}
fromResult : Result String a -> Decoder a
fromResult result =
case result of
Ok great ->
succeed great
Err problem ->
fail problem
{-| Like [`fromResult`](#fromResult) but you have to specify the error
message since `Nothing` has no further information.
For example, you could implement something like [`int`](#int) using this:
myInt : Decoder Int
myInt =
andThen
(\value ->
fromMaybe "Expected an int"
(String.toInt value)
)
string
decodeCsv NoFieldNames myInt "123"
--> Ok [ 123 ]
(That said, you probably want to use [`int`](#int) instead... it has better
error messages and is more tolerant of unusual situations!)
-}
fromMaybe : String -> Maybe a -> Decoder a
fromMaybe problem maybe =
case maybe of
Just value ->
succeed value
Nothing ->
fail problem
| elm |
[
{
"context": "M de la Vallée Verte de la \n Couze Chambon qui regroupe les communes de Chambon \n ",
"end": 2759,
"score": 0.9355800748,
"start": 2746,
"tag": "NAME",
"value": "Couze Chambon"
},
{
"context": " Murol, Saint-Nectaire et Saint-Victor-la-Rivière. Sébastien GOUTTEBEL, \n le maire de Murol, est l",
"end": 2899,
"score": 0.9998685718,
"start": 2880,
"tag": "NAME",
"value": "Sébastien GOUTTEBEL"
},
{
"context": " [text \"Le secrétariat du SIVOM est assuré par Frédérique \n Heitz, dans les locaux de l",
"end": 3142,
"score": 0.9527310729,
"start": 3132,
"tag": "NAME",
"value": "Frédérique"
},
{
"context": "OM est assuré par Frédérique \n Heitz, dans les locaux de la mairie de \n ",
"end": 3170,
"score": 0.8174504042,
"start": 3165,
"tag": "NAME",
"value": "Heitz"
},
{
"context": " par la \n cuisinière du SIVOM, Monique Picot. Un repas «bio» \n est servi a",
"end": 7546,
"score": 0.9998687506,
"start": 7533,
"tag": "NAME",
"value": "Monique Picot"
},
{
"context": "par les personnels du \n SIVOM, Karine Fouquet, Emmanuelle Delorme et Florence Planeix. \"]\n ",
"end": 7743,
"score": 0.9998731613,
"start": 7729,
"tag": "NAME",
"value": "Karine Fouquet"
},
{
"context": "ls du \n SIVOM, Karine Fouquet, Emmanuelle Delorme et Florence Planeix. \"]\n , p [] [ text \"Les ",
"end": 7763,
"score": 0.9998742938,
"start": 7745,
"tag": "NAME",
"value": "Emmanuelle Delorme"
},
{
"context": " SIVOM, Karine Fouquet, Emmanuelle Delorme et Florence Planeix. \"]\n , p [] [ text \"Les enfants sont tenus d",
"end": 7783,
"score": 0.9998701811,
"start": 7767,
"tag": "NAME",
"value": "Florence Planeix"
},
{
"context": "ac. \"]\n , p [] [text \"Ils sont surveillés par Karine Fouquet (et Frédérique \n Heitz sur les",
"end": 11291,
"score": 0.9998944402,
"start": 11277,
"tag": "NAME",
"value": "Karine Fouquet"
},
{
"context": "Karine Fouquet (et Frédérique \n Heitz sur les créneaux de plus forte affluence). \"]\n",
"end": 11330,
"score": 0.7082388401,
"start": 11328,
"tag": "NAME",
"value": "He"
},
{
"context": " , tr []\n -- [ td [] [text \"Maternelle de Murol\"]\n -- , td [] [text \"Mardi et ven",
"end": 14618,
"score": 0.9537964463,
"start": 14599,
"tag": "NAME",
"value": "Maternelle de Murol"
},
{
"context": "lle de Murol\"]\n -- , td [] [text \"Mardi et vendredi\"]\n -- , td [] [text \"15h00 à 16h3",
"end": 14673,
"score": 0.9862654209,
"start": 14656,
"tag": "NAME",
"value": "Mardi et vendredi"
},
{
"context": "5h00 à 16h30\"]\n -- , td [] [text \"Karine Fouquet\"]\n -- , td [] [a [href \"/baseDocu",
"end": 14776,
"score": 0.9998419881,
"start": 14762,
"tag": "NAME",
"value": "Karine Fouquet"
},
{
"context": " , tr []\n -- [ td [] [text \"Elémentaire de Murol\"]\n -- , td [] [text \"Lundi et jeu",
"end": 15027,
"score": 0.9188513756,
"start": 15007,
"tag": "NAME",
"value": "Elémentaire de Murol"
},
{
"context": "5h00 à 16h30\"]\n -- , td [] [text \"Frédérique Heitz\"]\n -- , td [] [a [href \"/baseDocu",
"end": 15184,
"score": 0.9995734692,
"start": 15168,
"tag": "NAME",
"value": "Frédérique Heitz"
},
{
"context": " , tr []\n -- [ td [] [text \"Elémentaire du Chambon\"]\n -- , td [] [text \"Lundi et jeu",
"end": 15422,
"score": 0.9727365375,
"start": 15400,
"tag": "NAME",
"value": "Elémentaire du Chambon"
},
{
"context": "5h15 à 16h45\"]\n -- , td [] [text \"Karine Fouquet\"]\n -- , td [] [a [href \"/baseDocu",
"end": 15577,
"score": 0.9998087883,
"start": 15563,
"tag": "NAME",
"value": "Karine Fouquet"
},
{
"context": " , tr []\n -- [ td [] [text \"Primaire de St Nectaire\"]\n -- , td [] [text \"Mardi et ven",
"end": 15825,
"score": 0.9927660227,
"start": 15802,
"tag": "NAME",
"value": "Primaire de St Nectaire"
},
{
"context": " St Nectaire\"]\n -- , td [] [text \"Mardi et vendredi\"]\n -- , td [] [text \"15h00 à 16h3",
"end": 15880,
"score": 0.9969975948,
"start": 15863,
"tag": "NAME",
"value": "Mardi et vendredi"
},
{
"context": "5h00 à 16h30\"]\n -- , td [] [text \"Frédérique Heitz\"]\n -- , td [] [a [href \"/baseDocu",
"end": 15985,
"score": 0.9997723699,
"start": 15969,
"tag": "NAME",
"value": "Frédérique Heitz"
}
] | src/Periscolaire.elm | eniac314/mairieMurol | 0 | module Periscolaire 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 TiledMenu exposing (initAtWithLink,view,update,Action)
import StarTable exposing (makeTable, emptyTe, Label(..))
import Utils exposing (mainMenu,
renderMainMenu,
pageFooter,
capitalize,
renderListImg,
logos,
renderSubMenu,
mail,
site,
link)
-- Model
subMenu : Utils.Submenu
subMenu = { current = "", entries = []}
type alias MainContent =
{ wrapper : (Html -> Bool -> Html)
, tiledMenu : TiledMenu.Model
}
type alias Model =
{ mainMenu : Utils.Menu
, subMenu : Utils.Submenu
, mainContent : MainContent
, showIntro : Bool
}
initialModel =
{ mainMenu = mainMenu
, subMenu = subMenu
, mainContent = initialContent
, showIntro = if String.isEmpty locationSearch
then True
else False
}
-- View
view : Signal.Address Action -> Model -> Html
view address model =
div [ id "container"]
[ renderMainMenu ["Vie locale", "Péri et extra-scolaire"]
(.mainMenu model)
, div [ id "subContainer"]
[ (.wrapper (.mainContent model))
(TiledMenu.view (Signal.forwardTo address TiledMenuAction) (.tiledMenu (.mainContent model)))
(.showIntro model)
]
, pageFooter
]
-- Update
type Action =
NoOp
| TiledMenuAction (TiledMenu.Action)
update : Action -> Model -> Model
update action model =
case action of
NoOp -> model
TiledMenuAction act ->
let mc = (.mainContent model)
tm = (.tiledMenu (.mainContent model))
in
{ model |
showIntro = not (.showIntro model)
, mainContent =
{ mc | tiledMenu = TiledMenu.update act tm }
}
--Main
main =
StartApp.start
{ model = initialModel
, view = view
, update = update
}
port locationSearch : String
initialContent =
{ wrapper =
(\content showIntro ->
div [ class "subContainerData noSubmenu", id "periscolaire"]
[ h2 [] [ text "Péri et extra-scolaire"]
, p [classList [("intro",True),("displayIntro", showIntro)]]
[text "Les compétences péri et extrascolaires sont portées par
le SIVOM de la Vallée Verte de la
Couze Chambon qui regroupe les communes de Chambon
sur Lac, Murol, Saint-Nectaire et Saint-Victor-la-Rivière. Sébastien GOUTTEBEL,
le maire de Murol, est le président du
SIVOM. "]
, p [classList [("intro",True),("displayIntro", showIntro)]]
[text "Le secrétariat du SIVOM est assuré par Frédérique
Heitz, dans les locaux de la mairie de
Murol. Elle vous accueille les lundis, mardis et
jeudis de 9h30 à 12h30 dans son bureau
au 1er étage ou par téléphone au 04
73 88 60 67. "]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS MUROL 2017-2018.pdf"
-- , target "_blank"]
-- [ text "fiche de renseignements Murol"]
-- ]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS CHAMBON 2017 2018.pdf"
-- , target "_blank"]
-- [ text "fiche de renseignements Chambon"]
-- ]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS ST NECTAIRE 2017-2018.pdf"
-- , target "_blank"]
-- [ text "fiche de renseignements Saint-Nectaire"]
-- ]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/reglementCharte.pdf"
-- , target "_blank"]
-- [ text "règlement intérieur et charte du savoir vivre"]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie murol 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie chambon 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS ST NECTAIRE 2017-2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Saint-Nectaire"]
-- ]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
, target "_blank"]
[ text "Charte du savoir-vivre"]
]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/règlement sivom 2018.pdf"
-- , target "_blank"]
-- [ text "Règlement intérieur"]
--]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf"
, target "_blank"]
[ text "Règlement et tarifs SIVOM juin 2018"]
]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
-- , target "_blank"]
-- [ text "charte du savoir vivre"]
-- ]
, content])
, tiledMenu =
initAtWithLink locationSearch peri
}
-- Data
peri =
[ ("Restaurant scolaire"
,"/images/tiles/periscolaire/restaurant scolaire.jpg"
, [ p [] [ text "Le restaurant scolaire est un service non obligatoire
assuré par le SIVOM de la Vallée Verte.
Il accueille les enfants de la maternelle et
de l’école élémentaire de Murol les lundis, mardis,
jeudis et vendredis de 12h à 13h30. "]
, p [] [ text "Les enfants déjeunent en deux services (petits puis
grands) pour limiter le bruit dans le réfectoire. "]
, p [] [ text "Les repas sont préparés sur place par la
cuisinière du SIVOM, Monique Picot. Un repas «bio»
est servi aux enfants une fois par mois. "]
, p [] [ text "La surveillance est assurée par les personnels du
SIVOM, Karine Fouquet, Emmanuelle Delorme et Florence Planeix. "]
, p [] [ text "Les enfants sont tenus de se comporter correctement,
selon les préconisations détaillées dans la charte du
savoir-vivre et le règlement intérieur. En cas de
problème de discipline, les parents sont informés par
le biais d’avertissements remis aux enfants."]
, p [] [ text "Si votre enfant présente des allergies alimentaires, un
protocole devra être établi avant qu’il ne soit
accueilli au restaurant scolaire (PAI). "]
, p [] [ text "Le montant de la participation des familles est fonction des revenus
de celles-ci (tarification selon le quotient familial): "]
, table [ id "quotient"]
[ tr [ class "quotLine"]
[ td [] [ text "Quotient familial"]
, td [] [ text "de 0 à 350€"]
, td [] [ text "de 351 à 500€"]
, td [] [ text "de 501 à 600€"]
, td [] [ text "plus de 600€"]
]
, tr [ class "quotAltLine"]
[ td [] [ text "Tarif maternelle"]
, td [] [ text "2,10€"]
, td [] [ text "2,50€"]
, td [] [ text "2,80€"]
, td [] [ text "3,05€"]
]
, tr [ class "quotLine"]
[ td [] [ text "Tarif élémentaire"]
, td [] [ text "2,10€"]
, td [] [ text "2,60€"]
, td [] [ text "2,95€"]
, td [] [ text "3,20€"]
]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie murol 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie chambon 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
, target "_blank"]
[ text "Charte du savoir-vivre"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf"
, target "_blank"]
[ text "Règlement et tarifs SIVOM juin 2018"]
]
]
,"")
, ("Garderie périscolaire"
,"/images/tiles/periscolaire/garderie.jpg"
, [ p [] [text "La garderie périscolaire est un service non obligatoire
assuré par le SIVOM de la Vallée Verte.
Ce service est subventionné par la CAF et
la MSA. "]
, text "La garderie est ouverte: "
, ul []
[ li [] [text "le matin de 7h à 9h les lundis,
mardis, mercredis, jeudis et vendredis"]
, li [] [text "le soir de 16h30 à 19h les lundis,
mardis, jeudis et vendredis. "]
]
, p [] [text "La garderie accueille les enfants de la maternelle
de Murol ainsi que des écoles élémentaires de
Murol et de Chambon sur Lac. "]
, p [] [text "Ils sont surveillés par Karine Fouquet (et Frédérique
Heitz sur les créneaux de plus forte affluence). "]
, p [] [text "La garderie est un temps de détente et
de jeux libres. Mais pour le bien-être de
tous, les enfants sont tenus de se comporter
correctement, selon les préconisations détaillées dans la charte
du savoir-vivre et le règlement intérieur. En cas
de problème de discipline, les parents sont informés
par le biais d’avertissements remis aux enfants. "]
, text "La participation des familles est fonction des revenus
de celles-ci : "
, ul []
[ li [] [text "Familles non-imposables : 1,25€ de l’heure "]
, li [] [text "Familles imposables : 1,45€ de l’heure "]
]
, p [] [text "NB : le créneau 16h30/18h est facturé comme
1 heure. "]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie murol 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie chambon 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
, target "_blank"]
[ text "Charte du savoir-vivre"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf"
, target "_blank"]
[ text "Règlement et tarifs SIVOM juin 2018"]
]
]
,""
)
, ("Temps d'activités périscolaires (TAP)"
,"/images/tiles/periscolaire/TAP.jpg"
,[ p []
[text "Les écoles des communes du SIVOM de la Vallée Verte verront leurs rythmes scolaires modifiés à la rentrée 2018. Les élèves auront classe sur 4 jours, les lundis, mardis, jeudis et vendredis. Le SIVOM de la Vallée Verte a donc délibéré pour la suppression des temps d'activités périscolaires (TAP)."]
--p [] [text "L’organisation des activités périscolaires dans les quatre écoles
-- de la vallée est réalisée par le SIVOM
-- dans le cadre d’un projet éducatif territorial qui
-- garantit un encadrement de qualité pour les enfants
-- et une programmation qui répond à des objectifs
-- éducatifs. Le financement est assuré par le SIVOM,
-- l’Etat, la CAF et la participation des parents."]
-- , p [] [text "Les enfants inscrits bénéficient de deux séances d’activités
-- hebdomadaires: "]
-- , table [ id "tableTAP"]
-- [ tr []
-- [ th [] [text "ECOLE"]
-- , th [] [text "JOURS DE TAP"]
-- , th [] [text "HORAIRES DE TAP"]
-- , th [] [text "DIRECTION"]
-- , th [] [text "PROGRAMMES"]
-- ]
-- , tr []
-- [ td [] [text "Maternelle de Murol"]
-- , td [] [text "Mardi et vendredi"]
-- , td [] [text "15h00 à 16h30"]
-- , td [] [text "Karine Fouquet"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/PROGRAMME TAP MATERNELLE 2017 2018.pdf", target "_blank"] [text "maternelle"]]
-- ]
-- , tr []
-- [ td [] [text "Elémentaire de Murol"]
-- , td [] [text "Lundi et jeudi"]
-- , td [] [text "15h00 à 16h30"]
-- , td [] [text "Frédérique Heitz"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/murol tap jusqu'à Pâques.pdf", target "_blank"] [text "Murol"]]
-- ]
-- , tr []
-- [ td [] [text "Elémentaire du Chambon"]
-- , td [] [text "Lundi et jeudi"]
-- , td [] [text "15h15 à 16h45"]
-- , td [] [text "Karine Fouquet"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/PROGRAMME TAP CHAMBON 2017 2018.pdf", target "_blank"] [text "Chambon"]]
-- ]
-- , tr []
-- [ td [] [text "Primaire de St Nectaire"]
-- , td [] [text "Mardi et vendredi"]
-- , td [] [text "15h00 à 16h30"]
-- , td [] [text "Frédérique Heitz"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/tap st nectaire jusqu'à Pâques.pdf", target "_blank"] [text "Saint-Nectaire"]]
-- ]
-- ]
-- , p [] [text "L’inscription est annuelle et la participation
-- des familles est de 12€ par trimestre et par enfant."]
-- , p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS MUROL 2017-2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
-- ]
-- , p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS CHAMBON 2017 2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
-- ]
-- , p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS ST NECTAIRE 2017-2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Saint-Nectaire"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/TAP murol 2017 rentrée à toussaint-1.pdf"
-- , target "_blank"]
-- [ text "programme TAP Murol - rentrée à Toussaint"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/PROGRAMME TAP CHAMBON 2017 2018.pdf"
-- , target "_blank"]
-- [ text "programme annuel TAP Chambon"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/TAP St Nect 2017 rentrée à toussaint-1.pdf"
-- , target "_blank"]
-- [ text "programme TAP Saint-Nectaire - rentrée à Toussaint"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/PROGRAMME TAP MATERNELLE 2017 2018.pdf"
-- , target "_blank"]
-- [ text "programme TAP Maternelle"]
-- ]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/délibération rythmes scolaires.pdf"
, target "_blank"]
[ text "Délibération rythmes scolaires"]
]
]
,""
)
, ("Centre de loisirs"
,"/images/tiles/periscolaire/centre de loisirs.jpg"
, [ p [] [text "Le Centre de Loisirs du SIVOM de la
Vallée Verte propose d’accueillir les enfants des communes
de Chambon sur Lac, Murol, Saint-Nectaire et Saint-Victor-la-Rivière,
ayant 3 ans révolus
et déjà inscrits dans un établissement scolaire."]
, text "Il sera ouvert dans les locaux de l’école
maternelle de Murol du lundi au vendredi de
8h à 18h:"
, ul []
[ li [] [text "Du 12 au 23 février 2018"]
--li [] [text "Du 20 février au 3 mars 2017"]
, li [] [text "Du 9 au 20 avril 2018"
]
, li [] [text "Du 9 juillet au 24 août 2018"
]
]
--, p [] [ a [ href "/baseDocumentaire/periscolaire/PROJET PEDAGOGIQUE ET PROGRAMME JUILLET 2017.pdf", target "_blank"]
-- [ text "programme des activités et projet pédagogique - Juillet 2017"]
-- ]
--, p [] [ a [ href "/baseDocumentaire/periscolaire/planning activités avril 2018.pdf", target "_blank"]
-- [ text "programme des activités et projet pédagogique - Juillet 2018"]
-- ]
, p [] [a [ href "/baseDocumentaire/periscolaire/plaquette clsh été 2018.pdf"
, target "_blank"
]
[ text "plaquette de présentation du centre de loisirs été" ]
]
, p [] [ a [ href "/baseDocumentaire/periscolaire/PROJET PEDAGOGIQUE karine juillet 2018.pdf", target "_blank"]
[ text "programme des activités et projet pédagogique - Juillet 2018"]
]
, p [] [ a [ href "/baseDocumentaire/periscolaire/planning août 2018.pdf", target "_blank"]
[ text "programme des activités - Août 2018"]
]
, p [] [ a [ href "/baseDocumentaire/periscolaire/PP aout 2018.pdf", target "_blank"]
[ text "projet pédagogique - Août 2018"]
]
--, p [] [ a [href "/baseDocumentaire/periscolaire/préinscription clsh avril 2018.pdf", target "_blank"]
-- [text "la fiche de préinscription CLSH"]
-- ]
, p [] [ a [href "/baseDocumentaire/periscolaire/dossier inscription Centre Aéré été 2018.pdf", target "_blank"]
[text "la fiche d’inscription CLSH"]
]
, p [] [text "Des enfants d’autres communes d’origine, de la population
touristique notamment, pourront être également accueillis, dans la
limite des places disponibles. "]
, p [] [text "Les familles pourront inscrire leurs enfants à la
semaine, à la journée ou à la demi-journée
avec ou sans repas. Un service de ramassage
est assuré matin et soir. "]
, p [] [text "Ce service est subventionné par la CAF et
la MSA. La participation des familles est fonction
des revenus de celles-ci ("
,a [href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf", target "_blank"]
[text "règlement et tarifs SIVOM juin 2018"]
,text ")"
]
, text "Liens:"
, p [] [a [href "/baseDocumentaire/periscolaire/PROJET EDUCATIF 2018.pdf", target "_blank"]
[text "Projet éducatif du centre de loisirs du SIVOM de la Vallée Verte"]]
--, p [] [a [href "/baseDocumentaire/periscolaire/projet pédagogique avril 2018.pdf", target "_blank"]
-- [text "Projet pédagogique vacances de printemps "]
-- ]
--, p [] [a [ href "/baseDocumentaire/periscolaire/plaquette CLSH 2017.pdf"
-- , target "_blank"
-- ]
-- [ text "Tarifs SIVOM 2017" ]
-- ]
--, p [] [a [ href "/baseDocumentaire/periscolaire/plaquette 2017 centre de loisirs printemps.pdf"
-- , target "_blank"
-- ]
-- [ text "Plaquette de présentation du centre de loisirs printemps" ]
-- ]
]
,""
)
, ("Transport scolaire"
,"/images/tiles/periscolaire/navette.jpg"
, [
--p [] [ text "Pour le transport scolaire, la participation des familles
-- a été fixée forfaitairement par le Conseil Général
-- pour l’année scolaire 2008 / 2009 à 12,80€
-- par mois (64€ par mois pour les élèves
-- non subventionnés)."]
]
,"http://www.puy-de-dome.fr/transports/transports-scolaires/bus-scolaire.html"
)
, ("Activités jeunesse de la communauté de communes"
,"/images/tiles/periscolaire/actiJeunesse.jpg"
,[]
,"http://www.cc-massifdusancy.fr/enfance-jeunesse/activites-jeunesse_5675.cfm"
)
]
| 47647 | module Periscolaire 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 TiledMenu exposing (initAtWithLink,view,update,Action)
import StarTable exposing (makeTable, emptyTe, Label(..))
import Utils exposing (mainMenu,
renderMainMenu,
pageFooter,
capitalize,
renderListImg,
logos,
renderSubMenu,
mail,
site,
link)
-- Model
subMenu : Utils.Submenu
subMenu = { current = "", entries = []}
type alias MainContent =
{ wrapper : (Html -> Bool -> Html)
, tiledMenu : TiledMenu.Model
}
type alias Model =
{ mainMenu : Utils.Menu
, subMenu : Utils.Submenu
, mainContent : MainContent
, showIntro : Bool
}
initialModel =
{ mainMenu = mainMenu
, subMenu = subMenu
, mainContent = initialContent
, showIntro = if String.isEmpty locationSearch
then True
else False
}
-- View
view : Signal.Address Action -> Model -> Html
view address model =
div [ id "container"]
[ renderMainMenu ["Vie locale", "Péri et extra-scolaire"]
(.mainMenu model)
, div [ id "subContainer"]
[ (.wrapper (.mainContent model))
(TiledMenu.view (Signal.forwardTo address TiledMenuAction) (.tiledMenu (.mainContent model)))
(.showIntro model)
]
, pageFooter
]
-- Update
type Action =
NoOp
| TiledMenuAction (TiledMenu.Action)
update : Action -> Model -> Model
update action model =
case action of
NoOp -> model
TiledMenuAction act ->
let mc = (.mainContent model)
tm = (.tiledMenu (.mainContent model))
in
{ model |
showIntro = not (.showIntro model)
, mainContent =
{ mc | tiledMenu = TiledMenu.update act tm }
}
--Main
main =
StartApp.start
{ model = initialModel
, view = view
, update = update
}
port locationSearch : String
initialContent =
{ wrapper =
(\content showIntro ->
div [ class "subContainerData noSubmenu", id "periscolaire"]
[ h2 [] [ text "Péri et extra-scolaire"]
, p [classList [("intro",True),("displayIntro", showIntro)]]
[text "Les compétences péri et extrascolaires sont portées par
le SIVOM de la Vallée Verte de la
<NAME> qui regroupe les communes de Chambon
sur Lac, Murol, Saint-Nectaire et Saint-Victor-la-Rivière. <NAME>,
le maire de Murol, est le président du
SIVOM. "]
, p [classList [("intro",True),("displayIntro", showIntro)]]
[text "Le secrétariat du SIVOM est assuré par <NAME>
<NAME>, dans les locaux de la mairie de
Murol. Elle vous accueille les lundis, mardis et
jeudis de 9h30 à 12h30 dans son bureau
au 1er étage ou par téléphone au 04
73 88 60 67. "]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS MUROL 2017-2018.pdf"
-- , target "_blank"]
-- [ text "fiche de renseignements Murol"]
-- ]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS CHAMBON 2017 2018.pdf"
-- , target "_blank"]
-- [ text "fiche de renseignements Chambon"]
-- ]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS ST NECTAIRE 2017-2018.pdf"
-- , target "_blank"]
-- [ text "fiche de renseignements Saint-Nectaire"]
-- ]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/reglementCharte.pdf"
-- , target "_blank"]
-- [ text "règlement intérieur et charte du savoir vivre"]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie murol 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie chambon 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS ST NECTAIRE 2017-2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Saint-Nectaire"]
-- ]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
, target "_blank"]
[ text "Charte du savoir-vivre"]
]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/règlement sivom 2018.pdf"
-- , target "_blank"]
-- [ text "Règlement intérieur"]
--]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf"
, target "_blank"]
[ text "Règlement et tarifs SIVOM juin 2018"]
]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
-- , target "_blank"]
-- [ text "charte du savoir vivre"]
-- ]
, content])
, tiledMenu =
initAtWithLink locationSearch peri
}
-- Data
peri =
[ ("Restaurant scolaire"
,"/images/tiles/periscolaire/restaurant scolaire.jpg"
, [ p [] [ text "Le restaurant scolaire est un service non obligatoire
assuré par le SIVOM de la Vallée Verte.
Il accueille les enfants de la maternelle et
de l’école élémentaire de Murol les lundis, mardis,
jeudis et vendredis de 12h à 13h30. "]
, p [] [ text "Les enfants déjeunent en deux services (petits puis
grands) pour limiter le bruit dans le réfectoire. "]
, p [] [ text "Les repas sont préparés sur place par la
cuisinière du SIVOM, <NAME>. Un repas «bio»
est servi aux enfants une fois par mois. "]
, p [] [ text "La surveillance est assurée par les personnels du
SIVOM, <NAME>, <NAME> et <NAME>. "]
, p [] [ text "Les enfants sont tenus de se comporter correctement,
selon les préconisations détaillées dans la charte du
savoir-vivre et le règlement intérieur. En cas de
problème de discipline, les parents sont informés par
le biais d’avertissements remis aux enfants."]
, p [] [ text "Si votre enfant présente des allergies alimentaires, un
protocole devra être établi avant qu’il ne soit
accueilli au restaurant scolaire (PAI). "]
, p [] [ text "Le montant de la participation des familles est fonction des revenus
de celles-ci (tarification selon le quotient familial): "]
, table [ id "quotient"]
[ tr [ class "quotLine"]
[ td [] [ text "Quotient familial"]
, td [] [ text "de 0 à 350€"]
, td [] [ text "de 351 à 500€"]
, td [] [ text "de 501 à 600€"]
, td [] [ text "plus de 600€"]
]
, tr [ class "quotAltLine"]
[ td [] [ text "Tarif maternelle"]
, td [] [ text "2,10€"]
, td [] [ text "2,50€"]
, td [] [ text "2,80€"]
, td [] [ text "3,05€"]
]
, tr [ class "quotLine"]
[ td [] [ text "Tarif élémentaire"]
, td [] [ text "2,10€"]
, td [] [ text "2,60€"]
, td [] [ text "2,95€"]
, td [] [ text "3,20€"]
]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie murol 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie chambon 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
, target "_blank"]
[ text "Charte du savoir-vivre"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf"
, target "_blank"]
[ text "Règlement et tarifs SIVOM juin 2018"]
]
]
,"")
, ("Garderie périscolaire"
,"/images/tiles/periscolaire/garderie.jpg"
, [ p [] [text "La garderie périscolaire est un service non obligatoire
assuré par le SIVOM de la Vallée Verte.
Ce service est subventionné par la CAF et
la MSA. "]
, text "La garderie est ouverte: "
, ul []
[ li [] [text "le matin de 7h à 9h les lundis,
mardis, mercredis, jeudis et vendredis"]
, li [] [text "le soir de 16h30 à 19h les lundis,
mardis, jeudis et vendredis. "]
]
, p [] [text "La garderie accueille les enfants de la maternelle
de Murol ainsi que des écoles élémentaires de
Murol et de Chambon sur Lac. "]
, p [] [text "Ils sont surveillés par <NAME> (et Frédérique
<NAME>itz sur les créneaux de plus forte affluence). "]
, p [] [text "La garderie est un temps de détente et
de jeux libres. Mais pour le bien-être de
tous, les enfants sont tenus de se comporter
correctement, selon les préconisations détaillées dans la charte
du savoir-vivre et le règlement intérieur. En cas
de problème de discipline, les parents sont informés
par le biais d’avertissements remis aux enfants. "]
, text "La participation des familles est fonction des revenus
de celles-ci : "
, ul []
[ li [] [text "Familles non-imposables : 1,25€ de l’heure "]
, li [] [text "Familles imposables : 1,45€ de l’heure "]
]
, p [] [text "NB : le créneau 16h30/18h est facturé comme
1 heure. "]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie murol 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie chambon 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
, target "_blank"]
[ text "Charte du savoir-vivre"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf"
, target "_blank"]
[ text "Règlement et tarifs SIVOM juin 2018"]
]
]
,""
)
, ("Temps d'activités périscolaires (TAP)"
,"/images/tiles/periscolaire/TAP.jpg"
,[ p []
[text "Les écoles des communes du SIVOM de la Vallée Verte verront leurs rythmes scolaires modifiés à la rentrée 2018. Les élèves auront classe sur 4 jours, les lundis, mardis, jeudis et vendredis. Le SIVOM de la Vallée Verte a donc délibéré pour la suppression des temps d'activités périscolaires (TAP)."]
--p [] [text "L’organisation des activités périscolaires dans les quatre écoles
-- de la vallée est réalisée par le SIVOM
-- dans le cadre d’un projet éducatif territorial qui
-- garantit un encadrement de qualité pour les enfants
-- et une programmation qui répond à des objectifs
-- éducatifs. Le financement est assuré par le SIVOM,
-- l’Etat, la CAF et la participation des parents."]
-- , p [] [text "Les enfants inscrits bénéficient de deux séances d’activités
-- hebdomadaires: "]
-- , table [ id "tableTAP"]
-- [ tr []
-- [ th [] [text "ECOLE"]
-- , th [] [text "JOURS DE TAP"]
-- , th [] [text "HORAIRES DE TAP"]
-- , th [] [text "DIRECTION"]
-- , th [] [text "PROGRAMMES"]
-- ]
-- , tr []
-- [ td [] [text "<NAME>"]
-- , td [] [text "<NAME>"]
-- , td [] [text "15h00 à 16h30"]
-- , td [] [text "<NAME>"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/PROGRAMME TAP MATERNELLE 2017 2018.pdf", target "_blank"] [text "maternelle"]]
-- ]
-- , tr []
-- [ td [] [text "<NAME>"]
-- , td [] [text "Lundi et jeudi"]
-- , td [] [text "15h00 à 16h30"]
-- , td [] [text "<NAME>"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/murol tap jusqu'à Pâques.pdf", target "_blank"] [text "Murol"]]
-- ]
-- , tr []
-- [ td [] [text "<NAME>"]
-- , td [] [text "Lundi et jeudi"]
-- , td [] [text "15h15 à 16h45"]
-- , td [] [text "<NAME>"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/PROGRAMME TAP CHAMBON 2017 2018.pdf", target "_blank"] [text "Chambon"]]
-- ]
-- , tr []
-- [ td [] [text "<NAME>"]
-- , td [] [text "<NAME>"]
-- , td [] [text "15h00 à 16h30"]
-- , td [] [text "<NAME>"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/tap st nectaire jusqu'à Pâques.pdf", target "_blank"] [text "Saint-Nectaire"]]
-- ]
-- ]
-- , p [] [text "L’inscription est annuelle et la participation
-- des familles est de 12€ par trimestre et par enfant."]
-- , p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS MUROL 2017-2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
-- ]
-- , p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS CHAMBON 2017 2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
-- ]
-- , p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS ST NECTAIRE 2017-2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Saint-Nectaire"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/TAP murol 2017 rentrée à toussaint-1.pdf"
-- , target "_blank"]
-- [ text "programme TAP Murol - rentrée à Toussaint"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/PROGRAMME TAP CHAMBON 2017 2018.pdf"
-- , target "_blank"]
-- [ text "programme annuel TAP Chambon"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/TAP St Nect 2017 rentrée à toussaint-1.pdf"
-- , target "_blank"]
-- [ text "programme TAP Saint-Nectaire - rentrée à Toussaint"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/PROGRAMME TAP MATERNELLE 2017 2018.pdf"
-- , target "_blank"]
-- [ text "programme TAP Maternelle"]
-- ]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/délibération rythmes scolaires.pdf"
, target "_blank"]
[ text "Délibération rythmes scolaires"]
]
]
,""
)
, ("Centre de loisirs"
,"/images/tiles/periscolaire/centre de loisirs.jpg"
, [ p [] [text "Le Centre de Loisirs du SIVOM de la
Vallée Verte propose d’accueillir les enfants des communes
de Chambon sur Lac, Murol, Saint-Nectaire et Saint-Victor-la-Rivière,
ayant 3 ans révolus
et déjà inscrits dans un établissement scolaire."]
, text "Il sera ouvert dans les locaux de l’école
maternelle de Murol du lundi au vendredi de
8h à 18h:"
, ul []
[ li [] [text "Du 12 au 23 février 2018"]
--li [] [text "Du 20 février au 3 mars 2017"]
, li [] [text "Du 9 au 20 avril 2018"
]
, li [] [text "Du 9 juillet au 24 août 2018"
]
]
--, p [] [ a [ href "/baseDocumentaire/periscolaire/PROJET PEDAGOGIQUE ET PROGRAMME JUILLET 2017.pdf", target "_blank"]
-- [ text "programme des activités et projet pédagogique - Juillet 2017"]
-- ]
--, p [] [ a [ href "/baseDocumentaire/periscolaire/planning activités avril 2018.pdf", target "_blank"]
-- [ text "programme des activités et projet pédagogique - Juillet 2018"]
-- ]
, p [] [a [ href "/baseDocumentaire/periscolaire/plaquette clsh été 2018.pdf"
, target "_blank"
]
[ text "plaquette de présentation du centre de loisirs été" ]
]
, p [] [ a [ href "/baseDocumentaire/periscolaire/PROJET PEDAGOGIQUE karine juillet 2018.pdf", target "_blank"]
[ text "programme des activités et projet pédagogique - Juillet 2018"]
]
, p [] [ a [ href "/baseDocumentaire/periscolaire/planning août 2018.pdf", target "_blank"]
[ text "programme des activités - Août 2018"]
]
, p [] [ a [ href "/baseDocumentaire/periscolaire/PP aout 2018.pdf", target "_blank"]
[ text "projet pédagogique - Août 2018"]
]
--, p [] [ a [href "/baseDocumentaire/periscolaire/préinscription clsh avril 2018.pdf", target "_blank"]
-- [text "la fiche de préinscription CLSH"]
-- ]
, p [] [ a [href "/baseDocumentaire/periscolaire/dossier inscription Centre Aéré été 2018.pdf", target "_blank"]
[text "la fiche d’inscription CLSH"]
]
, p [] [text "Des enfants d’autres communes d’origine, de la population
touristique notamment, pourront être également accueillis, dans la
limite des places disponibles. "]
, p [] [text "Les familles pourront inscrire leurs enfants à la
semaine, à la journée ou à la demi-journée
avec ou sans repas. Un service de ramassage
est assuré matin et soir. "]
, p [] [text "Ce service est subventionné par la CAF et
la MSA. La participation des familles est fonction
des revenus de celles-ci ("
,a [href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf", target "_blank"]
[text "règlement et tarifs SIVOM juin 2018"]
,text ")"
]
, text "Liens:"
, p [] [a [href "/baseDocumentaire/periscolaire/PROJET EDUCATIF 2018.pdf", target "_blank"]
[text "Projet éducatif du centre de loisirs du SIVOM de la Vallée Verte"]]
--, p [] [a [href "/baseDocumentaire/periscolaire/projet pédagogique avril 2018.pdf", target "_blank"]
-- [text "Projet pédagogique vacances de printemps "]
-- ]
--, p [] [a [ href "/baseDocumentaire/periscolaire/plaquette CLSH 2017.pdf"
-- , target "_blank"
-- ]
-- [ text "Tarifs SIVOM 2017" ]
-- ]
--, p [] [a [ href "/baseDocumentaire/periscolaire/plaquette 2017 centre de loisirs printemps.pdf"
-- , target "_blank"
-- ]
-- [ text "Plaquette de présentation du centre de loisirs printemps" ]
-- ]
]
,""
)
, ("Transport scolaire"
,"/images/tiles/periscolaire/navette.jpg"
, [
--p [] [ text "Pour le transport scolaire, la participation des familles
-- a été fixée forfaitairement par le Conseil Général
-- pour l’année scolaire 2008 / 2009 à 12,80€
-- par mois (64€ par mois pour les élèves
-- non subventionnés)."]
]
,"http://www.puy-de-dome.fr/transports/transports-scolaires/bus-scolaire.html"
)
, ("Activités jeunesse de la communauté de communes"
,"/images/tiles/periscolaire/actiJeunesse.jpg"
,[]
,"http://www.cc-massifdusancy.fr/enfance-jeunesse/activites-jeunesse_5675.cfm"
)
]
| true | module Periscolaire 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 TiledMenu exposing (initAtWithLink,view,update,Action)
import StarTable exposing (makeTable, emptyTe, Label(..))
import Utils exposing (mainMenu,
renderMainMenu,
pageFooter,
capitalize,
renderListImg,
logos,
renderSubMenu,
mail,
site,
link)
-- Model
subMenu : Utils.Submenu
subMenu = { current = "", entries = []}
type alias MainContent =
{ wrapper : (Html -> Bool -> Html)
, tiledMenu : TiledMenu.Model
}
type alias Model =
{ mainMenu : Utils.Menu
, subMenu : Utils.Submenu
, mainContent : MainContent
, showIntro : Bool
}
initialModel =
{ mainMenu = mainMenu
, subMenu = subMenu
, mainContent = initialContent
, showIntro = if String.isEmpty locationSearch
then True
else False
}
-- View
view : Signal.Address Action -> Model -> Html
view address model =
div [ id "container"]
[ renderMainMenu ["Vie locale", "Péri et extra-scolaire"]
(.mainMenu model)
, div [ id "subContainer"]
[ (.wrapper (.mainContent model))
(TiledMenu.view (Signal.forwardTo address TiledMenuAction) (.tiledMenu (.mainContent model)))
(.showIntro model)
]
, pageFooter
]
-- Update
type Action =
NoOp
| TiledMenuAction (TiledMenu.Action)
update : Action -> Model -> Model
update action model =
case action of
NoOp -> model
TiledMenuAction act ->
let mc = (.mainContent model)
tm = (.tiledMenu (.mainContent model))
in
{ model |
showIntro = not (.showIntro model)
, mainContent =
{ mc | tiledMenu = TiledMenu.update act tm }
}
--Main
main =
StartApp.start
{ model = initialModel
, view = view
, update = update
}
port locationSearch : String
initialContent =
{ wrapper =
(\content showIntro ->
div [ class "subContainerData noSubmenu", id "periscolaire"]
[ h2 [] [ text "Péri et extra-scolaire"]
, p [classList [("intro",True),("displayIntro", showIntro)]]
[text "Les compétences péri et extrascolaires sont portées par
le SIVOM de la Vallée Verte de la
PI:NAME:<NAME>END_PI qui regroupe les communes de Chambon
sur Lac, Murol, Saint-Nectaire et Saint-Victor-la-Rivière. PI:NAME:<NAME>END_PI,
le maire de Murol, est le président du
SIVOM. "]
, p [classList [("intro",True),("displayIntro", showIntro)]]
[text "Le secrétariat du SIVOM est assuré par PI:NAME:<NAME>END_PI
PI:NAME:<NAME>END_PI, dans les locaux de la mairie de
Murol. Elle vous accueille les lundis, mardis et
jeudis de 9h30 à 12h30 dans son bureau
au 1er étage ou par téléphone au 04
73 88 60 67. "]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS MUROL 2017-2018.pdf"
-- , target "_blank"]
-- [ text "fiche de renseignements Murol"]
-- ]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS CHAMBON 2017 2018.pdf"
-- , target "_blank"]
-- [ text "fiche de renseignements Chambon"]
-- ]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS ST NECTAIRE 2017-2018.pdf"
-- , target "_blank"]
-- [ text "fiche de renseignements Saint-Nectaire"]
-- ]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/reglementCharte.pdf"
-- , target "_blank"]
-- [ text "règlement intérieur et charte du savoir vivre"]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie murol 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie chambon 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS ST NECTAIRE 2017-2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Saint-Nectaire"]
-- ]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
, target "_blank"]
[ text "Charte du savoir-vivre"]
]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/règlement sivom 2018.pdf"
-- , target "_blank"]
-- [ text "Règlement intérieur"]
--]
, p [ classList [("intro",True),("displayIntro", showIntro)]]
[ a [ href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf"
, target "_blank"]
[ text "Règlement et tarifs SIVOM juin 2018"]
]
--, p [ classList [("intro",True),("displayIntro", showIntro)]]
-- [ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
-- , target "_blank"]
-- [ text "charte du savoir vivre"]
-- ]
, content])
, tiledMenu =
initAtWithLink locationSearch peri
}
-- Data
peri =
[ ("Restaurant scolaire"
,"/images/tiles/periscolaire/restaurant scolaire.jpg"
, [ p [] [ text "Le restaurant scolaire est un service non obligatoire
assuré par le SIVOM de la Vallée Verte.
Il accueille les enfants de la maternelle et
de l’école élémentaire de Murol les lundis, mardis,
jeudis et vendredis de 12h à 13h30. "]
, p [] [ text "Les enfants déjeunent en deux services (petits puis
grands) pour limiter le bruit dans le réfectoire. "]
, p [] [ text "Les repas sont préparés sur place par la
cuisinière du SIVOM, PI:NAME:<NAME>END_PI. Un repas «bio»
est servi aux enfants une fois par mois. "]
, p [] [ text "La surveillance est assurée par les personnels du
SIVOM, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI et PI:NAME:<NAME>END_PI. "]
, p [] [ text "Les enfants sont tenus de se comporter correctement,
selon les préconisations détaillées dans la charte du
savoir-vivre et le règlement intérieur. En cas de
problème de discipline, les parents sont informés par
le biais d’avertissements remis aux enfants."]
, p [] [ text "Si votre enfant présente des allergies alimentaires, un
protocole devra être établi avant qu’il ne soit
accueilli au restaurant scolaire (PAI). "]
, p [] [ text "Le montant de la participation des familles est fonction des revenus
de celles-ci (tarification selon le quotient familial): "]
, table [ id "quotient"]
[ tr [ class "quotLine"]
[ td [] [ text "Quotient familial"]
, td [] [ text "de 0 à 350€"]
, td [] [ text "de 351 à 500€"]
, td [] [ text "de 501 à 600€"]
, td [] [ text "plus de 600€"]
]
, tr [ class "quotAltLine"]
[ td [] [ text "Tarif maternelle"]
, td [] [ text "2,10€"]
, td [] [ text "2,50€"]
, td [] [ text "2,80€"]
, td [] [ text "3,05€"]
]
, tr [ class "quotLine"]
[ td [] [ text "Tarif élémentaire"]
, td [] [ text "2,10€"]
, td [] [ text "2,60€"]
, td [] [ text "2,95€"]
, td [] [ text "3,20€"]
]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie murol 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie chambon 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
, target "_blank"]
[ text "Charte du savoir-vivre"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf"
, target "_blank"]
[ text "Règlement et tarifs SIVOM juin 2018"]
]
]
,"")
, ("Garderie périscolaire"
,"/images/tiles/periscolaire/garderie.jpg"
, [ p [] [text "La garderie périscolaire est un service non obligatoire
assuré par le SIVOM de la Vallée Verte.
Ce service est subventionné par la CAF et
la MSA. "]
, text "La garderie est ouverte: "
, ul []
[ li [] [text "le matin de 7h à 9h les lundis,
mardis, mercredis, jeudis et vendredis"]
, li [] [text "le soir de 16h30 à 19h les lundis,
mardis, jeudis et vendredis. "]
]
, p [] [text "La garderie accueille les enfants de la maternelle
de Murol ainsi que des écoles élémentaires de
Murol et de Chambon sur Lac. "]
, p [] [text "Ils sont surveillés par PI:NAME:<NAME>END_PI (et Frédérique
PI:NAME:<NAME>END_PIitz sur les créneaux de plus forte affluence). "]
, p [] [text "La garderie est un temps de détente et
de jeux libres. Mais pour le bien-être de
tous, les enfants sont tenus de se comporter
correctement, selon les préconisations détaillées dans la charte
du savoir-vivre et le règlement intérieur. En cas
de problème de discipline, les parents sont informés
par le biais d’avertissements remis aux enfants. "]
, text "La participation des familles est fonction des revenus
de celles-ci : "
, ul []
[ li [] [text "Familles non-imposables : 1,25€ de l’heure "]
, li [] [text "Familles imposables : 1,45€ de l’heure "]
]
, p [] [text "NB : le créneau 16h30/18h est facturé comme
1 heure. "]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie murol 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/dossier d'inscription cantine garderie chambon 2018-2019.pdf"
, target "_blank"]
[ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/Charte du SAVOIR VIVRE.pdf"
, target "_blank"]
[ text "Charte du savoir-vivre"]
]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf"
, target "_blank"]
[ text "Règlement et tarifs SIVOM juin 2018"]
]
]
,""
)
, ("Temps d'activités périscolaires (TAP)"
,"/images/tiles/periscolaire/TAP.jpg"
,[ p []
[text "Les écoles des communes du SIVOM de la Vallée Verte verront leurs rythmes scolaires modifiés à la rentrée 2018. Les élèves auront classe sur 4 jours, les lundis, mardis, jeudis et vendredis. Le SIVOM de la Vallée Verte a donc délibéré pour la suppression des temps d'activités périscolaires (TAP)."]
--p [] [text "L’organisation des activités périscolaires dans les quatre écoles
-- de la vallée est réalisée par le SIVOM
-- dans le cadre d’un projet éducatif territorial qui
-- garantit un encadrement de qualité pour les enfants
-- et une programmation qui répond à des objectifs
-- éducatifs. Le financement est assuré par le SIVOM,
-- l’Etat, la CAF et la participation des parents."]
-- , p [] [text "Les enfants inscrits bénéficient de deux séances d’activités
-- hebdomadaires: "]
-- , table [ id "tableTAP"]
-- [ tr []
-- [ th [] [text "ECOLE"]
-- , th [] [text "JOURS DE TAP"]
-- , th [] [text "HORAIRES DE TAP"]
-- , th [] [text "DIRECTION"]
-- , th [] [text "PROGRAMMES"]
-- ]
-- , tr []
-- [ td [] [text "PI:NAME:<NAME>END_PI"]
-- , td [] [text "PI:NAME:<NAME>END_PI"]
-- , td [] [text "15h00 à 16h30"]
-- , td [] [text "PI:NAME:<NAME>END_PI"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/PROGRAMME TAP MATERNELLE 2017 2018.pdf", target "_blank"] [text "maternelle"]]
-- ]
-- , tr []
-- [ td [] [text "PI:NAME:<NAME>END_PI"]
-- , td [] [text "Lundi et jeudi"]
-- , td [] [text "15h00 à 16h30"]
-- , td [] [text "PI:NAME:<NAME>END_PI"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/murol tap jusqu'à Pâques.pdf", target "_blank"] [text "Murol"]]
-- ]
-- , tr []
-- [ td [] [text "PI:NAME:<NAME>END_PI"]
-- , td [] [text "Lundi et jeudi"]
-- , td [] [text "15h15 à 16h45"]
-- , td [] [text "PI:NAME:<NAME>END_PI"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/PROGRAMME TAP CHAMBON 2017 2018.pdf", target "_blank"] [text "Chambon"]]
-- ]
-- , tr []
-- [ td [] [text "PI:NAME:<NAME>END_PI"]
-- , td [] [text "PI:NAME:<NAME>END_PI"]
-- , td [] [text "15h00 à 16h30"]
-- , td [] [text "PI:NAME:<NAME>END_PI"]
-- , td [] [a [href "/baseDocumentaire/periscolaire/tap st nectaire jusqu'à Pâques.pdf", target "_blank"] [text "Saint-Nectaire"]]
-- ]
-- ]
-- , p [] [text "L’inscription est annuelle et la participation
-- des familles est de 12€ par trimestre et par enfant."]
-- , p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS MUROL 2017-2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Murol"]
-- ]
-- , p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS CHAMBON 2017 2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés au Chambon"]
-- ]
-- , p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/FICHE RENSEIGNEMENTS ST NECTAIRE 2017-2018.pdf"
-- , target "_blank"]
-- [ text "Dossier d’inscription SIVOM pour les enfants scolarisés à Saint-Nectaire"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/TAP murol 2017 rentrée à toussaint-1.pdf"
-- , target "_blank"]
-- [ text "programme TAP Murol - rentrée à Toussaint"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/PROGRAMME TAP CHAMBON 2017 2018.pdf"
-- , target "_blank"]
-- [ text "programme annuel TAP Chambon"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/TAP St Nect 2017 rentrée à toussaint-1.pdf"
-- , target "_blank"]
-- [ text "programme TAP Saint-Nectaire - rentrée à Toussaint"]
-- ]
--, p [ ]
-- [ a [ href "/baseDocumentaire/periscolaire/PROGRAMME TAP MATERNELLE 2017 2018.pdf"
-- , target "_blank"]
-- [ text "programme TAP Maternelle"]
-- ]
, p [ ]
[ a [ href "/baseDocumentaire/periscolaire/délibération rythmes scolaires.pdf"
, target "_blank"]
[ text "Délibération rythmes scolaires"]
]
]
,""
)
, ("Centre de loisirs"
,"/images/tiles/periscolaire/centre de loisirs.jpg"
, [ p [] [text "Le Centre de Loisirs du SIVOM de la
Vallée Verte propose d’accueillir les enfants des communes
de Chambon sur Lac, Murol, Saint-Nectaire et Saint-Victor-la-Rivière,
ayant 3 ans révolus
et déjà inscrits dans un établissement scolaire."]
, text "Il sera ouvert dans les locaux de l’école
maternelle de Murol du lundi au vendredi de
8h à 18h:"
, ul []
[ li [] [text "Du 12 au 23 février 2018"]
--li [] [text "Du 20 février au 3 mars 2017"]
, li [] [text "Du 9 au 20 avril 2018"
]
, li [] [text "Du 9 juillet au 24 août 2018"
]
]
--, p [] [ a [ href "/baseDocumentaire/periscolaire/PROJET PEDAGOGIQUE ET PROGRAMME JUILLET 2017.pdf", target "_blank"]
-- [ text "programme des activités et projet pédagogique - Juillet 2017"]
-- ]
--, p [] [ a [ href "/baseDocumentaire/periscolaire/planning activités avril 2018.pdf", target "_blank"]
-- [ text "programme des activités et projet pédagogique - Juillet 2018"]
-- ]
, p [] [a [ href "/baseDocumentaire/periscolaire/plaquette clsh été 2018.pdf"
, target "_blank"
]
[ text "plaquette de présentation du centre de loisirs été" ]
]
, p [] [ a [ href "/baseDocumentaire/periscolaire/PROJET PEDAGOGIQUE karine juillet 2018.pdf", target "_blank"]
[ text "programme des activités et projet pédagogique - Juillet 2018"]
]
, p [] [ a [ href "/baseDocumentaire/periscolaire/planning août 2018.pdf", target "_blank"]
[ text "programme des activités - Août 2018"]
]
, p [] [ a [ href "/baseDocumentaire/periscolaire/PP aout 2018.pdf", target "_blank"]
[ text "projet pédagogique - Août 2018"]
]
--, p [] [ a [href "/baseDocumentaire/periscolaire/préinscription clsh avril 2018.pdf", target "_blank"]
-- [text "la fiche de préinscription CLSH"]
-- ]
, p [] [ a [href "/baseDocumentaire/periscolaire/dossier inscription Centre Aéré été 2018.pdf", target "_blank"]
[text "la fiche d’inscription CLSH"]
]
, p [] [text "Des enfants d’autres communes d’origine, de la population
touristique notamment, pourront être également accueillis, dans la
limite des places disponibles. "]
, p [] [text "Les familles pourront inscrire leurs enfants à la
semaine, à la journée ou à la demi-journée
avec ou sans repas. Un service de ramassage
est assuré matin et soir. "]
, p [] [text "Ce service est subventionné par la CAF et
la MSA. La participation des familles est fonction
des revenus de celles-ci ("
,a [href "/baseDocumentaire/periscolaire/règlement et tarifs SIVOM juin 2018.pdf", target "_blank"]
[text "règlement et tarifs SIVOM juin 2018"]
,text ")"
]
, text "Liens:"
, p [] [a [href "/baseDocumentaire/periscolaire/PROJET EDUCATIF 2018.pdf", target "_blank"]
[text "Projet éducatif du centre de loisirs du SIVOM de la Vallée Verte"]]
--, p [] [a [href "/baseDocumentaire/periscolaire/projet pédagogique avril 2018.pdf", target "_blank"]
-- [text "Projet pédagogique vacances de printemps "]
-- ]
--, p [] [a [ href "/baseDocumentaire/periscolaire/plaquette CLSH 2017.pdf"
-- , target "_blank"
-- ]
-- [ text "Tarifs SIVOM 2017" ]
-- ]
--, p [] [a [ href "/baseDocumentaire/periscolaire/plaquette 2017 centre de loisirs printemps.pdf"
-- , target "_blank"
-- ]
-- [ text "Plaquette de présentation du centre de loisirs printemps" ]
-- ]
]
,""
)
, ("Transport scolaire"
,"/images/tiles/periscolaire/navette.jpg"
, [
--p [] [ text "Pour le transport scolaire, la participation des familles
-- a été fixée forfaitairement par le Conseil Général
-- pour l’année scolaire 2008 / 2009 à 12,80€
-- par mois (64€ par mois pour les élèves
-- non subventionnés)."]
]
,"http://www.puy-de-dome.fr/transports/transports-scolaires/bus-scolaire.html"
)
, ("Activités jeunesse de la communauté de communes"
,"/images/tiles/periscolaire/actiJeunesse.jpg"
,[]
,"http://www.cc-massifdusancy.fr/enfance-jeunesse/activites-jeunesse_5675.cfm"
)
]
| elm |
[
{
"context": " (.creator >> .firstname) >> Expect.equalLists [ \"John\", \"John\" ]\n , List",
"end": 1456,
"score": 0.9084410071,
"start": 1452,
"tag": "NAME",
"value": "John"
},
{
"context": "or >> .firstname) >> Expect.equalLists [ \"John\", \"John\" ]\n , List.map (.c",
"end": 1464,
"score": 0.9963316321,
"start": 1460,
"tag": "NAME",
"value": "John"
},
{
"context": " (.creator >> .firstname) >> Expect.equalLists [ \"John\", \"John\" ]\n , List",
"end": 5487,
"score": 0.9993531704,
"start": 5483,
"tag": "NAME",
"value": "John"
},
{
"context": "or >> .firstname) >> Expect.equalLists [ \"John\", \"John\" ]\n , List.map (.c",
"end": 5495,
"score": 0.9996238947,
"start": 5491,
"tag": "NAME",
"value": "John"
},
{
"context": " , .creator >> .firstname >> Expect.equal \"John\"\n , .creator >> .l",
"end": 7552,
"score": 0.9989492297,
"start": 7548,
"tag": "NAME",
"value": "John"
},
{
"context": " , .creator >> .lastname >> Expect.equal \"Doe\"\n , .comments >> L",
"end": 7630,
"score": 0.9986451864,
"start": 7627,
"tag": "NAME",
"value": "Doe"
},
{
"context": " , .creator >> .firstname >> Expect.equal \"John\"\n , .creator >> .l",
"end": 10592,
"score": 0.99957937,
"start": 10588,
"tag": "NAME",
"value": "John"
},
{
"context": " , .creator >> .lastname >> Expect.equal \"Doe\"\n , .comments >> L",
"end": 10670,
"score": 0.9988516569,
"start": 10667,
"tag": "NAME",
"value": "Doe"
}
] | tests/JsonApi/EncodeTest.elm | ChristophP/jsonapi | 0 | module JsonApi.EncodeTest exposing (..)
import Expect exposing (Expectation)
import Test exposing (..)
import JsonApi.Encode as Encode
import JsonApi.Decode as Decode
import JsonApi exposing (ResourceInfo)
import Json.Encode exposing (string, encode)
import Json.Decode as JD exposing (decodeString, Decoder, list, field, map2)
import Dict exposing (Dict)
import JsonApi.Data.Posts exposing (..)
suite : Test
suite =
describe "Encode"
[ describe "resources"
[ test "encode resources" <|
\() ->
case encode 0 (Encode.resources (List.map postToResource posts)) |> decodeString (Decode.resources "posts" postDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, [ ( "self", "http://url-to-post/2" ) ]
]
, List.map .title >> Expect.equalLists [ "Post no link", "Post 2" ]
, List.map .content >> Expect.equalLists [ "Post content no link", "Post content 2" ]
, List.map (.creator >> .firstname) >> Expect.equalLists [ "John", "John" ]
, List.map (.creator >> .lastname) >> Expect.equalLists [ "Doe", "Doe" ]
, List.map (.comments >> List.map .content) >> Expect.equalLists [ [ "Comment 1", "Comment 2" ], [ "Comment 3" ] ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no relationship succeeds with decoder without relationship" <|
\() ->
case encode 0 (Encode.resources (List.map postToResourceWithoutRelationship posts)) |> decodeString (Decode.resources "posts" postWithoutRelationshipsDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, [ ( "self", "http://url-to-post/2" ) ]
]
, List.map .title >> Expect.equalLists [ "Post no link", "Post 2" ]
, List.map .content >> Expect.equalLists [ "Post content no link", "Post content 2" ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no relationship fails with decoder with relationship" <|
\() ->
encode 0 (Encode.resources (List.map postToResourceWithoutRelationship posts))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
, test "encode resources with no link succeeds" <|
\() ->
case encode 0 (Encode.resources (List.map postToResourceWithoutLinks posts)) |> decodeString (Decode.resources "posts" postDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, []
]
, List.map .title >> Expect.equalLists [ "Post no link", "Post 2" ]
, List.map .content >> Expect.equalLists [ "Post content no link", "Post content 2" ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no attribute succeeds with decoder without attribute needed" <|
\() ->
case encode 0 (Encode.resources (List.map postToResourceWithoutAttributes posts)) |> decodeString (Decode.resources "posts" postWithoutAttributesDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, [ ( "self", "http://url-to-post/2" ) ]
]
, List.map .title >> Expect.equalLists [ "fake title", "fake title" ]
, List.map .content >> Expect.equalLists [ "fake content", "fake content" ]
, List.map (.creator >> .firstname) >> Expect.equalLists [ "John", "John" ]
, List.map (.creator >> .lastname) >> Expect.equalLists [ "Doe", "Doe" ]
, List.map (.comments >> List.map .content) >> Expect.equalLists [ [ "Comment 1", "Comment 2" ], [ "Comment 3" ] ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no attribute fails with decoder with attribute" <|
\() ->
encode 0 (Encode.resources (List.map postToResourceWithoutAttributes posts))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
, test "encode resources with no id fails with decoder" <|
\() ->
encode 0 (Encode.resources (List.map postToResourceWithoutId posts))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
, test "encode resources makes decoding fail with an object" <|
\() ->
encode 0 (Encode.resources (List.map postToResource posts))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
]
, describe "resource"
[ test "encode resource" <|
\() ->
case encode 0 (Encode.resource (postToResource post2)) |> decodeString (Decode.resource "posts" postDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists [ ( "self", "http://url-to-post/2" ) ]
, .title >> Expect.equal "Post 2"
, .content >> Expect.equal "Post content 2"
, .creator >> .firstname >> Expect.equal "John"
, .creator >> .lastname >> Expect.equal "Doe"
, .comments >> List.map .content >> Expect.equalLists [ "Comment 3" ]
]
resource
Err error ->
Expect.fail error
, test "encode resource with no relationship succeeds with decoder without relationship" <|
\() ->
case encode 0 (Encode.resource (postToResourceWithoutRelationship post2)) |> decodeString (Decode.resource "posts" postWithoutRelationshipsDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists [ ( "self", "http://url-to-post/2" ) ]
, .title >> Expect.equal "Post 2"
, .content >> Expect.equal "Post content 2"
]
resource
Err error ->
Expect.fail error
, test "encode resource with no relationship fails with decoder with relationship" <|
\() ->
encode 0 (Encode.resource (postToResourceWithoutRelationship post2))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
, test "encode resource with no link succeeds" <|
\() ->
case encode 0 (Encode.resource (postToResourceWithoutLinks post2)) |> decodeString (Decode.resource "posts" postDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists []
, .title >> Expect.equal "Post 2"
, .content >> Expect.equal "Post content 2"
]
resource
Err error ->
Expect.fail error
, test "encode resource with no attribute succeeds with decoder without attribute" <|
\() ->
case encode 0 (Encode.resource (postToResourceWithoutAttributes post2)) |> decodeString (Decode.resource "posts" postWithoutAttributesDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists [ ( "self", "http://url-to-post/2" ) ]
, .title >> Expect.equal "fake title"
, .content >> Expect.equal "fake content"
, .creator >> .firstname >> Expect.equal "John"
, .creator >> .lastname >> Expect.equal "Doe"
, .comments >> List.map .content >> Expect.equalLists [ "Comment 3" ]
]
resource
Err error ->
Expect.fail error
, test "encode resource with no attribute fails with decoder with attribute" <|
\() ->
encode 0 (Encode.resource (postToResourceWithoutAttributes post2))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
, test "encode resource with no id fails with decoder" <|
\() ->
encode 0 (Encode.resource (postToResourceWithoutId post2))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
, test "encode resource makes decoding fail with a list" <|
\() ->
encode 0 (Encode.resource (postToResource post2))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
]
, describe "relationships"
[ test "duplicate relationships return only one relationship in payload" <|
\() ->
case encode 0 (Encode.resources (List.map postToResource [ post2, post2 ])) |> decodeString includedDecoder of
Ok resources ->
resources
|> List.sortBy .id
|> Expect.all
[ List.map .id >> Expect.equalLists [ "comment-3", "creator-1" ]
, List.map .type_ >> Expect.equalLists [ "comment", "creators" ]
]
Err error ->
Expect.fail error
, test "relationships in relationships should be added in included" <|
\() ->
case encode 0 (Encode.resource (groupToResource group)) |> decodeString includedDecoder of
Ok resources ->
resources
|> List.sortBy .id
|> Expect.all
[ List.map .id >> Expect.equalLists [ "comment-1", "comment-2", "comment-3", "creator-1", "post-1", "post-2" ]
, List.map .type_ >> Expect.equalLists [ "comment", "comment", "comment", "creators", "posts", "posts" ]
]
Err error ->
Expect.fail error
]
]
postToResource : Post -> ResourceInfo
postToResource post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withLinks post.links
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
postToResourceWithoutId : Post -> ResourceInfo
postToResourceWithoutId post =
JsonApi.build "posts"
|> JsonApi.withLinks post.links
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
postToResourceWithoutRelationship : Post -> ResourceInfo
postToResourceWithoutRelationship post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withLinks post.links
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
postToResourceWithoutLinks : Post -> ResourceInfo
postToResourceWithoutLinks post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
postToResourceWithoutAttributes : Post -> ResourceInfo
postToResourceWithoutAttributes post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withLinks post.links
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
creatorToResource : Creator -> ResourceInfo
creatorToResource creator =
JsonApi.build "creators"
|> JsonApi.withId creator.id
|> JsonApi.withLinks creator.links
|> JsonApi.withAttributes
[ ( "firstname", string creator.firstname )
, ( "lastname", string creator.lastname )
]
commentRelationship : Comment -> ( String, ResourceInfo )
commentRelationship comment =
( comment.id, commentToResource comment )
commentToResource : Comment -> ResourceInfo
commentToResource comment =
JsonApi.build "comment"
|> JsonApi.withId comment.id
|> JsonApi.withLinks comment.links
|> JsonApi.withAttributes
[ ( "content", string comment.content )
, ( "email", string comment.email )
]
type alias Group =
{ name : String
, posts : List Post
}
groupToResource : Group -> ResourceInfo
groupToResource group =
JsonApi.build "groups"
|> JsonApi.withAttributes
[ ( "name", string group.name ) ]
|> JsonApi.withRelationship "post" (JsonApi.relationships (List.map postRelationship group.posts))
postRelationship : Post -> ( String, ResourceInfo )
postRelationship post =
( post.id, postToResource post )
group : Group
group =
{ name = "group 1", posts = posts }
type alias Included =
{ id : String, type_ : String }
includedDecoder : Decoder (List Included)
includedDecoder =
field "included" <|
list <|
map2 Included
(field "id" JD.string)
(field "type" JD.string)
| 31354 | module JsonApi.EncodeTest exposing (..)
import Expect exposing (Expectation)
import Test exposing (..)
import JsonApi.Encode as Encode
import JsonApi.Decode as Decode
import JsonApi exposing (ResourceInfo)
import Json.Encode exposing (string, encode)
import Json.Decode as JD exposing (decodeString, Decoder, list, field, map2)
import Dict exposing (Dict)
import JsonApi.Data.Posts exposing (..)
suite : Test
suite =
describe "Encode"
[ describe "resources"
[ test "encode resources" <|
\() ->
case encode 0 (Encode.resources (List.map postToResource posts)) |> decodeString (Decode.resources "posts" postDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, [ ( "self", "http://url-to-post/2" ) ]
]
, List.map .title >> Expect.equalLists [ "Post no link", "Post 2" ]
, List.map .content >> Expect.equalLists [ "Post content no link", "Post content 2" ]
, List.map (.creator >> .firstname) >> Expect.equalLists [ "<NAME>", "<NAME>" ]
, List.map (.creator >> .lastname) >> Expect.equalLists [ "Doe", "Doe" ]
, List.map (.comments >> List.map .content) >> Expect.equalLists [ [ "Comment 1", "Comment 2" ], [ "Comment 3" ] ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no relationship succeeds with decoder without relationship" <|
\() ->
case encode 0 (Encode.resources (List.map postToResourceWithoutRelationship posts)) |> decodeString (Decode.resources "posts" postWithoutRelationshipsDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, [ ( "self", "http://url-to-post/2" ) ]
]
, List.map .title >> Expect.equalLists [ "Post no link", "Post 2" ]
, List.map .content >> Expect.equalLists [ "Post content no link", "Post content 2" ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no relationship fails with decoder with relationship" <|
\() ->
encode 0 (Encode.resources (List.map postToResourceWithoutRelationship posts))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
, test "encode resources with no link succeeds" <|
\() ->
case encode 0 (Encode.resources (List.map postToResourceWithoutLinks posts)) |> decodeString (Decode.resources "posts" postDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, []
]
, List.map .title >> Expect.equalLists [ "Post no link", "Post 2" ]
, List.map .content >> Expect.equalLists [ "Post content no link", "Post content 2" ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no attribute succeeds with decoder without attribute needed" <|
\() ->
case encode 0 (Encode.resources (List.map postToResourceWithoutAttributes posts)) |> decodeString (Decode.resources "posts" postWithoutAttributesDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, [ ( "self", "http://url-to-post/2" ) ]
]
, List.map .title >> Expect.equalLists [ "fake title", "fake title" ]
, List.map .content >> Expect.equalLists [ "fake content", "fake content" ]
, List.map (.creator >> .firstname) >> Expect.equalLists [ "<NAME>", "<NAME>" ]
, List.map (.creator >> .lastname) >> Expect.equalLists [ "Doe", "Doe" ]
, List.map (.comments >> List.map .content) >> Expect.equalLists [ [ "Comment 1", "Comment 2" ], [ "Comment 3" ] ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no attribute fails with decoder with attribute" <|
\() ->
encode 0 (Encode.resources (List.map postToResourceWithoutAttributes posts))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
, test "encode resources with no id fails with decoder" <|
\() ->
encode 0 (Encode.resources (List.map postToResourceWithoutId posts))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
, test "encode resources makes decoding fail with an object" <|
\() ->
encode 0 (Encode.resources (List.map postToResource posts))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
]
, describe "resource"
[ test "encode resource" <|
\() ->
case encode 0 (Encode.resource (postToResource post2)) |> decodeString (Decode.resource "posts" postDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists [ ( "self", "http://url-to-post/2" ) ]
, .title >> Expect.equal "Post 2"
, .content >> Expect.equal "Post content 2"
, .creator >> .firstname >> Expect.equal "<NAME>"
, .creator >> .lastname >> Expect.equal "<NAME>"
, .comments >> List.map .content >> Expect.equalLists [ "Comment 3" ]
]
resource
Err error ->
Expect.fail error
, test "encode resource with no relationship succeeds with decoder without relationship" <|
\() ->
case encode 0 (Encode.resource (postToResourceWithoutRelationship post2)) |> decodeString (Decode.resource "posts" postWithoutRelationshipsDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists [ ( "self", "http://url-to-post/2" ) ]
, .title >> Expect.equal "Post 2"
, .content >> Expect.equal "Post content 2"
]
resource
Err error ->
Expect.fail error
, test "encode resource with no relationship fails with decoder with relationship" <|
\() ->
encode 0 (Encode.resource (postToResourceWithoutRelationship post2))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
, test "encode resource with no link succeeds" <|
\() ->
case encode 0 (Encode.resource (postToResourceWithoutLinks post2)) |> decodeString (Decode.resource "posts" postDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists []
, .title >> Expect.equal "Post 2"
, .content >> Expect.equal "Post content 2"
]
resource
Err error ->
Expect.fail error
, test "encode resource with no attribute succeeds with decoder without attribute" <|
\() ->
case encode 0 (Encode.resource (postToResourceWithoutAttributes post2)) |> decodeString (Decode.resource "posts" postWithoutAttributesDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists [ ( "self", "http://url-to-post/2" ) ]
, .title >> Expect.equal "fake title"
, .content >> Expect.equal "fake content"
, .creator >> .firstname >> Expect.equal "<NAME>"
, .creator >> .lastname >> Expect.equal "<NAME>"
, .comments >> List.map .content >> Expect.equalLists [ "Comment 3" ]
]
resource
Err error ->
Expect.fail error
, test "encode resource with no attribute fails with decoder with attribute" <|
\() ->
encode 0 (Encode.resource (postToResourceWithoutAttributes post2))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
, test "encode resource with no id fails with decoder" <|
\() ->
encode 0 (Encode.resource (postToResourceWithoutId post2))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
, test "encode resource makes decoding fail with a list" <|
\() ->
encode 0 (Encode.resource (postToResource post2))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
]
, describe "relationships"
[ test "duplicate relationships return only one relationship in payload" <|
\() ->
case encode 0 (Encode.resources (List.map postToResource [ post2, post2 ])) |> decodeString includedDecoder of
Ok resources ->
resources
|> List.sortBy .id
|> Expect.all
[ List.map .id >> Expect.equalLists [ "comment-3", "creator-1" ]
, List.map .type_ >> Expect.equalLists [ "comment", "creators" ]
]
Err error ->
Expect.fail error
, test "relationships in relationships should be added in included" <|
\() ->
case encode 0 (Encode.resource (groupToResource group)) |> decodeString includedDecoder of
Ok resources ->
resources
|> List.sortBy .id
|> Expect.all
[ List.map .id >> Expect.equalLists [ "comment-1", "comment-2", "comment-3", "creator-1", "post-1", "post-2" ]
, List.map .type_ >> Expect.equalLists [ "comment", "comment", "comment", "creators", "posts", "posts" ]
]
Err error ->
Expect.fail error
]
]
postToResource : Post -> ResourceInfo
postToResource post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withLinks post.links
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
postToResourceWithoutId : Post -> ResourceInfo
postToResourceWithoutId post =
JsonApi.build "posts"
|> JsonApi.withLinks post.links
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
postToResourceWithoutRelationship : Post -> ResourceInfo
postToResourceWithoutRelationship post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withLinks post.links
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
postToResourceWithoutLinks : Post -> ResourceInfo
postToResourceWithoutLinks post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
postToResourceWithoutAttributes : Post -> ResourceInfo
postToResourceWithoutAttributes post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withLinks post.links
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
creatorToResource : Creator -> ResourceInfo
creatorToResource creator =
JsonApi.build "creators"
|> JsonApi.withId creator.id
|> JsonApi.withLinks creator.links
|> JsonApi.withAttributes
[ ( "firstname", string creator.firstname )
, ( "lastname", string creator.lastname )
]
commentRelationship : Comment -> ( String, ResourceInfo )
commentRelationship comment =
( comment.id, commentToResource comment )
commentToResource : Comment -> ResourceInfo
commentToResource comment =
JsonApi.build "comment"
|> JsonApi.withId comment.id
|> JsonApi.withLinks comment.links
|> JsonApi.withAttributes
[ ( "content", string comment.content )
, ( "email", string comment.email )
]
type alias Group =
{ name : String
, posts : List Post
}
groupToResource : Group -> ResourceInfo
groupToResource group =
JsonApi.build "groups"
|> JsonApi.withAttributes
[ ( "name", string group.name ) ]
|> JsonApi.withRelationship "post" (JsonApi.relationships (List.map postRelationship group.posts))
postRelationship : Post -> ( String, ResourceInfo )
postRelationship post =
( post.id, postToResource post )
group : Group
group =
{ name = "group 1", posts = posts }
type alias Included =
{ id : String, type_ : String }
includedDecoder : Decoder (List Included)
includedDecoder =
field "included" <|
list <|
map2 Included
(field "id" JD.string)
(field "type" JD.string)
| true | module JsonApi.EncodeTest exposing (..)
import Expect exposing (Expectation)
import Test exposing (..)
import JsonApi.Encode as Encode
import JsonApi.Decode as Decode
import JsonApi exposing (ResourceInfo)
import Json.Encode exposing (string, encode)
import Json.Decode as JD exposing (decodeString, Decoder, list, field, map2)
import Dict exposing (Dict)
import JsonApi.Data.Posts exposing (..)
suite : Test
suite =
describe "Encode"
[ describe "resources"
[ test "encode resources" <|
\() ->
case encode 0 (Encode.resources (List.map postToResource posts)) |> decodeString (Decode.resources "posts" postDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, [ ( "self", "http://url-to-post/2" ) ]
]
, List.map .title >> Expect.equalLists [ "Post no link", "Post 2" ]
, List.map .content >> Expect.equalLists [ "Post content no link", "Post content 2" ]
, List.map (.creator >> .firstname) >> Expect.equalLists [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ]
, List.map (.creator >> .lastname) >> Expect.equalLists [ "Doe", "Doe" ]
, List.map (.comments >> List.map .content) >> Expect.equalLists [ [ "Comment 1", "Comment 2" ], [ "Comment 3" ] ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no relationship succeeds with decoder without relationship" <|
\() ->
case encode 0 (Encode.resources (List.map postToResourceWithoutRelationship posts)) |> decodeString (Decode.resources "posts" postWithoutRelationshipsDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, [ ( "self", "http://url-to-post/2" ) ]
]
, List.map .title >> Expect.equalLists [ "Post no link", "Post 2" ]
, List.map .content >> Expect.equalLists [ "Post content no link", "Post content 2" ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no relationship fails with decoder with relationship" <|
\() ->
encode 0 (Encode.resources (List.map postToResourceWithoutRelationship posts))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
, test "encode resources with no link succeeds" <|
\() ->
case encode 0 (Encode.resources (List.map postToResourceWithoutLinks posts)) |> decodeString (Decode.resources "posts" postDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, []
]
, List.map .title >> Expect.equalLists [ "Post no link", "Post 2" ]
, List.map .content >> Expect.equalLists [ "Post content no link", "Post content 2" ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no attribute succeeds with decoder without attribute needed" <|
\() ->
case encode 0 (Encode.resources (List.map postToResourceWithoutAttributes posts)) |> decodeString (Decode.resources "posts" postWithoutAttributesDecoder) of
Ok resources ->
Expect.all
[ List.map .id >> Expect.equalLists [ "post-1", "post-2" ]
, List.map (.links >> Dict.toList)
>> Expect.equalLists
[ []
, [ ( "self", "http://url-to-post/2" ) ]
]
, List.map .title >> Expect.equalLists [ "fake title", "fake title" ]
, List.map .content >> Expect.equalLists [ "fake content", "fake content" ]
, List.map (.creator >> .firstname) >> Expect.equalLists [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ]
, List.map (.creator >> .lastname) >> Expect.equalLists [ "Doe", "Doe" ]
, List.map (.comments >> List.map .content) >> Expect.equalLists [ [ "Comment 1", "Comment 2" ], [ "Comment 3" ] ]
]
resources
Err error ->
Expect.fail error
, test "encode resources with no attribute fails with decoder with attribute" <|
\() ->
encode 0 (Encode.resources (List.map postToResourceWithoutAttributes posts))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
, test "encode resources with no id fails with decoder" <|
\() ->
encode 0 (Encode.resources (List.map postToResourceWithoutId posts))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
, test "encode resources makes decoding fail with an object" <|
\() ->
encode 0 (Encode.resources (List.map postToResource posts))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
]
, describe "resource"
[ test "encode resource" <|
\() ->
case encode 0 (Encode.resource (postToResource post2)) |> decodeString (Decode.resource "posts" postDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists [ ( "self", "http://url-to-post/2" ) ]
, .title >> Expect.equal "Post 2"
, .content >> Expect.equal "Post content 2"
, .creator >> .firstname >> Expect.equal "PI:NAME:<NAME>END_PI"
, .creator >> .lastname >> Expect.equal "PI:NAME:<NAME>END_PI"
, .comments >> List.map .content >> Expect.equalLists [ "Comment 3" ]
]
resource
Err error ->
Expect.fail error
, test "encode resource with no relationship succeeds with decoder without relationship" <|
\() ->
case encode 0 (Encode.resource (postToResourceWithoutRelationship post2)) |> decodeString (Decode.resource "posts" postWithoutRelationshipsDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists [ ( "self", "http://url-to-post/2" ) ]
, .title >> Expect.equal "Post 2"
, .content >> Expect.equal "Post content 2"
]
resource
Err error ->
Expect.fail error
, test "encode resource with no relationship fails with decoder with relationship" <|
\() ->
encode 0 (Encode.resource (postToResourceWithoutRelationship post2))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
, test "encode resource with no link succeeds" <|
\() ->
case encode 0 (Encode.resource (postToResourceWithoutLinks post2)) |> decodeString (Decode.resource "posts" postDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists []
, .title >> Expect.equal "Post 2"
, .content >> Expect.equal "Post content 2"
]
resource
Err error ->
Expect.fail error
, test "encode resource with no attribute succeeds with decoder without attribute" <|
\() ->
case encode 0 (Encode.resource (postToResourceWithoutAttributes post2)) |> decodeString (Decode.resource "posts" postWithoutAttributesDecoder) of
Ok resource ->
Expect.all
[ .id >> Expect.equal "post-2"
, .links >> Dict.toList >> Expect.equalLists [ ( "self", "http://url-to-post/2" ) ]
, .title >> Expect.equal "fake title"
, .content >> Expect.equal "fake content"
, .creator >> .firstname >> Expect.equal "PI:NAME:<NAME>END_PI"
, .creator >> .lastname >> Expect.equal "PI:NAME:<NAME>END_PI"
, .comments >> List.map .content >> Expect.equalLists [ "Comment 3" ]
]
resource
Err error ->
Expect.fail error
, test "encode resource with no attribute fails with decoder with attribute" <|
\() ->
encode 0 (Encode.resource (postToResourceWithoutAttributes post2))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
, test "encode resource with no id fails with decoder" <|
\() ->
encode 0 (Encode.resource (postToResourceWithoutId post2))
|> decodeString (Decode.resource "posts" postDecoder)
|> Expect.err
, test "encode resource makes decoding fail with a list" <|
\() ->
encode 0 (Encode.resource (postToResource post2))
|> decodeString (Decode.resources "posts" postDecoder)
|> Expect.err
]
, describe "relationships"
[ test "duplicate relationships return only one relationship in payload" <|
\() ->
case encode 0 (Encode.resources (List.map postToResource [ post2, post2 ])) |> decodeString includedDecoder of
Ok resources ->
resources
|> List.sortBy .id
|> Expect.all
[ List.map .id >> Expect.equalLists [ "comment-3", "creator-1" ]
, List.map .type_ >> Expect.equalLists [ "comment", "creators" ]
]
Err error ->
Expect.fail error
, test "relationships in relationships should be added in included" <|
\() ->
case encode 0 (Encode.resource (groupToResource group)) |> decodeString includedDecoder of
Ok resources ->
resources
|> List.sortBy .id
|> Expect.all
[ List.map .id >> Expect.equalLists [ "comment-1", "comment-2", "comment-3", "creator-1", "post-1", "post-2" ]
, List.map .type_ >> Expect.equalLists [ "comment", "comment", "comment", "creators", "posts", "posts" ]
]
Err error ->
Expect.fail error
]
]
postToResource : Post -> ResourceInfo
postToResource post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withLinks post.links
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
postToResourceWithoutId : Post -> ResourceInfo
postToResourceWithoutId post =
JsonApi.build "posts"
|> JsonApi.withLinks post.links
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
postToResourceWithoutRelationship : Post -> ResourceInfo
postToResourceWithoutRelationship post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withLinks post.links
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
postToResourceWithoutLinks : Post -> ResourceInfo
postToResourceWithoutLinks post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withAttributes
[ ( "title", string post.title )
, ( "content", string post.content )
]
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
postToResourceWithoutAttributes : Post -> ResourceInfo
postToResourceWithoutAttributes post =
JsonApi.build "posts"
|> JsonApi.withId post.id
|> JsonApi.withLinks post.links
|> JsonApi.withRelationship "creator" (JsonApi.relationship post.creator.id (creatorToResource post.creator))
|> JsonApi.withRelationship "comments" (JsonApi.relationships (List.map commentRelationship post.comments))
creatorToResource : Creator -> ResourceInfo
creatorToResource creator =
JsonApi.build "creators"
|> JsonApi.withId creator.id
|> JsonApi.withLinks creator.links
|> JsonApi.withAttributes
[ ( "firstname", string creator.firstname )
, ( "lastname", string creator.lastname )
]
commentRelationship : Comment -> ( String, ResourceInfo )
commentRelationship comment =
( comment.id, commentToResource comment )
commentToResource : Comment -> ResourceInfo
commentToResource comment =
JsonApi.build "comment"
|> JsonApi.withId comment.id
|> JsonApi.withLinks comment.links
|> JsonApi.withAttributes
[ ( "content", string comment.content )
, ( "email", string comment.email )
]
type alias Group =
{ name : String
, posts : List Post
}
groupToResource : Group -> ResourceInfo
groupToResource group =
JsonApi.build "groups"
|> JsonApi.withAttributes
[ ( "name", string group.name ) ]
|> JsonApi.withRelationship "post" (JsonApi.relationships (List.map postRelationship group.posts))
postRelationship : Post -> ( String, ResourceInfo )
postRelationship post =
( post.id, postToResource post )
group : Group
group =
{ name = "group 1", posts = posts }
type alias Included =
{ id : String, type_ : String }
includedDecoder : Decoder (List Included)
includedDecoder =
field "included" <|
list <|
map2 Included
(field "id" JD.string)
(field "type" JD.string)
| elm |
[
{
"context": "-- Copyright 2018 Gregor Uhlenheuer\n--\n-- Licensed under the Apache License, Version ",
"end": 35,
"score": 0.9998847246,
"start": 18,
"tag": "NAME",
"value": "Gregor Uhlenheuer"
}
] | client/src/Ports.elm | kongo2002/ogonek | 1 | -- Copyright 2018 Gregor Uhlenheuer
--
-- 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.
port module Ports exposing (NotificationPort, fromWebsocket, notification, toWebsocket)
import Json.Encode exposing (Value)
type alias NotificationPort msg =
Value -> Cmd msg
port notification : NotificationPort msg
port toWebsocket : Value -> Cmd msg
port fromWebsocket : (Value -> a) -> Sub a
-- vim: et sw=2 sts=2
| 20153 | -- 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.
port module Ports exposing (NotificationPort, fromWebsocket, notification, toWebsocket)
import Json.Encode exposing (Value)
type alias NotificationPort msg =
Value -> Cmd msg
port notification : NotificationPort msg
port toWebsocket : Value -> Cmd msg
port fromWebsocket : (Value -> a) -> Sub a
-- vim: et sw=2 sts=2
| true | -- 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.
port module Ports exposing (NotificationPort, fromWebsocket, notification, toWebsocket)
import Json.Encode exposing (Value)
type alias NotificationPort msg =
Value -> Cmd msg
port notification : NotificationPort msg
port toWebsocket : Value -> Cmd msg
port fromWebsocket : (Value -> a) -> Sub a
-- vim: et sw=2 sts=2
| elm |
[
{
"context": "{-\n Swaggy Jenkins\n Jenkins API clients generated from Swagger / O",
"end": 20,
"score": 0.9995821118,
"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.9999132156,
"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.9996281862,
"start": 240,
"tag": "USERNAME",
"value": "openapitools"
}
] | clients/elm/generated/src/Data/HudsonMasterComputerexecutors.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.HudsonMasterComputerexecutors exposing (HudsonMasterComputerexecutors, hudsonMasterComputerexecutorsDecoder, hudsonMasterComputerexecutorsEncoder)
import Data.FreeStyleBuild exposing (FreeStyleBuild, freeStyleBuildDecoder, freeStyleBuildEncoder)
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 HudsonMasterComputerexecutors =
{ currentExecutable : Maybe FreeStyleBuild
, idle : Maybe Bool
, likelyStuck : Maybe Bool
, number : Maybe Int
, progress : Maybe Int
, class : Maybe String
}
hudsonMasterComputerexecutorsDecoder : Decoder HudsonMasterComputerexecutors
hudsonMasterComputerexecutorsDecoder =
decode HudsonMasterComputerexecutors
|> optional "currentExecutable" (Decode.nullable freeStyleBuildDecoder) Nothing
|> optional "idle" (Decode.nullable Decode.bool) Nothing
|> optional "likelyStuck" (Decode.nullable Decode.bool) Nothing
|> optional "number" (Decode.nullable Decode.int) Nothing
|> optional "progress" (Decode.nullable Decode.int) Nothing
|> optional "_class" (Decode.nullable Decode.string) Nothing
hudsonMasterComputerexecutorsEncoder : HudsonMasterComputerexecutors -> Encode.Value
hudsonMasterComputerexecutorsEncoder model =
Encode.object
[ ( "currentExecutable", withDefault Encode.null (map freeStyleBuildEncoder model.currentExecutable) )
, ( "idle", withDefault Encode.null (map Encode.bool model.idle) )
, ( "likelyStuck", withDefault Encode.null (map Encode.bool model.likelyStuck) )
, ( "number", withDefault Encode.null (map Encode.int model.number) )
, ( "progress", withDefault Encode.null (map Encode.int model.progress) )
, ( "_class", withDefault Encode.null (map Encode.string model.class) )
]
| 7426 | {-
<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.HudsonMasterComputerexecutors exposing (HudsonMasterComputerexecutors, hudsonMasterComputerexecutorsDecoder, hudsonMasterComputerexecutorsEncoder)
import Data.FreeStyleBuild exposing (FreeStyleBuild, freeStyleBuildDecoder, freeStyleBuildEncoder)
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 HudsonMasterComputerexecutors =
{ currentExecutable : Maybe FreeStyleBuild
, idle : Maybe Bool
, likelyStuck : Maybe Bool
, number : Maybe Int
, progress : Maybe Int
, class : Maybe String
}
hudsonMasterComputerexecutorsDecoder : Decoder HudsonMasterComputerexecutors
hudsonMasterComputerexecutorsDecoder =
decode HudsonMasterComputerexecutors
|> optional "currentExecutable" (Decode.nullable freeStyleBuildDecoder) Nothing
|> optional "idle" (Decode.nullable Decode.bool) Nothing
|> optional "likelyStuck" (Decode.nullable Decode.bool) Nothing
|> optional "number" (Decode.nullable Decode.int) Nothing
|> optional "progress" (Decode.nullable Decode.int) Nothing
|> optional "_class" (Decode.nullable Decode.string) Nothing
hudsonMasterComputerexecutorsEncoder : HudsonMasterComputerexecutors -> Encode.Value
hudsonMasterComputerexecutorsEncoder model =
Encode.object
[ ( "currentExecutable", withDefault Encode.null (map freeStyleBuildEncoder model.currentExecutable) )
, ( "idle", withDefault Encode.null (map Encode.bool model.idle) )
, ( "likelyStuck", withDefault Encode.null (map Encode.bool model.likelyStuck) )
, ( "number", withDefault Encode.null (map Encode.int model.number) )
, ( "progress", withDefault Encode.null (map Encode.int model.progress) )
, ( "_class", withDefault Encode.null (map Encode.string model.class) )
]
| 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.HudsonMasterComputerexecutors exposing (HudsonMasterComputerexecutors, hudsonMasterComputerexecutorsDecoder, hudsonMasterComputerexecutorsEncoder)
import Data.FreeStyleBuild exposing (FreeStyleBuild, freeStyleBuildDecoder, freeStyleBuildEncoder)
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 HudsonMasterComputerexecutors =
{ currentExecutable : Maybe FreeStyleBuild
, idle : Maybe Bool
, likelyStuck : Maybe Bool
, number : Maybe Int
, progress : Maybe Int
, class : Maybe String
}
hudsonMasterComputerexecutorsDecoder : Decoder HudsonMasterComputerexecutors
hudsonMasterComputerexecutorsDecoder =
decode HudsonMasterComputerexecutors
|> optional "currentExecutable" (Decode.nullable freeStyleBuildDecoder) Nothing
|> optional "idle" (Decode.nullable Decode.bool) Nothing
|> optional "likelyStuck" (Decode.nullable Decode.bool) Nothing
|> optional "number" (Decode.nullable Decode.int) Nothing
|> optional "progress" (Decode.nullable Decode.int) Nothing
|> optional "_class" (Decode.nullable Decode.string) Nothing
hudsonMasterComputerexecutorsEncoder : HudsonMasterComputerexecutors -> Encode.Value
hudsonMasterComputerexecutorsEncoder model =
Encode.object
[ ( "currentExecutable", withDefault Encode.null (map freeStyleBuildEncoder model.currentExecutable) )
, ( "idle", withDefault Encode.null (map Encode.bool model.idle) )
, ( "likelyStuck", withDefault Encode.null (map Encode.bool model.likelyStuck) )
, ( "number", withDefault Encode.null (map Encode.int model.number) )
, ( "progress", withDefault Encode.null (map Encode.int model.progress) )
, ( "_class", withDefault Encode.null (map Encode.string model.class) )
]
| elm |
[
{
"context": "he version of the OpenAPI document: v1\n Contact: support@coinapi.io\n\n NOTE: This file is auto generated by the open",
"end": 343,
"score": 0.9999224544,
"start": 325,
"tag": "EMAIL",
"value": "support@coinapi.io"
},
{
"context": "d by the openapi-generator.\n https://github.com/openapitools/openapi-generator.git\n Do not edit this file ma",
"end": 442,
"score": 0.999548614,
"start": 430,
"tag": "USERNAME",
"value": "openapitools"
}
] | oeml-sdk/elm/src/Data/OrderCancelAllRequest.elm | oskaralfons/coinapi-sdk | 1 | {-
OEML - REST API
This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a>
The version of the OpenAPI document: v1
Contact: support@coinapi.io
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.OrderCancelAllRequest exposing (OrderCancelAllRequest, decoder, encode, encodeWithTag, toString)
import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (optional, required)
import Json.Encode as Encode
{-| Cancel all orders request object.
-}
type alias OrderCancelAllRequest =
{ exchangeId : String
}
decoder : Decoder OrderCancelAllRequest
decoder =
Decode.succeed OrderCancelAllRequest
|> required "exchange_id" Decode.string
encode : OrderCancelAllRequest -> Encode.Value
encode =
Encode.object << encodePairs
encodeWithTag : ( String, String ) -> OrderCancelAllRequest -> Encode.Value
encodeWithTag (tagField, tag) model =
Encode.object <| encodePairs model ++ [ ( tagField, Encode.string tag ) ]
encodePairs : OrderCancelAllRequest -> List (String, Encode.Value)
encodePairs model =
[ ( "exchange_id", Encode.string model.exchangeId )
]
toString : OrderCancelAllRequest -> String
toString =
Encode.encode 0 << encode
| 11501 | {-
OEML - REST API
This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a>
The version of the OpenAPI document: v1
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.OrderCancelAllRequest exposing (OrderCancelAllRequest, decoder, encode, encodeWithTag, toString)
import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (optional, required)
import Json.Encode as Encode
{-| Cancel all orders request object.
-}
type alias OrderCancelAllRequest =
{ exchangeId : String
}
decoder : Decoder OrderCancelAllRequest
decoder =
Decode.succeed OrderCancelAllRequest
|> required "exchange_id" Decode.string
encode : OrderCancelAllRequest -> Encode.Value
encode =
Encode.object << encodePairs
encodeWithTag : ( String, String ) -> OrderCancelAllRequest -> Encode.Value
encodeWithTag (tagField, tag) model =
Encode.object <| encodePairs model ++ [ ( tagField, Encode.string tag ) ]
encodePairs : OrderCancelAllRequest -> List (String, Encode.Value)
encodePairs model =
[ ( "exchange_id", Encode.string model.exchangeId )
]
toString : OrderCancelAllRequest -> String
toString =
Encode.encode 0 << encode
| true | {-
OEML - REST API
This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a>
The version of the OpenAPI document: v1
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.OrderCancelAllRequest exposing (OrderCancelAllRequest, decoder, encode, encodeWithTag, toString)
import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (optional, required)
import Json.Encode as Encode
{-| Cancel all orders request object.
-}
type alias OrderCancelAllRequest =
{ exchangeId : String
}
decoder : Decoder OrderCancelAllRequest
decoder =
Decode.succeed OrderCancelAllRequest
|> required "exchange_id" Decode.string
encode : OrderCancelAllRequest -> Encode.Value
encode =
Encode.object << encodePairs
encodeWithTag : ( String, String ) -> OrderCancelAllRequest -> Encode.Value
encodeWithTag (tagField, tag) model =
Encode.object <| encodePairs model ++ [ ( tagField, Encode.string tag ) ]
encodePairs : OrderCancelAllRequest -> List (String, Encode.Value)
encodePairs model =
[ ( "exchange_id", Encode.string model.exchangeId )
]
toString : OrderCancelAllRequest -> String
toString =
Encode.encode 0 << encode
| elm |
[
{
"context": "Table\n myTable = makeTable\n [ { name = \"Alice\", age = 17, gender = Female }\n , { name ",
"end": 2559,
"score": 0.9998303652,
"start": 2554,
"tag": "NAME",
"value": "Alice"
},
{
"context": " age = 17, gender = Female }\n , { name = \"Bob\", age = 8, gender = Male }\n , { nam",
"end": 2615,
"score": 0.9998544455,
"start": 2612,
"tag": "NAME",
"value": "Bob"
},
{
"context": " age = 8, gender = Male }\n , { name = \"Charlie\", age = 35, gender = Male }\n ]\n\n getF",
"end": 2677,
"score": 0.9996687174,
"start": 2670,
"tag": "NAME",
"value": "Charlie"
},
{
"context": "\n ]\n\n getField nameField myTable -- [\"Alice\", \"Bob\", \"Charlie\"]\n getField ageField myTable",
"end": 2762,
"score": 0.9998511672,
"start": 2757,
"tag": "NAME",
"value": "Alice"
},
{
"context": "]\n\n getField nameField myTable -- [\"Alice\", \"Bob\", \"Charlie\"]\n getField ageField myTable -- ",
"end": 2769,
"score": 0.9997703433,
"start": 2766,
"tag": "NAME",
"value": "Bob"
},
{
"context": "getField nameField myTable -- [\"Alice\", \"Bob\", \"Charlie\"]\n getField ageField myTable -- [17, 8, 35]",
"end": 2780,
"score": 0.9997118711,
"start": 2773,
"tag": "NAME",
"value": "Charlie"
}
] | src/PivotTable.elm | integral424/elm-pivot-table | 3 | module PivotTable exposing
( Table, Field
, makeTable, getField
, Aggregator, pivotTable, pivotTableHtml
)
{-| This package provides a pivot table view function with which
you can analyze and visualize your data by grouping various fields.
# Definition
@docs Table, Field
# Table operations
@docs makeTable, getField
# Pivot table
In this package, a pivot table is
a table to show values grouped by some fields.
## Example 1
genderToString : Gender -> String
genderToString gender =
case gender of
Male -> "Male"
Female -> "Female"
pivotTable
{ rowGroupFields = []
, colGroupFields = [ genderField ]
, aggregator = List.length
, viewRow = always Element.none
, viewCol = Element.text
, viewAgg = String.fromInt >> Element.text
}
myTable
The code above produces a table:
```text
|Male |Female |
|-----|-------|
|2 |1 |
```
@docs Aggregator, pivotTable, pivotTableHtml
-}
import Array exposing (Array)
import Element
exposing
( Element
, column
, el
, fill
, fillPortion
, height
, none
, row
, shrink
, width
)
import Html
exposing
( Html
, table
, td
, th
, tr
, div
)
import Html.Attributes
exposing
( colspan
, rowspan
, style
)
import List.Extra
import Set exposing (Set)
{-| In this package, a table is defined as a list of rows.
In the most naive case, a table may be represented by a list of records like:
type alias Person =
{ name : String
, age : Int
, gender : Gender
}
type Gender
= Male
| Female
type alias MyTable =
Table Person
**Note:** Notice that rows can be any type.
-}
type Table row
= Table (List row)
{-| A function to create a table.
Since the `Table` is an opaque type, all user of this package must use this
function to create a `Table` value.
-}
makeTable : List row -> Table row
makeTable rows =
Table rows
{-| In this package, a field is defined as a function from row to something.
-}
type alias Field row a =
row -> a
{-| A function to get values from a table.
With the example appeared in the [`Table` doc](#Table),
each field can be accessed like:
nameField = .name
ageField = .age
genderField = .gender
myTable : MyTable
myTable = makeTable
[ { name = "Alice", age = 17, gender = Female }
, { name = "Bob", age = 8, gender = Male }
, { name = "Charlie", age = 35, gender = Male }
]
getField nameField myTable -- ["Alice", "Bob", "Charlie"]
getField ageField myTable -- [17, 8, 35]
getField genderField myTable -- [Female, Male, Male]
**Note:** Notice that a field does not have to be a record element.
This is a valid code:
nameInitialLetterField = .name >> String.left 1
getField nameInitialLetterField myTable -- ["A", "B", "C"]
-}
getField : Field row a -> Table row -> List a
getField field (Table rows) =
List.map field rows
-- Utility functions for `Table`
length : Table row -> Int
length (Table rows) =
List.length rows
map : (row1 -> row2) -> Table row1 -> Table row2
map f (Table rows) =
rows |> List.map f |> Table
indexedMap : (Int -> row1 -> row2) -> Table row1 -> Table row2
indexedMap f (Table rows) =
rows |> List.indexedMap f |> Table
-- Grouping functions
{-| Group rows by a given field, that is, the same group has the same field value.
Result is a list of groups.
A group is composed of a field value (of type `comparable`) and a table value.
All rows in this table has the same field value.
-}
groupByField : Field row comparable -> Table row -> List ( comparable, Table row )
groupByField field (Table rows) =
rows
|> List.sortBy field
-- sorting is necessary for `List.Extra.groupWhile`
|> List.Extra.groupWhile (\r1 r2 -> field r1 == field r2)
|> List.map (\( first, rest ) -> ( field first, Table (first :: rest) ))
{-| Group rows by given several fields.
Notice that group of a group forms a tree.
See [`Tree` definition](#Tree) for detail.
-}
group : List (Field row comparable) -> Table row -> Tree row comparable
group fields tbl =
let
reduce : Field row comparable -> Tree row comparable -> Tree row comparable
reduce field tree =
case tree of
Leaf tbl_ ->
groupByField field tbl_
|> List.map (Tuple.mapSecond Leaf)
|> Node
Node lst ->
lst
|> List.map (Tuple.mapSecond (reduce field))
|> Node
in
List.foldl reduce (Leaf tbl) fields
{-| A type representing a result of the `group` function.
Grouping by several fields forms a tree.
## Example
myTable2 =
makeTable
[ { col1 = "A", col2 = 1, col3 = "a", col4 = 1 }
, { col1 = "A", col2 = 1, col3 = "b", col4 = 2 }
, { col1 = "A", col2 = 2, col3 = "a", col4 = 1 }
, { col1 = "A", col2 = 2, col3 = "b", col4 = 2 }
, { col1 = "A", col2 = 2, col3 = "c", col4 = 3 }
, { col1 = "A", col2 = 3, col3 = "a", col4 = 1 }
, { col1 = "A", col2 = 3, col3 = "a", col4 = 2 }
, { col1 = "B", col2 = 2, col3 = "a", col4 = 1 }
, { col1 = "B", col2 = 2, col3 = "b", col4 = 2 }
, { col1 = "B", col2 = 2, col3 = "c", col4 = 3 }
]
- col1 = "A"
- col2 = 1
- col3 = "a"
- row#1
- col3 = \*b
- row#2
- col2 = 2
- col3 = "a"
- row#3
- col3 = "b"
- row#4
- col3 = "c"
- row#5
- col2 = 3
- col3 = "a"
- row#6, row#7
- col1 = "B"
- col2 = 2
- col3 = "a"
- row#8
- col3 = "b"
- row#9
- col3 = "c"
- row#10
-}
type Tree row comparable
= Node (List ( comparable, Tree row comparable ))
| Leaf (Table row)
-- Tree utility functions
{-| A path of a tree from the root to a leaf
-}
type alias TreePath comparable =
List comparable
{-| Get a tree by path.
-}
getTreeAt : TreePath comparable -> Tree row comparable -> Maybe (Tree row comparable)
getTreeAt path tree =
case path of
[] ->
Just tree
first :: rest ->
case tree of
Leaf _ ->
Nothing
Node lst ->
lst
|> List.filter (\( c, _ ) -> c == first)
|> List.head
|> Maybe.andThen (\( _, subTree ) -> getTreeAt rest subTree)
{-| Get a tree by path, only when the path reaches a leaf.
-}
getAt : TreePath comparable -> Tree row comparable -> Maybe (Table row)
getAt path tree =
case getTreeAt path tree of
Nothing ->
Nothing
Just (Node _) ->
Nothing
Just (Leaf tbl) ->
Just tbl
{-| Get possible paths from given tree.
-}
getPaths : Tree row comparable -> List (TreePath comparable)
getPaths tree =
case tree of
Leaf _ ->
[ [] ]
Node lst ->
lst
|> List.map (Tuple.mapSecond getPaths)
|> List.concatMap (\( c, paths ) -> paths |> List.map (\path -> c :: path))
{-| Convert row type into another type.
-}
mapTree : (row1 -> row2) -> Tree row1 comparable -> Tree row2 comparable
mapTree f tree =
case tree of
Node lst ->
lst
|> List.map (Tuple.mapSecond (mapTree f))
|> Node
Leaf tbl ->
Leaf (map f tbl)
{-| Extract all `Table` values from given tree.
The result is a list of tables ordered by depth-first-search order.
-}
treeToTableList : Tree row comparable -> List (Table row)
treeToTableList tree =
case tree of
Leaf tbl ->
[ tbl ]
Node lst ->
List.concatMap (Tuple.second >> treeToTableList) lst
{-| Get the width of a tree, which is the number of leafs the tree has.
-}
getWidth : Tree row comparable -> Int
getWidth tree =
case tree of
Leaf _ ->
1
Node lst ->
lst |> List.map (Tuple.second >> getWidth) |> List.sum
{-| Apply a function in breadth-first-search order.
The result is a list of each levels result, that is:
result = applyHorizontally f tree
List.Extra.getAt 0 result == Just firstDepthResult
List.Extra.getAt 1 result == Just secondDepthResult
List.Extra.getAt 2 result == Just thirdDepthResult
-}
applyHorizontally : (( comparable, Tree row comparable ) -> a) -> Tree row comparable -> List (List a)
applyHorizontally f tree =
let
applyOneLevel : Tree row comparable -> List a
applyOneLevel tree_ =
case tree_ of
Leaf _ ->
[]
Node lst ->
List.map f lst
getSubTrees : Tree row comparable -> List (Tree row comparable)
getSubTrees tree_ =
case tree_ of
Leaf _ ->
[]
Node lst ->
List.map Tuple.second lst
g : List (Tree row comparable) -> List (List a) -> List (List a)
g trees prevResult =
let
result : List a
result =
List.concatMap applyOneLevel trees
nextResult : List (List a)
nextResult =
result :: prevResult
in
case result of
[] ->
prevResult
_ ->
g (List.concatMap getSubTrees trees) nextResult
in
g [ tree ] [] |> List.reverse
-- Pivot table functions
{-| The pivot table groups table rows.
After that, the `Aggregator` aggregates
the list of rows into a single value (of any type).
-}
type alias Aggregator row agg =
List row -> agg
{-| Draws a pivot table of `Html` type.
This view makes use of grid attributes of html table.
Use this view function when you want to avoid using `elm-ui`.
-}
pivotTableHtml :
{ rowGroupFields : List (Field row comparable1)
, colGroupFields : List (Field row comparable2)
, aggregator : Aggregator row agg
, viewRow : comparable1 -> Html msg
, viewCol : comparable2 -> Html msg
, viewAgg : agg -> Html msg
}
-> Table row
-> Html msg
pivotTableHtml { rowGroupFields, colGroupFields, aggregator, viewRow, viewCol, viewAgg } tbl =
let
indexedTable : Table ( Int, row )
indexedTable =
indexedMap Tuple.pair tbl
getRowByIndex : Table row -> Int -> Maybe row
getRowByIndex (Table lst) index =
List.Extra.getAt index lst
-- ignore index
columnShim : Field row comparable -> Field ( Int, row ) comparable
columnShim col =
Tuple.second >> col
rowGroup : Tree Int comparable1
rowGroup =
group (List.map columnShim rowGroupFields) indexedTable |> mapTree Tuple.first
colGroup : Tree Int comparable2
colGroup =
group (List.map columnShim colGroupFields) indexedTable |> mapTree Tuple.first
getIndices : Table Int -> Set Int
getIndices (Table indices) =
Set.fromList indices
rowDepth : Int
rowDepth = List.length rowGroupFields
colDepth : Int
colDepth = List.length colGroupFields
rowIndexSets : List (Int, Set Int)
rowIndexSets = getPaths rowGroup
|> List.filterMap (\path -> getAt path rowGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
colIndexSets : List (Int, Set Int)
colIndexSets = getPaths colGroup
|> List.filterMap (\path -> getAt path colGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
viewHeadersHelper :
(comparable -> Html msg)
-> Tree Int comparable
-> List
{ depth : Int
, view : Html msg
, span : Int
, offset : Int
}
viewHeadersHelper viewer grp = grp
|> applyHorizontally identity
|> List.indexedMap (\i lst -> lst
|> List.foldl (\(c, subTree) result ->
{ depth = i
, view = viewer c
, span = getWidth subTree
, offset = result |> List.map .span |> List.sum
} :: result)
[]
)
|> List.concatMap identity
rowHeaders : List (Html msg)
rowHeaders = viewHeadersHelper viewRow rowGroup
|> List.map (\{ depth, view, span, offset } -> div
[ style "grid-row-start" <| String.fromInt <| colDepth + offset + 1
, style "grid-row-end" <| String.fromInt <| colDepth + offset + 1 + span
, style "grid-column-start" <| String.fromInt <| depth + 1
, style "grid-column-end" <| String.fromInt <| depth + 2
]
[ view ]
)
colHeaders : List (Html msg)
colHeaders = viewHeadersHelper viewCol colGroup
|> List.map (\{ depth, view, span, offset } -> div
[ style "grid-row-start" <| String.fromInt <| depth + 1
, style "grid-row-end" <| String.fromInt <| depth + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + offset + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + offset + 1 + span
]
[ view ]
)
dataCells : List (Html msg)
dataCells = List.Extra.cartesianProduct [rowIndexSets, colIndexSets]
|> List.filterMap (\lst ->
case lst of
item1 :: item2 :: [] -> Just (item1, item2)
_ -> Nothing
)
|> List.map (\((i, rowIndices), (j, colIndices)) -> div
[ style "grid-row-start" <| String.fromInt <| colDepth + i + 1
, style "grid-row-end" <| String.fromInt <| colDepth + i + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + j + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + j + 2
]
[ Set.intersect rowIndices colIndices
|> Set.toList
|> List.filterMap (getRowByIndex tbl)
|> aggregator
|> viewAgg
])
in
div
[ style "display" "inline-grid"
, style "grid-template-rows" <| String.join " " <| List.repeat (colDepth + getWidth rowGroup) "auto"
, style "grid-template-columns" <| String.join " " <| List.repeat (rowDepth + getWidth colGroup) "auto"
]
(rowHeaders ++ colHeaders ++ dataCells)
{- Draws a pivot table of `Html` type.
This view makes use of `colspan` and `rowspan` attributes of html table.
Use this view function when you want to avoid using `elm-ui`.
-}
{-
pivotTableHtml :
{ rowGroupFields : List (Field row comparable1)
, colGroupFields : List (Field row comparable2)
, aggregator : Aggregator row agg
, viewRow : comparable1 -> Html msg
, viewCol : comparable2 -> Html msg
, viewAgg : agg -> Html msg
}
-> Table row
-> Html msg
pivotTableHtml { rowGroupFields, colGroupFields, aggregator, viewRow, viewCol, viewAgg } tbl =
let
indexedTable : Table ( Int, row )
indexedTable =
indexedMap Tuple.pair tbl
getRowByIndex : Table row -> Int -> Maybe row
getRowByIndex (Table lst) index =
List.Extra.getAt index lst
-- ignore index
columnShim : Field row comparable -> Field ( Int, row ) comparable
columnShim col =
Tuple.second >> col
rowGroup : Tree Int comparable1
rowGroup =
group (List.map columnShim rowGroupFields) indexedTable |> mapTree Tuple.first
colGroup : Tree Int comparable2
colGroup =
group (List.map columnShim colGroupFields) indexedTable |> mapTree Tuple.first
-- rowPaths : List (TreePath comparable1)
-- rowPaths = getPaths rowGroup
colPaths : List (TreePath comparable2)
colPaths =
getPaths colGroup
viewColHeaderCells : Tree Int comparable2 -> List ( Html msg, Tree Int comparable2 )
viewColHeaderCells tree =
let
f : ( comparable2, Tree Int comparable2 ) -> ( Html msg, Tree Int comparable2 )
f ( c, subTree ) =
( th [ colspan <| getWidth subTree ] [ viewCol c ], subTree )
in
case tree of
Leaf _ ->
[]
Node lst ->
List.map f lst
viewColHeaders : List (Tree Int comparable2) -> List (Html msg)
viewColHeaders trees =
case trees of
[] ->
[]
_ ->
let
tmp1 : List ( Html msg, Tree Int comparable2 )
tmp1 =
List.concatMap viewColHeaderCells trees
cells : List (Html msg)
cells =
List.map Tuple.first tmp1
subTrees : List (Tree Int comparable2)
subTrees =
List.map Tuple.second tmp1
shim : Html msg
shim =
td [ colspan <| List.length rowGroupFields ] []
in
if List.length rowGroupFields == 0 then
tr [] cells :: viewColHeaders subTrees
else
tr [] (shim :: cells) :: viewColHeaders subTrees
pathToTableItems : List (Maybe ( Int, comparable1 )) -> List (Html msg)
pathToTableItems lst =
List.filterMap (Maybe.map (\( width, c ) -> th [ rowspan width ] [ viewRow c ])) lst
aggregateForRow : Table Int -> List (Html msg)
aggregateForRow tbl_ =
colPaths
|> List.filterMap (\path -> getAt path colGroup)
|> List.map getIndices
|> List.map (Set.intersect (getIndices tbl_))
|> List.map Set.toList
|> List.map (List.filterMap (getRowByIndex tbl))
|> List.map aggregator
|> List.map viewAgg
|> List.map List.singleton
|> List.map (td [])
viewRows : Tree Int comparable1 -> List (Html msg)
viewRows tree =
List.map2 Tuple.pair (organize tree) (treeToTableList tree)
|> List.map (Tuple.mapBoth pathToTableItems aggregateForRow)
|> List.map (\( x, y ) -> List.append x y)
|> List.map (tr [])
organize : Tree Int comparable1 -> List (List (Maybe ( Int, comparable1 )))
organize tree =
let
f :
( comparable1, Tree Int comparable1 )
-> List (List (Maybe ( Int, comparable1 )))
f ( c, subTree ) =
organize subTree
|> List.indexedMap (g c subTree)
g :
comparable1
-> Tree Int comparable1
-> Int
-> List (Maybe ( Int, comparable1 ))
-> List (Maybe ( Int, comparable1 ))
g c subTree i path =
if i == 0 then
Just ( getWidth subTree, c ) :: path
else
Nothing :: path
in
case tree of
Leaf _ ->
[ [] ]
Node lst ->
List.concatMap f lst
getIndices : Table Int -> Set Int
getIndices (Table indices) =
Set.fromList indices
in
viewColHeaders [ colGroup ] ++ viewRows rowGroup |> table []
-}
{-| Draws a pivot table.
- `rowGroupFields` is a list of `Field`'s to group and generates grouped _rows_.
- `colGroupFields` is a list of `Field`'s to group and generates grouped _columns_.
- `aggregator` aggregates each grouped set of table data into a single value.
- `viewRow`, `viewCol` and `viewAgg` are view functions to show each headers and cells.
-}
pivotTable :
{ rowGroupFields : List (Field row comparable1)
, colGroupFields : List (Field row comparable2)
, aggregator : Aggregator row agg
, viewRow : comparable1 -> Element msg
, viewCol : comparable2 -> Element msg
, viewAgg : agg -> Element msg
}
-> Table row
-> Element msg
pivotTable { rowGroupFields, colGroupFields, aggregator, viewRow, viewCol, viewAgg } (Table rows) =
let
indexedTable : Table ( Int, row )
indexedTable =
indexedMap Tuple.pair (Table rows)
getRowByIndex : Table row -> Int -> Maybe row
getRowByIndex (Table lst) index =
List.Extra.getAt index lst
-- ignore index
columnShim : Field row comparable -> Field ( Int, row ) comparable
columnShim col =
Tuple.second >> col
rowGroup : Tree Int comparable1
rowGroup =
group (List.map columnShim rowGroupFields) indexedTable |> mapTree Tuple.first
colGroup : Tree Int comparable2
colGroup =
group (List.map columnShim colGroupFields) indexedTable |> mapTree Tuple.first
getIndices : Table Int -> Set Int
getIndices (Table indices) =
Set.fromList indices
rowDepth : Int
rowDepth = List.length rowGroupFields
colDepth : Int
colDepth = List.length colGroupFields
rowIndexSets : List (Int, Set Int)
rowIndexSets = getPaths rowGroup
|> List.filterMap (\path -> getAt path rowGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
colIndexSets : List (Int, Set Int)
colIndexSets = getPaths colGroup
|> List.filterMap (\path -> getAt path colGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
viewHeadersHelper :
(comparable -> Element msg)
-> Tree Int comparable
-> List
{ depth : Int
, view : Element msg
, span : Int
, offset : Int
}
viewHeadersHelper viewer grp = grp
|> applyHorizontally identity
|> List.indexedMap (\i lst -> lst
|> List.foldl (\(c, subTree) result ->
{ depth = i
, view = viewer c
, span = getWidth subTree
, offset = result |> List.map .span |> List.sum
} :: result)
[]
)
|> List.concatMap identity
rowHeaders : List (Element msg)
rowHeaders = viewHeadersHelper viewRow rowGroup
|> List.map (\{ depth, view, span, offset } -> el
(List.map Element.htmlAttribute
[ style "grid-row-start" <| String.fromInt <| colDepth + offset + 1
, style "grid-row-end" <| String.fromInt <| colDepth + offset + 1 + span
, style "grid-column-start" <| String.fromInt <| depth + 1
, style "grid-column-end" <| String.fromInt <| depth + 2
])
view
)
colHeaders : List (Element msg)
colHeaders = viewHeadersHelper viewCol colGroup
|> List.map (\{ depth, view, span, offset } -> el
(List.map Element.htmlAttribute
[ style "grid-row-start" <| String.fromInt <| depth + 1
, style "grid-row-end" <| String.fromInt <| depth + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + offset + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + offset + 1 + span
])
view
)
dataCells : List (Element msg)
dataCells = List.Extra.cartesianProduct [rowIndexSets, colIndexSets]
|> List.filterMap (\lst ->
case lst of
item1 :: item2 :: [] -> Just (item1, item2)
_ -> Nothing
)
|> List.map (\((i, rowIndices), (j, colIndices)) -> el
(List.map Element.htmlAttribute
[ style "grid-row-start" <| String.fromInt <| colDepth + i + 1
, style "grid-row-end" <| String.fromInt <| colDepth + i + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + j + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + j + 2
])
(Set.intersect rowIndices colIndices
|> Set.toList
|> List.filterMap (getRowByIndex (Table rows))
|> aggregator
|> viewAgg
))
in
Element.paragraph
(List.map Element.htmlAttribute
[ style "display" "inline-grid"
, style "grid-template-rows" <| String.join " " <| List.repeat (colDepth + getWidth rowGroup) "auto"
, style "grid-template-columns" <| String.join " " <| List.repeat (rowDepth + getWidth colGroup) "auto"
] ++ [Element.width Element.shrink])
(rowHeaders ++ colHeaders ++ dataCells)
| 44445 | module PivotTable exposing
( Table, Field
, makeTable, getField
, Aggregator, pivotTable, pivotTableHtml
)
{-| This package provides a pivot table view function with which
you can analyze and visualize your data by grouping various fields.
# Definition
@docs Table, Field
# Table operations
@docs makeTable, getField
# Pivot table
In this package, a pivot table is
a table to show values grouped by some fields.
## Example 1
genderToString : Gender -> String
genderToString gender =
case gender of
Male -> "Male"
Female -> "Female"
pivotTable
{ rowGroupFields = []
, colGroupFields = [ genderField ]
, aggregator = List.length
, viewRow = always Element.none
, viewCol = Element.text
, viewAgg = String.fromInt >> Element.text
}
myTable
The code above produces a table:
```text
|Male |Female |
|-----|-------|
|2 |1 |
```
@docs Aggregator, pivotTable, pivotTableHtml
-}
import Array exposing (Array)
import Element
exposing
( Element
, column
, el
, fill
, fillPortion
, height
, none
, row
, shrink
, width
)
import Html
exposing
( Html
, table
, td
, th
, tr
, div
)
import Html.Attributes
exposing
( colspan
, rowspan
, style
)
import List.Extra
import Set exposing (Set)
{-| In this package, a table is defined as a list of rows.
In the most naive case, a table may be represented by a list of records like:
type alias Person =
{ name : String
, age : Int
, gender : Gender
}
type Gender
= Male
| Female
type alias MyTable =
Table Person
**Note:** Notice that rows can be any type.
-}
type Table row
= Table (List row)
{-| A function to create a table.
Since the `Table` is an opaque type, all user of this package must use this
function to create a `Table` value.
-}
makeTable : List row -> Table row
makeTable rows =
Table rows
{-| In this package, a field is defined as a function from row to something.
-}
type alias Field row a =
row -> a
{-| A function to get values from a table.
With the example appeared in the [`Table` doc](#Table),
each field can be accessed like:
nameField = .name
ageField = .age
genderField = .gender
myTable : MyTable
myTable = makeTable
[ { name = "<NAME>", age = 17, gender = Female }
, { name = "<NAME>", age = 8, gender = Male }
, { name = "<NAME>", age = 35, gender = Male }
]
getField nameField myTable -- ["<NAME>", "<NAME>", "<NAME>"]
getField ageField myTable -- [17, 8, 35]
getField genderField myTable -- [Female, Male, Male]
**Note:** Notice that a field does not have to be a record element.
This is a valid code:
nameInitialLetterField = .name >> String.left 1
getField nameInitialLetterField myTable -- ["A", "B", "C"]
-}
getField : Field row a -> Table row -> List a
getField field (Table rows) =
List.map field rows
-- Utility functions for `Table`
length : Table row -> Int
length (Table rows) =
List.length rows
map : (row1 -> row2) -> Table row1 -> Table row2
map f (Table rows) =
rows |> List.map f |> Table
indexedMap : (Int -> row1 -> row2) -> Table row1 -> Table row2
indexedMap f (Table rows) =
rows |> List.indexedMap f |> Table
-- Grouping functions
{-| Group rows by a given field, that is, the same group has the same field value.
Result is a list of groups.
A group is composed of a field value (of type `comparable`) and a table value.
All rows in this table has the same field value.
-}
groupByField : Field row comparable -> Table row -> List ( comparable, Table row )
groupByField field (Table rows) =
rows
|> List.sortBy field
-- sorting is necessary for `List.Extra.groupWhile`
|> List.Extra.groupWhile (\r1 r2 -> field r1 == field r2)
|> List.map (\( first, rest ) -> ( field first, Table (first :: rest) ))
{-| Group rows by given several fields.
Notice that group of a group forms a tree.
See [`Tree` definition](#Tree) for detail.
-}
group : List (Field row comparable) -> Table row -> Tree row comparable
group fields tbl =
let
reduce : Field row comparable -> Tree row comparable -> Tree row comparable
reduce field tree =
case tree of
Leaf tbl_ ->
groupByField field tbl_
|> List.map (Tuple.mapSecond Leaf)
|> Node
Node lst ->
lst
|> List.map (Tuple.mapSecond (reduce field))
|> Node
in
List.foldl reduce (Leaf tbl) fields
{-| A type representing a result of the `group` function.
Grouping by several fields forms a tree.
## Example
myTable2 =
makeTable
[ { col1 = "A", col2 = 1, col3 = "a", col4 = 1 }
, { col1 = "A", col2 = 1, col3 = "b", col4 = 2 }
, { col1 = "A", col2 = 2, col3 = "a", col4 = 1 }
, { col1 = "A", col2 = 2, col3 = "b", col4 = 2 }
, { col1 = "A", col2 = 2, col3 = "c", col4 = 3 }
, { col1 = "A", col2 = 3, col3 = "a", col4 = 1 }
, { col1 = "A", col2 = 3, col3 = "a", col4 = 2 }
, { col1 = "B", col2 = 2, col3 = "a", col4 = 1 }
, { col1 = "B", col2 = 2, col3 = "b", col4 = 2 }
, { col1 = "B", col2 = 2, col3 = "c", col4 = 3 }
]
- col1 = "A"
- col2 = 1
- col3 = "a"
- row#1
- col3 = \*b
- row#2
- col2 = 2
- col3 = "a"
- row#3
- col3 = "b"
- row#4
- col3 = "c"
- row#5
- col2 = 3
- col3 = "a"
- row#6, row#7
- col1 = "B"
- col2 = 2
- col3 = "a"
- row#8
- col3 = "b"
- row#9
- col3 = "c"
- row#10
-}
type Tree row comparable
= Node (List ( comparable, Tree row comparable ))
| Leaf (Table row)
-- Tree utility functions
{-| A path of a tree from the root to a leaf
-}
type alias TreePath comparable =
List comparable
{-| Get a tree by path.
-}
getTreeAt : TreePath comparable -> Tree row comparable -> Maybe (Tree row comparable)
getTreeAt path tree =
case path of
[] ->
Just tree
first :: rest ->
case tree of
Leaf _ ->
Nothing
Node lst ->
lst
|> List.filter (\( c, _ ) -> c == first)
|> List.head
|> Maybe.andThen (\( _, subTree ) -> getTreeAt rest subTree)
{-| Get a tree by path, only when the path reaches a leaf.
-}
getAt : TreePath comparable -> Tree row comparable -> Maybe (Table row)
getAt path tree =
case getTreeAt path tree of
Nothing ->
Nothing
Just (Node _) ->
Nothing
Just (Leaf tbl) ->
Just tbl
{-| Get possible paths from given tree.
-}
getPaths : Tree row comparable -> List (TreePath comparable)
getPaths tree =
case tree of
Leaf _ ->
[ [] ]
Node lst ->
lst
|> List.map (Tuple.mapSecond getPaths)
|> List.concatMap (\( c, paths ) -> paths |> List.map (\path -> c :: path))
{-| Convert row type into another type.
-}
mapTree : (row1 -> row2) -> Tree row1 comparable -> Tree row2 comparable
mapTree f tree =
case tree of
Node lst ->
lst
|> List.map (Tuple.mapSecond (mapTree f))
|> Node
Leaf tbl ->
Leaf (map f tbl)
{-| Extract all `Table` values from given tree.
The result is a list of tables ordered by depth-first-search order.
-}
treeToTableList : Tree row comparable -> List (Table row)
treeToTableList tree =
case tree of
Leaf tbl ->
[ tbl ]
Node lst ->
List.concatMap (Tuple.second >> treeToTableList) lst
{-| Get the width of a tree, which is the number of leafs the tree has.
-}
getWidth : Tree row comparable -> Int
getWidth tree =
case tree of
Leaf _ ->
1
Node lst ->
lst |> List.map (Tuple.second >> getWidth) |> List.sum
{-| Apply a function in breadth-first-search order.
The result is a list of each levels result, that is:
result = applyHorizontally f tree
List.Extra.getAt 0 result == Just firstDepthResult
List.Extra.getAt 1 result == Just secondDepthResult
List.Extra.getAt 2 result == Just thirdDepthResult
-}
applyHorizontally : (( comparable, Tree row comparable ) -> a) -> Tree row comparable -> List (List a)
applyHorizontally f tree =
let
applyOneLevel : Tree row comparable -> List a
applyOneLevel tree_ =
case tree_ of
Leaf _ ->
[]
Node lst ->
List.map f lst
getSubTrees : Tree row comparable -> List (Tree row comparable)
getSubTrees tree_ =
case tree_ of
Leaf _ ->
[]
Node lst ->
List.map Tuple.second lst
g : List (Tree row comparable) -> List (List a) -> List (List a)
g trees prevResult =
let
result : List a
result =
List.concatMap applyOneLevel trees
nextResult : List (List a)
nextResult =
result :: prevResult
in
case result of
[] ->
prevResult
_ ->
g (List.concatMap getSubTrees trees) nextResult
in
g [ tree ] [] |> List.reverse
-- Pivot table functions
{-| The pivot table groups table rows.
After that, the `Aggregator` aggregates
the list of rows into a single value (of any type).
-}
type alias Aggregator row agg =
List row -> agg
{-| Draws a pivot table of `Html` type.
This view makes use of grid attributes of html table.
Use this view function when you want to avoid using `elm-ui`.
-}
pivotTableHtml :
{ rowGroupFields : List (Field row comparable1)
, colGroupFields : List (Field row comparable2)
, aggregator : Aggregator row agg
, viewRow : comparable1 -> Html msg
, viewCol : comparable2 -> Html msg
, viewAgg : agg -> Html msg
}
-> Table row
-> Html msg
pivotTableHtml { rowGroupFields, colGroupFields, aggregator, viewRow, viewCol, viewAgg } tbl =
let
indexedTable : Table ( Int, row )
indexedTable =
indexedMap Tuple.pair tbl
getRowByIndex : Table row -> Int -> Maybe row
getRowByIndex (Table lst) index =
List.Extra.getAt index lst
-- ignore index
columnShim : Field row comparable -> Field ( Int, row ) comparable
columnShim col =
Tuple.second >> col
rowGroup : Tree Int comparable1
rowGroup =
group (List.map columnShim rowGroupFields) indexedTable |> mapTree Tuple.first
colGroup : Tree Int comparable2
colGroup =
group (List.map columnShim colGroupFields) indexedTable |> mapTree Tuple.first
getIndices : Table Int -> Set Int
getIndices (Table indices) =
Set.fromList indices
rowDepth : Int
rowDepth = List.length rowGroupFields
colDepth : Int
colDepth = List.length colGroupFields
rowIndexSets : List (Int, Set Int)
rowIndexSets = getPaths rowGroup
|> List.filterMap (\path -> getAt path rowGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
colIndexSets : List (Int, Set Int)
colIndexSets = getPaths colGroup
|> List.filterMap (\path -> getAt path colGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
viewHeadersHelper :
(comparable -> Html msg)
-> Tree Int comparable
-> List
{ depth : Int
, view : Html msg
, span : Int
, offset : Int
}
viewHeadersHelper viewer grp = grp
|> applyHorizontally identity
|> List.indexedMap (\i lst -> lst
|> List.foldl (\(c, subTree) result ->
{ depth = i
, view = viewer c
, span = getWidth subTree
, offset = result |> List.map .span |> List.sum
} :: result)
[]
)
|> List.concatMap identity
rowHeaders : List (Html msg)
rowHeaders = viewHeadersHelper viewRow rowGroup
|> List.map (\{ depth, view, span, offset } -> div
[ style "grid-row-start" <| String.fromInt <| colDepth + offset + 1
, style "grid-row-end" <| String.fromInt <| colDepth + offset + 1 + span
, style "grid-column-start" <| String.fromInt <| depth + 1
, style "grid-column-end" <| String.fromInt <| depth + 2
]
[ view ]
)
colHeaders : List (Html msg)
colHeaders = viewHeadersHelper viewCol colGroup
|> List.map (\{ depth, view, span, offset } -> div
[ style "grid-row-start" <| String.fromInt <| depth + 1
, style "grid-row-end" <| String.fromInt <| depth + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + offset + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + offset + 1 + span
]
[ view ]
)
dataCells : List (Html msg)
dataCells = List.Extra.cartesianProduct [rowIndexSets, colIndexSets]
|> List.filterMap (\lst ->
case lst of
item1 :: item2 :: [] -> Just (item1, item2)
_ -> Nothing
)
|> List.map (\((i, rowIndices), (j, colIndices)) -> div
[ style "grid-row-start" <| String.fromInt <| colDepth + i + 1
, style "grid-row-end" <| String.fromInt <| colDepth + i + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + j + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + j + 2
]
[ Set.intersect rowIndices colIndices
|> Set.toList
|> List.filterMap (getRowByIndex tbl)
|> aggregator
|> viewAgg
])
in
div
[ style "display" "inline-grid"
, style "grid-template-rows" <| String.join " " <| List.repeat (colDepth + getWidth rowGroup) "auto"
, style "grid-template-columns" <| String.join " " <| List.repeat (rowDepth + getWidth colGroup) "auto"
]
(rowHeaders ++ colHeaders ++ dataCells)
{- Draws a pivot table of `Html` type.
This view makes use of `colspan` and `rowspan` attributes of html table.
Use this view function when you want to avoid using `elm-ui`.
-}
{-
pivotTableHtml :
{ rowGroupFields : List (Field row comparable1)
, colGroupFields : List (Field row comparable2)
, aggregator : Aggregator row agg
, viewRow : comparable1 -> Html msg
, viewCol : comparable2 -> Html msg
, viewAgg : agg -> Html msg
}
-> Table row
-> Html msg
pivotTableHtml { rowGroupFields, colGroupFields, aggregator, viewRow, viewCol, viewAgg } tbl =
let
indexedTable : Table ( Int, row )
indexedTable =
indexedMap Tuple.pair tbl
getRowByIndex : Table row -> Int -> Maybe row
getRowByIndex (Table lst) index =
List.Extra.getAt index lst
-- ignore index
columnShim : Field row comparable -> Field ( Int, row ) comparable
columnShim col =
Tuple.second >> col
rowGroup : Tree Int comparable1
rowGroup =
group (List.map columnShim rowGroupFields) indexedTable |> mapTree Tuple.first
colGroup : Tree Int comparable2
colGroup =
group (List.map columnShim colGroupFields) indexedTable |> mapTree Tuple.first
-- rowPaths : List (TreePath comparable1)
-- rowPaths = getPaths rowGroup
colPaths : List (TreePath comparable2)
colPaths =
getPaths colGroup
viewColHeaderCells : Tree Int comparable2 -> List ( Html msg, Tree Int comparable2 )
viewColHeaderCells tree =
let
f : ( comparable2, Tree Int comparable2 ) -> ( Html msg, Tree Int comparable2 )
f ( c, subTree ) =
( th [ colspan <| getWidth subTree ] [ viewCol c ], subTree )
in
case tree of
Leaf _ ->
[]
Node lst ->
List.map f lst
viewColHeaders : List (Tree Int comparable2) -> List (Html msg)
viewColHeaders trees =
case trees of
[] ->
[]
_ ->
let
tmp1 : List ( Html msg, Tree Int comparable2 )
tmp1 =
List.concatMap viewColHeaderCells trees
cells : List (Html msg)
cells =
List.map Tuple.first tmp1
subTrees : List (Tree Int comparable2)
subTrees =
List.map Tuple.second tmp1
shim : Html msg
shim =
td [ colspan <| List.length rowGroupFields ] []
in
if List.length rowGroupFields == 0 then
tr [] cells :: viewColHeaders subTrees
else
tr [] (shim :: cells) :: viewColHeaders subTrees
pathToTableItems : List (Maybe ( Int, comparable1 )) -> List (Html msg)
pathToTableItems lst =
List.filterMap (Maybe.map (\( width, c ) -> th [ rowspan width ] [ viewRow c ])) lst
aggregateForRow : Table Int -> List (Html msg)
aggregateForRow tbl_ =
colPaths
|> List.filterMap (\path -> getAt path colGroup)
|> List.map getIndices
|> List.map (Set.intersect (getIndices tbl_))
|> List.map Set.toList
|> List.map (List.filterMap (getRowByIndex tbl))
|> List.map aggregator
|> List.map viewAgg
|> List.map List.singleton
|> List.map (td [])
viewRows : Tree Int comparable1 -> List (Html msg)
viewRows tree =
List.map2 Tuple.pair (organize tree) (treeToTableList tree)
|> List.map (Tuple.mapBoth pathToTableItems aggregateForRow)
|> List.map (\( x, y ) -> List.append x y)
|> List.map (tr [])
organize : Tree Int comparable1 -> List (List (Maybe ( Int, comparable1 )))
organize tree =
let
f :
( comparable1, Tree Int comparable1 )
-> List (List (Maybe ( Int, comparable1 )))
f ( c, subTree ) =
organize subTree
|> List.indexedMap (g c subTree)
g :
comparable1
-> Tree Int comparable1
-> Int
-> List (Maybe ( Int, comparable1 ))
-> List (Maybe ( Int, comparable1 ))
g c subTree i path =
if i == 0 then
Just ( getWidth subTree, c ) :: path
else
Nothing :: path
in
case tree of
Leaf _ ->
[ [] ]
Node lst ->
List.concatMap f lst
getIndices : Table Int -> Set Int
getIndices (Table indices) =
Set.fromList indices
in
viewColHeaders [ colGroup ] ++ viewRows rowGroup |> table []
-}
{-| Draws a pivot table.
- `rowGroupFields` is a list of `Field`'s to group and generates grouped _rows_.
- `colGroupFields` is a list of `Field`'s to group and generates grouped _columns_.
- `aggregator` aggregates each grouped set of table data into a single value.
- `viewRow`, `viewCol` and `viewAgg` are view functions to show each headers and cells.
-}
pivotTable :
{ rowGroupFields : List (Field row comparable1)
, colGroupFields : List (Field row comparable2)
, aggregator : Aggregator row agg
, viewRow : comparable1 -> Element msg
, viewCol : comparable2 -> Element msg
, viewAgg : agg -> Element msg
}
-> Table row
-> Element msg
pivotTable { rowGroupFields, colGroupFields, aggregator, viewRow, viewCol, viewAgg } (Table rows) =
let
indexedTable : Table ( Int, row )
indexedTable =
indexedMap Tuple.pair (Table rows)
getRowByIndex : Table row -> Int -> Maybe row
getRowByIndex (Table lst) index =
List.Extra.getAt index lst
-- ignore index
columnShim : Field row comparable -> Field ( Int, row ) comparable
columnShim col =
Tuple.second >> col
rowGroup : Tree Int comparable1
rowGroup =
group (List.map columnShim rowGroupFields) indexedTable |> mapTree Tuple.first
colGroup : Tree Int comparable2
colGroup =
group (List.map columnShim colGroupFields) indexedTable |> mapTree Tuple.first
getIndices : Table Int -> Set Int
getIndices (Table indices) =
Set.fromList indices
rowDepth : Int
rowDepth = List.length rowGroupFields
colDepth : Int
colDepth = List.length colGroupFields
rowIndexSets : List (Int, Set Int)
rowIndexSets = getPaths rowGroup
|> List.filterMap (\path -> getAt path rowGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
colIndexSets : List (Int, Set Int)
colIndexSets = getPaths colGroup
|> List.filterMap (\path -> getAt path colGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
viewHeadersHelper :
(comparable -> Element msg)
-> Tree Int comparable
-> List
{ depth : Int
, view : Element msg
, span : Int
, offset : Int
}
viewHeadersHelper viewer grp = grp
|> applyHorizontally identity
|> List.indexedMap (\i lst -> lst
|> List.foldl (\(c, subTree) result ->
{ depth = i
, view = viewer c
, span = getWidth subTree
, offset = result |> List.map .span |> List.sum
} :: result)
[]
)
|> List.concatMap identity
rowHeaders : List (Element msg)
rowHeaders = viewHeadersHelper viewRow rowGroup
|> List.map (\{ depth, view, span, offset } -> el
(List.map Element.htmlAttribute
[ style "grid-row-start" <| String.fromInt <| colDepth + offset + 1
, style "grid-row-end" <| String.fromInt <| colDepth + offset + 1 + span
, style "grid-column-start" <| String.fromInt <| depth + 1
, style "grid-column-end" <| String.fromInt <| depth + 2
])
view
)
colHeaders : List (Element msg)
colHeaders = viewHeadersHelper viewCol colGroup
|> List.map (\{ depth, view, span, offset } -> el
(List.map Element.htmlAttribute
[ style "grid-row-start" <| String.fromInt <| depth + 1
, style "grid-row-end" <| String.fromInt <| depth + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + offset + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + offset + 1 + span
])
view
)
dataCells : List (Element msg)
dataCells = List.Extra.cartesianProduct [rowIndexSets, colIndexSets]
|> List.filterMap (\lst ->
case lst of
item1 :: item2 :: [] -> Just (item1, item2)
_ -> Nothing
)
|> List.map (\((i, rowIndices), (j, colIndices)) -> el
(List.map Element.htmlAttribute
[ style "grid-row-start" <| String.fromInt <| colDepth + i + 1
, style "grid-row-end" <| String.fromInt <| colDepth + i + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + j + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + j + 2
])
(Set.intersect rowIndices colIndices
|> Set.toList
|> List.filterMap (getRowByIndex (Table rows))
|> aggregator
|> viewAgg
))
in
Element.paragraph
(List.map Element.htmlAttribute
[ style "display" "inline-grid"
, style "grid-template-rows" <| String.join " " <| List.repeat (colDepth + getWidth rowGroup) "auto"
, style "grid-template-columns" <| String.join " " <| List.repeat (rowDepth + getWidth colGroup) "auto"
] ++ [Element.width Element.shrink])
(rowHeaders ++ colHeaders ++ dataCells)
| true | module PivotTable exposing
( Table, Field
, makeTable, getField
, Aggregator, pivotTable, pivotTableHtml
)
{-| This package provides a pivot table view function with which
you can analyze and visualize your data by grouping various fields.
# Definition
@docs Table, Field
# Table operations
@docs makeTable, getField
# Pivot table
In this package, a pivot table is
a table to show values grouped by some fields.
## Example 1
genderToString : Gender -> String
genderToString gender =
case gender of
Male -> "Male"
Female -> "Female"
pivotTable
{ rowGroupFields = []
, colGroupFields = [ genderField ]
, aggregator = List.length
, viewRow = always Element.none
, viewCol = Element.text
, viewAgg = String.fromInt >> Element.text
}
myTable
The code above produces a table:
```text
|Male |Female |
|-----|-------|
|2 |1 |
```
@docs Aggregator, pivotTable, pivotTableHtml
-}
import Array exposing (Array)
import Element
exposing
( Element
, column
, el
, fill
, fillPortion
, height
, none
, row
, shrink
, width
)
import Html
exposing
( Html
, table
, td
, th
, tr
, div
)
import Html.Attributes
exposing
( colspan
, rowspan
, style
)
import List.Extra
import Set exposing (Set)
{-| In this package, a table is defined as a list of rows.
In the most naive case, a table may be represented by a list of records like:
type alias Person =
{ name : String
, age : Int
, gender : Gender
}
type Gender
= Male
| Female
type alias MyTable =
Table Person
**Note:** Notice that rows can be any type.
-}
type Table row
= Table (List row)
{-| A function to create a table.
Since the `Table` is an opaque type, all user of this package must use this
function to create a `Table` value.
-}
makeTable : List row -> Table row
makeTable rows =
Table rows
{-| In this package, a field is defined as a function from row to something.
-}
type alias Field row a =
row -> a
{-| A function to get values from a table.
With the example appeared in the [`Table` doc](#Table),
each field can be accessed like:
nameField = .name
ageField = .age
genderField = .gender
myTable : MyTable
myTable = makeTable
[ { name = "PI:NAME:<NAME>END_PI", age = 17, gender = Female }
, { name = "PI:NAME:<NAME>END_PI", age = 8, gender = Male }
, { name = "PI:NAME:<NAME>END_PI", age = 35, gender = Male }
]
getField nameField myTable -- ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
getField ageField myTable -- [17, 8, 35]
getField genderField myTable -- [Female, Male, Male]
**Note:** Notice that a field does not have to be a record element.
This is a valid code:
nameInitialLetterField = .name >> String.left 1
getField nameInitialLetterField myTable -- ["A", "B", "C"]
-}
getField : Field row a -> Table row -> List a
getField field (Table rows) =
List.map field rows
-- Utility functions for `Table`
length : Table row -> Int
length (Table rows) =
List.length rows
map : (row1 -> row2) -> Table row1 -> Table row2
map f (Table rows) =
rows |> List.map f |> Table
indexedMap : (Int -> row1 -> row2) -> Table row1 -> Table row2
indexedMap f (Table rows) =
rows |> List.indexedMap f |> Table
-- Grouping functions
{-| Group rows by a given field, that is, the same group has the same field value.
Result is a list of groups.
A group is composed of a field value (of type `comparable`) and a table value.
All rows in this table has the same field value.
-}
groupByField : Field row comparable -> Table row -> List ( comparable, Table row )
groupByField field (Table rows) =
rows
|> List.sortBy field
-- sorting is necessary for `List.Extra.groupWhile`
|> List.Extra.groupWhile (\r1 r2 -> field r1 == field r2)
|> List.map (\( first, rest ) -> ( field first, Table (first :: rest) ))
{-| Group rows by given several fields.
Notice that group of a group forms a tree.
See [`Tree` definition](#Tree) for detail.
-}
group : List (Field row comparable) -> Table row -> Tree row comparable
group fields tbl =
let
reduce : Field row comparable -> Tree row comparable -> Tree row comparable
reduce field tree =
case tree of
Leaf tbl_ ->
groupByField field tbl_
|> List.map (Tuple.mapSecond Leaf)
|> Node
Node lst ->
lst
|> List.map (Tuple.mapSecond (reduce field))
|> Node
in
List.foldl reduce (Leaf tbl) fields
{-| A type representing a result of the `group` function.
Grouping by several fields forms a tree.
## Example
myTable2 =
makeTable
[ { col1 = "A", col2 = 1, col3 = "a", col4 = 1 }
, { col1 = "A", col2 = 1, col3 = "b", col4 = 2 }
, { col1 = "A", col2 = 2, col3 = "a", col4 = 1 }
, { col1 = "A", col2 = 2, col3 = "b", col4 = 2 }
, { col1 = "A", col2 = 2, col3 = "c", col4 = 3 }
, { col1 = "A", col2 = 3, col3 = "a", col4 = 1 }
, { col1 = "A", col2 = 3, col3 = "a", col4 = 2 }
, { col1 = "B", col2 = 2, col3 = "a", col4 = 1 }
, { col1 = "B", col2 = 2, col3 = "b", col4 = 2 }
, { col1 = "B", col2 = 2, col3 = "c", col4 = 3 }
]
- col1 = "A"
- col2 = 1
- col3 = "a"
- row#1
- col3 = \*b
- row#2
- col2 = 2
- col3 = "a"
- row#3
- col3 = "b"
- row#4
- col3 = "c"
- row#5
- col2 = 3
- col3 = "a"
- row#6, row#7
- col1 = "B"
- col2 = 2
- col3 = "a"
- row#8
- col3 = "b"
- row#9
- col3 = "c"
- row#10
-}
type Tree row comparable
= Node (List ( comparable, Tree row comparable ))
| Leaf (Table row)
-- Tree utility functions
{-| A path of a tree from the root to a leaf
-}
type alias TreePath comparable =
List comparable
{-| Get a tree by path.
-}
getTreeAt : TreePath comparable -> Tree row comparable -> Maybe (Tree row comparable)
getTreeAt path tree =
case path of
[] ->
Just tree
first :: rest ->
case tree of
Leaf _ ->
Nothing
Node lst ->
lst
|> List.filter (\( c, _ ) -> c == first)
|> List.head
|> Maybe.andThen (\( _, subTree ) -> getTreeAt rest subTree)
{-| Get a tree by path, only when the path reaches a leaf.
-}
getAt : TreePath comparable -> Tree row comparable -> Maybe (Table row)
getAt path tree =
case getTreeAt path tree of
Nothing ->
Nothing
Just (Node _) ->
Nothing
Just (Leaf tbl) ->
Just tbl
{-| Get possible paths from given tree.
-}
getPaths : Tree row comparable -> List (TreePath comparable)
getPaths tree =
case tree of
Leaf _ ->
[ [] ]
Node lst ->
lst
|> List.map (Tuple.mapSecond getPaths)
|> List.concatMap (\( c, paths ) -> paths |> List.map (\path -> c :: path))
{-| Convert row type into another type.
-}
mapTree : (row1 -> row2) -> Tree row1 comparable -> Tree row2 comparable
mapTree f tree =
case tree of
Node lst ->
lst
|> List.map (Tuple.mapSecond (mapTree f))
|> Node
Leaf tbl ->
Leaf (map f tbl)
{-| Extract all `Table` values from given tree.
The result is a list of tables ordered by depth-first-search order.
-}
treeToTableList : Tree row comparable -> List (Table row)
treeToTableList tree =
case tree of
Leaf tbl ->
[ tbl ]
Node lst ->
List.concatMap (Tuple.second >> treeToTableList) lst
{-| Get the width of a tree, which is the number of leafs the tree has.
-}
getWidth : Tree row comparable -> Int
getWidth tree =
case tree of
Leaf _ ->
1
Node lst ->
lst |> List.map (Tuple.second >> getWidth) |> List.sum
{-| Apply a function in breadth-first-search order.
The result is a list of each levels result, that is:
result = applyHorizontally f tree
List.Extra.getAt 0 result == Just firstDepthResult
List.Extra.getAt 1 result == Just secondDepthResult
List.Extra.getAt 2 result == Just thirdDepthResult
-}
applyHorizontally : (( comparable, Tree row comparable ) -> a) -> Tree row comparable -> List (List a)
applyHorizontally f tree =
let
applyOneLevel : Tree row comparable -> List a
applyOneLevel tree_ =
case tree_ of
Leaf _ ->
[]
Node lst ->
List.map f lst
getSubTrees : Tree row comparable -> List (Tree row comparable)
getSubTrees tree_ =
case tree_ of
Leaf _ ->
[]
Node lst ->
List.map Tuple.second lst
g : List (Tree row comparable) -> List (List a) -> List (List a)
g trees prevResult =
let
result : List a
result =
List.concatMap applyOneLevel trees
nextResult : List (List a)
nextResult =
result :: prevResult
in
case result of
[] ->
prevResult
_ ->
g (List.concatMap getSubTrees trees) nextResult
in
g [ tree ] [] |> List.reverse
-- Pivot table functions
{-| The pivot table groups table rows.
After that, the `Aggregator` aggregates
the list of rows into a single value (of any type).
-}
type alias Aggregator row agg =
List row -> agg
{-| Draws a pivot table of `Html` type.
This view makes use of grid attributes of html table.
Use this view function when you want to avoid using `elm-ui`.
-}
pivotTableHtml :
{ rowGroupFields : List (Field row comparable1)
, colGroupFields : List (Field row comparable2)
, aggregator : Aggregator row agg
, viewRow : comparable1 -> Html msg
, viewCol : comparable2 -> Html msg
, viewAgg : agg -> Html msg
}
-> Table row
-> Html msg
pivotTableHtml { rowGroupFields, colGroupFields, aggregator, viewRow, viewCol, viewAgg } tbl =
let
indexedTable : Table ( Int, row )
indexedTable =
indexedMap Tuple.pair tbl
getRowByIndex : Table row -> Int -> Maybe row
getRowByIndex (Table lst) index =
List.Extra.getAt index lst
-- ignore index
columnShim : Field row comparable -> Field ( Int, row ) comparable
columnShim col =
Tuple.second >> col
rowGroup : Tree Int comparable1
rowGroup =
group (List.map columnShim rowGroupFields) indexedTable |> mapTree Tuple.first
colGroup : Tree Int comparable2
colGroup =
group (List.map columnShim colGroupFields) indexedTable |> mapTree Tuple.first
getIndices : Table Int -> Set Int
getIndices (Table indices) =
Set.fromList indices
rowDepth : Int
rowDepth = List.length rowGroupFields
colDepth : Int
colDepth = List.length colGroupFields
rowIndexSets : List (Int, Set Int)
rowIndexSets = getPaths rowGroup
|> List.filterMap (\path -> getAt path rowGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
colIndexSets : List (Int, Set Int)
colIndexSets = getPaths colGroup
|> List.filterMap (\path -> getAt path colGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
viewHeadersHelper :
(comparable -> Html msg)
-> Tree Int comparable
-> List
{ depth : Int
, view : Html msg
, span : Int
, offset : Int
}
viewHeadersHelper viewer grp = grp
|> applyHorizontally identity
|> List.indexedMap (\i lst -> lst
|> List.foldl (\(c, subTree) result ->
{ depth = i
, view = viewer c
, span = getWidth subTree
, offset = result |> List.map .span |> List.sum
} :: result)
[]
)
|> List.concatMap identity
rowHeaders : List (Html msg)
rowHeaders = viewHeadersHelper viewRow rowGroup
|> List.map (\{ depth, view, span, offset } -> div
[ style "grid-row-start" <| String.fromInt <| colDepth + offset + 1
, style "grid-row-end" <| String.fromInt <| colDepth + offset + 1 + span
, style "grid-column-start" <| String.fromInt <| depth + 1
, style "grid-column-end" <| String.fromInt <| depth + 2
]
[ view ]
)
colHeaders : List (Html msg)
colHeaders = viewHeadersHelper viewCol colGroup
|> List.map (\{ depth, view, span, offset } -> div
[ style "grid-row-start" <| String.fromInt <| depth + 1
, style "grid-row-end" <| String.fromInt <| depth + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + offset + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + offset + 1 + span
]
[ view ]
)
dataCells : List (Html msg)
dataCells = List.Extra.cartesianProduct [rowIndexSets, colIndexSets]
|> List.filterMap (\lst ->
case lst of
item1 :: item2 :: [] -> Just (item1, item2)
_ -> Nothing
)
|> List.map (\((i, rowIndices), (j, colIndices)) -> div
[ style "grid-row-start" <| String.fromInt <| colDepth + i + 1
, style "grid-row-end" <| String.fromInt <| colDepth + i + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + j + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + j + 2
]
[ Set.intersect rowIndices colIndices
|> Set.toList
|> List.filterMap (getRowByIndex tbl)
|> aggregator
|> viewAgg
])
in
div
[ style "display" "inline-grid"
, style "grid-template-rows" <| String.join " " <| List.repeat (colDepth + getWidth rowGroup) "auto"
, style "grid-template-columns" <| String.join " " <| List.repeat (rowDepth + getWidth colGroup) "auto"
]
(rowHeaders ++ colHeaders ++ dataCells)
{- Draws a pivot table of `Html` type.
This view makes use of `colspan` and `rowspan` attributes of html table.
Use this view function when you want to avoid using `elm-ui`.
-}
{-
pivotTableHtml :
{ rowGroupFields : List (Field row comparable1)
, colGroupFields : List (Field row comparable2)
, aggregator : Aggregator row agg
, viewRow : comparable1 -> Html msg
, viewCol : comparable2 -> Html msg
, viewAgg : agg -> Html msg
}
-> Table row
-> Html msg
pivotTableHtml { rowGroupFields, colGroupFields, aggregator, viewRow, viewCol, viewAgg } tbl =
let
indexedTable : Table ( Int, row )
indexedTable =
indexedMap Tuple.pair tbl
getRowByIndex : Table row -> Int -> Maybe row
getRowByIndex (Table lst) index =
List.Extra.getAt index lst
-- ignore index
columnShim : Field row comparable -> Field ( Int, row ) comparable
columnShim col =
Tuple.second >> col
rowGroup : Tree Int comparable1
rowGroup =
group (List.map columnShim rowGroupFields) indexedTable |> mapTree Tuple.first
colGroup : Tree Int comparable2
colGroup =
group (List.map columnShim colGroupFields) indexedTable |> mapTree Tuple.first
-- rowPaths : List (TreePath comparable1)
-- rowPaths = getPaths rowGroup
colPaths : List (TreePath comparable2)
colPaths =
getPaths colGroup
viewColHeaderCells : Tree Int comparable2 -> List ( Html msg, Tree Int comparable2 )
viewColHeaderCells tree =
let
f : ( comparable2, Tree Int comparable2 ) -> ( Html msg, Tree Int comparable2 )
f ( c, subTree ) =
( th [ colspan <| getWidth subTree ] [ viewCol c ], subTree )
in
case tree of
Leaf _ ->
[]
Node lst ->
List.map f lst
viewColHeaders : List (Tree Int comparable2) -> List (Html msg)
viewColHeaders trees =
case trees of
[] ->
[]
_ ->
let
tmp1 : List ( Html msg, Tree Int comparable2 )
tmp1 =
List.concatMap viewColHeaderCells trees
cells : List (Html msg)
cells =
List.map Tuple.first tmp1
subTrees : List (Tree Int comparable2)
subTrees =
List.map Tuple.second tmp1
shim : Html msg
shim =
td [ colspan <| List.length rowGroupFields ] []
in
if List.length rowGroupFields == 0 then
tr [] cells :: viewColHeaders subTrees
else
tr [] (shim :: cells) :: viewColHeaders subTrees
pathToTableItems : List (Maybe ( Int, comparable1 )) -> List (Html msg)
pathToTableItems lst =
List.filterMap (Maybe.map (\( width, c ) -> th [ rowspan width ] [ viewRow c ])) lst
aggregateForRow : Table Int -> List (Html msg)
aggregateForRow tbl_ =
colPaths
|> List.filterMap (\path -> getAt path colGroup)
|> List.map getIndices
|> List.map (Set.intersect (getIndices tbl_))
|> List.map Set.toList
|> List.map (List.filterMap (getRowByIndex tbl))
|> List.map aggregator
|> List.map viewAgg
|> List.map List.singleton
|> List.map (td [])
viewRows : Tree Int comparable1 -> List (Html msg)
viewRows tree =
List.map2 Tuple.pair (organize tree) (treeToTableList tree)
|> List.map (Tuple.mapBoth pathToTableItems aggregateForRow)
|> List.map (\( x, y ) -> List.append x y)
|> List.map (tr [])
organize : Tree Int comparable1 -> List (List (Maybe ( Int, comparable1 )))
organize tree =
let
f :
( comparable1, Tree Int comparable1 )
-> List (List (Maybe ( Int, comparable1 )))
f ( c, subTree ) =
organize subTree
|> List.indexedMap (g c subTree)
g :
comparable1
-> Tree Int comparable1
-> Int
-> List (Maybe ( Int, comparable1 ))
-> List (Maybe ( Int, comparable1 ))
g c subTree i path =
if i == 0 then
Just ( getWidth subTree, c ) :: path
else
Nothing :: path
in
case tree of
Leaf _ ->
[ [] ]
Node lst ->
List.concatMap f lst
getIndices : Table Int -> Set Int
getIndices (Table indices) =
Set.fromList indices
in
viewColHeaders [ colGroup ] ++ viewRows rowGroup |> table []
-}
{-| Draws a pivot table.
- `rowGroupFields` is a list of `Field`'s to group and generates grouped _rows_.
- `colGroupFields` is a list of `Field`'s to group and generates grouped _columns_.
- `aggregator` aggregates each grouped set of table data into a single value.
- `viewRow`, `viewCol` and `viewAgg` are view functions to show each headers and cells.
-}
pivotTable :
{ rowGroupFields : List (Field row comparable1)
, colGroupFields : List (Field row comparable2)
, aggregator : Aggregator row agg
, viewRow : comparable1 -> Element msg
, viewCol : comparable2 -> Element msg
, viewAgg : agg -> Element msg
}
-> Table row
-> Element msg
pivotTable { rowGroupFields, colGroupFields, aggregator, viewRow, viewCol, viewAgg } (Table rows) =
let
indexedTable : Table ( Int, row )
indexedTable =
indexedMap Tuple.pair (Table rows)
getRowByIndex : Table row -> Int -> Maybe row
getRowByIndex (Table lst) index =
List.Extra.getAt index lst
-- ignore index
columnShim : Field row comparable -> Field ( Int, row ) comparable
columnShim col =
Tuple.second >> col
rowGroup : Tree Int comparable1
rowGroup =
group (List.map columnShim rowGroupFields) indexedTable |> mapTree Tuple.first
colGroup : Tree Int comparable2
colGroup =
group (List.map columnShim colGroupFields) indexedTable |> mapTree Tuple.first
getIndices : Table Int -> Set Int
getIndices (Table indices) =
Set.fromList indices
rowDepth : Int
rowDepth = List.length rowGroupFields
colDepth : Int
colDepth = List.length colGroupFields
rowIndexSets : List (Int, Set Int)
rowIndexSets = getPaths rowGroup
|> List.filterMap (\path -> getAt path rowGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
colIndexSets : List (Int, Set Int)
colIndexSets = getPaths colGroup
|> List.filterMap (\path -> getAt path colGroup)
|> List.map getIndices
|> List.indexedMap Tuple.pair
viewHeadersHelper :
(comparable -> Element msg)
-> Tree Int comparable
-> List
{ depth : Int
, view : Element msg
, span : Int
, offset : Int
}
viewHeadersHelper viewer grp = grp
|> applyHorizontally identity
|> List.indexedMap (\i lst -> lst
|> List.foldl (\(c, subTree) result ->
{ depth = i
, view = viewer c
, span = getWidth subTree
, offset = result |> List.map .span |> List.sum
} :: result)
[]
)
|> List.concatMap identity
rowHeaders : List (Element msg)
rowHeaders = viewHeadersHelper viewRow rowGroup
|> List.map (\{ depth, view, span, offset } -> el
(List.map Element.htmlAttribute
[ style "grid-row-start" <| String.fromInt <| colDepth + offset + 1
, style "grid-row-end" <| String.fromInt <| colDepth + offset + 1 + span
, style "grid-column-start" <| String.fromInt <| depth + 1
, style "grid-column-end" <| String.fromInt <| depth + 2
])
view
)
colHeaders : List (Element msg)
colHeaders = viewHeadersHelper viewCol colGroup
|> List.map (\{ depth, view, span, offset } -> el
(List.map Element.htmlAttribute
[ style "grid-row-start" <| String.fromInt <| depth + 1
, style "grid-row-end" <| String.fromInt <| depth + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + offset + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + offset + 1 + span
])
view
)
dataCells : List (Element msg)
dataCells = List.Extra.cartesianProduct [rowIndexSets, colIndexSets]
|> List.filterMap (\lst ->
case lst of
item1 :: item2 :: [] -> Just (item1, item2)
_ -> Nothing
)
|> List.map (\((i, rowIndices), (j, colIndices)) -> el
(List.map Element.htmlAttribute
[ style "grid-row-start" <| String.fromInt <| colDepth + i + 1
, style "grid-row-end" <| String.fromInt <| colDepth + i + 2
, style "grid-column-start" <| String.fromInt <| rowDepth + j + 1
, style "grid-column-end" <| String.fromInt <| rowDepth + j + 2
])
(Set.intersect rowIndices colIndices
|> Set.toList
|> List.filterMap (getRowByIndex (Table rows))
|> aggregator
|> viewAgg
))
in
Element.paragraph
(List.map Element.htmlAttribute
[ style "display" "inline-grid"
, style "grid-template-rows" <| String.join " " <| List.repeat (colDepth + getWidth rowGroup) "auto"
, style "grid-template-columns" <| String.join " " <| List.repeat (rowDepth + getWidth colGroup) "auto"
] ++ [Element.width Element.shrink])
(rowHeaders ++ colHeaders ++ dataCells)
| elm |
[
{
"context": " , itemTypeColumn\n , friendshipColumn Shulk\n , friendshipColumn Reyn\n ,",
"end": 783,
"score": 0.9984579086,
"start": 778,
"tag": "NAME",
"value": "Shulk"
},
{
"context": "endshipColumn Shulk\n , friendshipColumn Reyn\n , friendshipColumn Fiora\n ",
"end": 819,
"score": 0.9985998869,
"start": 815,
"tag": "NAME",
"value": "Reyn"
},
{
"context": "iendshipColumn Reyn\n , friendshipColumn Fiora\n , friendshipColumn Sharla\n ",
"end": 856,
"score": 0.9989851117,
"start": 851,
"tag": "NAME",
"value": "Fiora"
},
{
"context": "endshipColumn Fiora\n , friendshipColumn Sharla\n , friendshipColumn Dunban\n ",
"end": 894,
"score": 0.9990932941,
"start": 888,
"tag": "NAME",
"value": "Sharla"
},
{
"context": "ndshipColumn Sharla\n , friendshipColumn Dunban\n , friendshipColumn Melia\n ",
"end": 932,
"score": 0.9974961877,
"start": 926,
"tag": "NAME",
"value": "Dunban"
},
{
"context": "ndshipColumn Dunban\n , friendshipColumn Melia\n , friendshipColumn Riki\n ]",
"end": 969,
"score": 0.9992474318,
"start": 964,
"tag": "NAME",
"value": "Melia"
},
{
"context": "endshipColumn Melia\n , friendshipColumn Riki\n ]\n , customizations =\n ",
"end": 1005,
"score": 0.999255836,
"start": 1001,
"tag": "NAME",
"value": "Riki"
}
] | src/ItemTable.elm | solkaz/xeno-gifts-app | 0 | module ItemTable exposing (view)
import Character exposing (Character(..))
import FriendshipColumn exposing (friendshipColumn)
import Html exposing (Html)
import Html.Attributes exposing (class)
import Item exposing (Item)
import ItemNameColumn exposing (itemNameColumn)
import ItemTypeColumn exposing (itemTypeColumn)
import LocationColumn exposing (locationColumn)
import Msg exposing (Msg)
import Table
view : Table.State -> List Item -> Html Msg
view tableState items =
Table.view config tableState items
config : Table.Config Item Msg
config =
Table.customConfig
{ toId = .name
, toMsg = Msg.SetTableState
, columns =
[ itemNameColumn
, locationColumn
, itemTypeColumn
, friendshipColumn Shulk
, friendshipColumn Reyn
, friendshipColumn Fiora
, friendshipColumn Sharla
, friendshipColumn Dunban
, friendshipColumn Melia
, friendshipColumn Riki
]
, customizations =
{ tableAttrs = [ class "table is-fullwidth is-bordered has-text-centered" ]
, caption = Table.defaultCustomizations.caption
, tfoot = Table.defaultCustomizations.tfoot
, tbodyAttrs = Table.defaultCustomizations.tbodyAttrs
, thead = Table.defaultCustomizations.thead
, rowAttrs = Table.defaultCustomizations.rowAttrs
}
}
| 36340 | module ItemTable exposing (view)
import Character exposing (Character(..))
import FriendshipColumn exposing (friendshipColumn)
import Html exposing (Html)
import Html.Attributes exposing (class)
import Item exposing (Item)
import ItemNameColumn exposing (itemNameColumn)
import ItemTypeColumn exposing (itemTypeColumn)
import LocationColumn exposing (locationColumn)
import Msg exposing (Msg)
import Table
view : Table.State -> List Item -> Html Msg
view tableState items =
Table.view config tableState items
config : Table.Config Item Msg
config =
Table.customConfig
{ toId = .name
, toMsg = Msg.SetTableState
, columns =
[ itemNameColumn
, locationColumn
, itemTypeColumn
, friendshipColumn <NAME>
, friendshipColumn <NAME>
, friendshipColumn <NAME>
, friendshipColumn <NAME>
, friendshipColumn <NAME>
, friendshipColumn <NAME>
, friendshipColumn <NAME>
]
, customizations =
{ tableAttrs = [ class "table is-fullwidth is-bordered has-text-centered" ]
, caption = Table.defaultCustomizations.caption
, tfoot = Table.defaultCustomizations.tfoot
, tbodyAttrs = Table.defaultCustomizations.tbodyAttrs
, thead = Table.defaultCustomizations.thead
, rowAttrs = Table.defaultCustomizations.rowAttrs
}
}
| true | module ItemTable exposing (view)
import Character exposing (Character(..))
import FriendshipColumn exposing (friendshipColumn)
import Html exposing (Html)
import Html.Attributes exposing (class)
import Item exposing (Item)
import ItemNameColumn exposing (itemNameColumn)
import ItemTypeColumn exposing (itemTypeColumn)
import LocationColumn exposing (locationColumn)
import Msg exposing (Msg)
import Table
view : Table.State -> List Item -> Html Msg
view tableState items =
Table.view config tableState items
config : Table.Config Item Msg
config =
Table.customConfig
{ toId = .name
, toMsg = Msg.SetTableState
, columns =
[ itemNameColumn
, locationColumn
, itemTypeColumn
, friendshipColumn PI:NAME:<NAME>END_PI
, friendshipColumn PI:NAME:<NAME>END_PI
, friendshipColumn PI:NAME:<NAME>END_PI
, friendshipColumn PI:NAME:<NAME>END_PI
, friendshipColumn PI:NAME:<NAME>END_PI
, friendshipColumn PI:NAME:<NAME>END_PI
, friendshipColumn PI:NAME:<NAME>END_PI
]
, customizations =
{ tableAttrs = [ class "table is-fullwidth is-bordered has-text-centered" ]
, caption = Table.defaultCustomizations.caption
, tfoot = Table.defaultCustomizations.tfoot
, tbodyAttrs = Table.defaultCustomizations.tbodyAttrs
, thead = Table.defaultCustomizations.thead
, rowAttrs = Table.defaultCustomizations.rowAttrs
}
}
| elm |
[
{
"context": "me\n (Just \"https://www.patreon.com/parasrah\")\n \"Patreon\"\n (Mark",
"end": 4191,
"score": 0.999687314,
"start": 4183,
"tag": "USERNAME",
"value": "parasrah"
},
{
"context": "://www.patreon.com/parasrah\")\n \"Patreon\"\n (Markdown.create \"If you want to",
"end": 4218,
"score": 0.7142974138,
"start": 4214,
"tag": "NAME",
"value": "reon"
},
{
"context": "reon account setup [here](https://www.patreon.com/parasrah). Patreon is a platform designed to make it easy ",
"end": 4382,
"score": 0.9996873736,
"start": 4374,
"tag": "USERNAME",
"value": "parasrah"
},
{
"context": "5fe482ee079955\n```\n\n### Basic Attention Token\n```\n0xDA9c1fdE56c3D8b71aB65Cd75380BF17fFD81B17\n```\n \"\"\"\n )\n ",
"end": 5149,
"score": 0.9776180387,
"start": 5107,
"tag": "KEY",
"value": "0xDA9c1fdE56c3D8b71aB65Cd75380BF17fFD81B17"
},
{
"context": "aveUrl : String\nbraveUrl =\n \"https://brave.com/par269\"\n\n\n\n{- Styles -}\n\n\nsectionStyle : Style\nsectionSt",
"end": 9772,
"score": 0.9995071292,
"start": 9766,
"tag": "USERNAME",
"value": "par269"
}
] | src/Page/Donate.elm | breadblog/web | 0 | module Page.Donate exposing (Model, Msg, fromContext, init, toContext, update, view)
import Css exposing (..)
import Data.Context as Context exposing (Context)
import Data.Markdown as Markdown exposing (Markdown)
import Data.Route as Route exposing (Route(..))
import Data.Theme exposing (Theme)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (..)
import Html.Styled.Events exposing (onClick)
import Page
import Style.Card as Card
import Style.Color as Color
import Style.Post
import Style.Screen as Screen exposing (Screen(..))
import Svg.Styled.Attributes as SvgAttr
import View.Svg as Svg
-- Model --
type alias Model =
{ context : Context }
init : Context -> ( Model, Cmd Msg )
init context =
( { context = context }, Cmd.none )
toContext : Model -> Context
toContext =
Page.toContext
fromContext : Context -> Model -> Model
fromContext =
Page.fromContext
-- Message --
type Msg
= NoOp
-- Update --
update : msg -> Model -> ( Model, Cmd Msg )
update _ model =
( model, Cmd.none )
-- View --
view : Model -> List (Html Msg)
view { context } =
let
theme =
Context.getTheme context
in
[ div
[ id "donate-page"
, css
[ flex3 (int 1) (int 0) (int 0)
, displayFlex
, alignItems center
, flexDirection column
, overflowY auto
, position relative
, overflowX Css.hidden
]
]
[ div
[ class "summary"
, css
[ Css.width (pct 80)
, displayFlex
, flexDirection column
, alignItems center
, marginTop (px 100)
, Card.style theme
, marginBottom (px 200)
, lineHeight (pct 180)
, Screen.style Screen.mobile
[ marginBottom (px 120) ]
]
]
[ div
[ css
[ Card.headingStyle theme ]
]
[ h1
[ css
[ fontSize (rem 1.4)
, margin4 (px 0) (px 0) (px 0) (px 15)
]
]
[ text "Considering Donating?" ]
]
, p
[ css
[ fontSize (rem 1.2)
, padding2 (px 0) (px 15)
, letterSpacing (px 0.3)
]
]
[ text "Before you do, we just wanted to clarify that our content does not depend on donations from our readers. We are fortunate enough to use some great services that support open source, which allows our hosting fees to be negligible. If you still want to donate and support us, know that we greatly appreciate it!"
]
]
, div
[ class "brave"
, id "donate-brave-section"
, css
[ sectionStyle ]
]
[ sectionImg "/brave_lion.svg" Left
, sectionDescription
theme
(Just braveUrl)
"Brave Browser"
(Markdown.create "Brave is an open source browser aiming to give users back their privacy online. It has built in ad & tracker blocking, so you can browse safely. And if you choose to, you can get paid to view ads integrated into the browser, allowing you to get paid for your attention in a private and secure way. And if you want to give back to content creators like us, Brave makes it easy to do so. You can check it out [here](https://brave.com/par269). For full transparency, please be aware this is an affiliate link")
Right
]
, div
[ class "patreon"
, id "donate-patreon-section"
, css
[ sectionStyle
, flexDirection rowReverse
]
]
[ sectionImg "/patreon.png" Right
, sectionDescription
theme
(Just "https://www.patreon.com/parasrah")
"Patreon"
(Markdown.create "If you want to contribute in a more traditional fashion, we have a patreon account setup [here](https://www.patreon.com/parasrah). Patreon is a platform designed to make it easy to give back to content creators.")
Left
]
, div
[ class "crypto"
, id "donate-crypto-section"
, css
[ sectionStyle ]
]
[ sectionImg "/ethereum.svg" Left
, sectionDescription
theme
Nothing
"Cryptocurrency"
(Markdown.create
"""
If you want a more untraceable way to make donations, cryptocurrency is always welcome!
### Bitcoin
```
3KuP9Jim8yinsG6RdAADZFFC95Hj6Jd1zX
```
### Ethereum
```
0xaB0Ea5a4505d85773CE143aEa45fe482ee079955
```
### Basic Attention Token
```
0xDA9c1fdE56c3D8b71aB65Cd75380BF17fFD81B17
```
"""
)
Right
]
]
, div
[ class "overlay"
, css
[ position absolute
, Css.height (pct 30)
]
]
[]
]
type Side
= Left
| Right
sectionImg : String -> Side -> Html msg
sectionImg imgSrc side =
div
[ class "animation-container"
, css
[ justifyContent center
, flex3 (int 0) (int 0) (pct 33)
, animationContainerStyle
, Screen.style Screen.mobile
[ marginBottom (px 30)
, marginTop (px 0)
, Css.property "flex" "0 0 auto"
, Css.width (pct 100)
]
]
]
[ img
[ src imgSrc
, classList
[ ( "right", side == Right )
, ( "left", side == Left )
, ( "animated", True )
, ( "hidden", True )
, ( "animation-target", True )
]
, css
[ Css.height (px 150)
, Screen.style Screen.mobile
[ Css.height auto
, Css.width (pct 40)
]
]
]
[]
]
sectionDescription : Theme -> Maybe String -> String -> Markdown -> Side -> Html msg
sectionDescription theme maybeUrl title description side =
div
[ class "animation-container"
, css
[ flex3 (int 0) (int 0) (pct 66)
, if side == Right then
Css.batch [ justifyContent flexStart ]
else
Css.batch [ justifyContent flexEnd ]
, animationContainerStyle
, Screen.style Screen.mobile
[ Css.property "flex" "0 0 auto"
, marginBottom (px 120)
, maxWidth (pct 90)
]
]
]
[ div
[ classList
[ ( "right", side == Right )
, ( "left", side == Left )
, ( "animated", True )
, ( "hidden", True )
, ( "content", True )
, ( "animation-target", True )
]
, css
[ displayFlex
, flexDirection column
, flex3 (int 0) (int 0) (pct 85)
, Card.style theme
, maxWidth (pct 100)
]
]
[ div
[ css
[ Card.headingStyle theme
, flexBasis auto
, justifyContent spaceBetween
]
]
[ h1
[ class "title"
, css
[ fontSize (rem 1.2)
, fontWeight (int 500)
, margin4 (px 5) (px 0) (px 5) (px 20)
]
]
[ text title ]
, case maybeUrl of
Just url ->
a
[ href url
, css
[ color (Color.secondaryFont theme)
, marginRight (px 15)
, displayFlex
, alignItems center
, textDecoration none
]
]
[ Svg.link
[ SvgAttr.css
[ Css.width (px 18)
, Css.height (px 18)
, marginLeft (px 5)
, position relative
]
]
]
Nothing ->
text ""
]
, div
[ class "content"
, css
[ fontSize (rem 1.0)
, padding2 (px 0) (px 20)
, letterSpacing (px 0.5)
, lineHeight (pct 150)
]
]
[ Markdown.toHtml
"donate-desc"
[]
(Style.Post.style theme)
description
]
]
]
braveUrl : String
braveUrl =
"https://brave.com/par269"
{- Styles -}
sectionStyle : Style
sectionStyle =
Css.batch
[ displayFlex
, alignItems center
, justifyContent spaceBetween
, flexBasis auto
, Css.property "flex" "1 0 auto"
, marginBottom (px 200)
, Css.width (pct 100)
, Screen.style Screen.mobile
[ flexDirection column
, minHeight (px 0)
, margin (px 0)
]
]
animationContainerStyle : Style
animationContainerStyle =
Css.batch
[ minHeight (pct 100)
, alignItems center
, displayFlex
, Screen.style Screen.mobile
[ justifyContent center
, minHeight (px 0)
, marginTop (px 0)
]
]
| 61707 | module Page.Donate exposing (Model, Msg, fromContext, init, toContext, update, view)
import Css exposing (..)
import Data.Context as Context exposing (Context)
import Data.Markdown as Markdown exposing (Markdown)
import Data.Route as Route exposing (Route(..))
import Data.Theme exposing (Theme)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (..)
import Html.Styled.Events exposing (onClick)
import Page
import Style.Card as Card
import Style.Color as Color
import Style.Post
import Style.Screen as Screen exposing (Screen(..))
import Svg.Styled.Attributes as SvgAttr
import View.Svg as Svg
-- Model --
type alias Model =
{ context : Context }
init : Context -> ( Model, Cmd Msg )
init context =
( { context = context }, Cmd.none )
toContext : Model -> Context
toContext =
Page.toContext
fromContext : Context -> Model -> Model
fromContext =
Page.fromContext
-- Message --
type Msg
= NoOp
-- Update --
update : msg -> Model -> ( Model, Cmd Msg )
update _ model =
( model, Cmd.none )
-- View --
view : Model -> List (Html Msg)
view { context } =
let
theme =
Context.getTheme context
in
[ div
[ id "donate-page"
, css
[ flex3 (int 1) (int 0) (int 0)
, displayFlex
, alignItems center
, flexDirection column
, overflowY auto
, position relative
, overflowX Css.hidden
]
]
[ div
[ class "summary"
, css
[ Css.width (pct 80)
, displayFlex
, flexDirection column
, alignItems center
, marginTop (px 100)
, Card.style theme
, marginBottom (px 200)
, lineHeight (pct 180)
, Screen.style Screen.mobile
[ marginBottom (px 120) ]
]
]
[ div
[ css
[ Card.headingStyle theme ]
]
[ h1
[ css
[ fontSize (rem 1.4)
, margin4 (px 0) (px 0) (px 0) (px 15)
]
]
[ text "Considering Donating?" ]
]
, p
[ css
[ fontSize (rem 1.2)
, padding2 (px 0) (px 15)
, letterSpacing (px 0.3)
]
]
[ text "Before you do, we just wanted to clarify that our content does not depend on donations from our readers. We are fortunate enough to use some great services that support open source, which allows our hosting fees to be negligible. If you still want to donate and support us, know that we greatly appreciate it!"
]
]
, div
[ class "brave"
, id "donate-brave-section"
, css
[ sectionStyle ]
]
[ sectionImg "/brave_lion.svg" Left
, sectionDescription
theme
(Just braveUrl)
"Brave Browser"
(Markdown.create "Brave is an open source browser aiming to give users back their privacy online. It has built in ad & tracker blocking, so you can browse safely. And if you choose to, you can get paid to view ads integrated into the browser, allowing you to get paid for your attention in a private and secure way. And if you want to give back to content creators like us, Brave makes it easy to do so. You can check it out [here](https://brave.com/par269). For full transparency, please be aware this is an affiliate link")
Right
]
, div
[ class "patreon"
, id "donate-patreon-section"
, css
[ sectionStyle
, flexDirection rowReverse
]
]
[ sectionImg "/patreon.png" Right
, sectionDescription
theme
(Just "https://www.patreon.com/parasrah")
"Pat<NAME>"
(Markdown.create "If you want to contribute in a more traditional fashion, we have a patreon account setup [here](https://www.patreon.com/parasrah). Patreon is a platform designed to make it easy to give back to content creators.")
Left
]
, div
[ class "crypto"
, id "donate-crypto-section"
, css
[ sectionStyle ]
]
[ sectionImg "/ethereum.svg" Left
, sectionDescription
theme
Nothing
"Cryptocurrency"
(Markdown.create
"""
If you want a more untraceable way to make donations, cryptocurrency is always welcome!
### Bitcoin
```
3KuP9Jim8yinsG6RdAADZFFC95Hj6Jd1zX
```
### Ethereum
```
0xaB0Ea5a4505d85773CE143aEa45fe482ee079955
```
### Basic Attention Token
```
<KEY>
```
"""
)
Right
]
]
, div
[ class "overlay"
, css
[ position absolute
, Css.height (pct 30)
]
]
[]
]
type Side
= Left
| Right
sectionImg : String -> Side -> Html msg
sectionImg imgSrc side =
div
[ class "animation-container"
, css
[ justifyContent center
, flex3 (int 0) (int 0) (pct 33)
, animationContainerStyle
, Screen.style Screen.mobile
[ marginBottom (px 30)
, marginTop (px 0)
, Css.property "flex" "0 0 auto"
, Css.width (pct 100)
]
]
]
[ img
[ src imgSrc
, classList
[ ( "right", side == Right )
, ( "left", side == Left )
, ( "animated", True )
, ( "hidden", True )
, ( "animation-target", True )
]
, css
[ Css.height (px 150)
, Screen.style Screen.mobile
[ Css.height auto
, Css.width (pct 40)
]
]
]
[]
]
sectionDescription : Theme -> Maybe String -> String -> Markdown -> Side -> Html msg
sectionDescription theme maybeUrl title description side =
div
[ class "animation-container"
, css
[ flex3 (int 0) (int 0) (pct 66)
, if side == Right then
Css.batch [ justifyContent flexStart ]
else
Css.batch [ justifyContent flexEnd ]
, animationContainerStyle
, Screen.style Screen.mobile
[ Css.property "flex" "0 0 auto"
, marginBottom (px 120)
, maxWidth (pct 90)
]
]
]
[ div
[ classList
[ ( "right", side == Right )
, ( "left", side == Left )
, ( "animated", True )
, ( "hidden", True )
, ( "content", True )
, ( "animation-target", True )
]
, css
[ displayFlex
, flexDirection column
, flex3 (int 0) (int 0) (pct 85)
, Card.style theme
, maxWidth (pct 100)
]
]
[ div
[ css
[ Card.headingStyle theme
, flexBasis auto
, justifyContent spaceBetween
]
]
[ h1
[ class "title"
, css
[ fontSize (rem 1.2)
, fontWeight (int 500)
, margin4 (px 5) (px 0) (px 5) (px 20)
]
]
[ text title ]
, case maybeUrl of
Just url ->
a
[ href url
, css
[ color (Color.secondaryFont theme)
, marginRight (px 15)
, displayFlex
, alignItems center
, textDecoration none
]
]
[ Svg.link
[ SvgAttr.css
[ Css.width (px 18)
, Css.height (px 18)
, marginLeft (px 5)
, position relative
]
]
]
Nothing ->
text ""
]
, div
[ class "content"
, css
[ fontSize (rem 1.0)
, padding2 (px 0) (px 20)
, letterSpacing (px 0.5)
, lineHeight (pct 150)
]
]
[ Markdown.toHtml
"donate-desc"
[]
(Style.Post.style theme)
description
]
]
]
braveUrl : String
braveUrl =
"https://brave.com/par269"
{- Styles -}
sectionStyle : Style
sectionStyle =
Css.batch
[ displayFlex
, alignItems center
, justifyContent spaceBetween
, flexBasis auto
, Css.property "flex" "1 0 auto"
, marginBottom (px 200)
, Css.width (pct 100)
, Screen.style Screen.mobile
[ flexDirection column
, minHeight (px 0)
, margin (px 0)
]
]
animationContainerStyle : Style
animationContainerStyle =
Css.batch
[ minHeight (pct 100)
, alignItems center
, displayFlex
, Screen.style Screen.mobile
[ justifyContent center
, minHeight (px 0)
, marginTop (px 0)
]
]
| true | module Page.Donate exposing (Model, Msg, fromContext, init, toContext, update, view)
import Css exposing (..)
import Data.Context as Context exposing (Context)
import Data.Markdown as Markdown exposing (Markdown)
import Data.Route as Route exposing (Route(..))
import Data.Theme exposing (Theme)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (..)
import Html.Styled.Events exposing (onClick)
import Page
import Style.Card as Card
import Style.Color as Color
import Style.Post
import Style.Screen as Screen exposing (Screen(..))
import Svg.Styled.Attributes as SvgAttr
import View.Svg as Svg
-- Model --
type alias Model =
{ context : Context }
init : Context -> ( Model, Cmd Msg )
init context =
( { context = context }, Cmd.none )
toContext : Model -> Context
toContext =
Page.toContext
fromContext : Context -> Model -> Model
fromContext =
Page.fromContext
-- Message --
type Msg
= NoOp
-- Update --
update : msg -> Model -> ( Model, Cmd Msg )
update _ model =
( model, Cmd.none )
-- View --
view : Model -> List (Html Msg)
view { context } =
let
theme =
Context.getTheme context
in
[ div
[ id "donate-page"
, css
[ flex3 (int 1) (int 0) (int 0)
, displayFlex
, alignItems center
, flexDirection column
, overflowY auto
, position relative
, overflowX Css.hidden
]
]
[ div
[ class "summary"
, css
[ Css.width (pct 80)
, displayFlex
, flexDirection column
, alignItems center
, marginTop (px 100)
, Card.style theme
, marginBottom (px 200)
, lineHeight (pct 180)
, Screen.style Screen.mobile
[ marginBottom (px 120) ]
]
]
[ div
[ css
[ Card.headingStyle theme ]
]
[ h1
[ css
[ fontSize (rem 1.4)
, margin4 (px 0) (px 0) (px 0) (px 15)
]
]
[ text "Considering Donating?" ]
]
, p
[ css
[ fontSize (rem 1.2)
, padding2 (px 0) (px 15)
, letterSpacing (px 0.3)
]
]
[ text "Before you do, we just wanted to clarify that our content does not depend on donations from our readers. We are fortunate enough to use some great services that support open source, which allows our hosting fees to be negligible. If you still want to donate and support us, know that we greatly appreciate it!"
]
]
, div
[ class "brave"
, id "donate-brave-section"
, css
[ sectionStyle ]
]
[ sectionImg "/brave_lion.svg" Left
, sectionDescription
theme
(Just braveUrl)
"Brave Browser"
(Markdown.create "Brave is an open source browser aiming to give users back their privacy online. It has built in ad & tracker blocking, so you can browse safely. And if you choose to, you can get paid to view ads integrated into the browser, allowing you to get paid for your attention in a private and secure way. And if you want to give back to content creators like us, Brave makes it easy to do so. You can check it out [here](https://brave.com/par269). For full transparency, please be aware this is an affiliate link")
Right
]
, div
[ class "patreon"
, id "donate-patreon-section"
, css
[ sectionStyle
, flexDirection rowReverse
]
]
[ sectionImg "/patreon.png" Right
, sectionDescription
theme
(Just "https://www.patreon.com/parasrah")
"PatPI:NAME:<NAME>END_PI"
(Markdown.create "If you want to contribute in a more traditional fashion, we have a patreon account setup [here](https://www.patreon.com/parasrah). Patreon is a platform designed to make it easy to give back to content creators.")
Left
]
, div
[ class "crypto"
, id "donate-crypto-section"
, css
[ sectionStyle ]
]
[ sectionImg "/ethereum.svg" Left
, sectionDescription
theme
Nothing
"Cryptocurrency"
(Markdown.create
"""
If you want a more untraceable way to make donations, cryptocurrency is always welcome!
### Bitcoin
```
3KuP9Jim8yinsG6RdAADZFFC95Hj6Jd1zX
```
### Ethereum
```
0xaB0Ea5a4505d85773CE143aEa45fe482ee079955
```
### Basic Attention Token
```
PI:KEY:<KEY>END_PI
```
"""
)
Right
]
]
, div
[ class "overlay"
, css
[ position absolute
, Css.height (pct 30)
]
]
[]
]
type Side
= Left
| Right
sectionImg : String -> Side -> Html msg
sectionImg imgSrc side =
div
[ class "animation-container"
, css
[ justifyContent center
, flex3 (int 0) (int 0) (pct 33)
, animationContainerStyle
, Screen.style Screen.mobile
[ marginBottom (px 30)
, marginTop (px 0)
, Css.property "flex" "0 0 auto"
, Css.width (pct 100)
]
]
]
[ img
[ src imgSrc
, classList
[ ( "right", side == Right )
, ( "left", side == Left )
, ( "animated", True )
, ( "hidden", True )
, ( "animation-target", True )
]
, css
[ Css.height (px 150)
, Screen.style Screen.mobile
[ Css.height auto
, Css.width (pct 40)
]
]
]
[]
]
sectionDescription : Theme -> Maybe String -> String -> Markdown -> Side -> Html msg
sectionDescription theme maybeUrl title description side =
div
[ class "animation-container"
, css
[ flex3 (int 0) (int 0) (pct 66)
, if side == Right then
Css.batch [ justifyContent flexStart ]
else
Css.batch [ justifyContent flexEnd ]
, animationContainerStyle
, Screen.style Screen.mobile
[ Css.property "flex" "0 0 auto"
, marginBottom (px 120)
, maxWidth (pct 90)
]
]
]
[ div
[ classList
[ ( "right", side == Right )
, ( "left", side == Left )
, ( "animated", True )
, ( "hidden", True )
, ( "content", True )
, ( "animation-target", True )
]
, css
[ displayFlex
, flexDirection column
, flex3 (int 0) (int 0) (pct 85)
, Card.style theme
, maxWidth (pct 100)
]
]
[ div
[ css
[ Card.headingStyle theme
, flexBasis auto
, justifyContent spaceBetween
]
]
[ h1
[ class "title"
, css
[ fontSize (rem 1.2)
, fontWeight (int 500)
, margin4 (px 5) (px 0) (px 5) (px 20)
]
]
[ text title ]
, case maybeUrl of
Just url ->
a
[ href url
, css
[ color (Color.secondaryFont theme)
, marginRight (px 15)
, displayFlex
, alignItems center
, textDecoration none
]
]
[ Svg.link
[ SvgAttr.css
[ Css.width (px 18)
, Css.height (px 18)
, marginLeft (px 5)
, position relative
]
]
]
Nothing ->
text ""
]
, div
[ class "content"
, css
[ fontSize (rem 1.0)
, padding2 (px 0) (px 20)
, letterSpacing (px 0.5)
, lineHeight (pct 150)
]
]
[ Markdown.toHtml
"donate-desc"
[]
(Style.Post.style theme)
description
]
]
]
braveUrl : String
braveUrl =
"https://brave.com/par269"
{- Styles -}
sectionStyle : Style
sectionStyle =
Css.batch
[ displayFlex
, alignItems center
, justifyContent spaceBetween
, flexBasis auto
, Css.property "flex" "1 0 auto"
, marginBottom (px 200)
, Css.width (pct 100)
, Screen.style Screen.mobile
[ flexDirection column
, minHeight (px 0)
, margin (px 0)
]
]
animationContainerStyle : Style
animationContainerStyle =
Css.batch
[ minHeight (pct 100)
, alignItems center
, displayFlex
, Screen.style Screen.mobile
[ justifyContent center
, minHeight (px 0)
, marginTop (px 0)
]
]
| elm |
[
{
"context": " { userProfileBefore | chosenName = chosenName }\n\n usersProfiles =\n ",
"end": 16014,
"score": 0.9569107294,
"start": 16004,
"tag": "NAME",
"value": "chosenName"
}
] | implement/example-apps/rich-chat-room/src/Backend/Main.elm | sharon-06/elm-fullstack | 1 | module Backend.Main exposing
( State
, backendMain
)
import Base64
import Bytes
import Bytes.Decode
import Bytes.Encode
import CompilationInterface.ElmMake
import CompilationInterface.GenerateJsonCoders as GenerateJsonCoders
import CompilationInterface.SourceFiles
import Conversation exposing (UserId)
import Dict
import ElmFullstack
import FrontendBackendInterface
import Json.Decode
import Json.Encode
import SHA1
import Url
type alias State =
{ posixTimeMilli : Int
, conversationHistory : List Conversation.Event
, usersSessions : Dict.Dict String UserSessionState
, usersProfiles : Dict.Dict UserId UserProfile
, usersLastSeen : Dict.Dict UserId { posixTime : Int }
, pendingHttpRequests : Dict.Dict String PendingHttpRequest
}
type alias PendingHttpRequest =
{ posixTimeMilli : Int
, userSessionId : String
, userId : Maybe UserId
, requestFromUser : FrontendBackendInterface.RequestFromUser
}
type alias UserSessionState =
{ beginPosixTime : Int
, clientAddress : Maybe String
, userId : Maybe UserId
, lastUsePosixTime : Int
}
type alias UserProfile =
{ chosenName : String
}
backendMain : ElmFullstack.BackendConfig State
backendMain =
{ init = ( initState, [] )
, subscriptions = subscriptions
}
subscriptions : State -> ElmFullstack.BackendSubs State
subscriptions state =
{ httpRequest = updateForHttpRequestEvent
, posixTimeIsPast =
if Dict.isEmpty state.pendingHttpRequests then
Nothing
else
Just
{ minimumPosixTimeMilli = state.posixTimeMilli + 1000
, update =
\{ currentPosixTimeMilli } stateBefore ->
processPendingHttpRequests { stateBefore | posixTimeMilli = currentPosixTimeMilli }
}
}
processPendingHttpRequests : State -> ( State, ElmFullstack.BackendCmds State )
processPendingHttpRequests stateBefore =
let
( state, httpResponses ) =
stateBefore.pendingHttpRequests
|> Dict.toList
|> List.foldl
(\( pendingHttpRequestId, pendingHttpRequest ) ( intermediateState, intermediateHttpResponses ) ->
case
processRequestFromUser
{ posixTimeMilli = stateBefore.posixTimeMilli
, loginUrl = ""
}
{ posixTimeMilli = pendingHttpRequest.posixTimeMilli
, userId = pendingHttpRequest.userId
, requestFromUser = pendingHttpRequest.requestFromUser
}
intermediateState
of
Nothing ->
( intermediateState
, intermediateHttpResponses
)
Just ( completeHttpResponseState, completeHttpResponseResponseToUser ) ->
let
responseToClient =
{ currentPosixTimeMilli = intermediateState.posixTimeMilli
, currentUserId = pendingHttpRequest.userId
, responseToUser =
completeHttpResponseResponseToUser
}
httpResponse =
{ httpRequestId = pendingHttpRequestId
, response =
{ statusCode = 200
, bodyAsBase64 =
responseToClient
|> GenerateJsonCoders.jsonEncodeMessageToClient
|> Json.Encode.encode 0
|> encodeStringToBytes
|> Base64.fromBytes
, headersToAdd = []
}
|> addCookieUserSessionId pendingHttpRequest.userSessionId
}
in
( completeHttpResponseState
, httpResponse :: intermediateHttpResponses
)
)
( stateBefore, [] )
pendingHttpRequests =
httpResponses
|> List.map .httpRequestId
|> List.foldl Dict.remove stateBefore.pendingHttpRequests
in
( { state | pendingHttpRequests = pendingHttpRequests }
, List.map ElmFullstack.RespondToHttpRequest httpResponses
)
updateForHttpRequestEvent : ElmFullstack.HttpRequestEventStruct -> State -> ( State, ElmFullstack.BackendCmds State )
updateForHttpRequestEvent httpRequestEvent stateBefore =
let
( ( state, pendingHttpRequestsCmds ), directCmds ) =
updateForHttpRequestEventWithoutPendingHttpRequests httpRequestEvent stateBefore
|> Tuple.mapFirst processPendingHttpRequests
in
( state
, directCmds ++ pendingHttpRequestsCmds
)
updateForHttpRequestEventWithoutPendingHttpRequests : ElmFullstack.HttpRequestEventStruct -> State -> ( State, ElmFullstack.BackendCmds State )
updateForHttpRequestEventWithoutPendingHttpRequests httpRequestEvent stateBeforeUpdatingTime =
let
stateBefore =
{ stateBeforeUpdatingTime | posixTimeMilli = httpRequestEvent.posixTimeMilli }
respondWithFrontendHtmlDocument { enableInspector } =
( stateBefore
, [ ElmFullstack.RespondToHttpRequest
{ httpRequestId = httpRequestEvent.httpRequestId
, response =
{ statusCode = 200
, bodyAsBase64 =
Just
(if enableInspector then
CompilationInterface.ElmMake.elm_make____src_Frontend_Main_elm.debug.gzip.base64
else
CompilationInterface.ElmMake.elm_make____src_Frontend_Main_elm.gzip.base64
)
, headersToAdd = [ { name = "Content-Encoding", values = [ "gzip" ] } ]
}
}
]
)
in
case
httpRequestEvent.request.uri
|> Url.fromString
|> Maybe.andThen FrontendBackendInterface.routeFromUrl
of
Nothing ->
respondWithFrontendHtmlDocument { enableInspector = False }
Just FrontendBackendInterface.FrontendWithInspectorRoute ->
respondWithFrontendHtmlDocument { enableInspector = True }
Just FrontendBackendInterface.ApiRoute ->
case
httpRequestEvent.request.bodyAsBase64
|> Maybe.map (Base64.toBytes >> Maybe.map (decodeBytesToString >> Maybe.withDefault "Failed to decode bytes to string") >> Maybe.withDefault "Failed to decode from base64")
|> Maybe.withDefault "Missing HTTP body"
|> Json.Decode.decodeString GenerateJsonCoders.jsonDecodeRequestFromUser
of
Err decodeError ->
let
httpResponse =
{ httpRequestId = httpRequestEvent.httpRequestId
, response =
{ statusCode = 400
, bodyAsBase64 =
("Failed to decode request: " ++ (decodeError |> Json.Decode.errorToString))
|> encodeStringToBytes
|> Base64.fromBytes
, headersToAdd = []
}
}
in
( stateBefore
, [ ElmFullstack.RespondToHttpRequest httpResponse ]
)
Ok requestFromUser ->
let
( userSessionId, userSessionStateBefore ) =
userSessionIdAndStateFromRequestOrCreateNew httpRequestEvent.request stateBefore
userSessionState =
userSessionStateBefore
usersLastSeen =
case userSessionStateBefore.userId of
Nothing ->
stateBefore.usersLastSeen
Just userId ->
stateBefore.usersLastSeen
|> Dict.insert userId { posixTime = stateBefore.posixTimeMilli // 1000 }
usersSessions =
stateBefore.usersSessions
|> Dict.insert userSessionId userSessionState
in
( { stateBefore
| usersLastSeen = usersLastSeen
, usersSessions = usersSessions
, pendingHttpRequests =
stateBefore.pendingHttpRequests
|> Dict.insert httpRequestEvent.httpRequestId
{ posixTimeMilli = httpRequestEvent.posixTimeMilli
, userSessionId = userSessionId
, userId = userSessionStateBefore.userId
, requestFromUser = requestFromUser
}
}
, []
)
Just (FrontendBackendInterface.StaticContentRoute contentName) ->
let
httpResponse =
case availableStaticContent |> Dict.get contentName of
Nothing ->
{ statusCode = 404
, bodyAsBase64 =
("Found no content with the name " ++ contentName)
|> encodeStringToBytes
|> Base64.fromBytes
, headersToAdd = []
}
Just content ->
{ statusCode = 200
, bodyAsBase64 = content |> Base64.fromBytes
, headersToAdd = [ { name = "Cache-Control", values = [ "public, max-age=31536000" ] } ]
}
in
( stateBefore
, [ ElmFullstack.RespondToHttpRequest
{ httpRequestId = httpRequestEvent.httpRequestId
, response = httpResponse
}
]
)
availableStaticContent : Dict.Dict String Bytes.Bytes
availableStaticContent =
[ CompilationInterface.SourceFiles.file____static_chat_message_added_0_mp3.bytes ]
|> List.map (\content -> ( content |> FrontendBackendInterface.staticContentFileName, content ))
|> Dict.fromList
seeingLobbyFromState : State -> FrontendBackendInterface.SeeingLobbyStructure
seeingLobbyFromState state =
let
usersOnline =
state.usersLastSeen
|> Dict.filter (\_ lastSeen -> state.posixTimeMilli // 1000 - 10 < lastSeen.posixTime)
|> Dict.keys
in
{ conversationHistory = state.conversationHistory
, usersOnline = usersOnline
}
processRequestFromUser :
{ posixTimeMilli : Int, loginUrl : String }
-> { posixTimeMilli : Int, userId : Maybe Int, requestFromUser : FrontendBackendInterface.RequestFromUser }
-> State
-> Maybe ( State, FrontendBackendInterface.ResponseToUser )
processRequestFromUser context requestFromUser stateBefore =
case requestFromUser.requestFromUser of
FrontendBackendInterface.ShowUpRequest showUpRequest ->
let
seeingLobby =
seeingLobbyFromState stateBefore
requestAgeMilli =
context.posixTimeMilli - requestFromUser.posixTimeMilli
in
if
((seeingLobby.conversationHistory |> List.map .posixTimeMilli |> List.maximum)
/= showUpRequest.lastSeenEventPosixTimeMilli
)
|| (5000 <= requestAgeMilli)
then
Just
( stateBefore
, FrontendBackendInterface.SeeingLobby seeingLobby
)
else
Nothing
FrontendBackendInterface.AddTextMessageRequest message ->
case requestFromUser.userId of
Nothing ->
Just
( stateBefore
, ([ Conversation.LeafPlainText "⚠️ To add a message, please sign in first at "
, Conversation.LeafLinkToUrl { url = context.loginUrl }
]
|> Conversation.SequenceOfNodes
)
|> FrontendBackendInterface.MessageToUser
)
Just userId ->
if hasUserExhaustedRateLimitToAddMessage stateBefore { userId = userId } then
Just
( stateBefore
, Conversation.LeafPlainText "❌ Too many messages – Maximum sending rate exceeded."
|> FrontendBackendInterface.MessageToUser
)
else
let
conversationHistory =
{ posixTimeMilli = stateBefore.posixTimeMilli
, origin = Conversation.FromUser { userId = userId }
, message = Conversation.LeafPlainText message
}
:: stateBefore.conversationHistory
stateAfterAddingMessage =
{ stateBefore | conversationHistory = conversationHistory }
in
Just
( stateAfterAddingMessage
, stateAfterAddingMessage |> seeingLobbyFromState |> FrontendBackendInterface.SeeingLobby
)
FrontendBackendInterface.ChooseNameRequest chosenName ->
case requestFromUser.userId of
Nothing ->
Just
( stateBefore
, ([ Conversation.LeafPlainText "⚠️ To choose a name, please sign in first at "
, Conversation.LeafLinkToUrl { url = context.loginUrl }
]
|> Conversation.SequenceOfNodes
)
|> FrontendBackendInterface.MessageToUser
)
Just userId ->
let
userProfileBefore =
stateBefore.usersProfiles |> Dict.get userId |> Maybe.withDefault initUserProfile
userProfile =
{ userProfileBefore | chosenName = chosenName }
usersProfiles =
stateBefore.usersProfiles |> Dict.insert userId userProfile
in
Just
( { stateBefore | usersProfiles = usersProfiles }
, userProfile |> FrontendBackendInterface.ReadUserProfile
)
FrontendBackendInterface.ReadUserProfileRequest userId ->
Just
( stateBefore
, stateBefore.usersProfiles
|> Dict.get userId
|> Maybe.withDefault initUserProfile
|> FrontendBackendInterface.ReadUserProfile
)
initUserProfile : UserProfile
initUserProfile =
{ chosenName = "" }
userSessionIdAndStateFromRequestOrCreateNew : ElmFullstack.HttpRequestProperties -> State -> ( String, UserSessionState )
userSessionIdAndStateFromRequestOrCreateNew httpRequest state =
state |> getFirstMatchingUserSessionOrCreateNew (getSessionIdsFromHttpRequest httpRequest)
getFirstMatchingUserSessionOrCreateNew : List String -> State -> ( String, UserSessionState )
getFirstMatchingUserSessionOrCreateNew sessionIds state =
sessionIds
|> List.filterMap
(\requestSessionId ->
state.usersSessions
|> Dict.get requestSessionId
|> Maybe.map
(\sessionState ->
( requestSessionId, sessionState )
)
)
|> List.sortBy
(\( _, sessionState ) ->
if sessionState.userId == Nothing then
1
else
0
)
|> List.head
|> Maybe.withDefault (state |> getNextUserSessionIdAndState)
getSessionIdsFromHttpRequest : ElmFullstack.HttpRequestProperties -> List String
getSessionIdsFromHttpRequest httpRequest =
let
cookies =
httpRequest.headers
|> List.filter (\{ name } -> (name |> String.toLower) == "cookie")
|> List.head
|> Maybe.map .values
|> Maybe.withDefault []
|> List.concatMap (String.split ";")
|> List.map String.trim
prefix =
httpSessionIdCookieName ++ "="
in
cookies
|> List.filter (String.startsWith prefix)
|> List.map (\sessionIdCookie -> sessionIdCookie |> String.dropLeft (prefix |> String.length))
getNextUserSessionIdAndState : State -> ( String, UserSessionState )
getNextUserSessionIdAndState state =
let
posixTime =
state.posixTimeMilli // 1000
in
( state |> getNextUserSessionId
, { userId = Just ((state |> getLastUserId |> Maybe.withDefault 0) + 1)
, beginPosixTime = posixTime
, lastUsePosixTime = posixTime
, clientAddress = Nothing
}
)
getLastUserId : State -> Maybe Int
getLastUserId state =
[ state.usersProfiles |> Dict.keys
, state.usersSessions |> Dict.values |> List.filterMap .userId
]
|> List.concat
|> List.maximum
getNextUserSessionId : State -> String
getNextUserSessionId state =
let
otherSessionsIds =
state.usersSessions |> Dict.keys
source =
(otherSessionsIds |> String.concat) ++ (state.posixTimeMilli |> String.fromInt)
in
source |> SHA1.fromString |> SHA1.toHex |> String.left 30
hasUserExhaustedRateLimitToAddMessage : State -> { userId : Int } -> Bool
hasUserExhaustedRateLimitToAddMessage state { userId } =
let
addedMessagesAges =
state.conversationHistory
|> List.filterMap
(\event ->
case event.origin of
Conversation.FromSystem ->
Nothing
Conversation.FromUser fromUser ->
if fromUser.userId /= userId then
Nothing
else
Just event.posixTimeMilli
)
|> List.map (\addedMessagePosixTimeMilli -> (state.posixTimeMilli - addedMessagePosixTimeMilli) // 1000)
numberOfMessagesWithinAge ageInSeconds =
addedMessagesAges
|> List.filter (\messageAge -> messageAge <= ageInSeconds)
|> List.length
in
userAddMessageRateLimits
|> List.any (\limit -> limit.numberOfMessages <= numberOfMessagesWithinAge limit.timespanInSeconds)
userAddMessageRateLimits : List { timespanInSeconds : Int, numberOfMessages : Int }
userAddMessageRateLimits =
[ { timespanInSeconds = 3, numberOfMessages = 2 }
, { timespanInSeconds = 10, numberOfMessages = 3 }
, { timespanInSeconds = 60, numberOfMessages = 8 }
, { timespanInSeconds = 60 * 10, numberOfMessages = 50 }
]
decodeBytesToString : Bytes.Bytes -> Maybe String
decodeBytesToString bytes =
bytes |> Bytes.Decode.decode (Bytes.Decode.string (bytes |> Bytes.width))
encodeStringToBytes : String -> Bytes.Bytes
encodeStringToBytes =
Bytes.Encode.string >> Bytes.Encode.encode
addCookieUserSessionId : String -> ElmFullstack.HttpResponse -> ElmFullstack.HttpResponse
addCookieUserSessionId userSessionId httpResponse =
let
cookieHeader =
{ name = "Set-Cookie", values = [ httpSessionIdCookieName ++ "=" ++ userSessionId ++ "; Path=/; Max-Age=3600" ] }
in
{ httpResponse | headersToAdd = cookieHeader :: httpResponse.headersToAdd }
httpSessionIdCookieName : String
httpSessionIdCookieName =
"sessionid"
initState : State
initState =
{ posixTimeMilli = 0
, conversationHistory = []
, usersProfiles = Dict.empty
, usersSessions = Dict.empty
, usersLastSeen = Dict.empty
, pendingHttpRequests = Dict.empty
}
| 33560 | module Backend.Main exposing
( State
, backendMain
)
import Base64
import Bytes
import Bytes.Decode
import Bytes.Encode
import CompilationInterface.ElmMake
import CompilationInterface.GenerateJsonCoders as GenerateJsonCoders
import CompilationInterface.SourceFiles
import Conversation exposing (UserId)
import Dict
import ElmFullstack
import FrontendBackendInterface
import Json.Decode
import Json.Encode
import SHA1
import Url
type alias State =
{ posixTimeMilli : Int
, conversationHistory : List Conversation.Event
, usersSessions : Dict.Dict String UserSessionState
, usersProfiles : Dict.Dict UserId UserProfile
, usersLastSeen : Dict.Dict UserId { posixTime : Int }
, pendingHttpRequests : Dict.Dict String PendingHttpRequest
}
type alias PendingHttpRequest =
{ posixTimeMilli : Int
, userSessionId : String
, userId : Maybe UserId
, requestFromUser : FrontendBackendInterface.RequestFromUser
}
type alias UserSessionState =
{ beginPosixTime : Int
, clientAddress : Maybe String
, userId : Maybe UserId
, lastUsePosixTime : Int
}
type alias UserProfile =
{ chosenName : String
}
backendMain : ElmFullstack.BackendConfig State
backendMain =
{ init = ( initState, [] )
, subscriptions = subscriptions
}
subscriptions : State -> ElmFullstack.BackendSubs State
subscriptions state =
{ httpRequest = updateForHttpRequestEvent
, posixTimeIsPast =
if Dict.isEmpty state.pendingHttpRequests then
Nothing
else
Just
{ minimumPosixTimeMilli = state.posixTimeMilli + 1000
, update =
\{ currentPosixTimeMilli } stateBefore ->
processPendingHttpRequests { stateBefore | posixTimeMilli = currentPosixTimeMilli }
}
}
processPendingHttpRequests : State -> ( State, ElmFullstack.BackendCmds State )
processPendingHttpRequests stateBefore =
let
( state, httpResponses ) =
stateBefore.pendingHttpRequests
|> Dict.toList
|> List.foldl
(\( pendingHttpRequestId, pendingHttpRequest ) ( intermediateState, intermediateHttpResponses ) ->
case
processRequestFromUser
{ posixTimeMilli = stateBefore.posixTimeMilli
, loginUrl = ""
}
{ posixTimeMilli = pendingHttpRequest.posixTimeMilli
, userId = pendingHttpRequest.userId
, requestFromUser = pendingHttpRequest.requestFromUser
}
intermediateState
of
Nothing ->
( intermediateState
, intermediateHttpResponses
)
Just ( completeHttpResponseState, completeHttpResponseResponseToUser ) ->
let
responseToClient =
{ currentPosixTimeMilli = intermediateState.posixTimeMilli
, currentUserId = pendingHttpRequest.userId
, responseToUser =
completeHttpResponseResponseToUser
}
httpResponse =
{ httpRequestId = pendingHttpRequestId
, response =
{ statusCode = 200
, bodyAsBase64 =
responseToClient
|> GenerateJsonCoders.jsonEncodeMessageToClient
|> Json.Encode.encode 0
|> encodeStringToBytes
|> Base64.fromBytes
, headersToAdd = []
}
|> addCookieUserSessionId pendingHttpRequest.userSessionId
}
in
( completeHttpResponseState
, httpResponse :: intermediateHttpResponses
)
)
( stateBefore, [] )
pendingHttpRequests =
httpResponses
|> List.map .httpRequestId
|> List.foldl Dict.remove stateBefore.pendingHttpRequests
in
( { state | pendingHttpRequests = pendingHttpRequests }
, List.map ElmFullstack.RespondToHttpRequest httpResponses
)
updateForHttpRequestEvent : ElmFullstack.HttpRequestEventStruct -> State -> ( State, ElmFullstack.BackendCmds State )
updateForHttpRequestEvent httpRequestEvent stateBefore =
let
( ( state, pendingHttpRequestsCmds ), directCmds ) =
updateForHttpRequestEventWithoutPendingHttpRequests httpRequestEvent stateBefore
|> Tuple.mapFirst processPendingHttpRequests
in
( state
, directCmds ++ pendingHttpRequestsCmds
)
updateForHttpRequestEventWithoutPendingHttpRequests : ElmFullstack.HttpRequestEventStruct -> State -> ( State, ElmFullstack.BackendCmds State )
updateForHttpRequestEventWithoutPendingHttpRequests httpRequestEvent stateBeforeUpdatingTime =
let
stateBefore =
{ stateBeforeUpdatingTime | posixTimeMilli = httpRequestEvent.posixTimeMilli }
respondWithFrontendHtmlDocument { enableInspector } =
( stateBefore
, [ ElmFullstack.RespondToHttpRequest
{ httpRequestId = httpRequestEvent.httpRequestId
, response =
{ statusCode = 200
, bodyAsBase64 =
Just
(if enableInspector then
CompilationInterface.ElmMake.elm_make____src_Frontend_Main_elm.debug.gzip.base64
else
CompilationInterface.ElmMake.elm_make____src_Frontend_Main_elm.gzip.base64
)
, headersToAdd = [ { name = "Content-Encoding", values = [ "gzip" ] } ]
}
}
]
)
in
case
httpRequestEvent.request.uri
|> Url.fromString
|> Maybe.andThen FrontendBackendInterface.routeFromUrl
of
Nothing ->
respondWithFrontendHtmlDocument { enableInspector = False }
Just FrontendBackendInterface.FrontendWithInspectorRoute ->
respondWithFrontendHtmlDocument { enableInspector = True }
Just FrontendBackendInterface.ApiRoute ->
case
httpRequestEvent.request.bodyAsBase64
|> Maybe.map (Base64.toBytes >> Maybe.map (decodeBytesToString >> Maybe.withDefault "Failed to decode bytes to string") >> Maybe.withDefault "Failed to decode from base64")
|> Maybe.withDefault "Missing HTTP body"
|> Json.Decode.decodeString GenerateJsonCoders.jsonDecodeRequestFromUser
of
Err decodeError ->
let
httpResponse =
{ httpRequestId = httpRequestEvent.httpRequestId
, response =
{ statusCode = 400
, bodyAsBase64 =
("Failed to decode request: " ++ (decodeError |> Json.Decode.errorToString))
|> encodeStringToBytes
|> Base64.fromBytes
, headersToAdd = []
}
}
in
( stateBefore
, [ ElmFullstack.RespondToHttpRequest httpResponse ]
)
Ok requestFromUser ->
let
( userSessionId, userSessionStateBefore ) =
userSessionIdAndStateFromRequestOrCreateNew httpRequestEvent.request stateBefore
userSessionState =
userSessionStateBefore
usersLastSeen =
case userSessionStateBefore.userId of
Nothing ->
stateBefore.usersLastSeen
Just userId ->
stateBefore.usersLastSeen
|> Dict.insert userId { posixTime = stateBefore.posixTimeMilli // 1000 }
usersSessions =
stateBefore.usersSessions
|> Dict.insert userSessionId userSessionState
in
( { stateBefore
| usersLastSeen = usersLastSeen
, usersSessions = usersSessions
, pendingHttpRequests =
stateBefore.pendingHttpRequests
|> Dict.insert httpRequestEvent.httpRequestId
{ posixTimeMilli = httpRequestEvent.posixTimeMilli
, userSessionId = userSessionId
, userId = userSessionStateBefore.userId
, requestFromUser = requestFromUser
}
}
, []
)
Just (FrontendBackendInterface.StaticContentRoute contentName) ->
let
httpResponse =
case availableStaticContent |> Dict.get contentName of
Nothing ->
{ statusCode = 404
, bodyAsBase64 =
("Found no content with the name " ++ contentName)
|> encodeStringToBytes
|> Base64.fromBytes
, headersToAdd = []
}
Just content ->
{ statusCode = 200
, bodyAsBase64 = content |> Base64.fromBytes
, headersToAdd = [ { name = "Cache-Control", values = [ "public, max-age=31536000" ] } ]
}
in
( stateBefore
, [ ElmFullstack.RespondToHttpRequest
{ httpRequestId = httpRequestEvent.httpRequestId
, response = httpResponse
}
]
)
availableStaticContent : Dict.Dict String Bytes.Bytes
availableStaticContent =
[ CompilationInterface.SourceFiles.file____static_chat_message_added_0_mp3.bytes ]
|> List.map (\content -> ( content |> FrontendBackendInterface.staticContentFileName, content ))
|> Dict.fromList
seeingLobbyFromState : State -> FrontendBackendInterface.SeeingLobbyStructure
seeingLobbyFromState state =
let
usersOnline =
state.usersLastSeen
|> Dict.filter (\_ lastSeen -> state.posixTimeMilli // 1000 - 10 < lastSeen.posixTime)
|> Dict.keys
in
{ conversationHistory = state.conversationHistory
, usersOnline = usersOnline
}
processRequestFromUser :
{ posixTimeMilli : Int, loginUrl : String }
-> { posixTimeMilli : Int, userId : Maybe Int, requestFromUser : FrontendBackendInterface.RequestFromUser }
-> State
-> Maybe ( State, FrontendBackendInterface.ResponseToUser )
processRequestFromUser context requestFromUser stateBefore =
case requestFromUser.requestFromUser of
FrontendBackendInterface.ShowUpRequest showUpRequest ->
let
seeingLobby =
seeingLobbyFromState stateBefore
requestAgeMilli =
context.posixTimeMilli - requestFromUser.posixTimeMilli
in
if
((seeingLobby.conversationHistory |> List.map .posixTimeMilli |> List.maximum)
/= showUpRequest.lastSeenEventPosixTimeMilli
)
|| (5000 <= requestAgeMilli)
then
Just
( stateBefore
, FrontendBackendInterface.SeeingLobby seeingLobby
)
else
Nothing
FrontendBackendInterface.AddTextMessageRequest message ->
case requestFromUser.userId of
Nothing ->
Just
( stateBefore
, ([ Conversation.LeafPlainText "⚠️ To add a message, please sign in first at "
, Conversation.LeafLinkToUrl { url = context.loginUrl }
]
|> Conversation.SequenceOfNodes
)
|> FrontendBackendInterface.MessageToUser
)
Just userId ->
if hasUserExhaustedRateLimitToAddMessage stateBefore { userId = userId } then
Just
( stateBefore
, Conversation.LeafPlainText "❌ Too many messages – Maximum sending rate exceeded."
|> FrontendBackendInterface.MessageToUser
)
else
let
conversationHistory =
{ posixTimeMilli = stateBefore.posixTimeMilli
, origin = Conversation.FromUser { userId = userId }
, message = Conversation.LeafPlainText message
}
:: stateBefore.conversationHistory
stateAfterAddingMessage =
{ stateBefore | conversationHistory = conversationHistory }
in
Just
( stateAfterAddingMessage
, stateAfterAddingMessage |> seeingLobbyFromState |> FrontendBackendInterface.SeeingLobby
)
FrontendBackendInterface.ChooseNameRequest chosenName ->
case requestFromUser.userId of
Nothing ->
Just
( stateBefore
, ([ Conversation.LeafPlainText "⚠️ To choose a name, please sign in first at "
, Conversation.LeafLinkToUrl { url = context.loginUrl }
]
|> Conversation.SequenceOfNodes
)
|> FrontendBackendInterface.MessageToUser
)
Just userId ->
let
userProfileBefore =
stateBefore.usersProfiles |> Dict.get userId |> Maybe.withDefault initUserProfile
userProfile =
{ userProfileBefore | chosenName = <NAME> }
usersProfiles =
stateBefore.usersProfiles |> Dict.insert userId userProfile
in
Just
( { stateBefore | usersProfiles = usersProfiles }
, userProfile |> FrontendBackendInterface.ReadUserProfile
)
FrontendBackendInterface.ReadUserProfileRequest userId ->
Just
( stateBefore
, stateBefore.usersProfiles
|> Dict.get userId
|> Maybe.withDefault initUserProfile
|> FrontendBackendInterface.ReadUserProfile
)
initUserProfile : UserProfile
initUserProfile =
{ chosenName = "" }
userSessionIdAndStateFromRequestOrCreateNew : ElmFullstack.HttpRequestProperties -> State -> ( String, UserSessionState )
userSessionIdAndStateFromRequestOrCreateNew httpRequest state =
state |> getFirstMatchingUserSessionOrCreateNew (getSessionIdsFromHttpRequest httpRequest)
getFirstMatchingUserSessionOrCreateNew : List String -> State -> ( String, UserSessionState )
getFirstMatchingUserSessionOrCreateNew sessionIds state =
sessionIds
|> List.filterMap
(\requestSessionId ->
state.usersSessions
|> Dict.get requestSessionId
|> Maybe.map
(\sessionState ->
( requestSessionId, sessionState )
)
)
|> List.sortBy
(\( _, sessionState ) ->
if sessionState.userId == Nothing then
1
else
0
)
|> List.head
|> Maybe.withDefault (state |> getNextUserSessionIdAndState)
getSessionIdsFromHttpRequest : ElmFullstack.HttpRequestProperties -> List String
getSessionIdsFromHttpRequest httpRequest =
let
cookies =
httpRequest.headers
|> List.filter (\{ name } -> (name |> String.toLower) == "cookie")
|> List.head
|> Maybe.map .values
|> Maybe.withDefault []
|> List.concatMap (String.split ";")
|> List.map String.trim
prefix =
httpSessionIdCookieName ++ "="
in
cookies
|> List.filter (String.startsWith prefix)
|> List.map (\sessionIdCookie -> sessionIdCookie |> String.dropLeft (prefix |> String.length))
getNextUserSessionIdAndState : State -> ( String, UserSessionState )
getNextUserSessionIdAndState state =
let
posixTime =
state.posixTimeMilli // 1000
in
( state |> getNextUserSessionId
, { userId = Just ((state |> getLastUserId |> Maybe.withDefault 0) + 1)
, beginPosixTime = posixTime
, lastUsePosixTime = posixTime
, clientAddress = Nothing
}
)
getLastUserId : State -> Maybe Int
getLastUserId state =
[ state.usersProfiles |> Dict.keys
, state.usersSessions |> Dict.values |> List.filterMap .userId
]
|> List.concat
|> List.maximum
getNextUserSessionId : State -> String
getNextUserSessionId state =
let
otherSessionsIds =
state.usersSessions |> Dict.keys
source =
(otherSessionsIds |> String.concat) ++ (state.posixTimeMilli |> String.fromInt)
in
source |> SHA1.fromString |> SHA1.toHex |> String.left 30
hasUserExhaustedRateLimitToAddMessage : State -> { userId : Int } -> Bool
hasUserExhaustedRateLimitToAddMessage state { userId } =
let
addedMessagesAges =
state.conversationHistory
|> List.filterMap
(\event ->
case event.origin of
Conversation.FromSystem ->
Nothing
Conversation.FromUser fromUser ->
if fromUser.userId /= userId then
Nothing
else
Just event.posixTimeMilli
)
|> List.map (\addedMessagePosixTimeMilli -> (state.posixTimeMilli - addedMessagePosixTimeMilli) // 1000)
numberOfMessagesWithinAge ageInSeconds =
addedMessagesAges
|> List.filter (\messageAge -> messageAge <= ageInSeconds)
|> List.length
in
userAddMessageRateLimits
|> List.any (\limit -> limit.numberOfMessages <= numberOfMessagesWithinAge limit.timespanInSeconds)
userAddMessageRateLimits : List { timespanInSeconds : Int, numberOfMessages : Int }
userAddMessageRateLimits =
[ { timespanInSeconds = 3, numberOfMessages = 2 }
, { timespanInSeconds = 10, numberOfMessages = 3 }
, { timespanInSeconds = 60, numberOfMessages = 8 }
, { timespanInSeconds = 60 * 10, numberOfMessages = 50 }
]
decodeBytesToString : Bytes.Bytes -> Maybe String
decodeBytesToString bytes =
bytes |> Bytes.Decode.decode (Bytes.Decode.string (bytes |> Bytes.width))
encodeStringToBytes : String -> Bytes.Bytes
encodeStringToBytes =
Bytes.Encode.string >> Bytes.Encode.encode
addCookieUserSessionId : String -> ElmFullstack.HttpResponse -> ElmFullstack.HttpResponse
addCookieUserSessionId userSessionId httpResponse =
let
cookieHeader =
{ name = "Set-Cookie", values = [ httpSessionIdCookieName ++ "=" ++ userSessionId ++ "; Path=/; Max-Age=3600" ] }
in
{ httpResponse | headersToAdd = cookieHeader :: httpResponse.headersToAdd }
httpSessionIdCookieName : String
httpSessionIdCookieName =
"sessionid"
initState : State
initState =
{ posixTimeMilli = 0
, conversationHistory = []
, usersProfiles = Dict.empty
, usersSessions = Dict.empty
, usersLastSeen = Dict.empty
, pendingHttpRequests = Dict.empty
}
| true | module Backend.Main exposing
( State
, backendMain
)
import Base64
import Bytes
import Bytes.Decode
import Bytes.Encode
import CompilationInterface.ElmMake
import CompilationInterface.GenerateJsonCoders as GenerateJsonCoders
import CompilationInterface.SourceFiles
import Conversation exposing (UserId)
import Dict
import ElmFullstack
import FrontendBackendInterface
import Json.Decode
import Json.Encode
import SHA1
import Url
type alias State =
{ posixTimeMilli : Int
, conversationHistory : List Conversation.Event
, usersSessions : Dict.Dict String UserSessionState
, usersProfiles : Dict.Dict UserId UserProfile
, usersLastSeen : Dict.Dict UserId { posixTime : Int }
, pendingHttpRequests : Dict.Dict String PendingHttpRequest
}
type alias PendingHttpRequest =
{ posixTimeMilli : Int
, userSessionId : String
, userId : Maybe UserId
, requestFromUser : FrontendBackendInterface.RequestFromUser
}
type alias UserSessionState =
{ beginPosixTime : Int
, clientAddress : Maybe String
, userId : Maybe UserId
, lastUsePosixTime : Int
}
type alias UserProfile =
{ chosenName : String
}
backendMain : ElmFullstack.BackendConfig State
backendMain =
{ init = ( initState, [] )
, subscriptions = subscriptions
}
subscriptions : State -> ElmFullstack.BackendSubs State
subscriptions state =
{ httpRequest = updateForHttpRequestEvent
, posixTimeIsPast =
if Dict.isEmpty state.pendingHttpRequests then
Nothing
else
Just
{ minimumPosixTimeMilli = state.posixTimeMilli + 1000
, update =
\{ currentPosixTimeMilli } stateBefore ->
processPendingHttpRequests { stateBefore | posixTimeMilli = currentPosixTimeMilli }
}
}
processPendingHttpRequests : State -> ( State, ElmFullstack.BackendCmds State )
processPendingHttpRequests stateBefore =
let
( state, httpResponses ) =
stateBefore.pendingHttpRequests
|> Dict.toList
|> List.foldl
(\( pendingHttpRequestId, pendingHttpRequest ) ( intermediateState, intermediateHttpResponses ) ->
case
processRequestFromUser
{ posixTimeMilli = stateBefore.posixTimeMilli
, loginUrl = ""
}
{ posixTimeMilli = pendingHttpRequest.posixTimeMilli
, userId = pendingHttpRequest.userId
, requestFromUser = pendingHttpRequest.requestFromUser
}
intermediateState
of
Nothing ->
( intermediateState
, intermediateHttpResponses
)
Just ( completeHttpResponseState, completeHttpResponseResponseToUser ) ->
let
responseToClient =
{ currentPosixTimeMilli = intermediateState.posixTimeMilli
, currentUserId = pendingHttpRequest.userId
, responseToUser =
completeHttpResponseResponseToUser
}
httpResponse =
{ httpRequestId = pendingHttpRequestId
, response =
{ statusCode = 200
, bodyAsBase64 =
responseToClient
|> GenerateJsonCoders.jsonEncodeMessageToClient
|> Json.Encode.encode 0
|> encodeStringToBytes
|> Base64.fromBytes
, headersToAdd = []
}
|> addCookieUserSessionId pendingHttpRequest.userSessionId
}
in
( completeHttpResponseState
, httpResponse :: intermediateHttpResponses
)
)
( stateBefore, [] )
pendingHttpRequests =
httpResponses
|> List.map .httpRequestId
|> List.foldl Dict.remove stateBefore.pendingHttpRequests
in
( { state | pendingHttpRequests = pendingHttpRequests }
, List.map ElmFullstack.RespondToHttpRequest httpResponses
)
updateForHttpRequestEvent : ElmFullstack.HttpRequestEventStruct -> State -> ( State, ElmFullstack.BackendCmds State )
updateForHttpRequestEvent httpRequestEvent stateBefore =
let
( ( state, pendingHttpRequestsCmds ), directCmds ) =
updateForHttpRequestEventWithoutPendingHttpRequests httpRequestEvent stateBefore
|> Tuple.mapFirst processPendingHttpRequests
in
( state
, directCmds ++ pendingHttpRequestsCmds
)
updateForHttpRequestEventWithoutPendingHttpRequests : ElmFullstack.HttpRequestEventStruct -> State -> ( State, ElmFullstack.BackendCmds State )
updateForHttpRequestEventWithoutPendingHttpRequests httpRequestEvent stateBeforeUpdatingTime =
let
stateBefore =
{ stateBeforeUpdatingTime | posixTimeMilli = httpRequestEvent.posixTimeMilli }
respondWithFrontendHtmlDocument { enableInspector } =
( stateBefore
, [ ElmFullstack.RespondToHttpRequest
{ httpRequestId = httpRequestEvent.httpRequestId
, response =
{ statusCode = 200
, bodyAsBase64 =
Just
(if enableInspector then
CompilationInterface.ElmMake.elm_make____src_Frontend_Main_elm.debug.gzip.base64
else
CompilationInterface.ElmMake.elm_make____src_Frontend_Main_elm.gzip.base64
)
, headersToAdd = [ { name = "Content-Encoding", values = [ "gzip" ] } ]
}
}
]
)
in
case
httpRequestEvent.request.uri
|> Url.fromString
|> Maybe.andThen FrontendBackendInterface.routeFromUrl
of
Nothing ->
respondWithFrontendHtmlDocument { enableInspector = False }
Just FrontendBackendInterface.FrontendWithInspectorRoute ->
respondWithFrontendHtmlDocument { enableInspector = True }
Just FrontendBackendInterface.ApiRoute ->
case
httpRequestEvent.request.bodyAsBase64
|> Maybe.map (Base64.toBytes >> Maybe.map (decodeBytesToString >> Maybe.withDefault "Failed to decode bytes to string") >> Maybe.withDefault "Failed to decode from base64")
|> Maybe.withDefault "Missing HTTP body"
|> Json.Decode.decodeString GenerateJsonCoders.jsonDecodeRequestFromUser
of
Err decodeError ->
let
httpResponse =
{ httpRequestId = httpRequestEvent.httpRequestId
, response =
{ statusCode = 400
, bodyAsBase64 =
("Failed to decode request: " ++ (decodeError |> Json.Decode.errorToString))
|> encodeStringToBytes
|> Base64.fromBytes
, headersToAdd = []
}
}
in
( stateBefore
, [ ElmFullstack.RespondToHttpRequest httpResponse ]
)
Ok requestFromUser ->
let
( userSessionId, userSessionStateBefore ) =
userSessionIdAndStateFromRequestOrCreateNew httpRequestEvent.request stateBefore
userSessionState =
userSessionStateBefore
usersLastSeen =
case userSessionStateBefore.userId of
Nothing ->
stateBefore.usersLastSeen
Just userId ->
stateBefore.usersLastSeen
|> Dict.insert userId { posixTime = stateBefore.posixTimeMilli // 1000 }
usersSessions =
stateBefore.usersSessions
|> Dict.insert userSessionId userSessionState
in
( { stateBefore
| usersLastSeen = usersLastSeen
, usersSessions = usersSessions
, pendingHttpRequests =
stateBefore.pendingHttpRequests
|> Dict.insert httpRequestEvent.httpRequestId
{ posixTimeMilli = httpRequestEvent.posixTimeMilli
, userSessionId = userSessionId
, userId = userSessionStateBefore.userId
, requestFromUser = requestFromUser
}
}
, []
)
Just (FrontendBackendInterface.StaticContentRoute contentName) ->
let
httpResponse =
case availableStaticContent |> Dict.get contentName of
Nothing ->
{ statusCode = 404
, bodyAsBase64 =
("Found no content with the name " ++ contentName)
|> encodeStringToBytes
|> Base64.fromBytes
, headersToAdd = []
}
Just content ->
{ statusCode = 200
, bodyAsBase64 = content |> Base64.fromBytes
, headersToAdd = [ { name = "Cache-Control", values = [ "public, max-age=31536000" ] } ]
}
in
( stateBefore
, [ ElmFullstack.RespondToHttpRequest
{ httpRequestId = httpRequestEvent.httpRequestId
, response = httpResponse
}
]
)
availableStaticContent : Dict.Dict String Bytes.Bytes
availableStaticContent =
[ CompilationInterface.SourceFiles.file____static_chat_message_added_0_mp3.bytes ]
|> List.map (\content -> ( content |> FrontendBackendInterface.staticContentFileName, content ))
|> Dict.fromList
seeingLobbyFromState : State -> FrontendBackendInterface.SeeingLobbyStructure
seeingLobbyFromState state =
let
usersOnline =
state.usersLastSeen
|> Dict.filter (\_ lastSeen -> state.posixTimeMilli // 1000 - 10 < lastSeen.posixTime)
|> Dict.keys
in
{ conversationHistory = state.conversationHistory
, usersOnline = usersOnline
}
processRequestFromUser :
{ posixTimeMilli : Int, loginUrl : String }
-> { posixTimeMilli : Int, userId : Maybe Int, requestFromUser : FrontendBackendInterface.RequestFromUser }
-> State
-> Maybe ( State, FrontendBackendInterface.ResponseToUser )
processRequestFromUser context requestFromUser stateBefore =
case requestFromUser.requestFromUser of
FrontendBackendInterface.ShowUpRequest showUpRequest ->
let
seeingLobby =
seeingLobbyFromState stateBefore
requestAgeMilli =
context.posixTimeMilli - requestFromUser.posixTimeMilli
in
if
((seeingLobby.conversationHistory |> List.map .posixTimeMilli |> List.maximum)
/= showUpRequest.lastSeenEventPosixTimeMilli
)
|| (5000 <= requestAgeMilli)
then
Just
( stateBefore
, FrontendBackendInterface.SeeingLobby seeingLobby
)
else
Nothing
FrontendBackendInterface.AddTextMessageRequest message ->
case requestFromUser.userId of
Nothing ->
Just
( stateBefore
, ([ Conversation.LeafPlainText "⚠️ To add a message, please sign in first at "
, Conversation.LeafLinkToUrl { url = context.loginUrl }
]
|> Conversation.SequenceOfNodes
)
|> FrontendBackendInterface.MessageToUser
)
Just userId ->
if hasUserExhaustedRateLimitToAddMessage stateBefore { userId = userId } then
Just
( stateBefore
, Conversation.LeafPlainText "❌ Too many messages – Maximum sending rate exceeded."
|> FrontendBackendInterface.MessageToUser
)
else
let
conversationHistory =
{ posixTimeMilli = stateBefore.posixTimeMilli
, origin = Conversation.FromUser { userId = userId }
, message = Conversation.LeafPlainText message
}
:: stateBefore.conversationHistory
stateAfterAddingMessage =
{ stateBefore | conversationHistory = conversationHistory }
in
Just
( stateAfterAddingMessage
, stateAfterAddingMessage |> seeingLobbyFromState |> FrontendBackendInterface.SeeingLobby
)
FrontendBackendInterface.ChooseNameRequest chosenName ->
case requestFromUser.userId of
Nothing ->
Just
( stateBefore
, ([ Conversation.LeafPlainText "⚠️ To choose a name, please sign in first at "
, Conversation.LeafLinkToUrl { url = context.loginUrl }
]
|> Conversation.SequenceOfNodes
)
|> FrontendBackendInterface.MessageToUser
)
Just userId ->
let
userProfileBefore =
stateBefore.usersProfiles |> Dict.get userId |> Maybe.withDefault initUserProfile
userProfile =
{ userProfileBefore | chosenName = PI:NAME:<NAME>END_PI }
usersProfiles =
stateBefore.usersProfiles |> Dict.insert userId userProfile
in
Just
( { stateBefore | usersProfiles = usersProfiles }
, userProfile |> FrontendBackendInterface.ReadUserProfile
)
FrontendBackendInterface.ReadUserProfileRequest userId ->
Just
( stateBefore
, stateBefore.usersProfiles
|> Dict.get userId
|> Maybe.withDefault initUserProfile
|> FrontendBackendInterface.ReadUserProfile
)
initUserProfile : UserProfile
initUserProfile =
{ chosenName = "" }
userSessionIdAndStateFromRequestOrCreateNew : ElmFullstack.HttpRequestProperties -> State -> ( String, UserSessionState )
userSessionIdAndStateFromRequestOrCreateNew httpRequest state =
state |> getFirstMatchingUserSessionOrCreateNew (getSessionIdsFromHttpRequest httpRequest)
getFirstMatchingUserSessionOrCreateNew : List String -> State -> ( String, UserSessionState )
getFirstMatchingUserSessionOrCreateNew sessionIds state =
sessionIds
|> List.filterMap
(\requestSessionId ->
state.usersSessions
|> Dict.get requestSessionId
|> Maybe.map
(\sessionState ->
( requestSessionId, sessionState )
)
)
|> List.sortBy
(\( _, sessionState ) ->
if sessionState.userId == Nothing then
1
else
0
)
|> List.head
|> Maybe.withDefault (state |> getNextUserSessionIdAndState)
getSessionIdsFromHttpRequest : ElmFullstack.HttpRequestProperties -> List String
getSessionIdsFromHttpRequest httpRequest =
let
cookies =
httpRequest.headers
|> List.filter (\{ name } -> (name |> String.toLower) == "cookie")
|> List.head
|> Maybe.map .values
|> Maybe.withDefault []
|> List.concatMap (String.split ";")
|> List.map String.trim
prefix =
httpSessionIdCookieName ++ "="
in
cookies
|> List.filter (String.startsWith prefix)
|> List.map (\sessionIdCookie -> sessionIdCookie |> String.dropLeft (prefix |> String.length))
getNextUserSessionIdAndState : State -> ( String, UserSessionState )
getNextUserSessionIdAndState state =
let
posixTime =
state.posixTimeMilli // 1000
in
( state |> getNextUserSessionId
, { userId = Just ((state |> getLastUserId |> Maybe.withDefault 0) + 1)
, beginPosixTime = posixTime
, lastUsePosixTime = posixTime
, clientAddress = Nothing
}
)
getLastUserId : State -> Maybe Int
getLastUserId state =
[ state.usersProfiles |> Dict.keys
, state.usersSessions |> Dict.values |> List.filterMap .userId
]
|> List.concat
|> List.maximum
getNextUserSessionId : State -> String
getNextUserSessionId state =
let
otherSessionsIds =
state.usersSessions |> Dict.keys
source =
(otherSessionsIds |> String.concat) ++ (state.posixTimeMilli |> String.fromInt)
in
source |> SHA1.fromString |> SHA1.toHex |> String.left 30
hasUserExhaustedRateLimitToAddMessage : State -> { userId : Int } -> Bool
hasUserExhaustedRateLimitToAddMessage state { userId } =
let
addedMessagesAges =
state.conversationHistory
|> List.filterMap
(\event ->
case event.origin of
Conversation.FromSystem ->
Nothing
Conversation.FromUser fromUser ->
if fromUser.userId /= userId then
Nothing
else
Just event.posixTimeMilli
)
|> List.map (\addedMessagePosixTimeMilli -> (state.posixTimeMilli - addedMessagePosixTimeMilli) // 1000)
numberOfMessagesWithinAge ageInSeconds =
addedMessagesAges
|> List.filter (\messageAge -> messageAge <= ageInSeconds)
|> List.length
in
userAddMessageRateLimits
|> List.any (\limit -> limit.numberOfMessages <= numberOfMessagesWithinAge limit.timespanInSeconds)
userAddMessageRateLimits : List { timespanInSeconds : Int, numberOfMessages : Int }
userAddMessageRateLimits =
[ { timespanInSeconds = 3, numberOfMessages = 2 }
, { timespanInSeconds = 10, numberOfMessages = 3 }
, { timespanInSeconds = 60, numberOfMessages = 8 }
, { timespanInSeconds = 60 * 10, numberOfMessages = 50 }
]
decodeBytesToString : Bytes.Bytes -> Maybe String
decodeBytesToString bytes =
bytes |> Bytes.Decode.decode (Bytes.Decode.string (bytes |> Bytes.width))
encodeStringToBytes : String -> Bytes.Bytes
encodeStringToBytes =
Bytes.Encode.string >> Bytes.Encode.encode
addCookieUserSessionId : String -> ElmFullstack.HttpResponse -> ElmFullstack.HttpResponse
addCookieUserSessionId userSessionId httpResponse =
let
cookieHeader =
{ name = "Set-Cookie", values = [ httpSessionIdCookieName ++ "=" ++ userSessionId ++ "; Path=/; Max-Age=3600" ] }
in
{ httpResponse | headersToAdd = cookieHeader :: httpResponse.headersToAdd }
httpSessionIdCookieName : String
httpSessionIdCookieName =
"sessionid"
initState : State
initState =
{ posixTimeMilli = 0
, conversationHistory = []
, usersProfiles = Dict.empty
, usersSessions = Dict.empty
, usersLastSeen = Dict.empty
, pendingHttpRequests = Dict.empty
}
| elm |
[
{
"context": "lt\n in Typescript\n\n Copyright (c) 2014 -- 2020 Christian Speckner and contributors\n\n Permission is hereby granted",
"end": 143,
"score": 0.9997597933,
"start": 125,
"tag": "NAME",
"value": "Christian Speckner"
}
] | src/frontend/elm/Stellerator/View.elm | 6502ts/6502.ts | 49 | {-
This file is part of 6502.ts, an emulator for 6502 based systems built
in Typescript
Copyright (c) 2014 -- 2020 Christian Speckner and contributors
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 Stellerator.View exposing (view)
import Browser
import Css as C
import Css.Global as G
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (..)
import Stellerator.Model exposing (..)
import Stellerator.View.About as About
import Stellerator.View.Cartridges as Cartridges
import Stellerator.View.Emulation as Emulation
import Stellerator.View.Help as Help
import Stellerator.View.Modal exposing (modal)
import Stellerator.View.Navigation as Navigation
import Stellerator.View.Settings as Settings
body : Model -> List (Html Msg)
body model =
let
media =
effectiveMedia model
navbar =
Maybe.map (Navigation.navbar model) media |> Maybe.withDefault []
configureSize =
let
fontSize =
C.px <| toFloat model.settings.uiSize / 100 * 18
in
G.global <| [ G.body [ C.fontSize fontSize, C.lineHeight fontSize ] ]
content =
case ( model.currentRoute, media ) of
( RouteCartridges, Just m ) ->
Cartridges.page model m
( RouteSettings, Just m ) ->
Settings.page model m
( RouteEmulation, Just _ ) ->
Emulation.page model
( RouteHelp, Just _ ) ->
Help.page model
( RouteAbout, Just _ ) ->
About.page model
_ ->
[]
in
configureSize
:: navbar
++ (Maybe.map (modal model.messagePending) media |> Maybe.withDefault [])
++ content
view : Model -> Browser.Document Msg
view model =
{ title = runningCartridge model |> Maybe.map (\x -> "Stellerator: " ++ x.name) |> Maybe.withDefault "Stellerator"
, body = body model |> List.map toUnstyled
}
| 46196 | {-
This file is part of 6502.ts, an emulator for 6502 based systems built
in Typescript
Copyright (c) 2014 -- 2020 <NAME> and contributors
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 Stellerator.View exposing (view)
import Browser
import Css as C
import Css.Global as G
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (..)
import Stellerator.Model exposing (..)
import Stellerator.View.About as About
import Stellerator.View.Cartridges as Cartridges
import Stellerator.View.Emulation as Emulation
import Stellerator.View.Help as Help
import Stellerator.View.Modal exposing (modal)
import Stellerator.View.Navigation as Navigation
import Stellerator.View.Settings as Settings
body : Model -> List (Html Msg)
body model =
let
media =
effectiveMedia model
navbar =
Maybe.map (Navigation.navbar model) media |> Maybe.withDefault []
configureSize =
let
fontSize =
C.px <| toFloat model.settings.uiSize / 100 * 18
in
G.global <| [ G.body [ C.fontSize fontSize, C.lineHeight fontSize ] ]
content =
case ( model.currentRoute, media ) of
( RouteCartridges, Just m ) ->
Cartridges.page model m
( RouteSettings, Just m ) ->
Settings.page model m
( RouteEmulation, Just _ ) ->
Emulation.page model
( RouteHelp, Just _ ) ->
Help.page model
( RouteAbout, Just _ ) ->
About.page model
_ ->
[]
in
configureSize
:: navbar
++ (Maybe.map (modal model.messagePending) media |> Maybe.withDefault [])
++ content
view : Model -> Browser.Document Msg
view model =
{ title = runningCartridge model |> Maybe.map (\x -> "Stellerator: " ++ x.name) |> Maybe.withDefault "Stellerator"
, body = body model |> List.map toUnstyled
}
| true | {-
This file is part of 6502.ts, an emulator for 6502 based systems built
in Typescript
Copyright (c) 2014 -- 2020 PI:NAME:<NAME>END_PI and contributors
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 Stellerator.View exposing (view)
import Browser
import Css as C
import Css.Global as G
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (..)
import Stellerator.Model exposing (..)
import Stellerator.View.About as About
import Stellerator.View.Cartridges as Cartridges
import Stellerator.View.Emulation as Emulation
import Stellerator.View.Help as Help
import Stellerator.View.Modal exposing (modal)
import Stellerator.View.Navigation as Navigation
import Stellerator.View.Settings as Settings
body : Model -> List (Html Msg)
body model =
let
media =
effectiveMedia model
navbar =
Maybe.map (Navigation.navbar model) media |> Maybe.withDefault []
configureSize =
let
fontSize =
C.px <| toFloat model.settings.uiSize / 100 * 18
in
G.global <| [ G.body [ C.fontSize fontSize, C.lineHeight fontSize ] ]
content =
case ( model.currentRoute, media ) of
( RouteCartridges, Just m ) ->
Cartridges.page model m
( RouteSettings, Just m ) ->
Settings.page model m
( RouteEmulation, Just _ ) ->
Emulation.page model
( RouteHelp, Just _ ) ->
Help.page model
( RouteAbout, Just _ ) ->
About.page model
_ ->
[]
in
configureSize
:: navbar
++ (Maybe.map (modal model.messagePending) media |> Maybe.withDefault [])
++ content
view : Model -> Browser.Document Msg
view model =
{ title = runningCartridge model |> Maybe.map (\x -> "Stellerator: " ++ x.name) |> Maybe.withDefault "Stellerator"
, body = body model |> List.map toUnstyled
}
| elm |
[
{
"context": "Student String Num\n\nstudentsGrades = [\n Student \"Alice\" 64.7,\n Student \"Bob\" 78.5,\n Student \"Eve\" 57.9",
"end": 70,
"score": 0.9998695254,
"start": 65,
"tag": "NAME",
"value": "Alice"
},
{
"context": "entsGrades = [\n Student \"Alice\" 64.7,\n Student \"Bob\" 78.5,\n Student \"Eve\" 57.9,\n Student \"Seya\" 100",
"end": 92,
"score": 0.9998561144,
"start": 89,
"tag": "NAME",
"value": "Bob"
},
{
"context": "nt \"Alice\" 64.7,\n Student \"Bob\" 78.5,\n Student \"Eve\" 57.9,\n Student \"Seya\" 100,\n --http://listofran",
"end": 114,
"score": 0.999787569,
"start": 111,
"tag": "NAME",
"value": "Eve"
},
{
"context": "dent \"Bob\" 78.5,\n Student \"Eve\" 57.9,\n Student \"Seya\" 100,\n --http://listofrandomnames.com,\n Student",
"end": 137,
"score": 0.9997904301,
"start": 133,
"tag": "NAME",
"value": "Seya"
},
{
"context": "100,\n --http://listofrandomnames.com,\n Student \"Madelene\" 88.3,\n Student \"Mack\" 32.8,\n Student \"Clarita\"",
"end": 197,
"score": 0.9998202324,
"start": 189,
"tag": "NAME",
"value": "Madelene"
},
{
"context": "mnames.com,\n Student \"Madelene\" 88.3,\n Student \"Mack\" 32.8,\n Student \"Clarita\" 90.5,\n Student \"Ulrik",
"end": 220,
"score": 0.9997942448,
"start": 216,
"tag": "NAME",
"value": "Mack"
},
{
"context": "Madelene\" 88.3,\n Student \"Mack\" 32.8,\n Student \"Clarita\" 90.5,\n Student \"Ulrike\" 98.5,\n Student \"Ferdin",
"end": 246,
"score": 0.9997748733,
"start": 239,
"tag": "NAME",
"value": "Clarita"
},
{
"context": "\"Mack\" 32.8,\n Student \"Clarita\" 90.5,\n Student \"Ulrike\" 98.5,\n Student \"Ferdinand\" 74.4,\n Student \"Tam",
"end": 271,
"score": 0.9997751713,
"start": 265,
"tag": "NAME",
"value": "Ulrike"
},
{
"context": "larita\" 90.5,\n Student \"Ulrike\" 98.5,\n Student \"Ferdinand\" 74.4,\n Student \"Tamara\" 93.5,\n Student \"Kellee",
"end": 299,
"score": 0.9997723103,
"start": 290,
"tag": "NAME",
"value": "Ferdinand"
},
{
"context": "ike\" 98.5,\n Student \"Ferdinand\" 74.4,\n Student \"Tamara\" 93.5,\n Student \"Kellee\" 82.9,\n Student \"Leanne",
"end": 324,
"score": 0.9997529387,
"start": 318,
"tag": "NAME",
"value": "Tamara"
},
{
"context": "dinand\" 74.4,\n Student \"Tamara\" 93.5,\n Student \"Kellee\" 82.9,\n Student \"Leanne\" 83.7,\n Student \"Nataly",
"end": 349,
"score": 0.9997899532,
"start": 343,
"tag": "NAME",
"value": "Kellee"
},
{
"context": "Tamara\" 93.5,\n Student \"Kellee\" 82.9,\n Student \"Leanne\" 83.7,\n Student \"Natalya\" 43.8,\n Student \"Leono",
"end": 374,
"score": 0.9997792244,
"start": 368,
"tag": "NAME",
"value": "Leanne"
},
{
"context": "Kellee\" 82.9,\n Student \"Leanne\" 83.7,\n Student \"Natalya\" 43.8,\n Student \"Leonore\" 84.5,\n Student \"Linet",
"end": 400,
"score": 0.9997742176,
"start": 393,
"tag": "NAME",
"value": "Natalya"
},
{
"context": "eanne\" 83.7,\n Student \"Natalya\" 43.8,\n Student \"Leonore\" 84.5,\n Student \"Linette\" 98.5,\n Student \"Salle",
"end": 426,
"score": 0.9997319579,
"start": 419,
"tag": "NAME",
"value": "Leonore"
},
{
"context": "talya\" 43.8,\n Student \"Leonore\" 84.5,\n Student \"Linette\" 98.5,\n Student \"Salley\" 88.4,\n Student \"Aleish",
"end": 452,
"score": 0.9997909069,
"start": 445,
"tag": "NAME",
"value": "Linette"
},
{
"context": "onore\" 84.5,\n Student \"Linette\" 98.5,\n Student \"Salley\" 88.4,\n Student \"Aleisha\" 88.6,\n Student \"Sabin",
"end": 477,
"score": 0.9998421669,
"start": 471,
"tag": "NAME",
"value": "Salley"
},
{
"context": "inette\" 98.5,\n Student \"Salley\" 88.4,\n Student \"Aleisha\" 88.6,\n Student \"Sabine\" 92.2,\n Student \"Ozella",
"end": 503,
"score": 0.9997799397,
"start": 496,
"tag": "NAME",
"value": "Aleisha"
},
{
"context": "alley\" 88.4,\n Student \"Aleisha\" 88.6,\n Student \"Sabine\" 92.2,\n Student \"Ozella\" 60.9,\n Student \"Misti\"",
"end": 528,
"score": 0.9997673035,
"start": 522,
"tag": "NAME",
"value": "Sabine"
},
{
"context": "leisha\" 88.6,\n Student \"Sabine\" 92.2,\n Student \"Ozella\" 60.9,\n Student \"Misti\" 86.7,\n Student \"Jenny\" ",
"end": 553,
"score": 0.9997707009,
"start": 547,
"tag": "NAME",
"value": "Ozella"
},
{
"context": "Sabine\" 92.2,\n Student \"Ozella\" 60.9,\n Student \"Misti\" 86.7,\n Student \"Jenny\" 83.3,\n Student \"Nubia\" ",
"end": 577,
"score": 0.9997027516,
"start": 572,
"tag": "NAME",
"value": "Misti"
},
{
"context": "\"Ozella\" 60.9,\n Student \"Misti\" 86.7,\n Student \"Jenny\" 83.3,\n Student \"Nubia\" 92.3,\n Student \"Tennill",
"end": 601,
"score": 0.9996738434,
"start": 596,
"tag": "NAME",
"value": "Jenny"
},
{
"context": " \"Misti\" 86.7,\n Student \"Jenny\" 83.3,\n Student \"Nubia\" 92.3,\n Student \"Tennillee\" 95.1,\n Student \"Mar",
"end": 625,
"score": 0.9997112155,
"start": 620,
"tag": "NAME",
"value": "Nubia"
},
{
"context": " \"Jenny\" 83.3,\n Student \"Nubia\" 92.3,\n Student \"Tennillee\" 95.1,\n Student \"Margaret\" 81.9,\n Student \"Loid",
"end": 653,
"score": 0.9997913837,
"start": 644,
"tag": "NAME",
"value": "Tennillee"
},
{
"context": "bia\" 92.3,\n Student \"Tennillee\" 95.1,\n Student \"Margaret\" 81.9,\n Student \"Loida\" 82.8,\n Student \"Cassand",
"end": 680,
"score": 0.9997179508,
"start": 672,
"tag": "NAME",
"value": "Margaret"
},
{
"context": "llee\" 95.1,\n Student \"Margaret\" 81.9,\n Student \"Loida\" 82.8,\n Student \"Cassandra\" 65.3,\n Student \"Der",
"end": 704,
"score": 0.9997356534,
"start": 699,
"tag": "NAME",
"value": "Loida"
},
{
"context": "argaret\" 81.9,\n Student \"Loida\" 82.8,\n Student \"Cassandra\" 65.3,\n Student \"Derrick\" 66.4,\n Student \"Rudol",
"end": 732,
"score": 0.9996577501,
"start": 723,
"tag": "NAME",
"value": "Cassandra"
},
{
"context": "ida\" 82.8,\n Student \"Cassandra\" 65.3,\n Student \"Derrick\" 66.4,\n Student \"Rudolph\" 83.2,\n Student \"Rafae",
"end": 758,
"score": 0.9996897578,
"start": 751,
"tag": "NAME",
"value": "Derrick"
},
{
"context": "andra\" 65.3,\n Student \"Derrick\" 66.4,\n Student \"Rudolph\" 83.2,\n Student \"Rafael\" 86.6\n]\n\ngradeOf Student",
"end": 784,
"score": 0.9997394681,
"start": 777,
"tag": "NAME",
"value": "Rudolph"
},
{
"context": "rrick\" 66.4,\n Student \"Rudolph\" 83.2,\n Student \"Rafael\" 86.6\n]\n\ngradeOf Student _ avg = avg\n\ntype CutOff",
"end": 809,
"score": 0.9997590184,
"start": 803,
"tag": "NAME",
"value": "Rafael"
},
{
"context": "i % 2 == 0 then \"#dedede\" else \"white\")>\n <td>@name</td>\n <td title=(stds|>List.map(\\Student nam",
"end": 6188,
"score": 0.6315816641,
"start": 6183,
"tag": "USERNAME",
"value": "@name"
}
] | examples/StudentGrades.elm | digitalsatori/sketch-n-sketch | 565 | type Student = Student String Num
studentsGrades = [
Student "Alice" 64.7,
Student "Bob" 78.5,
Student "Eve" 57.9,
Student "Seya" 100,
--http://listofrandomnames.com,
Student "Madelene" 88.3,
Student "Mack" 32.8,
Student "Clarita" 90.5,
Student "Ulrike" 98.5,
Student "Ferdinand" 74.4,
Student "Tamara" 93.5,
Student "Kellee" 82.9,
Student "Leanne" 83.7,
Student "Natalya" 43.8,
Student "Leonore" 84.5,
Student "Linette" 98.5,
Student "Salley" 88.4,
Student "Aleisha" 88.6,
Student "Sabine" 92.2,
Student "Ozella" 60.9,
Student "Misti" 86.7,
Student "Jenny" 83.3,
Student "Nubia" 92.3,
Student "Tennillee" 95.1,
Student "Margaret" 81.9,
Student "Loida" 82.8,
Student "Cassandra" 65.3,
Student "Derrick" 66.4,
Student "Rudolph" 83.2,
Student "Rafael" 86.6
]
gradeOf Student _ avg = avg
type CutOff = CutOff String Num
cutoffs = [
CutOff "A+" 96.8,
CutOff "A" 90,
CutOff "A-" 86,
CutOff "B+" 80.4,
CutOff "B" 76,
CutOff "B-" 68.5,
CutOff "C+" 61,
CutOff "C" 55.8,
CutOff "C-" 40.4,
CutOff "D" 29.5,
CutOff "E" 0]
updateDecimal x = {
apply x = x
update {outputNew=xp} =
Ok (Inputs [round (xp * 10) / 10])
}.apply x
-- Step to freeze the grades but still allow changes in the names
weightedAverages = List.map (\Student name grade -> Student name (freeze grade)) studentsGrades
weightedAverages = sortBy (\(Student _ n1) (Student _ n2) -> n1 > n2) weightedAverages -- sort and shadow
assignLetter avg = let
foo cutoffs = case cutoffs of
[] -> error 'CRASH'
(CutOff letter cutoff) :: rest ->
if avg >= cutoff then letter else foo rest
in foo cutoffs
buckets = let
initBucket = List.map (\c -> (c, [])) cutoffs
addToBucket buckets letter std = case buckets of
(((CutOff bletter _) as c, v) as head)::tail ->
if bletter == letter then (c, v ++ [std])::tail
else head :: addToBucket tail letter std
[] -> error <| "Letter " + letter + " not found in buckets"
add sortedStudents buckets =
case sortedStudents of
[] -> buckets
((Student studName avg) as std) :: remaining_students ->
addToBucket buckets (assignLetter avg) std |>
add remaining_students
in
add weightedAverages initBucket
numStudents = List.length weightedAverages
barChart x y w h = let
barWidth = w / numStudents
bars = List.indexedMap (\i (Student name avg) -> let
xi = x + (i * barWidth)
hi = h * (freeze 0.01! * avg)
yi = y + h - hi
in line 'blue' 2 xi yi (xi + barWidth) yi)
<| List.reverse weightedAverages
separators = cutoffs |> List.concatMap
(\(CutOff abc cutoff) -> let
y = (freeze y + freeze h * freeze 0.01! * (freeze 100! - updateDecimal cutoff))
in
[line 'black' (Update.softFreeze 2) (Update.softFreeze x) y (Update.softFreeze <| x + w) y,
<text x=20 y=y style="fill:black;font-family:monospace;font-size:12pt">@abc</text>,
<text x=w+60 y=y style="fill:black;font-family:monospace;font-size:12pt">@abc</text>
])
background = rectWithBorder 'gray' 5 'lightgray' x y w h
in List.concatMap identity [
[background],
bars,
separators
]
checkAdjacentBuckets =
let epsilon = 0.72{0-1.9} in
<span>Ok</span> :: (
zip buckets (tl buckets) |>
List.map
(\((s1, l1), (s2, l2)) ->
if List.isEmpty l1 || List.isEmpty l2 then <span>Ok</span> else
let
Student n2 a2 = hd l2
Student n1 a1 = last l1
in
if a2 + epsilon < a1 then <span>Ok</span>
else <span>@n2 (grade @a2) and @n1 (grade @a1) are too close</span>
))
width = 550
height = 389
chart = barChart 50 0 width height
-- Lense to change the number of students in a category by modifying the category's threshold.
changeStudents index = Update.lens2 {
apply (cutoff, count) = count
update {input=(cutoff, prevCount), outputNew=newCount} =
if newCount > prevCount then let -- Lower the bar, we want more students
(CutOff _ nextCutoff, stds2) = nth buckets (index + 1)
(upgrading, staying) = List.split (newCount - prevCount) stds2
worstUpgradingAvg = gradeOf <| last upgrading
bestStayingAvg = case List.head staying of
Just std -> gradeOf std
Nothing -> nextCutoff + 0.1
newCutoff = (worstUpgradingAvg + bestStayingAvg) / 2
in Ok (Inputs [(newCutoff, prevCount)])
else let -- Raise the bar, we want less students
currentStudents = nth buckets index |> Tuple.second
(staying, declassed) = List.split (List.length currentStudents - (prevCount - newCount)) currentStudents
Student _ bestDeclassedAvg = hd declassed
in if List.isEmpty staying then
Ok (Inputs [(bestDeclassedAvg + 0.1, prevCount)])
else let
Student _ worstStayingAvg = last staying
newCutoff = (worstStayingAvg + bestDeclassedAvg) / 2
in Ok (Inputs [(newCutoff, prevCount)])
}
gradingData = Update.applyLens {
apply grades = List.map (\(Student name avg) -> name + "\t" + toString avg) grades |>
String.join "\n"
update {outputNew} = -- We need to parse outputNew.
let newStudents = Regex.split "\n" outputNew |> List.map (\line ->
case Regex.extract """([^\t,:]+)[\t,:]+([\d\.]+)""" line of
Just [name, avg] -> Student name (String.toFloat avg)
Nothing -> error <| "I do not recognize this as a name / grade: " + line
) in Ok (Inputs [newStudents])
} studentsGrades
<div style="margin:10px" contenteditable="true">
<h1>Fair Final Grades</h1>
<h2>Input averages</h2>
@Html.forceRefresh<|<textarea
onkeyup="if(this.getAttribute('v') != this.value) this.setAttribute('v', this.value)"
v=gradingData style="margin:0px;height:84px;width:217px">@gradingData</textarea>
<h2>Grade diagram</h2>
<svg width=(toString (width + 100)) height=toString(height)>@chart</svg>
<h2>Grade by category</h2>
<table>
<tr><th>Grade</th><th>Students</th><th>Groupped</th><th>Threshold</th><th>Status</th></tr>
@(List.indexedMap (\i ((CutOff name t, stds), feedback) ->
<tr style="background:"+(if i % 2 == 0 then "#dedede" else "white")>
<td>@name</td>
<td title=(stds|>List.map(\Student name grade ->"""@name:@grade""")|>String.join",")>
@changeStudents(i)(t)<|List.length(stds)</td>
@(if i % 3 == 0 then
<td rowspan="3">@(-- for above:
buckets |> List.drop i |> List.take 3 |>
List.map (\(n, stds) -> List.length stds) |> List.sum)
</td>
else [])
<td>@t</td>
<td>@feedback</td>
</tr>
) (zip buckets checkAdjacentBuckets))
</table>
</div> | 50694 | type Student = Student String Num
studentsGrades = [
Student "<NAME>" 64.7,
Student "<NAME>" 78.5,
Student "<NAME>" 57.9,
Student "<NAME>" 100,
--http://listofrandomnames.com,
Student "<NAME>" 88.3,
Student "<NAME>" 32.8,
Student "<NAME>" 90.5,
Student "<NAME>" 98.5,
Student "<NAME>" 74.4,
Student "<NAME>" 93.5,
Student "<NAME>" 82.9,
Student "<NAME>" 83.7,
Student "<NAME>" 43.8,
Student "<NAME>" 84.5,
Student "<NAME>" 98.5,
Student "<NAME>" 88.4,
Student "<NAME>" 88.6,
Student "<NAME>" 92.2,
Student "<NAME>" 60.9,
Student "<NAME>" 86.7,
Student "<NAME>" 83.3,
Student "<NAME>" 92.3,
Student "<NAME>" 95.1,
Student "<NAME>" 81.9,
Student "<NAME>" 82.8,
Student "<NAME>" 65.3,
Student "<NAME>" 66.4,
Student "<NAME>" 83.2,
Student "<NAME>" 86.6
]
gradeOf Student _ avg = avg
type CutOff = CutOff String Num
cutoffs = [
CutOff "A+" 96.8,
CutOff "A" 90,
CutOff "A-" 86,
CutOff "B+" 80.4,
CutOff "B" 76,
CutOff "B-" 68.5,
CutOff "C+" 61,
CutOff "C" 55.8,
CutOff "C-" 40.4,
CutOff "D" 29.5,
CutOff "E" 0]
updateDecimal x = {
apply x = x
update {outputNew=xp} =
Ok (Inputs [round (xp * 10) / 10])
}.apply x
-- Step to freeze the grades but still allow changes in the names
weightedAverages = List.map (\Student name grade -> Student name (freeze grade)) studentsGrades
weightedAverages = sortBy (\(Student _ n1) (Student _ n2) -> n1 > n2) weightedAverages -- sort and shadow
assignLetter avg = let
foo cutoffs = case cutoffs of
[] -> error 'CRASH'
(CutOff letter cutoff) :: rest ->
if avg >= cutoff then letter else foo rest
in foo cutoffs
buckets = let
initBucket = List.map (\c -> (c, [])) cutoffs
addToBucket buckets letter std = case buckets of
(((CutOff bletter _) as c, v) as head)::tail ->
if bletter == letter then (c, v ++ [std])::tail
else head :: addToBucket tail letter std
[] -> error <| "Letter " + letter + " not found in buckets"
add sortedStudents buckets =
case sortedStudents of
[] -> buckets
((Student studName avg) as std) :: remaining_students ->
addToBucket buckets (assignLetter avg) std |>
add remaining_students
in
add weightedAverages initBucket
numStudents = List.length weightedAverages
barChart x y w h = let
barWidth = w / numStudents
bars = List.indexedMap (\i (Student name avg) -> let
xi = x + (i * barWidth)
hi = h * (freeze 0.01! * avg)
yi = y + h - hi
in line 'blue' 2 xi yi (xi + barWidth) yi)
<| List.reverse weightedAverages
separators = cutoffs |> List.concatMap
(\(CutOff abc cutoff) -> let
y = (freeze y + freeze h * freeze 0.01! * (freeze 100! - updateDecimal cutoff))
in
[line 'black' (Update.softFreeze 2) (Update.softFreeze x) y (Update.softFreeze <| x + w) y,
<text x=20 y=y style="fill:black;font-family:monospace;font-size:12pt">@abc</text>,
<text x=w+60 y=y style="fill:black;font-family:monospace;font-size:12pt">@abc</text>
])
background = rectWithBorder 'gray' 5 'lightgray' x y w h
in List.concatMap identity [
[background],
bars,
separators
]
checkAdjacentBuckets =
let epsilon = 0.72{0-1.9} in
<span>Ok</span> :: (
zip buckets (tl buckets) |>
List.map
(\((s1, l1), (s2, l2)) ->
if List.isEmpty l1 || List.isEmpty l2 then <span>Ok</span> else
let
Student n2 a2 = hd l2
Student n1 a1 = last l1
in
if a2 + epsilon < a1 then <span>Ok</span>
else <span>@n2 (grade @a2) and @n1 (grade @a1) are too close</span>
))
width = 550
height = 389
chart = barChart 50 0 width height
-- Lense to change the number of students in a category by modifying the category's threshold.
changeStudents index = Update.lens2 {
apply (cutoff, count) = count
update {input=(cutoff, prevCount), outputNew=newCount} =
if newCount > prevCount then let -- Lower the bar, we want more students
(CutOff _ nextCutoff, stds2) = nth buckets (index + 1)
(upgrading, staying) = List.split (newCount - prevCount) stds2
worstUpgradingAvg = gradeOf <| last upgrading
bestStayingAvg = case List.head staying of
Just std -> gradeOf std
Nothing -> nextCutoff + 0.1
newCutoff = (worstUpgradingAvg + bestStayingAvg) / 2
in Ok (Inputs [(newCutoff, prevCount)])
else let -- Raise the bar, we want less students
currentStudents = nth buckets index |> Tuple.second
(staying, declassed) = List.split (List.length currentStudents - (prevCount - newCount)) currentStudents
Student _ bestDeclassedAvg = hd declassed
in if List.isEmpty staying then
Ok (Inputs [(bestDeclassedAvg + 0.1, prevCount)])
else let
Student _ worstStayingAvg = last staying
newCutoff = (worstStayingAvg + bestDeclassedAvg) / 2
in Ok (Inputs [(newCutoff, prevCount)])
}
gradingData = Update.applyLens {
apply grades = List.map (\(Student name avg) -> name + "\t" + toString avg) grades |>
String.join "\n"
update {outputNew} = -- We need to parse outputNew.
let newStudents = Regex.split "\n" outputNew |> List.map (\line ->
case Regex.extract """([^\t,:]+)[\t,:]+([\d\.]+)""" line of
Just [name, avg] -> Student name (String.toFloat avg)
Nothing -> error <| "I do not recognize this as a name / grade: " + line
) in Ok (Inputs [newStudents])
} studentsGrades
<div style="margin:10px" contenteditable="true">
<h1>Fair Final Grades</h1>
<h2>Input averages</h2>
@Html.forceRefresh<|<textarea
onkeyup="if(this.getAttribute('v') != this.value) this.setAttribute('v', this.value)"
v=gradingData style="margin:0px;height:84px;width:217px">@gradingData</textarea>
<h2>Grade diagram</h2>
<svg width=(toString (width + 100)) height=toString(height)>@chart</svg>
<h2>Grade by category</h2>
<table>
<tr><th>Grade</th><th>Students</th><th>Groupped</th><th>Threshold</th><th>Status</th></tr>
@(List.indexedMap (\i ((CutOff name t, stds), feedback) ->
<tr style="background:"+(if i % 2 == 0 then "#dedede" else "white")>
<td>@name</td>
<td title=(stds|>List.map(\Student name grade ->"""@name:@grade""")|>String.join",")>
@changeStudents(i)(t)<|List.length(stds)</td>
@(if i % 3 == 0 then
<td rowspan="3">@(-- for above:
buckets |> List.drop i |> List.take 3 |>
List.map (\(n, stds) -> List.length stds) |> List.sum)
</td>
else [])
<td>@t</td>
<td>@feedback</td>
</tr>
) (zip buckets checkAdjacentBuckets))
</table>
</div> | true | type Student = Student String Num
studentsGrades = [
Student "PI:NAME:<NAME>END_PI" 64.7,
Student "PI:NAME:<NAME>END_PI" 78.5,
Student "PI:NAME:<NAME>END_PI" 57.9,
Student "PI:NAME:<NAME>END_PI" 100,
--http://listofrandomnames.com,
Student "PI:NAME:<NAME>END_PI" 88.3,
Student "PI:NAME:<NAME>END_PI" 32.8,
Student "PI:NAME:<NAME>END_PI" 90.5,
Student "PI:NAME:<NAME>END_PI" 98.5,
Student "PI:NAME:<NAME>END_PI" 74.4,
Student "PI:NAME:<NAME>END_PI" 93.5,
Student "PI:NAME:<NAME>END_PI" 82.9,
Student "PI:NAME:<NAME>END_PI" 83.7,
Student "PI:NAME:<NAME>END_PI" 43.8,
Student "PI:NAME:<NAME>END_PI" 84.5,
Student "PI:NAME:<NAME>END_PI" 98.5,
Student "PI:NAME:<NAME>END_PI" 88.4,
Student "PI:NAME:<NAME>END_PI" 88.6,
Student "PI:NAME:<NAME>END_PI" 92.2,
Student "PI:NAME:<NAME>END_PI" 60.9,
Student "PI:NAME:<NAME>END_PI" 86.7,
Student "PI:NAME:<NAME>END_PI" 83.3,
Student "PI:NAME:<NAME>END_PI" 92.3,
Student "PI:NAME:<NAME>END_PI" 95.1,
Student "PI:NAME:<NAME>END_PI" 81.9,
Student "PI:NAME:<NAME>END_PI" 82.8,
Student "PI:NAME:<NAME>END_PI" 65.3,
Student "PI:NAME:<NAME>END_PI" 66.4,
Student "PI:NAME:<NAME>END_PI" 83.2,
Student "PI:NAME:<NAME>END_PI" 86.6
]
gradeOf Student _ avg = avg
type CutOff = CutOff String Num
cutoffs = [
CutOff "A+" 96.8,
CutOff "A" 90,
CutOff "A-" 86,
CutOff "B+" 80.4,
CutOff "B" 76,
CutOff "B-" 68.5,
CutOff "C+" 61,
CutOff "C" 55.8,
CutOff "C-" 40.4,
CutOff "D" 29.5,
CutOff "E" 0]
updateDecimal x = {
apply x = x
update {outputNew=xp} =
Ok (Inputs [round (xp * 10) / 10])
}.apply x
-- Step to freeze the grades but still allow changes in the names
weightedAverages = List.map (\Student name grade -> Student name (freeze grade)) studentsGrades
weightedAverages = sortBy (\(Student _ n1) (Student _ n2) -> n1 > n2) weightedAverages -- sort and shadow
assignLetter avg = let
foo cutoffs = case cutoffs of
[] -> error 'CRASH'
(CutOff letter cutoff) :: rest ->
if avg >= cutoff then letter else foo rest
in foo cutoffs
buckets = let
initBucket = List.map (\c -> (c, [])) cutoffs
addToBucket buckets letter std = case buckets of
(((CutOff bletter _) as c, v) as head)::tail ->
if bletter == letter then (c, v ++ [std])::tail
else head :: addToBucket tail letter std
[] -> error <| "Letter " + letter + " not found in buckets"
add sortedStudents buckets =
case sortedStudents of
[] -> buckets
((Student studName avg) as std) :: remaining_students ->
addToBucket buckets (assignLetter avg) std |>
add remaining_students
in
add weightedAverages initBucket
numStudents = List.length weightedAverages
barChart x y w h = let
barWidth = w / numStudents
bars = List.indexedMap (\i (Student name avg) -> let
xi = x + (i * barWidth)
hi = h * (freeze 0.01! * avg)
yi = y + h - hi
in line 'blue' 2 xi yi (xi + barWidth) yi)
<| List.reverse weightedAverages
separators = cutoffs |> List.concatMap
(\(CutOff abc cutoff) -> let
y = (freeze y + freeze h * freeze 0.01! * (freeze 100! - updateDecimal cutoff))
in
[line 'black' (Update.softFreeze 2) (Update.softFreeze x) y (Update.softFreeze <| x + w) y,
<text x=20 y=y style="fill:black;font-family:monospace;font-size:12pt">@abc</text>,
<text x=w+60 y=y style="fill:black;font-family:monospace;font-size:12pt">@abc</text>
])
background = rectWithBorder 'gray' 5 'lightgray' x y w h
in List.concatMap identity [
[background],
bars,
separators
]
checkAdjacentBuckets =
let epsilon = 0.72{0-1.9} in
<span>Ok</span> :: (
zip buckets (tl buckets) |>
List.map
(\((s1, l1), (s2, l2)) ->
if List.isEmpty l1 || List.isEmpty l2 then <span>Ok</span> else
let
Student n2 a2 = hd l2
Student n1 a1 = last l1
in
if a2 + epsilon < a1 then <span>Ok</span>
else <span>@n2 (grade @a2) and @n1 (grade @a1) are too close</span>
))
width = 550
height = 389
chart = barChart 50 0 width height
-- Lense to change the number of students in a category by modifying the category's threshold.
changeStudents index = Update.lens2 {
apply (cutoff, count) = count
update {input=(cutoff, prevCount), outputNew=newCount} =
if newCount > prevCount then let -- Lower the bar, we want more students
(CutOff _ nextCutoff, stds2) = nth buckets (index + 1)
(upgrading, staying) = List.split (newCount - prevCount) stds2
worstUpgradingAvg = gradeOf <| last upgrading
bestStayingAvg = case List.head staying of
Just std -> gradeOf std
Nothing -> nextCutoff + 0.1
newCutoff = (worstUpgradingAvg + bestStayingAvg) / 2
in Ok (Inputs [(newCutoff, prevCount)])
else let -- Raise the bar, we want less students
currentStudents = nth buckets index |> Tuple.second
(staying, declassed) = List.split (List.length currentStudents - (prevCount - newCount)) currentStudents
Student _ bestDeclassedAvg = hd declassed
in if List.isEmpty staying then
Ok (Inputs [(bestDeclassedAvg + 0.1, prevCount)])
else let
Student _ worstStayingAvg = last staying
newCutoff = (worstStayingAvg + bestDeclassedAvg) / 2
in Ok (Inputs [(newCutoff, prevCount)])
}
gradingData = Update.applyLens {
apply grades = List.map (\(Student name avg) -> name + "\t" + toString avg) grades |>
String.join "\n"
update {outputNew} = -- We need to parse outputNew.
let newStudents = Regex.split "\n" outputNew |> List.map (\line ->
case Regex.extract """([^\t,:]+)[\t,:]+([\d\.]+)""" line of
Just [name, avg] -> Student name (String.toFloat avg)
Nothing -> error <| "I do not recognize this as a name / grade: " + line
) in Ok (Inputs [newStudents])
} studentsGrades
<div style="margin:10px" contenteditable="true">
<h1>Fair Final Grades</h1>
<h2>Input averages</h2>
@Html.forceRefresh<|<textarea
onkeyup="if(this.getAttribute('v') != this.value) this.setAttribute('v', this.value)"
v=gradingData style="margin:0px;height:84px;width:217px">@gradingData</textarea>
<h2>Grade diagram</h2>
<svg width=(toString (width + 100)) height=toString(height)>@chart</svg>
<h2>Grade by category</h2>
<table>
<tr><th>Grade</th><th>Students</th><th>Groupped</th><th>Threshold</th><th>Status</th></tr>
@(List.indexedMap (\i ((CutOff name t, stds), feedback) ->
<tr style="background:"+(if i % 2 == 0 then "#dedede" else "white")>
<td>@name</td>
<td title=(stds|>List.map(\Student name grade ->"""@name:@grade""")|>String.join",")>
@changeStudents(i)(t)<|List.length(stds)</td>
@(if i % 3 == 0 then
<td rowspan="3">@(-- for above:
buckets |> List.drop i |> List.take 3 |>
List.map (\(n, stds) -> List.length stds) |> List.sum)
</td>
else [])
<td>@t</td>
<td>@feedback</td>
</tr>
) (zip buckets checkAdjacentBuckets))
</table>
</div> | elm |
[
{
"context": "sword password ->\n { model | password = password }\n\n PasswordAgain password ->\n ",
"end": 856,
"score": 0.9895142913,
"start": 848,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " password ->\n { model | passwordAgain = password }\n\n Age age ->\n { model | age =",
"end": 940,
"score": 0.6411162615,
"start": 932,
"tag": "PASSWORD",
"value": "password"
}
] | examples/03-form.elm | mkohler/elm-architecture-tutorial | 0 | module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
import Char
import String
import List
main =
Html.beginnerProgram
{ model = model
, view = view
, update = update
}
-- MODEL
type alias Model =
{ name : String
, password : String
, passwordAgain : String
, age : String
, lefthanded : Bool
, error : String
}
model : Model
model =
Model "" "" "" "" False ""
-- UPDATE
type Msg
= Name String
| Password String
| PasswordAgain String
| Age String
| Lefthanded
| Submit
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 }
Age age ->
{ model | age = age }
Submit ->
{ model | error = validate model }
Lefthanded ->
{ model | lefthanded = not model.lefthanded }
-- VIEW
fieldStyle =
style [ ( "display", "block" ), ( "margin", "10px" ) ]
view : Model -> Html Msg
view model =
div []
[ makeField [ type_ "text", placeholder "Name", onInput Name ] []
, makeField [ type_ "password", placeholder "Password", onInput Password ] []
, makeField [ type_ "password", placeholder "Re-enter Password", onInput PasswordAgain ] []
, makeField [ type_ "text", placeholder "Age", onInput Age ] []
, makeField [ type_ "checkbox", onClick Lefthanded ] []
, button [ onClick Submit, fieldStyle ] [ text "Submit" ]
, div [ fieldStyle ] [ text (model.error) ]
]
makeField : List (Html.Attribute msg) -> List (Html.Html msg) -> Html.Html msg
makeField attrs elems =
let
attrs_with_style =
attrs ++ [ fieldStyle ]
in
input attrs_with_style elems
validate : Model -> String
validate model =
let
age_okay : Bool
age_okay =
case String.toFloat model.age of
Err msg ->
False
Ok _ ->
True
message =
if String.length model.password <= 8 then
"Password needs to be longer than 8 characters."
else if not (String.any Char.isUpper model.password) then
"Password needs to include an upper-case character."
else if model.password /= model.passwordAgain then
"Passwords do not match!"
else if not age_okay then
"Age must be a number."
else if not model.lefthanded then
"Checkbox must be checked."
else
"OK"
in
message
| 22786 | module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
import Char
import String
import List
main =
Html.beginnerProgram
{ model = model
, view = view
, update = update
}
-- MODEL
type alias Model =
{ name : String
, password : String
, passwordAgain : String
, age : String
, lefthanded : Bool
, error : String
}
model : Model
model =
Model "" "" "" "" False ""
-- UPDATE
type Msg
= Name String
| Password String
| PasswordAgain String
| Age String
| Lefthanded
| Submit
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> }
Age age ->
{ model | age = age }
Submit ->
{ model | error = validate model }
Lefthanded ->
{ model | lefthanded = not model.lefthanded }
-- VIEW
fieldStyle =
style [ ( "display", "block" ), ( "margin", "10px" ) ]
view : Model -> Html Msg
view model =
div []
[ makeField [ type_ "text", placeholder "Name", onInput Name ] []
, makeField [ type_ "password", placeholder "Password", onInput Password ] []
, makeField [ type_ "password", placeholder "Re-enter Password", onInput PasswordAgain ] []
, makeField [ type_ "text", placeholder "Age", onInput Age ] []
, makeField [ type_ "checkbox", onClick Lefthanded ] []
, button [ onClick Submit, fieldStyle ] [ text "Submit" ]
, div [ fieldStyle ] [ text (model.error) ]
]
makeField : List (Html.Attribute msg) -> List (Html.Html msg) -> Html.Html msg
makeField attrs elems =
let
attrs_with_style =
attrs ++ [ fieldStyle ]
in
input attrs_with_style elems
validate : Model -> String
validate model =
let
age_okay : Bool
age_okay =
case String.toFloat model.age of
Err msg ->
False
Ok _ ->
True
message =
if String.length model.password <= 8 then
"Password needs to be longer than 8 characters."
else if not (String.any Char.isUpper model.password) then
"Password needs to include an upper-case character."
else if model.password /= model.passwordAgain then
"Passwords do not match!"
else if not age_okay then
"Age must be a number."
else if not model.lefthanded then
"Checkbox must be checked."
else
"OK"
in
message
| true | module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
import Char
import String
import List
main =
Html.beginnerProgram
{ model = model
, view = view
, update = update
}
-- MODEL
type alias Model =
{ name : String
, password : String
, passwordAgain : String
, age : String
, lefthanded : Bool
, error : String
}
model : Model
model =
Model "" "" "" "" False ""
-- UPDATE
type Msg
= Name String
| Password String
| PasswordAgain String
| Age String
| Lefthanded
| Submit
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 = PI:PASSWORD:<PASSWORD>END_PI }
Age age ->
{ model | age = age }
Submit ->
{ model | error = validate model }
Lefthanded ->
{ model | lefthanded = not model.lefthanded }
-- VIEW
fieldStyle =
style [ ( "display", "block" ), ( "margin", "10px" ) ]
view : Model -> Html Msg
view model =
div []
[ makeField [ type_ "text", placeholder "Name", onInput Name ] []
, makeField [ type_ "password", placeholder "Password", onInput Password ] []
, makeField [ type_ "password", placeholder "Re-enter Password", onInput PasswordAgain ] []
, makeField [ type_ "text", placeholder "Age", onInput Age ] []
, makeField [ type_ "checkbox", onClick Lefthanded ] []
, button [ onClick Submit, fieldStyle ] [ text "Submit" ]
, div [ fieldStyle ] [ text (model.error) ]
]
makeField : List (Html.Attribute msg) -> List (Html.Html msg) -> Html.Html msg
makeField attrs elems =
let
attrs_with_style =
attrs ++ [ fieldStyle ]
in
input attrs_with_style elems
validate : Model -> String
validate model =
let
age_okay : Bool
age_okay =
case String.toFloat model.age of
Err msg ->
False
Ok _ ->
True
message =
if String.length model.password <= 8 then
"Password needs to be longer than 8 characters."
else if not (String.any Char.isUpper model.password) then
"Password needs to include an upper-case character."
else if model.password /= model.passwordAgain then
"Passwords do not match!"
else if not age_okay then
"Age must be a number."
else if not model.lefthanded then
"Checkbox must be checked."
else
"OK"
in
message
| elm |
[
{
"context": " \"id\": \"id-2387\",\n \"name\": \"bold\",\n \"type\": \"EC2\",\n \"state\":",
"end": 372,
"score": 0.9376195669,
"start": 368,
"tag": "NAME",
"value": "bold"
},
{
"context": " \"id\": \"id-9375\",\n \"name\": \"beautiful\",\n \"type\": \"ASG\",\n \"state\":",
"end": 602,
"score": 0.9286112785,
"start": 593,
"tag": "NAME",
"value": "beautiful"
},
{
"context": " \"id\": \"id-9375\",\n \"name\": \"creepy\",\n \"type\": \"RDS\",\n \"state\":",
"end": 830,
"score": 0.9824645519,
"start": 824,
"tag": "NAME",
"value": "creepy"
},
{
"context": " \"\"\"\n\n\ncreepy : Resource\ncreepy =\n { name = \"creepy\"\n , id = \"id-9375\"\n , tipe = \"RDS\"\n , st",
"end": 1341,
"score": 0.9500772357,
"start": 1335,
"tag": "NAME",
"value": "creepy"
},
{
"context": "\n\n\nbeautiful : Resource\nbeautiful =\n { name = \"beautiful\"\n , id = \"id-9375\"\n , tipe = \"ASG\"\n , st",
"end": 1498,
"score": 0.836420536,
"start": 1489,
"tag": "NAME",
"value": "beautiful"
},
{
"context": "alse\n }\n\n\nbold : Resource\nbold =\n { name = \"bold\"\n , id = \"id-2387\"\n , tipe = \"EC2\"\n , st",
"end": 1645,
"score": 0.8372817039,
"start": 1641,
"tag": "NAME",
"value": "bold"
}
] | frontend/tests/Tests.elm | kpanic9/scheduler | 0 | module Tests exposing (beautiful, beautifulJson, bold, boldJson, creepy, creepyJson, jsonList, jsonMessage, msg, one, several)
import Expect
import Json.Decode as D
import Main exposing (Resource, Status, msgDecoder, resourceDecoder)
import Test exposing (Test, test)
boldJson : String
boldJson =
"""
{
"id": "id-2387",
"name": "bold",
"type": "EC2",
"state": "running",
"isAvailable": true
}
"""
beautifulJson : String
beautifulJson =
"""
{
"id": "id-9375",
"name": "beautiful",
"type": "ASG",
"state": "0/2 instances",
"isAvailable": false
}
"""
creepyJson : String
creepyJson =
"""
{
"id": "id-9375",
"name": "creepy",
"type": "RDS",
"state": "available",
"isAvailable": true
}
"""
jsonList : String
jsonList =
"[" ++ boldJson ++ "," ++ beautifulJson ++ "," ++ creepyJson ++ "]"
jsonMessage : String
jsonMessage =
"""
{
"clock": "9:25pm UTC",
"canExtend": true,
"weekdayStartMessage": "Auto start disabled",
"resources": """ ++ jsonList ++ """
}
"""
creepy : Resource
creepy =
{ name = "creepy"
, id = "id-9375"
, tipe = "RDS"
, state = "available"
, isAvailable = True
}
beautiful : Resource
beautiful =
{ name = "beautiful"
, id = "id-9375"
, tipe = "ASG"
, state = "0/2 instances"
, isAvailable = False
}
bold : Resource
bold =
{ name = "bold"
, id = "id-2387"
, tipe = "EC2"
, state = "running"
, isAvailable = True
}
msg : Test
msg =
test "Decode full status message" <|
\_ ->
Expect.equal
(msgDecoder jsonMessage)
<|
Ok
{ clock = "9:25pm UTC"
, canExtend = True
, remaining = Nothing
, weekdayStartMessage = "Auto start disabled"
, resources = [ bold, beautiful, creepy ]
}
several : Test
several =
test "Decode list of namespaces from JSON" <|
\_ ->
Expect.equal
(D.decodeString (D.list resourceDecoder) jsonList)
(Ok [ bold, beautiful, creepy ])
one : Test
one =
test "Decode namespace from JSON" <|
\_ ->
Expect.equal
(D.decodeString resourceDecoder beautifulJson)
(Ok beautiful)
| 15634 | module Tests exposing (beautiful, beautifulJson, bold, boldJson, creepy, creepyJson, jsonList, jsonMessage, msg, one, several)
import Expect
import Json.Decode as D
import Main exposing (Resource, Status, msgDecoder, resourceDecoder)
import Test exposing (Test, test)
boldJson : String
boldJson =
"""
{
"id": "id-2387",
"name": "<NAME>",
"type": "EC2",
"state": "running",
"isAvailable": true
}
"""
beautifulJson : String
beautifulJson =
"""
{
"id": "id-9375",
"name": "<NAME>",
"type": "ASG",
"state": "0/2 instances",
"isAvailable": false
}
"""
creepyJson : String
creepyJson =
"""
{
"id": "id-9375",
"name": "<NAME>",
"type": "RDS",
"state": "available",
"isAvailable": true
}
"""
jsonList : String
jsonList =
"[" ++ boldJson ++ "," ++ beautifulJson ++ "," ++ creepyJson ++ "]"
jsonMessage : String
jsonMessage =
"""
{
"clock": "9:25pm UTC",
"canExtend": true,
"weekdayStartMessage": "Auto start disabled",
"resources": """ ++ jsonList ++ """
}
"""
creepy : Resource
creepy =
{ name = "<NAME>"
, id = "id-9375"
, tipe = "RDS"
, state = "available"
, isAvailable = True
}
beautiful : Resource
beautiful =
{ name = "<NAME>"
, id = "id-9375"
, tipe = "ASG"
, state = "0/2 instances"
, isAvailable = False
}
bold : Resource
bold =
{ name = "<NAME>"
, id = "id-2387"
, tipe = "EC2"
, state = "running"
, isAvailable = True
}
msg : Test
msg =
test "Decode full status message" <|
\_ ->
Expect.equal
(msgDecoder jsonMessage)
<|
Ok
{ clock = "9:25pm UTC"
, canExtend = True
, remaining = Nothing
, weekdayStartMessage = "Auto start disabled"
, resources = [ bold, beautiful, creepy ]
}
several : Test
several =
test "Decode list of namespaces from JSON" <|
\_ ->
Expect.equal
(D.decodeString (D.list resourceDecoder) jsonList)
(Ok [ bold, beautiful, creepy ])
one : Test
one =
test "Decode namespace from JSON" <|
\_ ->
Expect.equal
(D.decodeString resourceDecoder beautifulJson)
(Ok beautiful)
| true | module Tests exposing (beautiful, beautifulJson, bold, boldJson, creepy, creepyJson, jsonList, jsonMessage, msg, one, several)
import Expect
import Json.Decode as D
import Main exposing (Resource, Status, msgDecoder, resourceDecoder)
import Test exposing (Test, test)
boldJson : String
boldJson =
"""
{
"id": "id-2387",
"name": "PI:NAME:<NAME>END_PI",
"type": "EC2",
"state": "running",
"isAvailable": true
}
"""
beautifulJson : String
beautifulJson =
"""
{
"id": "id-9375",
"name": "PI:NAME:<NAME>END_PI",
"type": "ASG",
"state": "0/2 instances",
"isAvailable": false
}
"""
creepyJson : String
creepyJson =
"""
{
"id": "id-9375",
"name": "PI:NAME:<NAME>END_PI",
"type": "RDS",
"state": "available",
"isAvailable": true
}
"""
jsonList : String
jsonList =
"[" ++ boldJson ++ "," ++ beautifulJson ++ "," ++ creepyJson ++ "]"
jsonMessage : String
jsonMessage =
"""
{
"clock": "9:25pm UTC",
"canExtend": true,
"weekdayStartMessage": "Auto start disabled",
"resources": """ ++ jsonList ++ """
}
"""
creepy : Resource
creepy =
{ name = "PI:NAME:<NAME>END_PI"
, id = "id-9375"
, tipe = "RDS"
, state = "available"
, isAvailable = True
}
beautiful : Resource
beautiful =
{ name = "PI:NAME:<NAME>END_PI"
, id = "id-9375"
, tipe = "ASG"
, state = "0/2 instances"
, isAvailable = False
}
bold : Resource
bold =
{ name = "PI:NAME:<NAME>END_PI"
, id = "id-2387"
, tipe = "EC2"
, state = "running"
, isAvailable = True
}
msg : Test
msg =
test "Decode full status message" <|
\_ ->
Expect.equal
(msgDecoder jsonMessage)
<|
Ok
{ clock = "9:25pm UTC"
, canExtend = True
, remaining = Nothing
, weekdayStartMessage = "Auto start disabled"
, resources = [ bold, beautiful, creepy ]
}
several : Test
several =
test "Decode list of namespaces from JSON" <|
\_ ->
Expect.equal
(D.decodeString (D.list resourceDecoder) jsonList)
(Ok [ bold, beautiful, creepy ])
one : Test
one =
test "Decode namespace from JSON" <|
\_ ->
Expect.equal
(D.decodeString resourceDecoder beautifulJson)
(Ok beautiful)
| elm |
[
{
"context": "->\n 28\n\n\nallPeople =\n A.fromList [ \"Adam\", \"Ron\", \"Natalie\", \"Jordan\" ]\n\n\ninit : () -> ( M",
"end": 1006,
"score": 0.9998847842,
"start": 1002,
"tag": "NAME",
"value": "Adam"
},
{
"context": " 28\n\n\nallPeople =\n A.fromList [ \"Adam\", \"Ron\", \"Natalie\", \"Jordan\" ]\n\n\ninit : () -> ( Model, C",
"end": 1013,
"score": 0.9998390675,
"start": 1010,
"tag": "NAME",
"value": "Ron"
},
{
"context": "28\n\n\nallPeople =\n A.fromList [ \"Adam\", \"Ron\", \"Natalie\", \"Jordan\" ]\n\n\ninit : () -> ( Model, Cmd Msg )\nin",
"end": 1024,
"score": 0.9998462796,
"start": 1017,
"tag": "NAME",
"value": "Natalie"
},
{
"context": "ple =\n A.fromList [ \"Adam\", \"Ron\", \"Natalie\", \"Jordan\" ]\n\n\ninit : () -> ( Model, Cmd Msg )\ninit _ =\n ",
"end": 1034,
"score": 0.9998564124,
"start": 1028,
"tag": "NAME",
"value": "Jordan"
}
] | src/Main.elm | adamchalmers/chores | 0 | port module Main exposing (Frequency(..), Model, Msg(..), init, main, personFor, toJs, update, view)
import Array as A exposing (Array)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
import Http exposing (Error(..))
import Json.Decode as Decode
import List as L
import String exposing (startsWith, toLower)
import Task exposing (Task)
import Time exposing (millisToPosix, toDay, utc)
-- ---------------------------
-- PORTS
-- ---------------------------
port toJs : String -> Cmd msg
-- ---------------------------
-- MODEL
-- ---------------------------
type alias Model =
{ chores : List Chore
, day : Int
, filter : String
}
type alias Chore =
{ name : String
, freq : Frequency
}
type Frequency
= Weekly
| Monthly
daysPer : Frequency -> Int
daysPer f =
case f of
Weekly ->
7
Monthly ->
28
allPeople =
A.fromList [ "Adam", "Ron", "Natalie", "Jordan" ]
init : () -> ( Model, Cmd Msg )
init _ =
( { chores =
[ { name = "Vacuum stairs", freq = Weekly }
, { name = "Vacuum landing", freq = Weekly }
, { name = "Stove", freq = Weekly }
, { name = "Sink", freq = Weekly }
, { name = "Mop downstairs", freq = Weekly }
, { name = "Wipe down countertops", freq = Weekly }
, { name = "Wash glass table", freq = Weekly }
, { name = "Wash glass doors/front door window", freq = Weekly }
, { name = "Wash fridge shelves", freq = Monthly }
, { name = "Wipe fridge outside", freq = Monthly }
, { name = "Clean microwave inside/outside", freq = Monthly }
, { name = "Dusting/baseboards", freq = Monthly }
, { name = "Clutter check (put away if you know where it is, if you don’t know whose it is, just send a photo to the group)", freq = Monthly }
]
, day = 0
, filter = ""
}
, Task.perform UpdateDay whatDayOfMonthIsToday
)
-- ---------------------------
-- UPDATE
-- ---------------------------
type Msg
= Noop
| Inc
| Dec
| UpdateDay Int
| UpdateFilter String
update : Msg -> Model -> ( Model, Cmd Msg )
update message model =
case message of
Noop ->
( model, Cmd.none )
UpdateDay t ->
( { model | day = t }, Cmd.none )
UpdateFilter s ->
( { model | filter = s }, Cmd.none )
Inc ->
( { model | day = model.day + 1 }, Cmd.none )
Dec ->
( { model | day = model.day - 1 }, Cmd.none )
millisecondsInAWeek =
1000 * 60 * 60 * 24 * 7
{-| Assume a month is 4 weeks
-}
millisecondsInAMonth =
millisecondsInAWeek * 4
whatDayOfMonthIsToday : Task x Int
whatDayOfMonthIsToday =
Task.map (dayOfMonth << Time.posixToMillis) Time.now
-- ---------------------------
-- VIEW
-- ---------------------------
toString chore =
case chore of
Weekly ->
"Weekly"
Monthly ->
"Monthly"
view : Model -> Html Msg
view model =
let
headerRow =
[ "Chore", "Frequency", "Who" ]
|> L.map (\s -> th [] [ text s ])
|> tr []
bodyRows =
model.chores
|> L.indexedMap (choreToRow <| model.day)
|> L.filter (\( _, person ) -> startsWith (toLower model.filter) (toLower person))
|> L.map (\( row, person ) -> row)
in
div [ class "container" ]
[ h1 [ style "text-align" "center" ] [ text <| "Housemate chore roster" ]
, text "Filter by person: "
, input [ type_ "input", onInput UpdateFilter ] []
, hr [] []
, br [] []
, table [ class "pure-table pure-table-bordered", style "width" "100%" ]
[ col [ style "width" "60%" ] []
, col [ style "width" "20%" ] []
, col [ style "width" "20%" ] []
, thead [] [ headerRow ]
, tbody [] bodyRows
]
, br [] []
, text <| "Showing day " ++ describeDay model ++ " of 28. Change date: "
, button [ onClick Inc, class "pure-button" ] [ text "+" ]
, button [ onClick Dec, class "pure-button" ] [ text "-" ]
]
describeDay model =
String.fromInt <| 1 + modBy 28 model.day
{-| Calculate what day of a (28 day) month it is, given how many ms since epoch.
-}
dayOfMonth millisecondsSinceEpoch =
modBy 28 <| (millisecondsSinceEpoch // millisecondsInAWeek)
choreToRow : Int -> Int -> Chore -> ( Html Msg, String )
choreToRow day i chore =
let
person =
personFor chore.freq day i allPeople
textTD s =
td [] [ text s ]
row =
tr []
[ textTD chore.name
, textTD (toString chore.freq)
, textTD person
]
in
( row, person )
{-| Given the day of the month (0-27) and a chore number, choose a person.
-}
personFor : Frequency -> Int -> Int -> Array String -> String
personFor freq day i people =
let
x =
day // daysPer freq
index =
(x + i) |> modBy (A.length people)
in
case A.get index people of
Just p ->
p
Nothing ->
"???"
-- ---------------------------
-- MAIN
-- ---------------------------
main : Program () Model Msg
main =
Browser.document
{ init = init
, update = update
, view =
\m ->
{ title = "Housemate chore roster"
, body = [ view m ]
}
, subscriptions = \_ -> Sub.none
}
| 5988 | port module Main exposing (Frequency(..), Model, Msg(..), init, main, personFor, toJs, update, view)
import Array as A exposing (Array)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
import Http exposing (Error(..))
import Json.Decode as Decode
import List as L
import String exposing (startsWith, toLower)
import Task exposing (Task)
import Time exposing (millisToPosix, toDay, utc)
-- ---------------------------
-- PORTS
-- ---------------------------
port toJs : String -> Cmd msg
-- ---------------------------
-- MODEL
-- ---------------------------
type alias Model =
{ chores : List Chore
, day : Int
, filter : String
}
type alias Chore =
{ name : String
, freq : Frequency
}
type Frequency
= Weekly
| Monthly
daysPer : Frequency -> Int
daysPer f =
case f of
Weekly ->
7
Monthly ->
28
allPeople =
A.fromList [ "<NAME>", "<NAME>", "<NAME>", "<NAME>" ]
init : () -> ( Model, Cmd Msg )
init _ =
( { chores =
[ { name = "Vacuum stairs", freq = Weekly }
, { name = "Vacuum landing", freq = Weekly }
, { name = "Stove", freq = Weekly }
, { name = "Sink", freq = Weekly }
, { name = "Mop downstairs", freq = Weekly }
, { name = "Wipe down countertops", freq = Weekly }
, { name = "Wash glass table", freq = Weekly }
, { name = "Wash glass doors/front door window", freq = Weekly }
, { name = "Wash fridge shelves", freq = Monthly }
, { name = "Wipe fridge outside", freq = Monthly }
, { name = "Clean microwave inside/outside", freq = Monthly }
, { name = "Dusting/baseboards", freq = Monthly }
, { name = "Clutter check (put away if you know where it is, if you don’t know whose it is, just send a photo to the group)", freq = Monthly }
]
, day = 0
, filter = ""
}
, Task.perform UpdateDay whatDayOfMonthIsToday
)
-- ---------------------------
-- UPDATE
-- ---------------------------
type Msg
= Noop
| Inc
| Dec
| UpdateDay Int
| UpdateFilter String
update : Msg -> Model -> ( Model, Cmd Msg )
update message model =
case message of
Noop ->
( model, Cmd.none )
UpdateDay t ->
( { model | day = t }, Cmd.none )
UpdateFilter s ->
( { model | filter = s }, Cmd.none )
Inc ->
( { model | day = model.day + 1 }, Cmd.none )
Dec ->
( { model | day = model.day - 1 }, Cmd.none )
millisecondsInAWeek =
1000 * 60 * 60 * 24 * 7
{-| Assume a month is 4 weeks
-}
millisecondsInAMonth =
millisecondsInAWeek * 4
whatDayOfMonthIsToday : Task x Int
whatDayOfMonthIsToday =
Task.map (dayOfMonth << Time.posixToMillis) Time.now
-- ---------------------------
-- VIEW
-- ---------------------------
toString chore =
case chore of
Weekly ->
"Weekly"
Monthly ->
"Monthly"
view : Model -> Html Msg
view model =
let
headerRow =
[ "Chore", "Frequency", "Who" ]
|> L.map (\s -> th [] [ text s ])
|> tr []
bodyRows =
model.chores
|> L.indexedMap (choreToRow <| model.day)
|> L.filter (\( _, person ) -> startsWith (toLower model.filter) (toLower person))
|> L.map (\( row, person ) -> row)
in
div [ class "container" ]
[ h1 [ style "text-align" "center" ] [ text <| "Housemate chore roster" ]
, text "Filter by person: "
, input [ type_ "input", onInput UpdateFilter ] []
, hr [] []
, br [] []
, table [ class "pure-table pure-table-bordered", style "width" "100%" ]
[ col [ style "width" "60%" ] []
, col [ style "width" "20%" ] []
, col [ style "width" "20%" ] []
, thead [] [ headerRow ]
, tbody [] bodyRows
]
, br [] []
, text <| "Showing day " ++ describeDay model ++ " of 28. Change date: "
, button [ onClick Inc, class "pure-button" ] [ text "+" ]
, button [ onClick Dec, class "pure-button" ] [ text "-" ]
]
describeDay model =
String.fromInt <| 1 + modBy 28 model.day
{-| Calculate what day of a (28 day) month it is, given how many ms since epoch.
-}
dayOfMonth millisecondsSinceEpoch =
modBy 28 <| (millisecondsSinceEpoch // millisecondsInAWeek)
choreToRow : Int -> Int -> Chore -> ( Html Msg, String )
choreToRow day i chore =
let
person =
personFor chore.freq day i allPeople
textTD s =
td [] [ text s ]
row =
tr []
[ textTD chore.name
, textTD (toString chore.freq)
, textTD person
]
in
( row, person )
{-| Given the day of the month (0-27) and a chore number, choose a person.
-}
personFor : Frequency -> Int -> Int -> Array String -> String
personFor freq day i people =
let
x =
day // daysPer freq
index =
(x + i) |> modBy (A.length people)
in
case A.get index people of
Just p ->
p
Nothing ->
"???"
-- ---------------------------
-- MAIN
-- ---------------------------
main : Program () Model Msg
main =
Browser.document
{ init = init
, update = update
, view =
\m ->
{ title = "Housemate chore roster"
, body = [ view m ]
}
, subscriptions = \_ -> Sub.none
}
| true | port module Main exposing (Frequency(..), Model, Msg(..), init, main, personFor, toJs, update, view)
import Array as A exposing (Array)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
import Http exposing (Error(..))
import Json.Decode as Decode
import List as L
import String exposing (startsWith, toLower)
import Task exposing (Task)
import Time exposing (millisToPosix, toDay, utc)
-- ---------------------------
-- PORTS
-- ---------------------------
port toJs : String -> Cmd msg
-- ---------------------------
-- MODEL
-- ---------------------------
type alias Model =
{ chores : List Chore
, day : Int
, filter : String
}
type alias Chore =
{ name : String
, freq : Frequency
}
type Frequency
= Weekly
| Monthly
daysPer : Frequency -> Int
daysPer f =
case f of
Weekly ->
7
Monthly ->
28
allPeople =
A.fromList [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ]
init : () -> ( Model, Cmd Msg )
init _ =
( { chores =
[ { name = "Vacuum stairs", freq = Weekly }
, { name = "Vacuum landing", freq = Weekly }
, { name = "Stove", freq = Weekly }
, { name = "Sink", freq = Weekly }
, { name = "Mop downstairs", freq = Weekly }
, { name = "Wipe down countertops", freq = Weekly }
, { name = "Wash glass table", freq = Weekly }
, { name = "Wash glass doors/front door window", freq = Weekly }
, { name = "Wash fridge shelves", freq = Monthly }
, { name = "Wipe fridge outside", freq = Monthly }
, { name = "Clean microwave inside/outside", freq = Monthly }
, { name = "Dusting/baseboards", freq = Monthly }
, { name = "Clutter check (put away if you know where it is, if you don’t know whose it is, just send a photo to the group)", freq = Monthly }
]
, day = 0
, filter = ""
}
, Task.perform UpdateDay whatDayOfMonthIsToday
)
-- ---------------------------
-- UPDATE
-- ---------------------------
type Msg
= Noop
| Inc
| Dec
| UpdateDay Int
| UpdateFilter String
update : Msg -> Model -> ( Model, Cmd Msg )
update message model =
case message of
Noop ->
( model, Cmd.none )
UpdateDay t ->
( { model | day = t }, Cmd.none )
UpdateFilter s ->
( { model | filter = s }, Cmd.none )
Inc ->
( { model | day = model.day + 1 }, Cmd.none )
Dec ->
( { model | day = model.day - 1 }, Cmd.none )
millisecondsInAWeek =
1000 * 60 * 60 * 24 * 7
{-| Assume a month is 4 weeks
-}
millisecondsInAMonth =
millisecondsInAWeek * 4
whatDayOfMonthIsToday : Task x Int
whatDayOfMonthIsToday =
Task.map (dayOfMonth << Time.posixToMillis) Time.now
-- ---------------------------
-- VIEW
-- ---------------------------
toString chore =
case chore of
Weekly ->
"Weekly"
Monthly ->
"Monthly"
view : Model -> Html Msg
view model =
let
headerRow =
[ "Chore", "Frequency", "Who" ]
|> L.map (\s -> th [] [ text s ])
|> tr []
bodyRows =
model.chores
|> L.indexedMap (choreToRow <| model.day)
|> L.filter (\( _, person ) -> startsWith (toLower model.filter) (toLower person))
|> L.map (\( row, person ) -> row)
in
div [ class "container" ]
[ h1 [ style "text-align" "center" ] [ text <| "Housemate chore roster" ]
, text "Filter by person: "
, input [ type_ "input", onInput UpdateFilter ] []
, hr [] []
, br [] []
, table [ class "pure-table pure-table-bordered", style "width" "100%" ]
[ col [ style "width" "60%" ] []
, col [ style "width" "20%" ] []
, col [ style "width" "20%" ] []
, thead [] [ headerRow ]
, tbody [] bodyRows
]
, br [] []
, text <| "Showing day " ++ describeDay model ++ " of 28. Change date: "
, button [ onClick Inc, class "pure-button" ] [ text "+" ]
, button [ onClick Dec, class "pure-button" ] [ text "-" ]
]
describeDay model =
String.fromInt <| 1 + modBy 28 model.day
{-| Calculate what day of a (28 day) month it is, given how many ms since epoch.
-}
dayOfMonth millisecondsSinceEpoch =
modBy 28 <| (millisecondsSinceEpoch // millisecondsInAWeek)
choreToRow : Int -> Int -> Chore -> ( Html Msg, String )
choreToRow day i chore =
let
person =
personFor chore.freq day i allPeople
textTD s =
td [] [ text s ]
row =
tr []
[ textTD chore.name
, textTD (toString chore.freq)
, textTD person
]
in
( row, person )
{-| Given the day of the month (0-27) and a chore number, choose a person.
-}
personFor : Frequency -> Int -> Int -> Array String -> String
personFor freq day i people =
let
x =
day // daysPer freq
index =
(x + i) |> modBy (A.length people)
in
case A.get index people of
Just p ->
p
Nothing ->
"???"
-- ---------------------------
-- MAIN
-- ---------------------------
main : Program () Model Msg
main =
Browser.document
{ init = init
, update = update
, view =
\m ->
{ title = "Housemate chore roster"
, body = [ view m ]
}
, subscriptions = \_ -> Sub.none
}
| elm |
[
{
"context": "{- Copyright (C) 2018 Mark D. Blackwell.\n All rights reserved.\n This program is distr",
"end": 39,
"score": 0.9998455048,
"start": 22,
"tag": "NAME",
"value": "Mark D. Blackwell"
}
] | src/front-end/update/CommentUpdate.elm | MarkDBlackwell/qplaylist-remember | 0 | {- Copyright (C) 2018 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 CommentUpdate exposing
( commentAreaInputTextChangeCaptureHand
, commentAreaOpenHand
, commentCancelHand
)
import Alert
import ElmCycle
import FocusUpdate
import ModelInitialize
import ModelType
exposing
( CommentAreaOptional(..)
, Model
)
import SongHelper
import SongInitialize
import SongType
exposing
( SongRememberedMaybe
, SongsRemembered
, SongsRememberedIndex
)
import UpdateHelper
-- UPDATE
commentAreaInputTextChangeCaptureHand : Model -> String -> ElmCycle.ElmCycle
commentAreaInputTextChangeCaptureHand model text =
case UpdateHelper.commentAreaStateVector model of
--( AwaitingServerResponse, CommentAreaOptional )
( True, _ ) ->
( { model
| commentText = text
}
, Cmd.none
)
_ ->
( { model
| alertMessageText = Alert.messageTextInit
, commentText = text
}
, Cmd.none
)
commentAreaOpenHand : Model -> SongsRememberedIndex -> ElmCycle.ElmCycle
commentAreaOpenHand model songsRememberedIndex =
case UpdateHelper.commentAreaStateVector model of
--( AwaitingServerResponse, CommentAreaOptional )
( True, _ ) ->
Alert.messageTextServerAwaitingElmCycle model
( _, CommentAreaOpen ) ->
( { model
| alertMessageText = Alert.messageTextInit
}
, FocusUpdate.cmdFocusInputPossibly model
)
_ ->
let
songsRememberedNew : SongsRemembered
songsRememberedNew =
model.songsRemembered
|> List.drop songsRememberedIndex
|> List.head
|> SongHelper.songsRememberedNewFromMaybeWithUpdate model
songsRememberedSelectOneMaybe : SongRememberedMaybe
songsRememberedSelectOneMaybe =
songsRememberedNew
|> List.drop songsRememberedIndex
|> List.head
in
case songsRememberedSelectOneMaybe of
Nothing ->
UpdateHelper.elmCycleDefault model
_ ->
( { model
| alertMessageText = Alert.messageTextInit
, commentText = ModelInitialize.commentTextInit
, songCommentingOnNowMaybe = songsRememberedSelectOneMaybe
, songsRemembered = songsRememberedNew
}
--'FocusUpdate.cmdFocusInputPossibly' doesn't work, here:
, FocusUpdate.cmdFocusSetId "input"
)
commentCancelHand : Model -> ElmCycle.ElmCycle
commentCancelHand model =
case UpdateHelper.commentAreaStateVector model of
--( AwaitingServerResponse, CommentAreaOptional )
( True, _ ) ->
Alert.messageTextServerAwaitingElmCycle model
_ ->
( { model
| alertMessageText = Alert.messageTextInit
, commentText = ModelInitialize.commentTextInit
, songCommentingOnNowMaybe = SongInitialize.songCommentingOnNowMaybeInit
}
, "Comment"
|> SongHelper.buttonIdReconstruct
model.songsRemembered
model.songCommentingOnNowMaybe
|> FocusUpdate.cmdFocusSetId
)
| 37037 | {- Copyright (C) 2018 <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 CommentUpdate exposing
( commentAreaInputTextChangeCaptureHand
, commentAreaOpenHand
, commentCancelHand
)
import Alert
import ElmCycle
import FocusUpdate
import ModelInitialize
import ModelType
exposing
( CommentAreaOptional(..)
, Model
)
import SongHelper
import SongInitialize
import SongType
exposing
( SongRememberedMaybe
, SongsRemembered
, SongsRememberedIndex
)
import UpdateHelper
-- UPDATE
commentAreaInputTextChangeCaptureHand : Model -> String -> ElmCycle.ElmCycle
commentAreaInputTextChangeCaptureHand model text =
case UpdateHelper.commentAreaStateVector model of
--( AwaitingServerResponse, CommentAreaOptional )
( True, _ ) ->
( { model
| commentText = text
}
, Cmd.none
)
_ ->
( { model
| alertMessageText = Alert.messageTextInit
, commentText = text
}
, Cmd.none
)
commentAreaOpenHand : Model -> SongsRememberedIndex -> ElmCycle.ElmCycle
commentAreaOpenHand model songsRememberedIndex =
case UpdateHelper.commentAreaStateVector model of
--( AwaitingServerResponse, CommentAreaOptional )
( True, _ ) ->
Alert.messageTextServerAwaitingElmCycle model
( _, CommentAreaOpen ) ->
( { model
| alertMessageText = Alert.messageTextInit
}
, FocusUpdate.cmdFocusInputPossibly model
)
_ ->
let
songsRememberedNew : SongsRemembered
songsRememberedNew =
model.songsRemembered
|> List.drop songsRememberedIndex
|> List.head
|> SongHelper.songsRememberedNewFromMaybeWithUpdate model
songsRememberedSelectOneMaybe : SongRememberedMaybe
songsRememberedSelectOneMaybe =
songsRememberedNew
|> List.drop songsRememberedIndex
|> List.head
in
case songsRememberedSelectOneMaybe of
Nothing ->
UpdateHelper.elmCycleDefault model
_ ->
( { model
| alertMessageText = Alert.messageTextInit
, commentText = ModelInitialize.commentTextInit
, songCommentingOnNowMaybe = songsRememberedSelectOneMaybe
, songsRemembered = songsRememberedNew
}
--'FocusUpdate.cmdFocusInputPossibly' doesn't work, here:
, FocusUpdate.cmdFocusSetId "input"
)
commentCancelHand : Model -> ElmCycle.ElmCycle
commentCancelHand model =
case UpdateHelper.commentAreaStateVector model of
--( AwaitingServerResponse, CommentAreaOptional )
( True, _ ) ->
Alert.messageTextServerAwaitingElmCycle model
_ ->
( { model
| alertMessageText = Alert.messageTextInit
, commentText = ModelInitialize.commentTextInit
, songCommentingOnNowMaybe = SongInitialize.songCommentingOnNowMaybeInit
}
, "Comment"
|> SongHelper.buttonIdReconstruct
model.songsRemembered
model.songCommentingOnNowMaybe
|> FocusUpdate.cmdFocusSetId
)
| true | {- Copyright (C) 2018 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 CommentUpdate exposing
( commentAreaInputTextChangeCaptureHand
, commentAreaOpenHand
, commentCancelHand
)
import Alert
import ElmCycle
import FocusUpdate
import ModelInitialize
import ModelType
exposing
( CommentAreaOptional(..)
, Model
)
import SongHelper
import SongInitialize
import SongType
exposing
( SongRememberedMaybe
, SongsRemembered
, SongsRememberedIndex
)
import UpdateHelper
-- UPDATE
commentAreaInputTextChangeCaptureHand : Model -> String -> ElmCycle.ElmCycle
commentAreaInputTextChangeCaptureHand model text =
case UpdateHelper.commentAreaStateVector model of
--( AwaitingServerResponse, CommentAreaOptional )
( True, _ ) ->
( { model
| commentText = text
}
, Cmd.none
)
_ ->
( { model
| alertMessageText = Alert.messageTextInit
, commentText = text
}
, Cmd.none
)
commentAreaOpenHand : Model -> SongsRememberedIndex -> ElmCycle.ElmCycle
commentAreaOpenHand model songsRememberedIndex =
case UpdateHelper.commentAreaStateVector model of
--( AwaitingServerResponse, CommentAreaOptional )
( True, _ ) ->
Alert.messageTextServerAwaitingElmCycle model
( _, CommentAreaOpen ) ->
( { model
| alertMessageText = Alert.messageTextInit
}
, FocusUpdate.cmdFocusInputPossibly model
)
_ ->
let
songsRememberedNew : SongsRemembered
songsRememberedNew =
model.songsRemembered
|> List.drop songsRememberedIndex
|> List.head
|> SongHelper.songsRememberedNewFromMaybeWithUpdate model
songsRememberedSelectOneMaybe : SongRememberedMaybe
songsRememberedSelectOneMaybe =
songsRememberedNew
|> List.drop songsRememberedIndex
|> List.head
in
case songsRememberedSelectOneMaybe of
Nothing ->
UpdateHelper.elmCycleDefault model
_ ->
( { model
| alertMessageText = Alert.messageTextInit
, commentText = ModelInitialize.commentTextInit
, songCommentingOnNowMaybe = songsRememberedSelectOneMaybe
, songsRemembered = songsRememberedNew
}
--'FocusUpdate.cmdFocusInputPossibly' doesn't work, here:
, FocusUpdate.cmdFocusSetId "input"
)
commentCancelHand : Model -> ElmCycle.ElmCycle
commentCancelHand model =
case UpdateHelper.commentAreaStateVector model of
--( AwaitingServerResponse, CommentAreaOptional )
( True, _ ) ->
Alert.messageTextServerAwaitingElmCycle model
_ ->
( { model
| alertMessageText = Alert.messageTextInit
, commentText = ModelInitialize.commentTextInit
, songCommentingOnNowMaybe = SongInitialize.songCommentingOnNowMaybeInit
}
, "Comment"
|> SongHelper.buttonIdReconstruct
model.songsRemembered
model.songCommentingOnNowMaybe
|> FocusUpdate.cmdFocusSetId
)
| elm |
[
{
"context": "nTree\n\n\nexampleJsonInput =\n \"\"\"\n{\n \"name\": \"Arnold\",\n \"age\": 70,\n \"isStrong\": true,\n \"known",
"end": 387,
"score": 0.9997754097,
"start": 381,
"tag": "NAME",
"value": "Arnold"
},
{
"context": "ue,\n \"knownWeakness\": null,\n \"nicknames\": [\"Terminator\", \"The Governator\"],\n \"extra\": {\n \"f",
"end": 483,
"score": 0.8848927617,
"start": 473,
"tag": "NAME",
"value": "Terminator"
},
{
"context": "Weakness\": null,\n \"nicknames\": [\"Terminator\", \"The Governator\"],\n \"extra\": {\n \"foo\": \"bar\"\n }\n}",
"end": 501,
"score": 0.7545538545,
"start": 487,
"tag": "NAME",
"value": "The Governator"
}
] | example/src/Main.elm | PascalLeMerrerPro/elm-json-tree-view | 58 | -- Copyright (c) Microsoft Corporation. All rights reserved.
-- Licensed under the MIT License.
module Main exposing (..)
import Browser
import Json.Decode as Decode
import Html exposing (..)
import Html.Attributes exposing (checked, class, style, type_, value)
import Html.Events exposing (onCheck, onClick, onInput)
import JsonTree
exampleJsonInput =
"""
{
"name": "Arnold",
"age": 70,
"isStrong": true,
"knownWeakness": null,
"nicknames": ["Terminator", "The Governator"],
"extra": {
"foo": "bar"
}
}
"""
---- MODEL ----
type alias Model =
{ jsonInput : String
, parseResult : Result Decode.Error JsonTree.Node
, treeState : JsonTree.State
, clickToSelectEnabled : Bool
, selections : List JsonTree.KeyPath
}
init : Model
init =
{ jsonInput = exampleJsonInput
, parseResult = JsonTree.parseString exampleJsonInput
, treeState = JsonTree.defaultState
, clickToSelectEnabled = False
, selections = []
}
---- UPDATE ----
type Msg
= SetJsonInput String
| Parse
| SetTreeViewState JsonTree.State
| ExpandAll
| CollapseAll
| ToggleSelectionMode
| Selected JsonTree.KeyPath
update : Msg -> Model -> Model
update msg model =
case msg of
SetJsonInput string ->
{ model | jsonInput = string }
Parse ->
{ model | parseResult = JsonTree.parseString model.jsonInput }
SetTreeViewState state ->
{ model | treeState = state }
ExpandAll ->
{ model | treeState = JsonTree.expandAll model.treeState }
CollapseAll ->
case model.parseResult of
Ok rootNode ->
{ model | treeState = JsonTree.collapseToDepth 1 rootNode model.treeState }
Err _ ->
model
ToggleSelectionMode ->
{ model
| clickToSelectEnabled = not model.clickToSelectEnabled
, selections = []
}
Selected keyPath ->
{ model | selections = model.selections ++ [ keyPath ] }
---- VIEW ----
view : Model -> Html Msg
view model =
div [ style "margin" "20px" ]
[ h1 [] [ text "JSON Tree View Example" ]
, viewInputArea model
, hr [] []
, viewJsonTree model
, if model.clickToSelectEnabled then
viewSelections model
else
text ""
]
viewInputArea : Model -> Html Msg
viewInputArea model =
div []
[ h3 [] [ text "Raw JSON input:" ]
, textarea
[ value model.jsonInput
, onInput SetJsonInput
, style "width" "400px"
, style "height" "200px"
, style "font-size" "14px"
]
[]
, div [] [ button [ onClick Parse ] [ text "Parse" ] ]
]
viewJsonTree : Model -> Html Msg
viewJsonTree model =
let
toolbar =
div []
[ label []
[ input
[ type_ "checkbox"
, onCheck (always ToggleSelectionMode)
, checked model.clickToSelectEnabled
]
[]
, text "Selection Mode"
]
, button [ onClick ExpandAll ] [ text "Expand All" ]
, button [ onClick CollapseAll ] [ text "Collapse All" ]
]
config allowSelection =
{ onSelect =
if allowSelection then
Just Selected
else
Nothing
, toMsg = SetTreeViewState
}
in
div []
[ h3 [] [ text "JSON Tree View" ]
, toolbar
, case model.parseResult of
Ok rootNode ->
JsonTree.view rootNode (config model.clickToSelectEnabled) model.treeState
Err e ->
pre [] [ text ("Invalid JSON: " ++ Decode.errorToString e)]
]
viewSelections : Model -> Html Msg
viewSelections model =
div []
[ hr [] []
, h3 [] [ text "Recently selected key-paths" ]
, if List.isEmpty model.selections then
text "No selections. Click any scalar value in the JSON tree view above to select it."
else
ul [] (List.map (\x -> li [] [ text x ]) model.selections)
]
---- PROGRAM ----
main : Program () Model Msg
main =
Browser.sandbox
{ init = init
, view = view
, update = update
}
| 3202 | -- Copyright (c) Microsoft Corporation. All rights reserved.
-- Licensed under the MIT License.
module Main exposing (..)
import Browser
import Json.Decode as Decode
import Html exposing (..)
import Html.Attributes exposing (checked, class, style, type_, value)
import Html.Events exposing (onCheck, onClick, onInput)
import JsonTree
exampleJsonInput =
"""
{
"name": "<NAME>",
"age": 70,
"isStrong": true,
"knownWeakness": null,
"nicknames": ["<NAME>", "<NAME>"],
"extra": {
"foo": "bar"
}
}
"""
---- MODEL ----
type alias Model =
{ jsonInput : String
, parseResult : Result Decode.Error JsonTree.Node
, treeState : JsonTree.State
, clickToSelectEnabled : Bool
, selections : List JsonTree.KeyPath
}
init : Model
init =
{ jsonInput = exampleJsonInput
, parseResult = JsonTree.parseString exampleJsonInput
, treeState = JsonTree.defaultState
, clickToSelectEnabled = False
, selections = []
}
---- UPDATE ----
type Msg
= SetJsonInput String
| Parse
| SetTreeViewState JsonTree.State
| ExpandAll
| CollapseAll
| ToggleSelectionMode
| Selected JsonTree.KeyPath
update : Msg -> Model -> Model
update msg model =
case msg of
SetJsonInput string ->
{ model | jsonInput = string }
Parse ->
{ model | parseResult = JsonTree.parseString model.jsonInput }
SetTreeViewState state ->
{ model | treeState = state }
ExpandAll ->
{ model | treeState = JsonTree.expandAll model.treeState }
CollapseAll ->
case model.parseResult of
Ok rootNode ->
{ model | treeState = JsonTree.collapseToDepth 1 rootNode model.treeState }
Err _ ->
model
ToggleSelectionMode ->
{ model
| clickToSelectEnabled = not model.clickToSelectEnabled
, selections = []
}
Selected keyPath ->
{ model | selections = model.selections ++ [ keyPath ] }
---- VIEW ----
view : Model -> Html Msg
view model =
div [ style "margin" "20px" ]
[ h1 [] [ text "JSON Tree View Example" ]
, viewInputArea model
, hr [] []
, viewJsonTree model
, if model.clickToSelectEnabled then
viewSelections model
else
text ""
]
viewInputArea : Model -> Html Msg
viewInputArea model =
div []
[ h3 [] [ text "Raw JSON input:" ]
, textarea
[ value model.jsonInput
, onInput SetJsonInput
, style "width" "400px"
, style "height" "200px"
, style "font-size" "14px"
]
[]
, div [] [ button [ onClick Parse ] [ text "Parse" ] ]
]
viewJsonTree : Model -> Html Msg
viewJsonTree model =
let
toolbar =
div []
[ label []
[ input
[ type_ "checkbox"
, onCheck (always ToggleSelectionMode)
, checked model.clickToSelectEnabled
]
[]
, text "Selection Mode"
]
, button [ onClick ExpandAll ] [ text "Expand All" ]
, button [ onClick CollapseAll ] [ text "Collapse All" ]
]
config allowSelection =
{ onSelect =
if allowSelection then
Just Selected
else
Nothing
, toMsg = SetTreeViewState
}
in
div []
[ h3 [] [ text "JSON Tree View" ]
, toolbar
, case model.parseResult of
Ok rootNode ->
JsonTree.view rootNode (config model.clickToSelectEnabled) model.treeState
Err e ->
pre [] [ text ("Invalid JSON: " ++ Decode.errorToString e)]
]
viewSelections : Model -> Html Msg
viewSelections model =
div []
[ hr [] []
, h3 [] [ text "Recently selected key-paths" ]
, if List.isEmpty model.selections then
text "No selections. Click any scalar value in the JSON tree view above to select it."
else
ul [] (List.map (\x -> li [] [ text x ]) model.selections)
]
---- PROGRAM ----
main : Program () Model Msg
main =
Browser.sandbox
{ init = init
, view = view
, update = update
}
| true | -- Copyright (c) Microsoft Corporation. All rights reserved.
-- Licensed under the MIT License.
module Main exposing (..)
import Browser
import Json.Decode as Decode
import Html exposing (..)
import Html.Attributes exposing (checked, class, style, type_, value)
import Html.Events exposing (onCheck, onClick, onInput)
import JsonTree
exampleJsonInput =
"""
{
"name": "PI:NAME:<NAME>END_PI",
"age": 70,
"isStrong": true,
"knownWeakness": null,
"nicknames": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"extra": {
"foo": "bar"
}
}
"""
---- MODEL ----
type alias Model =
{ jsonInput : String
, parseResult : Result Decode.Error JsonTree.Node
, treeState : JsonTree.State
, clickToSelectEnabled : Bool
, selections : List JsonTree.KeyPath
}
init : Model
init =
{ jsonInput = exampleJsonInput
, parseResult = JsonTree.parseString exampleJsonInput
, treeState = JsonTree.defaultState
, clickToSelectEnabled = False
, selections = []
}
---- UPDATE ----
type Msg
= SetJsonInput String
| Parse
| SetTreeViewState JsonTree.State
| ExpandAll
| CollapseAll
| ToggleSelectionMode
| Selected JsonTree.KeyPath
update : Msg -> Model -> Model
update msg model =
case msg of
SetJsonInput string ->
{ model | jsonInput = string }
Parse ->
{ model | parseResult = JsonTree.parseString model.jsonInput }
SetTreeViewState state ->
{ model | treeState = state }
ExpandAll ->
{ model | treeState = JsonTree.expandAll model.treeState }
CollapseAll ->
case model.parseResult of
Ok rootNode ->
{ model | treeState = JsonTree.collapseToDepth 1 rootNode model.treeState }
Err _ ->
model
ToggleSelectionMode ->
{ model
| clickToSelectEnabled = not model.clickToSelectEnabled
, selections = []
}
Selected keyPath ->
{ model | selections = model.selections ++ [ keyPath ] }
---- VIEW ----
view : Model -> Html Msg
view model =
div [ style "margin" "20px" ]
[ h1 [] [ text "JSON Tree View Example" ]
, viewInputArea model
, hr [] []
, viewJsonTree model
, if model.clickToSelectEnabled then
viewSelections model
else
text ""
]
viewInputArea : Model -> Html Msg
viewInputArea model =
div []
[ h3 [] [ text "Raw JSON input:" ]
, textarea
[ value model.jsonInput
, onInput SetJsonInput
, style "width" "400px"
, style "height" "200px"
, style "font-size" "14px"
]
[]
, div [] [ button [ onClick Parse ] [ text "Parse" ] ]
]
viewJsonTree : Model -> Html Msg
viewJsonTree model =
let
toolbar =
div []
[ label []
[ input
[ type_ "checkbox"
, onCheck (always ToggleSelectionMode)
, checked model.clickToSelectEnabled
]
[]
, text "Selection Mode"
]
, button [ onClick ExpandAll ] [ text "Expand All" ]
, button [ onClick CollapseAll ] [ text "Collapse All" ]
]
config allowSelection =
{ onSelect =
if allowSelection then
Just Selected
else
Nothing
, toMsg = SetTreeViewState
}
in
div []
[ h3 [] [ text "JSON Tree View" ]
, toolbar
, case model.parseResult of
Ok rootNode ->
JsonTree.view rootNode (config model.clickToSelectEnabled) model.treeState
Err e ->
pre [] [ text ("Invalid JSON: " ++ Decode.errorToString e)]
]
viewSelections : Model -> Html Msg
viewSelections model =
div []
[ hr [] []
, h3 [] [ text "Recently selected key-paths" ]
, if List.isEmpty model.selections then
text "No selections. Click any scalar value in the JSON tree view above to select it."
else
ul [] (List.map (\x -> li [] [ text x ]) model.selections)
]
---- PROGRAM ----
main : Program () Model Msg
main =
Browser.sandbox
{ init = init
, view = view
, update = update
}
| elm |
[
{
"context": "{-\n Copyright © 2017–2021 toastal <toastal@posteo.net> (https://toast.al)\n\n Licen",
"end": 35,
"score": 0.9997025728,
"start": 28,
"tag": "USERNAME",
"value": "toastal"
},
{
"context": "{-\n Copyright © 2017–2021 toastal <toastal@posteo.net> (https://toast.al)\n\n Licensed under the Apache",
"end": 55,
"score": 0.9999266863,
"start": 37,
"tag": "EMAIL",
"value": "toastal@posteo.net"
}
] | src/Html/SelectPrism.elm | toastal/select-prism | 6 | {-
Copyright © 2017–2021 toastal <toastal@posteo.net> (https://toast.al)
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 Html.SelectPrism exposing (selectp, selectpm)
{-| `selectp` and `selectpm` allow a user to push ADTs in and
get ADTs out of a `<select>`
# Selects
@docs selectp, selectpm
-}
import Html exposing (Attribute, Html, option, select, text)
import Html.Attributes exposing (multiple, selected, value)
import Html.Events exposing (on, targetValue)
import Json.Decode as Decode exposing (Decoder)
import Monocle.Prism exposing (Prism)
{-| `selectp` is wrapping up the idea of select box from a generic
comparable. However, Elm does everything through strings -- which is
why we’re using the `Prism`. That `Prism` onus is on you. The args are:
1. [Prism](http://package.elm-lang.org/packages/arturopala/elm-monocle/latest/Monocle-Prism)
from a `String` to our thing `a`
2. A function from the attempt to get--`Result String a`, where `a` is
our thing--to a msg for the onChange
3. The selected value
4. List of `Html.Attributes` for the `<select>` so you can have
custom classes, etc.
5. List tuples of `( String, a )` where the `String` is the label
for the option and the `a` is our thing.
-}
selectp : Prism String a -> (Result String a -> msg) -> a -> List (Attribute msg) -> List ( String, a ) -> Html msg
selectp prism msger selected_ attrs labelValues =
let
resultFromString : String -> Result String a
resultFromString x =
case prism.getOption x of
Just y ->
Ok y
_ ->
Err <| "Failed to get a valid option from " ++ x
change : Decoder msg
change =
Decode.map (resultFromString >> msger) targetValue
opt : ( String, a ) -> Html msg
opt ( labl, val ) =
option
[ selected <| selected_ == val
, value <| prism.reverseGet val
]
[ text labl ]
in
select (on "change" change :: attrs) <|
List.map opt labelValues
{-| Like `selectp`, but a `<select multiple>` which takes a list of
selected values and the Msg needs to be a list of results. Note:
[`selectOptions`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement#Browser_compatibility)
isn’t support in Internet Explorer and I don’t care enough to support
it (and maybe you shouldn’t either).
-}
selectpm : Prism String a -> (List (Result String a) -> msg) -> List a -> List (Attribute msg) -> List ( String, a ) -> Html msg
selectpm prism msger selecteds attrs labelValues =
let
resultFromString : String -> Result String a
resultFromString x =
case prism.getOption x of
Just y ->
Ok y
_ ->
Err <| "Failed to get a valid option from " ++ x
-- Don’t ask
change : Decoder msg
change =
let
loop idx xs =
Decode.maybe
(Decode.field (String.fromInt idx)
(Decode.field "value" Decode.string
|> Decode.map resultFromString
)
)
|> Decode.andThen
(Maybe.map (\x -> loop (idx + 1) (x :: xs))
>> Maybe.withDefault (Decode.succeed xs)
)
in
loop 0 []
|> Decode.at [ "target", "selectedOptions" ]
|> Decode.map (List.reverse >> msger)
opt : ( String, a ) -> Html msg
opt ( labl, val ) =
option
[ selected <| List.any ((==) val) selecteds
, value <| prism.reverseGet val
]
[ text labl ]
in
select (on "change" change :: multiple True :: attrs) <|
List.map opt labelValues
| 52464 | {-
Copyright © 2017–2021 toastal <<EMAIL>> (https://toast.al)
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 Html.SelectPrism exposing (selectp, selectpm)
{-| `selectp` and `selectpm` allow a user to push ADTs in and
get ADTs out of a `<select>`
# Selects
@docs selectp, selectpm
-}
import Html exposing (Attribute, Html, option, select, text)
import Html.Attributes exposing (multiple, selected, value)
import Html.Events exposing (on, targetValue)
import Json.Decode as Decode exposing (Decoder)
import Monocle.Prism exposing (Prism)
{-| `selectp` is wrapping up the idea of select box from a generic
comparable. However, Elm does everything through strings -- which is
why we’re using the `Prism`. That `Prism` onus is on you. The args are:
1. [Prism](http://package.elm-lang.org/packages/arturopala/elm-monocle/latest/Monocle-Prism)
from a `String` to our thing `a`
2. A function from the attempt to get--`Result String a`, where `a` is
our thing--to a msg for the onChange
3. The selected value
4. List of `Html.Attributes` for the `<select>` so you can have
custom classes, etc.
5. List tuples of `( String, a )` where the `String` is the label
for the option and the `a` is our thing.
-}
selectp : Prism String a -> (Result String a -> msg) -> a -> List (Attribute msg) -> List ( String, a ) -> Html msg
selectp prism msger selected_ attrs labelValues =
let
resultFromString : String -> Result String a
resultFromString x =
case prism.getOption x of
Just y ->
Ok y
_ ->
Err <| "Failed to get a valid option from " ++ x
change : Decoder msg
change =
Decode.map (resultFromString >> msger) targetValue
opt : ( String, a ) -> Html msg
opt ( labl, val ) =
option
[ selected <| selected_ == val
, value <| prism.reverseGet val
]
[ text labl ]
in
select (on "change" change :: attrs) <|
List.map opt labelValues
{-| Like `selectp`, but a `<select multiple>` which takes a list of
selected values and the Msg needs to be a list of results. Note:
[`selectOptions`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement#Browser_compatibility)
isn’t support in Internet Explorer and I don’t care enough to support
it (and maybe you shouldn’t either).
-}
selectpm : Prism String a -> (List (Result String a) -> msg) -> List a -> List (Attribute msg) -> List ( String, a ) -> Html msg
selectpm prism msger selecteds attrs labelValues =
let
resultFromString : String -> Result String a
resultFromString x =
case prism.getOption x of
Just y ->
Ok y
_ ->
Err <| "Failed to get a valid option from " ++ x
-- Don’t ask
change : Decoder msg
change =
let
loop idx xs =
Decode.maybe
(Decode.field (String.fromInt idx)
(Decode.field "value" Decode.string
|> Decode.map resultFromString
)
)
|> Decode.andThen
(Maybe.map (\x -> loop (idx + 1) (x :: xs))
>> Maybe.withDefault (Decode.succeed xs)
)
in
loop 0 []
|> Decode.at [ "target", "selectedOptions" ]
|> Decode.map (List.reverse >> msger)
opt : ( String, a ) -> Html msg
opt ( labl, val ) =
option
[ selected <| List.any ((==) val) selecteds
, value <| prism.reverseGet val
]
[ text labl ]
in
select (on "change" change :: multiple True :: attrs) <|
List.map opt labelValues
| true | {-
Copyright © 2017–2021 toastal <PI:EMAIL:<EMAIL>END_PI> (https://toast.al)
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 Html.SelectPrism exposing (selectp, selectpm)
{-| `selectp` and `selectpm` allow a user to push ADTs in and
get ADTs out of a `<select>`
# Selects
@docs selectp, selectpm
-}
import Html exposing (Attribute, Html, option, select, text)
import Html.Attributes exposing (multiple, selected, value)
import Html.Events exposing (on, targetValue)
import Json.Decode as Decode exposing (Decoder)
import Monocle.Prism exposing (Prism)
{-| `selectp` is wrapping up the idea of select box from a generic
comparable. However, Elm does everything through strings -- which is
why we’re using the `Prism`. That `Prism` onus is on you. The args are:
1. [Prism](http://package.elm-lang.org/packages/arturopala/elm-monocle/latest/Monocle-Prism)
from a `String` to our thing `a`
2. A function from the attempt to get--`Result String a`, where `a` is
our thing--to a msg for the onChange
3. The selected value
4. List of `Html.Attributes` for the `<select>` so you can have
custom classes, etc.
5. List tuples of `( String, a )` where the `String` is the label
for the option and the `a` is our thing.
-}
selectp : Prism String a -> (Result String a -> msg) -> a -> List (Attribute msg) -> List ( String, a ) -> Html msg
selectp prism msger selected_ attrs labelValues =
let
resultFromString : String -> Result String a
resultFromString x =
case prism.getOption x of
Just y ->
Ok y
_ ->
Err <| "Failed to get a valid option from " ++ x
change : Decoder msg
change =
Decode.map (resultFromString >> msger) targetValue
opt : ( String, a ) -> Html msg
opt ( labl, val ) =
option
[ selected <| selected_ == val
, value <| prism.reverseGet val
]
[ text labl ]
in
select (on "change" change :: attrs) <|
List.map opt labelValues
{-| Like `selectp`, but a `<select multiple>` which takes a list of
selected values and the Msg needs to be a list of results. Note:
[`selectOptions`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement#Browser_compatibility)
isn’t support in Internet Explorer and I don’t care enough to support
it (and maybe you shouldn’t either).
-}
selectpm : Prism String a -> (List (Result String a) -> msg) -> List a -> List (Attribute msg) -> List ( String, a ) -> Html msg
selectpm prism msger selecteds attrs labelValues =
let
resultFromString : String -> Result String a
resultFromString x =
case prism.getOption x of
Just y ->
Ok y
_ ->
Err <| "Failed to get a valid option from " ++ x
-- Don’t ask
change : Decoder msg
change =
let
loop idx xs =
Decode.maybe
(Decode.field (String.fromInt idx)
(Decode.field "value" Decode.string
|> Decode.map resultFromString
)
)
|> Decode.andThen
(Maybe.map (\x -> loop (idx + 1) (x :: xs))
>> Maybe.withDefault (Decode.succeed xs)
)
in
loop 0 []
|> Decode.at [ "target", "selectedOptions" ]
|> Decode.map (List.reverse >> msger)
opt : ( String, a ) -> Html msg
opt ( labl, val ) =
option
[ selected <| List.any ((==) val) selecteds
, value <| prism.reverseGet val
]
[ text labl ]
in
select (on "change" change :: multiple True :: attrs) <|
List.map opt labelValues
| elm |
[
{
"context": " \"#196ac8\"\n\n\nauthToken : String\nauthToken =\n \"some_auth_token\"\n\n\n\n-- SETUPS (i dunno, maybe use fuzzers?)\n\n\ntyp",
"end": 942,
"score": 0.8409511447,
"start": 927,
"tag": "PASSWORD",
"value": "some_auth_token"
}
] | web/elm/tests/FlySuccessTests.elm | benchristel/concourse | 0 | module FlySuccessTests exposing (all)
import Application.Application as Application
import Application.Msgs as Msgs
import Callback exposing (Callback(..))
import DashboardTests exposing (defineHoverBehaviour, iconSelector)
import Effects
import Expect exposing (Expectation)
import FlySuccess.Msgs
import Html.Attributes as Attr
import Http
import SubPage.Msgs
import Test exposing (..)
import Test.Html.Event as Event
import Test.Html.Query as Query
import Test.Html.Selector
exposing
( attribute
, containing
, id
, style
, tag
, text
)
-- CONSTANTS (might be able to remove this and refer to "configuration"-type
-- files like Colors.elm)
almostWhite : String
almostWhite =
"#e6e7e8"
darkGrey : String
darkGrey =
"#323030"
darkerGrey : String
darkerGrey =
"#242424"
blue : String
blue =
"#196ac8"
authToken : String
authToken =
"some_auth_token"
-- SETUPS (i dunno, maybe use fuzzers?)
type alias SetupSteps =
() -> Application.Model
type alias Setup =
( String, SetupSteps )
setupDesc : Setup -> String
setupDesc =
Tuple.first
steps : Setup -> SetupSteps
steps =
Tuple.second
setup : String -> SetupSteps -> Setup
setup =
(,)
whenOnFlySuccessPage : Setup
whenOnFlySuccessPage =
setup "when on fly success page"
(\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = ""
, csrfToken = ""
, authToken = authToken
, pipelineRunningKeyframes = ""
}
{ href = ""
, host = ""
, hostname = ""
, protocol = ""
, origin = ""
, port_ = ""
, pathname = "/fly_success"
, search = "?fly_port=1234"
, hash = ""
, username = ""
, password = ""
}
|> Tuple.first
)
invalidFlyPort : Setup
invalidFlyPort =
setup "with invalid fly port"
(\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = ""
, csrfToken = ""
, authToken = authToken
, pipelineRunningKeyframes = ""
}
{ href = ""
, host = ""
, hostname = ""
, protocol = ""
, origin = ""
, port_ = ""
, pathname = "/fly_success"
, search = "?fly_port=banana"
, hash = ""
, username = ""
, password = ""
}
|> Tuple.first
)
tokenSendSuccess : Setup
tokenSendSuccess =
setup "when token successfully sent to fly"
(steps whenOnFlySuccessPage
>> Application.handleCallback
(Effects.SubPage 1)
(TokenSentToFly (Ok ()))
>> Tuple.first
)
tokenSendFailed : Setup
tokenSendFailed =
setup "when token failed to send to fly"
(steps whenOnFlySuccessPage
>> Application.handleCallback
(Effects.SubPage 1)
(TokenSentToFly (Err Http.NetworkError))
>> Tuple.first
)
tokenCopied : Setup
tokenCopied =
setup "when token copied to clipboard"
(steps tokenSendFailed
>> Application.update
(Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyToken
)
>> Tuple.first
)
allCases : List Setup
allCases =
[ whenOnFlySuccessPage
, invalidFlyPort
, tokenSendFailed
, tokenSendSuccess
]
-- QUERIES
type alias Query =
Application.Model -> Query.Single Msgs.Msg
topBar : Query
topBar =
Application.view
>> Query.fromHtml
>> Query.find [ id "top-bar-app" ]
successCard : Query
successCard =
Application.view
>> Query.fromHtml
>> Query.find [ id "success-card" ]
title : Query
title =
successCard >> Query.find [ id "success-card-title" ]
body : Query
body =
successCard >> Query.find [ id "success-card-body" ]
firstParagraph : Query
firstParagraph =
successCard
>> Query.find [ id "success-card-body" ]
>> Query.find [ id "first-paragraph" ]
secondParagraph : Query
secondParagraph =
successCard
>> Query.find [ id "success-card-body" ]
>> Query.find [ id "second-paragraph" ]
button : Query
button =
body >> Query.find [ id "copy-token" ]
buttonIcon : Query
buttonIcon =
body
>> Query.find [ id "copy-token" ]
>> Query.find [ id "copy-icon" ]
-- PROPERTIES
type alias Assertion =
Query.Single Msgs.Msg -> Expectation
type alias Property =
Setup -> Test
property : Query -> String -> Assertion -> Property
property query description assertion setup =
test (setupDesc setup ++ ", " ++ description) <|
steps setup
>> query
>> assertion
-- top bar
topBarProperty : Property
topBarProperty =
property topBar "has bold font" <|
Query.has [ style [ ( "font-weight", "700" ) ] ]
-- card
cardProperties : List Property
cardProperties =
[ cardBackground
, cardSize
, cardPosition
, cardLayout
, cardStyle
]
cardBackground : Property
cardBackground =
property successCard "card has dark grey background" <|
Query.has [ style [ ( "background-color", darkGrey ) ] ]
cardSize : Property
cardSize =
property successCard "is 330px wide with 30px padding" <|
Query.has
[ style
[ ( "padding", "30px" )
, ( "width", "330px" )
]
]
cardPosition : Property
cardPosition =
property successCard "is centered 50px from the top of the document" <|
Query.has [ style [ ( "margin", "50px auto" ) ] ]
cardLayout : Property
cardLayout =
property successCard "lays out contents vertically and center aligned" <|
Query.has
[ style
[ ( "display", "flex" )
, ( "flex-direction", "column" )
, ( "align-items", "center" )
, ( "text-align", "center" )
]
]
cardStyle : Property
cardStyle =
property successCard "has smooth, non-bold font" <|
Query.has
[ style
[ ( "-webkit-font-smoothing", "antialiased" )
, ( "font-weight", "400" )
]
]
-- title
titleText : Property
titleText =
property title "has success text" <|
Query.has [ text "login successful!" ]
titleStyle : Property
titleStyle =
property title "has bold 18px font" <|
Query.has
[ style
[ ( "font-size", "18px" )
, ( "font-weight", "700" )
]
]
titleProperties : List Property
titleProperties =
[ titleText
, titleStyle
]
-- body
bodyPendingText : Property
bodyPendingText =
property body "has pending text" <|
Query.has [ text "sending token to fly..." ]
bodyNoButton : Property
bodyNoButton =
property body "has no 'copy token' button" <|
Query.hasNot [ id "copy-token" ]
bodyStyle : Property
bodyStyle =
property body "has 14px font" <|
Query.has [ style [ ( "font-size", "14px" ) ] ]
bodyPosition : Property
bodyPosition =
property body "has 10px margin above and below" <|
Query.has [ style [ ( "margin", "10px 0" ) ] ]
bodyLayout : Property
bodyLayout =
property body "lays out contents vertically, centering horizontally" <|
Query.has
[ style
[ ( "display", "flex" )
, ( "flex-direction", "column" )
, ( "align-items", "center" )
]
]
bodyParagraphPositions : Property
bodyParagraphPositions =
property body "paragraphs have 5px margin above and below" <|
Query.findAll [ tag "p" ]
>> Query.each
(Query.has [ style [ ( "margin", "5px 0" ) ] ])
-- body on invalid fly port
secondParagraphErrorText : Property
secondParagraphErrorText =
property secondParagraph "error message describes invalid fly port" <|
Query.children []
>> Expect.all
[ Query.count (Expect.equal 3)
, Query.index 0
>> Query.has
[ text "could not find a valid fly port to send to." ]
, Query.index 2
>> Query.has
[ text "maybe your URL is broken?" ]
]
-- body on successfully sending token
firstParagraphSuccessText : Property
firstParagraphSuccessText =
property firstParagraph "says 'your token has been transferred to fly'" <|
Query.has [ text "your token has been transferred to fly." ]
secondParagraphSuccessText : Property
secondParagraphSuccessText =
property secondParagraph "says 'you may now close this window'" <|
Query.has [ text "you may now close this window." ]
-- body on failing to send token
firstParagraphFailureText : Property
firstParagraphFailureText =
property firstParagraph
"says 'however, your token could not be sent to fly.'"
<|
Query.children []
>> Expect.all
[ Query.count (Expect.equal 3)
, Query.index 0
>> Query.has
[ text "however, your token could not be" ]
, Query.index 2 >> Query.has [ text "sent to fly." ]
]
secondParagraphFailureText : Property
secondParagraphFailureText =
property secondParagraph
("says 'after copying, return to fly and paste your token "
++ "into the prompt.'"
)
<|
Query.children []
>> Expect.all
[ Query.count (Expect.equal 3)
, Query.index 0
>> Query.has
[ text "after copying, return to fly and paste" ]
, Query.index 2
>> Query.has
[ text "your token into the prompt." ]
]
-- button
buttonStyleUnclicked : Property
buttonStyleUnclicked =
property button "display inline and has almost-white border" <|
Query.has
[ tag "span"
, style [ ( "border", "1px solid " ++ almostWhite ) ]
]
buttonStyleClicked : Property
buttonStyleClicked =
property button "has blue border and background" <|
Query.has
[ style
[ ( "background-color", blue )
, ( "border", "1px solid " ++ blue )
]
]
buttonSize : Property
buttonSize =
property button "is 212px wide with 10px padding above and below" <|
Query.has
[ style
[ ( "width", "212px" )
, ( "padding", "10px 0" )
]
]
buttonPosition : Property
buttonPosition =
property button "has 15px margin above and below" <|
Query.has [ style [ ( "margin", "15px 0" ) ] ]
buttonLayout : Property
buttonLayout =
property button "lays out contents horizontally, centering" <|
Query.has
[ style
[ ( "display", "flex" )
, ( "justify-content", "center" )
, ( "align-items", "center" )
]
]
buttonTextPrompt : Property
buttonTextPrompt =
property button "says 'copy token to clipboard'" <|
Query.has [ text "copy token to clipboard" ]
buttonTextClicked : Property
buttonTextClicked =
property button "says 'token copied'" <|
Query.has [ text "token copied" ]
buttonCursorUnclicked : Property
buttonCursorUnclicked =
property button "has pointer cursor" <|
Query.has [ style [ ( "cursor", "pointer" ) ] ]
buttonCursorClicked : Property
buttonCursorClicked =
property button "has default cursor" <|
Query.has [ style [ ( "cursor", "default" ) ] ]
buttonClipboardAttr : Property
buttonClipboardAttr =
property button "has attribute that is readable by clipboard.js" <|
Query.has
[ attribute <|
Attr.attribute
"data-clipboard-text"
authToken
]
buttonClickHandler : Property
buttonClickHandler =
property button "sends CopyToken on click" <|
Event.simulate Event.click
>> Event.expect
(Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyToken
)
-- icon
iconStyle : Property
iconStyle =
property buttonIcon "has clipboard icon" <|
Query.has <|
iconSelector { size = "20px", image = "clippy.svg" }
iconPosition : Property
iconPosition =
property buttonIcon "has margin on the right" <|
Query.has [ style [ ( "margin-right", "5px" ) ] ]
-- TESTS
tests : List Setup -> List Property -> List Test
tests setups properties =
setups
|> List.concatMap
(\setup -> List.map ((|>) setup) properties)
cardTests : List Test
cardTests =
tests allCases cardProperties
titleTests : List Test
titleTests =
tests allCases titleProperties
all : Test
all =
describe "Fly login success page"
[ describe "top bar" <| tests allCases [ topBarProperty ]
, describe "card" cardTests
, describe "title" titleTests
, describe "body"
[ describe "style" <|
tests allCases
[ bodyStyle
, bodyPosition
, bodyLayout
, bodyParagraphPositions
]
, invalidFlyPort |> firstParagraphFailureText
, invalidFlyPort |> secondParagraphErrorText
, whenOnFlySuccessPage |> bodyPendingText
, whenOnFlySuccessPage |> bodyNoButton
, tokenSendSuccess |> firstParagraphSuccessText
, tokenSendSuccess |> secondParagraphSuccessText
]
, describe "button"
[ describe "always" <|
tests [ tokenSendFailed, tokenCopied ]
[ buttonSize
, buttonPosition
, buttonLayout
, buttonClipboardAttr
, firstParagraphFailureText
, secondParagraphFailureText
]
, describe "when token sending failed" <|
tests [ tokenSendFailed ]
[ buttonStyleUnclicked
, buttonClickHandler
, buttonTextPrompt
, iconStyle
, iconPosition
, buttonCursorUnclicked
]
, describe "after copying token" <|
tests [ tokenCopied ]
[ buttonStyleClicked
, buttonTextClicked
, iconStyle
, iconPosition
, buttonCursorClicked
]
, defineHoverBehaviour
{ name = "copy token button"
, setup = steps tokenSendFailed ()
, query = button
, updateFunc = \msg -> Application.update msg >> Tuple.first
, unhoveredSelector =
{ description =
"same background as card"
, selector = [ style [ ( "background-color", darkGrey ) ] ]
}
, mouseEnterMsg =
Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyTokenButtonHover
True
, mouseLeaveMsg =
Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyTokenButtonHover
False
, hoveredSelector =
{ description = "darker background"
, selector =
[ style [ ( "background-color", darkerGrey ) ] ]
}
}
]
]
| 33803 | module FlySuccessTests exposing (all)
import Application.Application as Application
import Application.Msgs as Msgs
import Callback exposing (Callback(..))
import DashboardTests exposing (defineHoverBehaviour, iconSelector)
import Effects
import Expect exposing (Expectation)
import FlySuccess.Msgs
import Html.Attributes as Attr
import Http
import SubPage.Msgs
import Test exposing (..)
import Test.Html.Event as Event
import Test.Html.Query as Query
import Test.Html.Selector
exposing
( attribute
, containing
, id
, style
, tag
, text
)
-- CONSTANTS (might be able to remove this and refer to "configuration"-type
-- files like Colors.elm)
almostWhite : String
almostWhite =
"#e6e7e8"
darkGrey : String
darkGrey =
"#323030"
darkerGrey : String
darkerGrey =
"#242424"
blue : String
blue =
"#196ac8"
authToken : String
authToken =
"<PASSWORD>"
-- SETUPS (i dunno, maybe use fuzzers?)
type alias SetupSteps =
() -> Application.Model
type alias Setup =
( String, SetupSteps )
setupDesc : Setup -> String
setupDesc =
Tuple.first
steps : Setup -> SetupSteps
steps =
Tuple.second
setup : String -> SetupSteps -> Setup
setup =
(,)
whenOnFlySuccessPage : Setup
whenOnFlySuccessPage =
setup "when on fly success page"
(\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = ""
, csrfToken = ""
, authToken = authToken
, pipelineRunningKeyframes = ""
}
{ href = ""
, host = ""
, hostname = ""
, protocol = ""
, origin = ""
, port_ = ""
, pathname = "/fly_success"
, search = "?fly_port=1234"
, hash = ""
, username = ""
, password = ""
}
|> Tuple.first
)
invalidFlyPort : Setup
invalidFlyPort =
setup "with invalid fly port"
(\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = ""
, csrfToken = ""
, authToken = authToken
, pipelineRunningKeyframes = ""
}
{ href = ""
, host = ""
, hostname = ""
, protocol = ""
, origin = ""
, port_ = ""
, pathname = "/fly_success"
, search = "?fly_port=banana"
, hash = ""
, username = ""
, password = ""
}
|> Tuple.first
)
tokenSendSuccess : Setup
tokenSendSuccess =
setup "when token successfully sent to fly"
(steps whenOnFlySuccessPage
>> Application.handleCallback
(Effects.SubPage 1)
(TokenSentToFly (Ok ()))
>> Tuple.first
)
tokenSendFailed : Setup
tokenSendFailed =
setup "when token failed to send to fly"
(steps whenOnFlySuccessPage
>> Application.handleCallback
(Effects.SubPage 1)
(TokenSentToFly (Err Http.NetworkError))
>> Tuple.first
)
tokenCopied : Setup
tokenCopied =
setup "when token copied to clipboard"
(steps tokenSendFailed
>> Application.update
(Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyToken
)
>> Tuple.first
)
allCases : List Setup
allCases =
[ whenOnFlySuccessPage
, invalidFlyPort
, tokenSendFailed
, tokenSendSuccess
]
-- QUERIES
type alias Query =
Application.Model -> Query.Single Msgs.Msg
topBar : Query
topBar =
Application.view
>> Query.fromHtml
>> Query.find [ id "top-bar-app" ]
successCard : Query
successCard =
Application.view
>> Query.fromHtml
>> Query.find [ id "success-card" ]
title : Query
title =
successCard >> Query.find [ id "success-card-title" ]
body : Query
body =
successCard >> Query.find [ id "success-card-body" ]
firstParagraph : Query
firstParagraph =
successCard
>> Query.find [ id "success-card-body" ]
>> Query.find [ id "first-paragraph" ]
secondParagraph : Query
secondParagraph =
successCard
>> Query.find [ id "success-card-body" ]
>> Query.find [ id "second-paragraph" ]
button : Query
button =
body >> Query.find [ id "copy-token" ]
buttonIcon : Query
buttonIcon =
body
>> Query.find [ id "copy-token" ]
>> Query.find [ id "copy-icon" ]
-- PROPERTIES
type alias Assertion =
Query.Single Msgs.Msg -> Expectation
type alias Property =
Setup -> Test
property : Query -> String -> Assertion -> Property
property query description assertion setup =
test (setupDesc setup ++ ", " ++ description) <|
steps setup
>> query
>> assertion
-- top bar
topBarProperty : Property
topBarProperty =
property topBar "has bold font" <|
Query.has [ style [ ( "font-weight", "700" ) ] ]
-- card
cardProperties : List Property
cardProperties =
[ cardBackground
, cardSize
, cardPosition
, cardLayout
, cardStyle
]
cardBackground : Property
cardBackground =
property successCard "card has dark grey background" <|
Query.has [ style [ ( "background-color", darkGrey ) ] ]
cardSize : Property
cardSize =
property successCard "is 330px wide with 30px padding" <|
Query.has
[ style
[ ( "padding", "30px" )
, ( "width", "330px" )
]
]
cardPosition : Property
cardPosition =
property successCard "is centered 50px from the top of the document" <|
Query.has [ style [ ( "margin", "50px auto" ) ] ]
cardLayout : Property
cardLayout =
property successCard "lays out contents vertically and center aligned" <|
Query.has
[ style
[ ( "display", "flex" )
, ( "flex-direction", "column" )
, ( "align-items", "center" )
, ( "text-align", "center" )
]
]
cardStyle : Property
cardStyle =
property successCard "has smooth, non-bold font" <|
Query.has
[ style
[ ( "-webkit-font-smoothing", "antialiased" )
, ( "font-weight", "400" )
]
]
-- title
titleText : Property
titleText =
property title "has success text" <|
Query.has [ text "login successful!" ]
titleStyle : Property
titleStyle =
property title "has bold 18px font" <|
Query.has
[ style
[ ( "font-size", "18px" )
, ( "font-weight", "700" )
]
]
titleProperties : List Property
titleProperties =
[ titleText
, titleStyle
]
-- body
bodyPendingText : Property
bodyPendingText =
property body "has pending text" <|
Query.has [ text "sending token to fly..." ]
bodyNoButton : Property
bodyNoButton =
property body "has no 'copy token' button" <|
Query.hasNot [ id "copy-token" ]
bodyStyle : Property
bodyStyle =
property body "has 14px font" <|
Query.has [ style [ ( "font-size", "14px" ) ] ]
bodyPosition : Property
bodyPosition =
property body "has 10px margin above and below" <|
Query.has [ style [ ( "margin", "10px 0" ) ] ]
bodyLayout : Property
bodyLayout =
property body "lays out contents vertically, centering horizontally" <|
Query.has
[ style
[ ( "display", "flex" )
, ( "flex-direction", "column" )
, ( "align-items", "center" )
]
]
bodyParagraphPositions : Property
bodyParagraphPositions =
property body "paragraphs have 5px margin above and below" <|
Query.findAll [ tag "p" ]
>> Query.each
(Query.has [ style [ ( "margin", "5px 0" ) ] ])
-- body on invalid fly port
secondParagraphErrorText : Property
secondParagraphErrorText =
property secondParagraph "error message describes invalid fly port" <|
Query.children []
>> Expect.all
[ Query.count (Expect.equal 3)
, Query.index 0
>> Query.has
[ text "could not find a valid fly port to send to." ]
, Query.index 2
>> Query.has
[ text "maybe your URL is broken?" ]
]
-- body on successfully sending token
firstParagraphSuccessText : Property
firstParagraphSuccessText =
property firstParagraph "says 'your token has been transferred to fly'" <|
Query.has [ text "your token has been transferred to fly." ]
secondParagraphSuccessText : Property
secondParagraphSuccessText =
property secondParagraph "says 'you may now close this window'" <|
Query.has [ text "you may now close this window." ]
-- body on failing to send token
firstParagraphFailureText : Property
firstParagraphFailureText =
property firstParagraph
"says 'however, your token could not be sent to fly.'"
<|
Query.children []
>> Expect.all
[ Query.count (Expect.equal 3)
, Query.index 0
>> Query.has
[ text "however, your token could not be" ]
, Query.index 2 >> Query.has [ text "sent to fly." ]
]
secondParagraphFailureText : Property
secondParagraphFailureText =
property secondParagraph
("says 'after copying, return to fly and paste your token "
++ "into the prompt.'"
)
<|
Query.children []
>> Expect.all
[ Query.count (Expect.equal 3)
, Query.index 0
>> Query.has
[ text "after copying, return to fly and paste" ]
, Query.index 2
>> Query.has
[ text "your token into the prompt." ]
]
-- button
buttonStyleUnclicked : Property
buttonStyleUnclicked =
property button "display inline and has almost-white border" <|
Query.has
[ tag "span"
, style [ ( "border", "1px solid " ++ almostWhite ) ]
]
buttonStyleClicked : Property
buttonStyleClicked =
property button "has blue border and background" <|
Query.has
[ style
[ ( "background-color", blue )
, ( "border", "1px solid " ++ blue )
]
]
buttonSize : Property
buttonSize =
property button "is 212px wide with 10px padding above and below" <|
Query.has
[ style
[ ( "width", "212px" )
, ( "padding", "10px 0" )
]
]
buttonPosition : Property
buttonPosition =
property button "has 15px margin above and below" <|
Query.has [ style [ ( "margin", "15px 0" ) ] ]
buttonLayout : Property
buttonLayout =
property button "lays out contents horizontally, centering" <|
Query.has
[ style
[ ( "display", "flex" )
, ( "justify-content", "center" )
, ( "align-items", "center" )
]
]
buttonTextPrompt : Property
buttonTextPrompt =
property button "says 'copy token to clipboard'" <|
Query.has [ text "copy token to clipboard" ]
buttonTextClicked : Property
buttonTextClicked =
property button "says 'token copied'" <|
Query.has [ text "token copied" ]
buttonCursorUnclicked : Property
buttonCursorUnclicked =
property button "has pointer cursor" <|
Query.has [ style [ ( "cursor", "pointer" ) ] ]
buttonCursorClicked : Property
buttonCursorClicked =
property button "has default cursor" <|
Query.has [ style [ ( "cursor", "default" ) ] ]
buttonClipboardAttr : Property
buttonClipboardAttr =
property button "has attribute that is readable by clipboard.js" <|
Query.has
[ attribute <|
Attr.attribute
"data-clipboard-text"
authToken
]
buttonClickHandler : Property
buttonClickHandler =
property button "sends CopyToken on click" <|
Event.simulate Event.click
>> Event.expect
(Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyToken
)
-- icon
iconStyle : Property
iconStyle =
property buttonIcon "has clipboard icon" <|
Query.has <|
iconSelector { size = "20px", image = "clippy.svg" }
iconPosition : Property
iconPosition =
property buttonIcon "has margin on the right" <|
Query.has [ style [ ( "margin-right", "5px" ) ] ]
-- TESTS
tests : List Setup -> List Property -> List Test
tests setups properties =
setups
|> List.concatMap
(\setup -> List.map ((|>) setup) properties)
cardTests : List Test
cardTests =
tests allCases cardProperties
titleTests : List Test
titleTests =
tests allCases titleProperties
all : Test
all =
describe "Fly login success page"
[ describe "top bar" <| tests allCases [ topBarProperty ]
, describe "card" cardTests
, describe "title" titleTests
, describe "body"
[ describe "style" <|
tests allCases
[ bodyStyle
, bodyPosition
, bodyLayout
, bodyParagraphPositions
]
, invalidFlyPort |> firstParagraphFailureText
, invalidFlyPort |> secondParagraphErrorText
, whenOnFlySuccessPage |> bodyPendingText
, whenOnFlySuccessPage |> bodyNoButton
, tokenSendSuccess |> firstParagraphSuccessText
, tokenSendSuccess |> secondParagraphSuccessText
]
, describe "button"
[ describe "always" <|
tests [ tokenSendFailed, tokenCopied ]
[ buttonSize
, buttonPosition
, buttonLayout
, buttonClipboardAttr
, firstParagraphFailureText
, secondParagraphFailureText
]
, describe "when token sending failed" <|
tests [ tokenSendFailed ]
[ buttonStyleUnclicked
, buttonClickHandler
, buttonTextPrompt
, iconStyle
, iconPosition
, buttonCursorUnclicked
]
, describe "after copying token" <|
tests [ tokenCopied ]
[ buttonStyleClicked
, buttonTextClicked
, iconStyle
, iconPosition
, buttonCursorClicked
]
, defineHoverBehaviour
{ name = "copy token button"
, setup = steps tokenSendFailed ()
, query = button
, updateFunc = \msg -> Application.update msg >> Tuple.first
, unhoveredSelector =
{ description =
"same background as card"
, selector = [ style [ ( "background-color", darkGrey ) ] ]
}
, mouseEnterMsg =
Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyTokenButtonHover
True
, mouseLeaveMsg =
Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyTokenButtonHover
False
, hoveredSelector =
{ description = "darker background"
, selector =
[ style [ ( "background-color", darkerGrey ) ] ]
}
}
]
]
| true | module FlySuccessTests exposing (all)
import Application.Application as Application
import Application.Msgs as Msgs
import Callback exposing (Callback(..))
import DashboardTests exposing (defineHoverBehaviour, iconSelector)
import Effects
import Expect exposing (Expectation)
import FlySuccess.Msgs
import Html.Attributes as Attr
import Http
import SubPage.Msgs
import Test exposing (..)
import Test.Html.Event as Event
import Test.Html.Query as Query
import Test.Html.Selector
exposing
( attribute
, containing
, id
, style
, tag
, text
)
-- CONSTANTS (might be able to remove this and refer to "configuration"-type
-- files like Colors.elm)
almostWhite : String
almostWhite =
"#e6e7e8"
darkGrey : String
darkGrey =
"#323030"
darkerGrey : String
darkerGrey =
"#242424"
blue : String
blue =
"#196ac8"
authToken : String
authToken =
"PI:PASSWORD:<PASSWORD>END_PI"
-- SETUPS (i dunno, maybe use fuzzers?)
type alias SetupSteps =
() -> Application.Model
type alias Setup =
( String, SetupSteps )
setupDesc : Setup -> String
setupDesc =
Tuple.first
steps : Setup -> SetupSteps
steps =
Tuple.second
setup : String -> SetupSteps -> Setup
setup =
(,)
whenOnFlySuccessPage : Setup
whenOnFlySuccessPage =
setup "when on fly success page"
(\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = ""
, csrfToken = ""
, authToken = authToken
, pipelineRunningKeyframes = ""
}
{ href = ""
, host = ""
, hostname = ""
, protocol = ""
, origin = ""
, port_ = ""
, pathname = "/fly_success"
, search = "?fly_port=1234"
, hash = ""
, username = ""
, password = ""
}
|> Tuple.first
)
invalidFlyPort : Setup
invalidFlyPort =
setup "with invalid fly port"
(\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = ""
, csrfToken = ""
, authToken = authToken
, pipelineRunningKeyframes = ""
}
{ href = ""
, host = ""
, hostname = ""
, protocol = ""
, origin = ""
, port_ = ""
, pathname = "/fly_success"
, search = "?fly_port=banana"
, hash = ""
, username = ""
, password = ""
}
|> Tuple.first
)
tokenSendSuccess : Setup
tokenSendSuccess =
setup "when token successfully sent to fly"
(steps whenOnFlySuccessPage
>> Application.handleCallback
(Effects.SubPage 1)
(TokenSentToFly (Ok ()))
>> Tuple.first
)
tokenSendFailed : Setup
tokenSendFailed =
setup "when token failed to send to fly"
(steps whenOnFlySuccessPage
>> Application.handleCallback
(Effects.SubPage 1)
(TokenSentToFly (Err Http.NetworkError))
>> Tuple.first
)
tokenCopied : Setup
tokenCopied =
setup "when token copied to clipboard"
(steps tokenSendFailed
>> Application.update
(Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyToken
)
>> Tuple.first
)
allCases : List Setup
allCases =
[ whenOnFlySuccessPage
, invalidFlyPort
, tokenSendFailed
, tokenSendSuccess
]
-- QUERIES
type alias Query =
Application.Model -> Query.Single Msgs.Msg
topBar : Query
topBar =
Application.view
>> Query.fromHtml
>> Query.find [ id "top-bar-app" ]
successCard : Query
successCard =
Application.view
>> Query.fromHtml
>> Query.find [ id "success-card" ]
title : Query
title =
successCard >> Query.find [ id "success-card-title" ]
body : Query
body =
successCard >> Query.find [ id "success-card-body" ]
firstParagraph : Query
firstParagraph =
successCard
>> Query.find [ id "success-card-body" ]
>> Query.find [ id "first-paragraph" ]
secondParagraph : Query
secondParagraph =
successCard
>> Query.find [ id "success-card-body" ]
>> Query.find [ id "second-paragraph" ]
button : Query
button =
body >> Query.find [ id "copy-token" ]
buttonIcon : Query
buttonIcon =
body
>> Query.find [ id "copy-token" ]
>> Query.find [ id "copy-icon" ]
-- PROPERTIES
type alias Assertion =
Query.Single Msgs.Msg -> Expectation
type alias Property =
Setup -> Test
property : Query -> String -> Assertion -> Property
property query description assertion setup =
test (setupDesc setup ++ ", " ++ description) <|
steps setup
>> query
>> assertion
-- top bar
topBarProperty : Property
topBarProperty =
property topBar "has bold font" <|
Query.has [ style [ ( "font-weight", "700" ) ] ]
-- card
cardProperties : List Property
cardProperties =
[ cardBackground
, cardSize
, cardPosition
, cardLayout
, cardStyle
]
cardBackground : Property
cardBackground =
property successCard "card has dark grey background" <|
Query.has [ style [ ( "background-color", darkGrey ) ] ]
cardSize : Property
cardSize =
property successCard "is 330px wide with 30px padding" <|
Query.has
[ style
[ ( "padding", "30px" )
, ( "width", "330px" )
]
]
cardPosition : Property
cardPosition =
property successCard "is centered 50px from the top of the document" <|
Query.has [ style [ ( "margin", "50px auto" ) ] ]
cardLayout : Property
cardLayout =
property successCard "lays out contents vertically and center aligned" <|
Query.has
[ style
[ ( "display", "flex" )
, ( "flex-direction", "column" )
, ( "align-items", "center" )
, ( "text-align", "center" )
]
]
cardStyle : Property
cardStyle =
property successCard "has smooth, non-bold font" <|
Query.has
[ style
[ ( "-webkit-font-smoothing", "antialiased" )
, ( "font-weight", "400" )
]
]
-- title
titleText : Property
titleText =
property title "has success text" <|
Query.has [ text "login successful!" ]
titleStyle : Property
titleStyle =
property title "has bold 18px font" <|
Query.has
[ style
[ ( "font-size", "18px" )
, ( "font-weight", "700" )
]
]
titleProperties : List Property
titleProperties =
[ titleText
, titleStyle
]
-- body
bodyPendingText : Property
bodyPendingText =
property body "has pending text" <|
Query.has [ text "sending token to fly..." ]
bodyNoButton : Property
bodyNoButton =
property body "has no 'copy token' button" <|
Query.hasNot [ id "copy-token" ]
bodyStyle : Property
bodyStyle =
property body "has 14px font" <|
Query.has [ style [ ( "font-size", "14px" ) ] ]
bodyPosition : Property
bodyPosition =
property body "has 10px margin above and below" <|
Query.has [ style [ ( "margin", "10px 0" ) ] ]
bodyLayout : Property
bodyLayout =
property body "lays out contents vertically, centering horizontally" <|
Query.has
[ style
[ ( "display", "flex" )
, ( "flex-direction", "column" )
, ( "align-items", "center" )
]
]
bodyParagraphPositions : Property
bodyParagraphPositions =
property body "paragraphs have 5px margin above and below" <|
Query.findAll [ tag "p" ]
>> Query.each
(Query.has [ style [ ( "margin", "5px 0" ) ] ])
-- body on invalid fly port
secondParagraphErrorText : Property
secondParagraphErrorText =
property secondParagraph "error message describes invalid fly port" <|
Query.children []
>> Expect.all
[ Query.count (Expect.equal 3)
, Query.index 0
>> Query.has
[ text "could not find a valid fly port to send to." ]
, Query.index 2
>> Query.has
[ text "maybe your URL is broken?" ]
]
-- body on successfully sending token
firstParagraphSuccessText : Property
firstParagraphSuccessText =
property firstParagraph "says 'your token has been transferred to fly'" <|
Query.has [ text "your token has been transferred to fly." ]
secondParagraphSuccessText : Property
secondParagraphSuccessText =
property secondParagraph "says 'you may now close this window'" <|
Query.has [ text "you may now close this window." ]
-- body on failing to send token
firstParagraphFailureText : Property
firstParagraphFailureText =
property firstParagraph
"says 'however, your token could not be sent to fly.'"
<|
Query.children []
>> Expect.all
[ Query.count (Expect.equal 3)
, Query.index 0
>> Query.has
[ text "however, your token could not be" ]
, Query.index 2 >> Query.has [ text "sent to fly." ]
]
secondParagraphFailureText : Property
secondParagraphFailureText =
property secondParagraph
("says 'after copying, return to fly and paste your token "
++ "into the prompt.'"
)
<|
Query.children []
>> Expect.all
[ Query.count (Expect.equal 3)
, Query.index 0
>> Query.has
[ text "after copying, return to fly and paste" ]
, Query.index 2
>> Query.has
[ text "your token into the prompt." ]
]
-- button
buttonStyleUnclicked : Property
buttonStyleUnclicked =
property button "display inline and has almost-white border" <|
Query.has
[ tag "span"
, style [ ( "border", "1px solid " ++ almostWhite ) ]
]
buttonStyleClicked : Property
buttonStyleClicked =
property button "has blue border and background" <|
Query.has
[ style
[ ( "background-color", blue )
, ( "border", "1px solid " ++ blue )
]
]
buttonSize : Property
buttonSize =
property button "is 212px wide with 10px padding above and below" <|
Query.has
[ style
[ ( "width", "212px" )
, ( "padding", "10px 0" )
]
]
buttonPosition : Property
buttonPosition =
property button "has 15px margin above and below" <|
Query.has [ style [ ( "margin", "15px 0" ) ] ]
buttonLayout : Property
buttonLayout =
property button "lays out contents horizontally, centering" <|
Query.has
[ style
[ ( "display", "flex" )
, ( "justify-content", "center" )
, ( "align-items", "center" )
]
]
buttonTextPrompt : Property
buttonTextPrompt =
property button "says 'copy token to clipboard'" <|
Query.has [ text "copy token to clipboard" ]
buttonTextClicked : Property
buttonTextClicked =
property button "says 'token copied'" <|
Query.has [ text "token copied" ]
buttonCursorUnclicked : Property
buttonCursorUnclicked =
property button "has pointer cursor" <|
Query.has [ style [ ( "cursor", "pointer" ) ] ]
buttonCursorClicked : Property
buttonCursorClicked =
property button "has default cursor" <|
Query.has [ style [ ( "cursor", "default" ) ] ]
buttonClipboardAttr : Property
buttonClipboardAttr =
property button "has attribute that is readable by clipboard.js" <|
Query.has
[ attribute <|
Attr.attribute
"data-clipboard-text"
authToken
]
buttonClickHandler : Property
buttonClickHandler =
property button "sends CopyToken on click" <|
Event.simulate Event.click
>> Event.expect
(Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyToken
)
-- icon
iconStyle : Property
iconStyle =
property buttonIcon "has clipboard icon" <|
Query.has <|
iconSelector { size = "20px", image = "clippy.svg" }
iconPosition : Property
iconPosition =
property buttonIcon "has margin on the right" <|
Query.has [ style [ ( "margin-right", "5px" ) ] ]
-- TESTS
tests : List Setup -> List Property -> List Test
tests setups properties =
setups
|> List.concatMap
(\setup -> List.map ((|>) setup) properties)
cardTests : List Test
cardTests =
tests allCases cardProperties
titleTests : List Test
titleTests =
tests allCases titleProperties
all : Test
all =
describe "Fly login success page"
[ describe "top bar" <| tests allCases [ topBarProperty ]
, describe "card" cardTests
, describe "title" titleTests
, describe "body"
[ describe "style" <|
tests allCases
[ bodyStyle
, bodyPosition
, bodyLayout
, bodyParagraphPositions
]
, invalidFlyPort |> firstParagraphFailureText
, invalidFlyPort |> secondParagraphErrorText
, whenOnFlySuccessPage |> bodyPendingText
, whenOnFlySuccessPage |> bodyNoButton
, tokenSendSuccess |> firstParagraphSuccessText
, tokenSendSuccess |> secondParagraphSuccessText
]
, describe "button"
[ describe "always" <|
tests [ tokenSendFailed, tokenCopied ]
[ buttonSize
, buttonPosition
, buttonLayout
, buttonClipboardAttr
, firstParagraphFailureText
, secondParagraphFailureText
]
, describe "when token sending failed" <|
tests [ tokenSendFailed ]
[ buttonStyleUnclicked
, buttonClickHandler
, buttonTextPrompt
, iconStyle
, iconPosition
, buttonCursorUnclicked
]
, describe "after copying token" <|
tests [ tokenCopied ]
[ buttonStyleClicked
, buttonTextClicked
, iconStyle
, iconPosition
, buttonCursorClicked
]
, defineHoverBehaviour
{ name = "copy token button"
, setup = steps tokenSendFailed ()
, query = button
, updateFunc = \msg -> Application.update msg >> Tuple.first
, unhoveredSelector =
{ description =
"same background as card"
, selector = [ style [ ( "background-color", darkGrey ) ] ]
}
, mouseEnterMsg =
Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyTokenButtonHover
True
, mouseLeaveMsg =
Msgs.SubMsg 1 <|
SubPage.Msgs.FlySuccessMsg <|
FlySuccess.Msgs.CopyTokenButtonHover
False
, hoveredSelector =
{ description = "darker background"
, selector =
[ style [ ( "background-color", darkerGrey ) ] ]
}
}
]
]
| elm |
[
{
"context": "est\n { method = \"setItem\"\n , key = \"likedItems\"\n , value = Just <| encodeLikedItemsForLoc",
"end": 10290,
"score": 0.8212141395,
"start": 10280,
"tag": "KEY",
"value": "likedItems"
}
] | assets/src/Main.elm | mikeonslow/elm-phoenix-example | 4 | port module Main exposing (Category, Item, Model, Msg(..), Portfolio, categoryDecoder, getPortfolioFromChannel, getSelectedCategoryId, getSelectedItem, init, initialModel, itemDecoder, main, portfolioDecoder, subscriptions, update, view, viewCategoryButton, viewCategoryNavbar, viewError, viewItem, viewItems, viewSelectedItem)
import Browser
import Html exposing (..)
import Html.Attributes exposing (attribute, class, classList, href, src, style, target, type_, width)
import Html.Events exposing (onClick)
import Http
import Json.Decode as Decode exposing (Decoder, Value)
import Json.Decode.Pipeline as Pipeline exposing (optional, required)
import Json.Encode as Encode
import Set
{--Model
The `initialModel` function initializes our `Model`. This function is called in `init` and outputs a `Model`
--}
initialModel : List LikedItem -> Model
initialModel likedItems =
{ errorMessage = ""
, portfolio =
{ categories = []
, items = []
}
, selectedCategoryId = Nothing
, selectedItemId = Nothing
, likedItems = likedItems
}
type alias Model =
{ errorMessage : String
, portfolio : Portfolio
, selectedCategoryId : Maybe Int
, selectedItemId : Maybe Int
, likedItems : List LikedItem
}
type alias Portfolio =
{ categories : List Category
, items : List Item
}
type alias Category =
{ id : Int, label : String }
type alias Item =
{ id : Int
, title : String
, categoryId : Int
, imageUrl : String
, linkUrl : String
, description : String
, overlayColor : String
, likes : Int
}
type alias LikedItem =
( Int, Int )
type alias LocalStorageRequest =
{ method : String
, key : String
, value : Maybe Encode.Value
}
type alias LocalStorageResponse =
{ method : String
, payload : Encode.Value
}
type alias ChannelRequest =
{ event : String
, payload : Encode.Value
}
type alias ChannelResponse =
{ code : Int
, response : Portfolio
}
{--View
The function `view` renders an Html element using our application model.
Note that the type signature is Model -> Html Msg. This means that this function transforms an argument
of `Model` into an `Html` element that, in turn produces messages tagged with `Msg`.
We will see this when we introduce some interaction.
--}
view : Model -> Html Msg
view model =
let
portfolio =
model.portfolio
selectedCategoryId =
getSelectedCategoryId model
selectedItem =
getSelectedItem model selectedCategoryId
in
div [ class "container" ]
[ div [ class "row" ]
[ div
[ class "col"
]
[ br [] [] ]
]
, div [ class "row" ]
[ div
[ class "col"
]
[ h1 [] [ text "Elmfolio" ] ]
]
, viewCategoryNavbar portfolio selectedCategoryId
, viewSelectedItem selectedItem
, viewItems model selectedCategoryId selectedItem
]
viewCategoryNavbar : Portfolio -> Int -> Html Msg
viewCategoryNavbar { categories } selectedCategoryId =
div [ class "row" ]
[ div
[ class "col" ]
[ div [ class "nav-category" ]
(List.map (viewCategoryButton selectedCategoryId) categories)
]
]
viewCategoryButton : Int -> Category -> Html Msg
viewCategoryButton selectedCategoryId category =
let
categorySelected =
selectedCategoryId == category.id
buttonsBaseAttrs =
[ type_ "button", classes ]
buttonOnClick =
if categorySelected then
[]
else
[ onClick (CategoryClicked category.id) ]
buttonAttrs =
buttonsBaseAttrs ++ buttonOnClick
classes =
classList
[ ( "btn btn-category", True )
, ( "btn-primary", categorySelected )
, ( "btn-secondary", not categorySelected )
]
in
button buttonAttrs [ text category.label ]
viewItems : Model -> Int -> Maybe Item -> Html Msg
viewItems { portfolio, errorMessage, likedItems } selectedCategoryId selectedItemId =
let
filteredItems =
portfolio.items |> List.filter (\i -> i.categoryId == selectedCategoryId) |> List.map (viewItem likedItems)
contents =
if String.isEmpty errorMessage then
div [ class "row items-container" ]
filteredItems
else
viewError errorMessage
in
contents
viewItem : List LikedItem -> Item -> Html Msg
viewItem likedItems item =
let
iconset =
if List.member ( item.categoryId, item.id ) likedItems then
"fas"
else
"far"
in
div
[ class "col-4 item-panel" ]
[ span [ style "display" "inline-blockw" ]
[ img
[ src item.imageUrl
, class "img-fluid"
, onClick (ItemClicked item.id)
]
[]
, span [ class "badge badge-info like-box", onClick (ToggleItemLiked item.id) ]
[ i [ class <| iconset ++ " fa-heart" ] []
, text <| " " ++ String.fromInt item.likes
]
]
]
viewSelectedItem : Maybe Item -> Html msg
viewSelectedItem item =
let
contents =
case item of
Nothing ->
[]
Just detail ->
[ div [ class "col-6" ]
[ img [ src detail.imageUrl, class "img-fluid" ] [] ]
, div [ class "col-6" ]
[ h3 [] [ text detail.title ]
, hr [] []
, text detail.description
, br [] []
, br [] []
, a [ href detail.linkUrl, target "_blank" ] [ text detail.linkUrl ]
]
]
in
div [ class "row selected-item-container" ]
contents
viewError : String -> Html Msg
viewError error =
div [ class "alert alert-danger", attribute "role" "alert" ]
[ strong []
[ text error ]
]
{--Update--
The `update` function will be called by `Browser.element` each time a message (`Msg`) is received.
This update function responds to messages (`Msg`), updating the model and returning commands as needed.
--}
type Msg
= HandleChannelResponse ChannelResponse
| HandleLocalStorageResponse LocalStorageResponse
| CategoryClicked Int
| ItemClicked Int
| ToggleItemLiked Int
| None
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
HandleChannelResponse channelResponse ->
let
{ code, response } =
channelResponse
updatedModel =
case ( code, response ) of
( 200, portfolio ) ->
{ model
| portfolio = portfolio
, selectedCategoryId = Just <| getSelectedCategoryId model
}
_ ->
model
in
( updatedModel, Cmd.none )
HandleLocalStorageResponse channelResponse ->
let
updatedModel =
model
in
( updatedModel, Cmd.none )
CategoryClicked categoryId ->
let
updatedModel =
{ model
| selectedCategoryId = Just categoryId
, selectedItemId = Nothing
}
in
( updatedModel, Cmd.none )
ItemClicked itemId ->
let
updatedModel =
{ model
| selectedItemId = Just itemId
}
in
( updatedModel, Cmd.none )
ToggleItemLiked itemId ->
let
selectedCategoryId =
model.selectedCategoryId |> Maybe.withDefault 0
likedItem =
( selectedCategoryId, itemId )
itemIsLiked =
model.likedItems
|> List.member
( selectedCategoryId, itemId )
( toggleCmd, updater ) =
if itemIsLiked then
( unlikeItemChannelRequest likedItem, removeLikedItem )
else
( likeItemChannelRequest likedItem, addLikedItem )
addLikedItem =
( selectedCategoryId, itemId )
:: model.likedItems
removeLikedItem =
model.likedItems
|> List.filter
(\( category, id ) ->
not (selectedCategoryId == category && itemId == id)
)
updatedModel =
case selectedCategoryId of
0 ->
model
_ ->
{ model | likedItems = updater }
in
( updatedModel
, Cmd.batch
[ toggleCmd
, saveLikesToLocalStorage updatedModel.likedItems
]
)
None ->
( model, Cmd.none )
getPortfolioFromChannel =
channelEventRequest { event = "get_items", payload = Encode.null }
likeItemChannelRequest likedItem =
channelEventRequest
{ event = "like_item"
, payload = encodeLikedItem likedItem
}
unlikeItemChannelRequest likedItem =
channelEventRequest
{ event = "unlike_item"
, payload = encodeLikedItem likedItem
}
saveLikesToLocalStorage likedItems =
localStorageRequest
{ method = "setItem"
, key = "likedItems"
, value = Just <| encodeLikedItemsForLocalStorage likedItems
}
-- JSON Decoders
portfolioDecoder : Decoder Portfolio
portfolioDecoder =
Decode.succeed Portfolio
|> required "categories" (Decode.list categoryDecoder)
|> required "items" (Decode.list itemDecoder)
categoryDecoder : Decoder Category
categoryDecoder =
Decode.succeed Category
|> required "id" Decode.int
|> required "label" Decode.string
itemDecoder : Decoder Item
itemDecoder =
Decode.succeed Item
|> required "id" Decode.int
|> required "title" Decode.string
|> required "categoryId" Decode.int
|> required "imageUrl" Decode.string
|> required "linkUrl" Decode.string
|> required "description" Decode.string
|> required "overlayColor" Decode.string
|> required "likes" Decode.int
-- JSON Encoders --
encodeLikedItems : List LikedItem -> Encode.Value
encodeLikedItems likedItems =
Encode.list encodeLikedItem likedItems
encodeLikedItem : LikedItem -> Encode.Value
encodeLikedItem ( categoryId, itemId ) =
Encode.object
[ ( "categoryId", Encode.int categoryId )
, ( "itemId", Encode.int itemId )
]
encodeLikedItemsForLocalStorage : List LikedItem -> Encode.Value
encodeLikedItemsForLocalStorage likedItems =
Encode.list encodeLikedItemForLocalStorage likedItems
encodeLikedItemForLocalStorage : LikedItem -> Encode.Value
encodeLikedItemForLocalStorage ( categoryId, itemId ) =
Encode.list Encode.int [ categoryId, itemId ]
-- Helpers --
receiveChannelEventReponse response =
HandleChannelResponse response
getSelectedCategoryId : Model -> Int
getSelectedCategoryId model =
model.selectedCategoryId
|> Maybe.withDefault (getFirstCategory model)
getSelectedItem : Model -> Int -> Maybe Item
getSelectedItem { portfolio, selectedItemId } selectedCategoryId =
case selectedItemId of
Nothing ->
Nothing
Just id ->
portfolio.items
|> List.filter (\i -> i.id == id && i.categoryId == selectedCategoryId)
|> List.head
getFirstCategory { portfolio } =
portfolio.categories
|> List.head
|> Maybe.map .id
|> Maybe.withDefault 1
-- Ports
-- Generic port for an outbound channel request
port channelEventRequest : ChannelRequest -> Cmd msg
-- Generic port for an outbound channel response
port channelEventResponse : (ChannelResponse -> msg) -> Sub msg
-- Generic port for an outbound request to update localStorage
port localStorageRequest : LocalStorageRequest -> Cmd msg
{--Subscriptions
In Elm, using subscriptions is how your application can listen for external input. Some examples are:
- Keyboard events
- Mouse movements
- Browser locations changes
- Websocket events
In this application, we don't have a need for any active subscriptions so we add in Sub.none
--}
-- Inbound port messages are handled via `subscriptions`
subscriptions _ =
Sub.batch [ channelEventResponse receiveChannelEventReponse ]
{--Program setup and initialization--}
{--
The `main` function is the entry point for our app which means it's the first thing that is run
--}
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
{--The `init` function is run by `main` upon application startup and allows us to set
our app's initial state as well as scheduling any commands we'd like to run after the app starts
up. For now, we don't need to run any commands so we'll use Cmd.none here.
--}
init : List LikedItem -> ( Model, Cmd Msg )
init likedItems =
( initialModel likedItems
, getPortfolioFromChannel
)
| 32113 | port module Main exposing (Category, Item, Model, Msg(..), Portfolio, categoryDecoder, getPortfolioFromChannel, getSelectedCategoryId, getSelectedItem, init, initialModel, itemDecoder, main, portfolioDecoder, subscriptions, update, view, viewCategoryButton, viewCategoryNavbar, viewError, viewItem, viewItems, viewSelectedItem)
import Browser
import Html exposing (..)
import Html.Attributes exposing (attribute, class, classList, href, src, style, target, type_, width)
import Html.Events exposing (onClick)
import Http
import Json.Decode as Decode exposing (Decoder, Value)
import Json.Decode.Pipeline as Pipeline exposing (optional, required)
import Json.Encode as Encode
import Set
{--Model
The `initialModel` function initializes our `Model`. This function is called in `init` and outputs a `Model`
--}
initialModel : List LikedItem -> Model
initialModel likedItems =
{ errorMessage = ""
, portfolio =
{ categories = []
, items = []
}
, selectedCategoryId = Nothing
, selectedItemId = Nothing
, likedItems = likedItems
}
type alias Model =
{ errorMessage : String
, portfolio : Portfolio
, selectedCategoryId : Maybe Int
, selectedItemId : Maybe Int
, likedItems : List LikedItem
}
type alias Portfolio =
{ categories : List Category
, items : List Item
}
type alias Category =
{ id : Int, label : String }
type alias Item =
{ id : Int
, title : String
, categoryId : Int
, imageUrl : String
, linkUrl : String
, description : String
, overlayColor : String
, likes : Int
}
type alias LikedItem =
( Int, Int )
type alias LocalStorageRequest =
{ method : String
, key : String
, value : Maybe Encode.Value
}
type alias LocalStorageResponse =
{ method : String
, payload : Encode.Value
}
type alias ChannelRequest =
{ event : String
, payload : Encode.Value
}
type alias ChannelResponse =
{ code : Int
, response : Portfolio
}
{--View
The function `view` renders an Html element using our application model.
Note that the type signature is Model -> Html Msg. This means that this function transforms an argument
of `Model` into an `Html` element that, in turn produces messages tagged with `Msg`.
We will see this when we introduce some interaction.
--}
view : Model -> Html Msg
view model =
let
portfolio =
model.portfolio
selectedCategoryId =
getSelectedCategoryId model
selectedItem =
getSelectedItem model selectedCategoryId
in
div [ class "container" ]
[ div [ class "row" ]
[ div
[ class "col"
]
[ br [] [] ]
]
, div [ class "row" ]
[ div
[ class "col"
]
[ h1 [] [ text "Elmfolio" ] ]
]
, viewCategoryNavbar portfolio selectedCategoryId
, viewSelectedItem selectedItem
, viewItems model selectedCategoryId selectedItem
]
viewCategoryNavbar : Portfolio -> Int -> Html Msg
viewCategoryNavbar { categories } selectedCategoryId =
div [ class "row" ]
[ div
[ class "col" ]
[ div [ class "nav-category" ]
(List.map (viewCategoryButton selectedCategoryId) categories)
]
]
viewCategoryButton : Int -> Category -> Html Msg
viewCategoryButton selectedCategoryId category =
let
categorySelected =
selectedCategoryId == category.id
buttonsBaseAttrs =
[ type_ "button", classes ]
buttonOnClick =
if categorySelected then
[]
else
[ onClick (CategoryClicked category.id) ]
buttonAttrs =
buttonsBaseAttrs ++ buttonOnClick
classes =
classList
[ ( "btn btn-category", True )
, ( "btn-primary", categorySelected )
, ( "btn-secondary", not categorySelected )
]
in
button buttonAttrs [ text category.label ]
viewItems : Model -> Int -> Maybe Item -> Html Msg
viewItems { portfolio, errorMessage, likedItems } selectedCategoryId selectedItemId =
let
filteredItems =
portfolio.items |> List.filter (\i -> i.categoryId == selectedCategoryId) |> List.map (viewItem likedItems)
contents =
if String.isEmpty errorMessage then
div [ class "row items-container" ]
filteredItems
else
viewError errorMessage
in
contents
viewItem : List LikedItem -> Item -> Html Msg
viewItem likedItems item =
let
iconset =
if List.member ( item.categoryId, item.id ) likedItems then
"fas"
else
"far"
in
div
[ class "col-4 item-panel" ]
[ span [ style "display" "inline-blockw" ]
[ img
[ src item.imageUrl
, class "img-fluid"
, onClick (ItemClicked item.id)
]
[]
, span [ class "badge badge-info like-box", onClick (ToggleItemLiked item.id) ]
[ i [ class <| iconset ++ " fa-heart" ] []
, text <| " " ++ String.fromInt item.likes
]
]
]
viewSelectedItem : Maybe Item -> Html msg
viewSelectedItem item =
let
contents =
case item of
Nothing ->
[]
Just detail ->
[ div [ class "col-6" ]
[ img [ src detail.imageUrl, class "img-fluid" ] [] ]
, div [ class "col-6" ]
[ h3 [] [ text detail.title ]
, hr [] []
, text detail.description
, br [] []
, br [] []
, a [ href detail.linkUrl, target "_blank" ] [ text detail.linkUrl ]
]
]
in
div [ class "row selected-item-container" ]
contents
viewError : String -> Html Msg
viewError error =
div [ class "alert alert-danger", attribute "role" "alert" ]
[ strong []
[ text error ]
]
{--Update--
The `update` function will be called by `Browser.element` each time a message (`Msg`) is received.
This update function responds to messages (`Msg`), updating the model and returning commands as needed.
--}
type Msg
= HandleChannelResponse ChannelResponse
| HandleLocalStorageResponse LocalStorageResponse
| CategoryClicked Int
| ItemClicked Int
| ToggleItemLiked Int
| None
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
HandleChannelResponse channelResponse ->
let
{ code, response } =
channelResponse
updatedModel =
case ( code, response ) of
( 200, portfolio ) ->
{ model
| portfolio = portfolio
, selectedCategoryId = Just <| getSelectedCategoryId model
}
_ ->
model
in
( updatedModel, Cmd.none )
HandleLocalStorageResponse channelResponse ->
let
updatedModel =
model
in
( updatedModel, Cmd.none )
CategoryClicked categoryId ->
let
updatedModel =
{ model
| selectedCategoryId = Just categoryId
, selectedItemId = Nothing
}
in
( updatedModel, Cmd.none )
ItemClicked itemId ->
let
updatedModel =
{ model
| selectedItemId = Just itemId
}
in
( updatedModel, Cmd.none )
ToggleItemLiked itemId ->
let
selectedCategoryId =
model.selectedCategoryId |> Maybe.withDefault 0
likedItem =
( selectedCategoryId, itemId )
itemIsLiked =
model.likedItems
|> List.member
( selectedCategoryId, itemId )
( toggleCmd, updater ) =
if itemIsLiked then
( unlikeItemChannelRequest likedItem, removeLikedItem )
else
( likeItemChannelRequest likedItem, addLikedItem )
addLikedItem =
( selectedCategoryId, itemId )
:: model.likedItems
removeLikedItem =
model.likedItems
|> List.filter
(\( category, id ) ->
not (selectedCategoryId == category && itemId == id)
)
updatedModel =
case selectedCategoryId of
0 ->
model
_ ->
{ model | likedItems = updater }
in
( updatedModel
, Cmd.batch
[ toggleCmd
, saveLikesToLocalStorage updatedModel.likedItems
]
)
None ->
( model, Cmd.none )
getPortfolioFromChannel =
channelEventRequest { event = "get_items", payload = Encode.null }
likeItemChannelRequest likedItem =
channelEventRequest
{ event = "like_item"
, payload = encodeLikedItem likedItem
}
unlikeItemChannelRequest likedItem =
channelEventRequest
{ event = "unlike_item"
, payload = encodeLikedItem likedItem
}
saveLikesToLocalStorage likedItems =
localStorageRequest
{ method = "setItem"
, key = "<KEY>"
, value = Just <| encodeLikedItemsForLocalStorage likedItems
}
-- JSON Decoders
portfolioDecoder : Decoder Portfolio
portfolioDecoder =
Decode.succeed Portfolio
|> required "categories" (Decode.list categoryDecoder)
|> required "items" (Decode.list itemDecoder)
categoryDecoder : Decoder Category
categoryDecoder =
Decode.succeed Category
|> required "id" Decode.int
|> required "label" Decode.string
itemDecoder : Decoder Item
itemDecoder =
Decode.succeed Item
|> required "id" Decode.int
|> required "title" Decode.string
|> required "categoryId" Decode.int
|> required "imageUrl" Decode.string
|> required "linkUrl" Decode.string
|> required "description" Decode.string
|> required "overlayColor" Decode.string
|> required "likes" Decode.int
-- JSON Encoders --
encodeLikedItems : List LikedItem -> Encode.Value
encodeLikedItems likedItems =
Encode.list encodeLikedItem likedItems
encodeLikedItem : LikedItem -> Encode.Value
encodeLikedItem ( categoryId, itemId ) =
Encode.object
[ ( "categoryId", Encode.int categoryId )
, ( "itemId", Encode.int itemId )
]
encodeLikedItemsForLocalStorage : List LikedItem -> Encode.Value
encodeLikedItemsForLocalStorage likedItems =
Encode.list encodeLikedItemForLocalStorage likedItems
encodeLikedItemForLocalStorage : LikedItem -> Encode.Value
encodeLikedItemForLocalStorage ( categoryId, itemId ) =
Encode.list Encode.int [ categoryId, itemId ]
-- Helpers --
receiveChannelEventReponse response =
HandleChannelResponse response
getSelectedCategoryId : Model -> Int
getSelectedCategoryId model =
model.selectedCategoryId
|> Maybe.withDefault (getFirstCategory model)
getSelectedItem : Model -> Int -> Maybe Item
getSelectedItem { portfolio, selectedItemId } selectedCategoryId =
case selectedItemId of
Nothing ->
Nothing
Just id ->
portfolio.items
|> List.filter (\i -> i.id == id && i.categoryId == selectedCategoryId)
|> List.head
getFirstCategory { portfolio } =
portfolio.categories
|> List.head
|> Maybe.map .id
|> Maybe.withDefault 1
-- Ports
-- Generic port for an outbound channel request
port channelEventRequest : ChannelRequest -> Cmd msg
-- Generic port for an outbound channel response
port channelEventResponse : (ChannelResponse -> msg) -> Sub msg
-- Generic port for an outbound request to update localStorage
port localStorageRequest : LocalStorageRequest -> Cmd msg
{--Subscriptions
In Elm, using subscriptions is how your application can listen for external input. Some examples are:
- Keyboard events
- Mouse movements
- Browser locations changes
- Websocket events
In this application, we don't have a need for any active subscriptions so we add in Sub.none
--}
-- Inbound port messages are handled via `subscriptions`
subscriptions _ =
Sub.batch [ channelEventResponse receiveChannelEventReponse ]
{--Program setup and initialization--}
{--
The `main` function is the entry point for our app which means it's the first thing that is run
--}
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
{--The `init` function is run by `main` upon application startup and allows us to set
our app's initial state as well as scheduling any commands we'd like to run after the app starts
up. For now, we don't need to run any commands so we'll use Cmd.none here.
--}
init : List LikedItem -> ( Model, Cmd Msg )
init likedItems =
( initialModel likedItems
, getPortfolioFromChannel
)
| true | port module Main exposing (Category, Item, Model, Msg(..), Portfolio, categoryDecoder, getPortfolioFromChannel, getSelectedCategoryId, getSelectedItem, init, initialModel, itemDecoder, main, portfolioDecoder, subscriptions, update, view, viewCategoryButton, viewCategoryNavbar, viewError, viewItem, viewItems, viewSelectedItem)
import Browser
import Html exposing (..)
import Html.Attributes exposing (attribute, class, classList, href, src, style, target, type_, width)
import Html.Events exposing (onClick)
import Http
import Json.Decode as Decode exposing (Decoder, Value)
import Json.Decode.Pipeline as Pipeline exposing (optional, required)
import Json.Encode as Encode
import Set
{--Model
The `initialModel` function initializes our `Model`. This function is called in `init` and outputs a `Model`
--}
initialModel : List LikedItem -> Model
initialModel likedItems =
{ errorMessage = ""
, portfolio =
{ categories = []
, items = []
}
, selectedCategoryId = Nothing
, selectedItemId = Nothing
, likedItems = likedItems
}
type alias Model =
{ errorMessage : String
, portfolio : Portfolio
, selectedCategoryId : Maybe Int
, selectedItemId : Maybe Int
, likedItems : List LikedItem
}
type alias Portfolio =
{ categories : List Category
, items : List Item
}
type alias Category =
{ id : Int, label : String }
type alias Item =
{ id : Int
, title : String
, categoryId : Int
, imageUrl : String
, linkUrl : String
, description : String
, overlayColor : String
, likes : Int
}
type alias LikedItem =
( Int, Int )
type alias LocalStorageRequest =
{ method : String
, key : String
, value : Maybe Encode.Value
}
type alias LocalStorageResponse =
{ method : String
, payload : Encode.Value
}
type alias ChannelRequest =
{ event : String
, payload : Encode.Value
}
type alias ChannelResponse =
{ code : Int
, response : Portfolio
}
{--View
The function `view` renders an Html element using our application model.
Note that the type signature is Model -> Html Msg. This means that this function transforms an argument
of `Model` into an `Html` element that, in turn produces messages tagged with `Msg`.
We will see this when we introduce some interaction.
--}
view : Model -> Html Msg
view model =
let
portfolio =
model.portfolio
selectedCategoryId =
getSelectedCategoryId model
selectedItem =
getSelectedItem model selectedCategoryId
in
div [ class "container" ]
[ div [ class "row" ]
[ div
[ class "col"
]
[ br [] [] ]
]
, div [ class "row" ]
[ div
[ class "col"
]
[ h1 [] [ text "Elmfolio" ] ]
]
, viewCategoryNavbar portfolio selectedCategoryId
, viewSelectedItem selectedItem
, viewItems model selectedCategoryId selectedItem
]
viewCategoryNavbar : Portfolio -> Int -> Html Msg
viewCategoryNavbar { categories } selectedCategoryId =
div [ class "row" ]
[ div
[ class "col" ]
[ div [ class "nav-category" ]
(List.map (viewCategoryButton selectedCategoryId) categories)
]
]
viewCategoryButton : Int -> Category -> Html Msg
viewCategoryButton selectedCategoryId category =
let
categorySelected =
selectedCategoryId == category.id
buttonsBaseAttrs =
[ type_ "button", classes ]
buttonOnClick =
if categorySelected then
[]
else
[ onClick (CategoryClicked category.id) ]
buttonAttrs =
buttonsBaseAttrs ++ buttonOnClick
classes =
classList
[ ( "btn btn-category", True )
, ( "btn-primary", categorySelected )
, ( "btn-secondary", not categorySelected )
]
in
button buttonAttrs [ text category.label ]
viewItems : Model -> Int -> Maybe Item -> Html Msg
viewItems { portfolio, errorMessage, likedItems } selectedCategoryId selectedItemId =
let
filteredItems =
portfolio.items |> List.filter (\i -> i.categoryId == selectedCategoryId) |> List.map (viewItem likedItems)
contents =
if String.isEmpty errorMessage then
div [ class "row items-container" ]
filteredItems
else
viewError errorMessage
in
contents
viewItem : List LikedItem -> Item -> Html Msg
viewItem likedItems item =
let
iconset =
if List.member ( item.categoryId, item.id ) likedItems then
"fas"
else
"far"
in
div
[ class "col-4 item-panel" ]
[ span [ style "display" "inline-blockw" ]
[ img
[ src item.imageUrl
, class "img-fluid"
, onClick (ItemClicked item.id)
]
[]
, span [ class "badge badge-info like-box", onClick (ToggleItemLiked item.id) ]
[ i [ class <| iconset ++ " fa-heart" ] []
, text <| " " ++ String.fromInt item.likes
]
]
]
viewSelectedItem : Maybe Item -> Html msg
viewSelectedItem item =
let
contents =
case item of
Nothing ->
[]
Just detail ->
[ div [ class "col-6" ]
[ img [ src detail.imageUrl, class "img-fluid" ] [] ]
, div [ class "col-6" ]
[ h3 [] [ text detail.title ]
, hr [] []
, text detail.description
, br [] []
, br [] []
, a [ href detail.linkUrl, target "_blank" ] [ text detail.linkUrl ]
]
]
in
div [ class "row selected-item-container" ]
contents
viewError : String -> Html Msg
viewError error =
div [ class "alert alert-danger", attribute "role" "alert" ]
[ strong []
[ text error ]
]
{--Update--
The `update` function will be called by `Browser.element` each time a message (`Msg`) is received.
This update function responds to messages (`Msg`), updating the model and returning commands as needed.
--}
type Msg
= HandleChannelResponse ChannelResponse
| HandleLocalStorageResponse LocalStorageResponse
| CategoryClicked Int
| ItemClicked Int
| ToggleItemLiked Int
| None
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
HandleChannelResponse channelResponse ->
let
{ code, response } =
channelResponse
updatedModel =
case ( code, response ) of
( 200, portfolio ) ->
{ model
| portfolio = portfolio
, selectedCategoryId = Just <| getSelectedCategoryId model
}
_ ->
model
in
( updatedModel, Cmd.none )
HandleLocalStorageResponse channelResponse ->
let
updatedModel =
model
in
( updatedModel, Cmd.none )
CategoryClicked categoryId ->
let
updatedModel =
{ model
| selectedCategoryId = Just categoryId
, selectedItemId = Nothing
}
in
( updatedModel, Cmd.none )
ItemClicked itemId ->
let
updatedModel =
{ model
| selectedItemId = Just itemId
}
in
( updatedModel, Cmd.none )
ToggleItemLiked itemId ->
let
selectedCategoryId =
model.selectedCategoryId |> Maybe.withDefault 0
likedItem =
( selectedCategoryId, itemId )
itemIsLiked =
model.likedItems
|> List.member
( selectedCategoryId, itemId )
( toggleCmd, updater ) =
if itemIsLiked then
( unlikeItemChannelRequest likedItem, removeLikedItem )
else
( likeItemChannelRequest likedItem, addLikedItem )
addLikedItem =
( selectedCategoryId, itemId )
:: model.likedItems
removeLikedItem =
model.likedItems
|> List.filter
(\( category, id ) ->
not (selectedCategoryId == category && itemId == id)
)
updatedModel =
case selectedCategoryId of
0 ->
model
_ ->
{ model | likedItems = updater }
in
( updatedModel
, Cmd.batch
[ toggleCmd
, saveLikesToLocalStorage updatedModel.likedItems
]
)
None ->
( model, Cmd.none )
getPortfolioFromChannel =
channelEventRequest { event = "get_items", payload = Encode.null }
likeItemChannelRequest likedItem =
channelEventRequest
{ event = "like_item"
, payload = encodeLikedItem likedItem
}
unlikeItemChannelRequest likedItem =
channelEventRequest
{ event = "unlike_item"
, payload = encodeLikedItem likedItem
}
saveLikesToLocalStorage likedItems =
localStorageRequest
{ method = "setItem"
, key = "PI:KEY:<KEY>END_PI"
, value = Just <| encodeLikedItemsForLocalStorage likedItems
}
-- JSON Decoders
portfolioDecoder : Decoder Portfolio
portfolioDecoder =
Decode.succeed Portfolio
|> required "categories" (Decode.list categoryDecoder)
|> required "items" (Decode.list itemDecoder)
categoryDecoder : Decoder Category
categoryDecoder =
Decode.succeed Category
|> required "id" Decode.int
|> required "label" Decode.string
itemDecoder : Decoder Item
itemDecoder =
Decode.succeed Item
|> required "id" Decode.int
|> required "title" Decode.string
|> required "categoryId" Decode.int
|> required "imageUrl" Decode.string
|> required "linkUrl" Decode.string
|> required "description" Decode.string
|> required "overlayColor" Decode.string
|> required "likes" Decode.int
-- JSON Encoders --
encodeLikedItems : List LikedItem -> Encode.Value
encodeLikedItems likedItems =
Encode.list encodeLikedItem likedItems
encodeLikedItem : LikedItem -> Encode.Value
encodeLikedItem ( categoryId, itemId ) =
Encode.object
[ ( "categoryId", Encode.int categoryId )
, ( "itemId", Encode.int itemId )
]
encodeLikedItemsForLocalStorage : List LikedItem -> Encode.Value
encodeLikedItemsForLocalStorage likedItems =
Encode.list encodeLikedItemForLocalStorage likedItems
encodeLikedItemForLocalStorage : LikedItem -> Encode.Value
encodeLikedItemForLocalStorage ( categoryId, itemId ) =
Encode.list Encode.int [ categoryId, itemId ]
-- Helpers --
receiveChannelEventReponse response =
HandleChannelResponse response
getSelectedCategoryId : Model -> Int
getSelectedCategoryId model =
model.selectedCategoryId
|> Maybe.withDefault (getFirstCategory model)
getSelectedItem : Model -> Int -> Maybe Item
getSelectedItem { portfolio, selectedItemId } selectedCategoryId =
case selectedItemId of
Nothing ->
Nothing
Just id ->
portfolio.items
|> List.filter (\i -> i.id == id && i.categoryId == selectedCategoryId)
|> List.head
getFirstCategory { portfolio } =
portfolio.categories
|> List.head
|> Maybe.map .id
|> Maybe.withDefault 1
-- Ports
-- Generic port for an outbound channel request
port channelEventRequest : ChannelRequest -> Cmd msg
-- Generic port for an outbound channel response
port channelEventResponse : (ChannelResponse -> msg) -> Sub msg
-- Generic port for an outbound request to update localStorage
port localStorageRequest : LocalStorageRequest -> Cmd msg
{--Subscriptions
In Elm, using subscriptions is how your application can listen for external input. Some examples are:
- Keyboard events
- Mouse movements
- Browser locations changes
- Websocket events
In this application, we don't have a need for any active subscriptions so we add in Sub.none
--}
-- Inbound port messages are handled via `subscriptions`
subscriptions _ =
Sub.batch [ channelEventResponse receiveChannelEventReponse ]
{--Program setup and initialization--}
{--
The `main` function is the entry point for our app which means it's the first thing that is run
--}
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
{--The `init` function is run by `main` upon application startup and allows us to set
our app's initial state as well as scheduling any commands we'd like to run after the app starts
up. For now, we don't need to run any commands so we'll use Cmd.none here.
--}
init : List LikedItem -> ( Model, Cmd Msg )
init likedItems =
( initialModel likedItems
, getPortfolioFromChannel
)
| elm |
[
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 470,
"score": 0.8337830901,
"start": 460,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 817,
"score": 0.9511047006,
"start": 807,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 1139,
"score": 0.9467638135,
"start": 1129,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 1491,
"score": 0.9530076385,
"start": 1481,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 1856,
"score": 0.9944424629,
"start": 1846,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 2232,
"score": 0.9940916896,
"start": 2222,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 2578,
"score": 0.9943385124,
"start": 2568,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "-world\"\n , title = \"Hello World\"\n , name = \"hello-world\"\n , publishedDate = fromCalendarDate 2017 Sep ",
"end": 2997,
"score": 0.9499855638,
"start": 2986,
"tag": "USERNAME",
"value": "hello-world"
},
{
"context": "Date = fromCalendarDate 2017 Sep 25\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , conten",
"end": 3075,
"score": 0.9942061901,
"start": 3065,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "tentType = Page\n , name = \"cyh\"\n , title = \"Chen Yinghao\"\n , publishedDate = fromCalendarDate 2018 Jun ",
"end": 3778,
"score": 0.998647809,
"start": 3766,
"tag": "NAME",
"value": "Chen Yinghao"
},
{
"context": "ntentType = Page\n , name = \"xw\"\n , title = \"Xiao Wen\"\n , publishedDate = fromCalendarDate 2018 Jun ",
"end": 4115,
"score": 0.9990944266,
"start": 4107,
"tag": "NAME",
"value": "Xiao Wen"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 4193,
"score": 0.7448558211,
"start": 4183,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "ntentType = Page\n , name = \"zj\"\n , title = \"Zhang Jing\"\n , publishedDate = fromCalendarDate 2018 Jun ",
"end": 4454,
"score": 0.9990392327,
"start": 4444,
"tag": "NAME",
"value": "Zhang Jing"
},
{
"context": "ntentType = Page\n , name = \"zy\"\n , title = \"Zou Yang\"\n , publishedDate = fromCalendarDate 2018 Jun ",
"end": 4791,
"score": 0.9979603887,
"start": 4783,
"tag": "NAME",
"value": "Zou Yang"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 4869,
"score": 0.8420467377,
"start": 4859,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "oute \"lky\"\n , contentType = Page\n , name = \"lky\"\n , title = \"Lai Kongyi\"\n , publishedDate =",
"end": 5108,
"score": 0.995695591,
"start": 5105,
"tag": "USERNAME",
"value": "lky"
},
{
"context": "tentType = Page\n , name = \"lky\"\n , title = \"Lai Kongyi\"\n , publishedDate = fromCalendarDate 2018 Jun ",
"end": 5135,
"score": 0.9709342718,
"start": 5125,
"tag": "NAME",
"value": "Lai Kongyi"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 5213,
"score": 0.8627970815,
"start": 5203,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "ntentType = Page\n , name = \"lj\"\n , title = \"Ling Jiang\"\n , publishedDate = fromCalendarDate 2018 Jun ",
"end": 5544,
"score": 0.9581506252,
"start": 5534,
"tag": "NAME",
"value": "Ling Jiang"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 5622,
"score": 0.8357238173,
"start": 5612,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "ntentType = Page\n , name = \"zz\"\n , title = \"Zhou Zheng\"\n , publishedDate = fromCalendarDate 2018 Jun ",
"end": 5883,
"score": 0.9947856069,
"start": 5873,
"tag": "NAME",
"value": "Zhou Zheng"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 5961,
"score": 0.84398669,
"start": 5951,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 6306,
"score": 0.8897719383,
"start": 6296,
"tag": "USERNAME",
"value": "Authors.wy"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , pre",
"end": 6756,
"score": 0.5591405034,
"start": 6749,
"tag": "USERNAME",
"value": "Authors"
},
{
"context": "omCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 6759,
"score": 0.54332757,
"start": 6757,
"tag": "USERNAME",
"value": "wy"
},
{
"context": "Date = fromCalendarDate 2018 Jun 15\n , author = Authors.wy\n , markdown = RemoteData.NotAsked\n , previe",
"end": 7147,
"score": 0.5789350271,
"start": 7137,
"tag": "USERNAME",
"value": "Authors.wy"
}
] | src/Contents.elm | meilab/johnny-art | 0 | module Contents exposing (..)
import Authors
import Date.Extra exposing (fromCalendarDate)
import Date exposing (Month(..))
import Types exposing (Hero, Content, ContentType(..))
import RemoteData exposing (RemoteData)
import Routing exposing (Route(..))
home : Content
home =
{ slug = "/"
, route = HomeRoute
, contentType = Page
, name = "index"
, title = "Johnny-Art"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
about : Content
about =
{ slug = "/about"
, route = AboutRoute
, contentType = Page
, name = "about"
, title = "About Johnny art center"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/about.jpg" "" ""
}
join : Content
join =
{ slug = "/join"
, route = JoinRoute
, contentType = Page
, name = "join"
, title = "Join"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
courselist : Content
courselist =
{ slug = "courselist"
, route = CoursesRoute
, contentType = Page
, name = "courselist"
, title = "Courses"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/courses.jpg" "" ""
}
teacherList : Content
teacherList =
{ slug = "teacherlist"
, route = TeachersRoute
, contentType = AuthorPage
, name = "teacherlist"
, title = "Teachers"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/teachers.jpg" "" ""
}
notFoundContent : Content
notFoundContent =
{ slug = "notfound"
, route = NotFoundRoute
, contentType = Page
, name = "not-found"
, title = "Couldn't find content"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
notFound404 : Content
notFound404 =
{ slug = "404"
, route = NotFoundRoute
, contentType = Page
, name = "404"
, title = "You Are lost"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
pages : List Content
pages =
[ home
, about
, join
, courselist
, teacherList
, notFoundContent
, notFound404
]
helloWorld : Content
helloWorld =
{ slug = "/hello-world"
, route = PostDetailRoute "hello-world"
, title = "Hello World"
, name = "hello-world"
, publishedDate = fromCalendarDate 2017 Sep 25
, author = Authors.wy
, markdown = RemoteData.NotAsked
, contentType = Post
, preview = "Hello World in Elm"
, hero = Hero "images/hero/cover1.jpg" "" ""
}
posts : List Content
posts =
[ helloWorld
]
ww : Content
ww =
{ slug = "teacher/ww"
, route = TeacherDetailRoute "ww"
, contentType = Page
, name = "ww"
, title = "Wu Wei"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
cyh : Content
cyh =
{ slug = "teacher/cyh"
, route = TeacherDetailRoute "cyh"
, contentType = Page
, name = "cyh"
, title = "Chen Yinghao"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
xw : Content
xw =
{ slug = "teacher/xw"
, route = TeacherDetailRoute "xw"
, contentType = Page
, name = "xw"
, title = "Xiao Wen"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
zj : Content
zj =
{ slug = "teacher/zj"
, route = TeacherDetailRoute "zj"
, contentType = Page
, name = "zj"
, title = "Zhang Jing"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
zy : Content
zy =
{ slug = "teacher/zy"
, route = TeacherDetailRoute "zy"
, contentType = Page
, name = "zy"
, title = "Zou Yang"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
lky : Content
lky =
{ slug = "teacher/lky"
, route = TeacherDetailRoute "lky"
, contentType = Page
, name = "lky"
, title = "Lai Kongyi"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
teachers : List Content
teachers =
[ ww, cyh, xw, zj, zy, lky ]
lj : Content
lj =
{ slug = "teacher/lj"
, route = TeacherDetailRoute "lj"
, contentType = Page
, name = "lj"
, title = "Ling Jiang"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
zz : Content
zz =
{ slug = "teacher/zz"
, route = TeacherDetailRoute "zz"
, contentType = Page
, name = "zz"
, title = "Zhou Zheng"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
yxz : Content
yxz =
{ slug = "teacher/yxz"
, route = TeacherDetailRoute "yxz"
, contentType = Page
, name = "yxz"
, title = "Ye Xiaozhou"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
consultants : List Content
consultants =
[ lj, zz, yxz ]
xiaoshengchu : Content
xiaoshengchu =
{ slug = "course/xiaoshengchu"
, route = CourseDetailRoute "xiaoshengchu"
, contentType = Page
, name = "xiaoshengchu"
, title = "Xiao Shengchu"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/xiaoshengchu.jpg" "" ""
}
xiaozhuchi : Content
xiaozhuchi =
{ slug = "course/xiaozhuchi"
, route = CourseDetailRoute "xiaozhuchi"
, contentType = Page
, name = "xiaozhuchi"
, title = "Xiao Zhuchi"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/xiaozhuchi.jpg" "" ""
}
yikao : Content
yikao =
{ slug = "course/yikao"
, route = CourseDetailRoute "yikao"
, contentType = Page
, name = "yikao"
, title = "Yi Kao"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/yikao.jpg" "" ""
}
courses : List Content
courses =
[ xiaoshengchu, xiaozhuchi, yikao ]
| 37000 | module Contents exposing (..)
import Authors
import Date.Extra exposing (fromCalendarDate)
import Date exposing (Month(..))
import Types exposing (Hero, Content, ContentType(..))
import RemoteData exposing (RemoteData)
import Routing exposing (Route(..))
home : Content
home =
{ slug = "/"
, route = HomeRoute
, contentType = Page
, name = "index"
, title = "Johnny-Art"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
about : Content
about =
{ slug = "/about"
, route = AboutRoute
, contentType = Page
, name = "about"
, title = "About Johnny art center"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/about.jpg" "" ""
}
join : Content
join =
{ slug = "/join"
, route = JoinRoute
, contentType = Page
, name = "join"
, title = "Join"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
courselist : Content
courselist =
{ slug = "courselist"
, route = CoursesRoute
, contentType = Page
, name = "courselist"
, title = "Courses"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/courses.jpg" "" ""
}
teacherList : Content
teacherList =
{ slug = "teacherlist"
, route = TeachersRoute
, contentType = AuthorPage
, name = "teacherlist"
, title = "Teachers"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/teachers.jpg" "" ""
}
notFoundContent : Content
notFoundContent =
{ slug = "notfound"
, route = NotFoundRoute
, contentType = Page
, name = "not-found"
, title = "Couldn't find content"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
notFound404 : Content
notFound404 =
{ slug = "404"
, route = NotFoundRoute
, contentType = Page
, name = "404"
, title = "You Are lost"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
pages : List Content
pages =
[ home
, about
, join
, courselist
, teacherList
, notFoundContent
, notFound404
]
helloWorld : Content
helloWorld =
{ slug = "/hello-world"
, route = PostDetailRoute "hello-world"
, title = "Hello World"
, name = "hello-world"
, publishedDate = fromCalendarDate 2017 Sep 25
, author = Authors.wy
, markdown = RemoteData.NotAsked
, contentType = Post
, preview = "Hello World in Elm"
, hero = Hero "images/hero/cover1.jpg" "" ""
}
posts : List Content
posts =
[ helloWorld
]
ww : Content
ww =
{ slug = "teacher/ww"
, route = TeacherDetailRoute "ww"
, contentType = Page
, name = "ww"
, title = "Wu Wei"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
cyh : Content
cyh =
{ slug = "teacher/cyh"
, route = TeacherDetailRoute "cyh"
, contentType = Page
, name = "cyh"
, title = "<NAME>"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
xw : Content
xw =
{ slug = "teacher/xw"
, route = TeacherDetailRoute "xw"
, contentType = Page
, name = "xw"
, title = "<NAME>"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
zj : Content
zj =
{ slug = "teacher/zj"
, route = TeacherDetailRoute "zj"
, contentType = Page
, name = "zj"
, title = "<NAME>"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
zy : Content
zy =
{ slug = "teacher/zy"
, route = TeacherDetailRoute "zy"
, contentType = Page
, name = "zy"
, title = "<NAME>"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
lky : Content
lky =
{ slug = "teacher/lky"
, route = TeacherDetailRoute "lky"
, contentType = Page
, name = "lky"
, title = "<NAME>"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
teachers : List Content
teachers =
[ ww, cyh, xw, zj, zy, lky ]
lj : Content
lj =
{ slug = "teacher/lj"
, route = TeacherDetailRoute "lj"
, contentType = Page
, name = "lj"
, title = "<NAME>"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
zz : Content
zz =
{ slug = "teacher/zz"
, route = TeacherDetailRoute "zz"
, contentType = Page
, name = "zz"
, title = "<NAME>"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
yxz : Content
yxz =
{ slug = "teacher/yxz"
, route = TeacherDetailRoute "yxz"
, contentType = Page
, name = "yxz"
, title = "Ye Xiaozhou"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
consultants : List Content
consultants =
[ lj, zz, yxz ]
xiaoshengchu : Content
xiaoshengchu =
{ slug = "course/xiaoshengchu"
, route = CourseDetailRoute "xiaoshengchu"
, contentType = Page
, name = "xiaoshengchu"
, title = "Xiao Shengchu"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/xiaoshengchu.jpg" "" ""
}
xiaozhuchi : Content
xiaozhuchi =
{ slug = "course/xiaozhuchi"
, route = CourseDetailRoute "xiaozhuchi"
, contentType = Page
, name = "xiaozhuchi"
, title = "Xiao Zhuchi"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/xiaozhuchi.jpg" "" ""
}
yikao : Content
yikao =
{ slug = "course/yikao"
, route = CourseDetailRoute "yikao"
, contentType = Page
, name = "yikao"
, title = "Yi Kao"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/yikao.jpg" "" ""
}
courses : List Content
courses =
[ xiaoshengchu, xiaozhuchi, yikao ]
| true | module Contents exposing (..)
import Authors
import Date.Extra exposing (fromCalendarDate)
import Date exposing (Month(..))
import Types exposing (Hero, Content, ContentType(..))
import RemoteData exposing (RemoteData)
import Routing exposing (Route(..))
home : Content
home =
{ slug = "/"
, route = HomeRoute
, contentType = Page
, name = "index"
, title = "Johnny-Art"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
about : Content
about =
{ slug = "/about"
, route = AboutRoute
, contentType = Page
, name = "about"
, title = "About Johnny art center"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/about.jpg" "" ""
}
join : Content
join =
{ slug = "/join"
, route = JoinRoute
, contentType = Page
, name = "join"
, title = "Join"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
courselist : Content
courselist =
{ slug = "courselist"
, route = CoursesRoute
, contentType = Page
, name = "courselist"
, title = "Courses"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/courses.jpg" "" ""
}
teacherList : Content
teacherList =
{ slug = "teacherlist"
, route = TeachersRoute
, contentType = AuthorPage
, name = "teacherlist"
, title = "Teachers"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/teachers.jpg" "" ""
}
notFoundContent : Content
notFoundContent =
{ slug = "notfound"
, route = NotFoundRoute
, contentType = Page
, name = "not-found"
, title = "Couldn't find content"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
notFound404 : Content
notFound404 =
{ slug = "404"
, route = NotFoundRoute
, contentType = Page
, name = "404"
, title = "You Are lost"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "images/hero/cover1.jpg" "" ""
}
pages : List Content
pages =
[ home
, about
, join
, courselist
, teacherList
, notFoundContent
, notFound404
]
helloWorld : Content
helloWorld =
{ slug = "/hello-world"
, route = PostDetailRoute "hello-world"
, title = "Hello World"
, name = "hello-world"
, publishedDate = fromCalendarDate 2017 Sep 25
, author = Authors.wy
, markdown = RemoteData.NotAsked
, contentType = Post
, preview = "Hello World in Elm"
, hero = Hero "images/hero/cover1.jpg" "" ""
}
posts : List Content
posts =
[ helloWorld
]
ww : Content
ww =
{ slug = "teacher/ww"
, route = TeacherDetailRoute "ww"
, contentType = Page
, name = "ww"
, title = "Wu Wei"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
cyh : Content
cyh =
{ slug = "teacher/cyh"
, route = TeacherDetailRoute "cyh"
, contentType = Page
, name = "cyh"
, title = "PI:NAME:<NAME>END_PI"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
xw : Content
xw =
{ slug = "teacher/xw"
, route = TeacherDetailRoute "xw"
, contentType = Page
, name = "xw"
, title = "PI:NAME:<NAME>END_PI"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
zj : Content
zj =
{ slug = "teacher/zj"
, route = TeacherDetailRoute "zj"
, contentType = Page
, name = "zj"
, title = "PI:NAME:<NAME>END_PI"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
zy : Content
zy =
{ slug = "teacher/zy"
, route = TeacherDetailRoute "zy"
, contentType = Page
, name = "zy"
, title = "PI:NAME:<NAME>END_PI"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
lky : Content
lky =
{ slug = "teacher/lky"
, route = TeacherDetailRoute "lky"
, contentType = Page
, name = "lky"
, title = "PI:NAME:<NAME>END_PI"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
teachers : List Content
teachers =
[ ww, cyh, xw, zj, zy, lky ]
lj : Content
lj =
{ slug = "teacher/lj"
, route = TeacherDetailRoute "lj"
, contentType = Page
, name = "lj"
, title = "PI:NAME:<NAME>END_PI"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
zz : Content
zz =
{ slug = "teacher/zz"
, route = TeacherDetailRoute "zz"
, contentType = Page
, name = "zz"
, title = "PI:NAME:<NAME>END_PI"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
yxz : Content
yxz =
{ slug = "teacher/yxz"
, route = TeacherDetailRoute "yxz"
, contentType = Page
, name = "yxz"
, title = "Ye Xiaozhou"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/ww.jpg" "" ""
}
consultants : List Content
consultants =
[ lj, zz, yxz ]
xiaoshengchu : Content
xiaoshengchu =
{ slug = "course/xiaoshengchu"
, route = CourseDetailRoute "xiaoshengchu"
, contentType = Page
, name = "xiaoshengchu"
, title = "Xiao Shengchu"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/xiaoshengchu.jpg" "" ""
}
xiaozhuchi : Content
xiaozhuchi =
{ slug = "course/xiaozhuchi"
, route = CourseDetailRoute "xiaozhuchi"
, contentType = Page
, name = "xiaozhuchi"
, title = "Xiao Zhuchi"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/xiaozhuchi.jpg" "" ""
}
yikao : Content
yikao =
{ slug = "course/yikao"
, route = CourseDetailRoute "yikao"
, contentType = Page
, name = "yikao"
, title = "Yi Kao"
, publishedDate = fromCalendarDate 2018 Jun 15
, author = Authors.wy
, markdown = RemoteData.NotAsked
, preview = ""
, hero = Hero "/images/hero/yikao.jpg" "" ""
}
courses : List Content
courses =
[ xiaoshengchu, xiaozhuchi, yikao ]
| elm |
[
{
"context": "-\n View/Automata/NonDeterministic.elm\n Author: Henrique da Cunha Buss\n Creation: October/2020\n This file contains f",
"end": 74,
"score": 0.9992794991,
"start": 52,
"tag": "NAME",
"value": "Henrique da Cunha Buss"
}
] | src/View/Automata/NonDeterministic.elm | NeoVier/LFC01 | 0 | {-
View/Automata/NonDeterministic.elm
Author: Henrique da Cunha Buss
Creation: October/2020
This file contains functions to view non deterministic automata
-}
module View.Automata.NonDeterministic exposing (viewAFND)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Models.Alphabet as Alphabet
import Models.Automata as Automata
import Models.Models as Models
import Models.State as State
import Models.Transition as Transition
import Types.Types as Types
import Utils.Utils as Utils
import View.Automata.Common as VC
import View.Styles exposing (..)
{- Given an AFND, return a table that represents it -}
viewAFND : Automata.AFND -> Html Types.Msg
viewAFND afnd =
table tableStyles
(VC.viewAutomataHeader (Alphabet.NonDeterministic afnd.alphabet)
:: getAutomatonRows afnd
)
{- Given an AFND, return a list of rows that represent the states and
transitions
-}
getAutomatonRows : Automata.AFND -> List (Html Types.Msg)
getAutomatonRows afnd =
List.map (\state -> getStateRow afnd state) afnd.states
{- Given an AFND and a State, return the row that represents the State -}
getStateRow : Automata.AFND -> State.State -> Html Types.Msg
getStateRow afnd prevState =
let
isInitial =
prevState == afnd.initialState
isFinal =
List.member prevState afnd.finalStates
prefix =
if isInitial && isFinal then
"->*"
else if isInitial then
"->"
else if isFinal then
"*"
else
""
prefixSelect =
select
[ onInput
(\new ->
case new of
"->*" ->
{ afnd
| initialState = prevState
, finalStates =
afnd.finalStates
++ [ prevState ]
|> Utils.removeDuplicates
}
|> afndToGeneral
|> Types.UpdateCurrent
"->" ->
{ afnd
| initialState = prevState
, finalStates =
List.filter ((/=) prevState)
afnd.finalStates
}
|> afndToGeneral
|> Types.UpdateCurrent
"*" ->
{ afnd
| finalStates =
afnd.finalStates
++ [ prevState ]
|> Utils.removeDuplicates
}
|> afndToGeneral
|> Types.UpdateCurrent
_ ->
{ afnd
| finalStates =
List.filter
((/=) prevState)
afnd.finalStates
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
(List.map
(\t ->
option
[ value t, selected (t == prefix) ]
[ text t ]
)
(if prevState == afnd.initialState then
[ "->*", "->" ]
else
[ "->*", "->", "*", "" ]
)
)
transitions =
Utils.getFlatOutTransitionsNonDeterministic afnd prevState
|> Utils.sortTransitionsNonDeterministic
|> Utils.swapFirstAndLast
in
tr tableRowStyles
(td tableItemStyles
[ button
[ disabled isInitial
, onClick
({ afnd
| states = List.filter ((/=) prevState) afnd.states
, finalStates =
List.filter ((/=) prevState) afnd.finalStates
, transitions =
List.filterMap
(\transition ->
if
List.member prevState
transition.nextStates
then
Just
{ transition
| nextStates =
case
transition.nextStates
|> List.filter
((/=) prevState)
of
[] ->
[ State.Dead ]
a ->
a
}
else if
transition.prevState
== prevState
then
Nothing
else
Just transition
)
afnd.transitions
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
[ text "Remover estado" ]
]
:: td tableItemStyles
[ prefixSelect
, text <| stateToString prevState
]
:: List.map
(\transition ->
viewFlatNonDeterministicTransition transition afnd
|> td tableItemStyles
)
transitions
)
{- Helper function to convert the nextState of a Transition to a String -}
viewFlatNonDeterministicTransition :
Transition.NonDeterministicTransition
-> Automata.AFND
-> List (Html Types.Msg)
viewFlatNonDeterministicTransition transition afnd =
List.map
(\state ->
select
[ onInput
(\new ->
{ afnd
| transitions =
Utils.replaceBy transition
{ transition
| nextStates =
case
Utils.replaceBy
state
(stringToState new)
transition.nextStates
|> Utils.removeDuplicates
|> List.filter
((/=) State.Dead)
of
[] ->
[ State.Dead ]
a ->
a
}
afnd.transitions
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
(List.filterMap
(\s ->
if
List.member s transition.nextStates
&& s
/= state
then
Nothing
else
Just <|
option
[ value (stateToString s)
, selected (s == state)
]
[ text (stateToString s) ]
)
(afnd.states ++ [ State.Dead ])
)
)
transition.nextStates
++ [ select
[ onInput
(\new ->
{ afnd
| transitions =
Utils.replaceBy transition
{ transition
| nextStates =
transition.nextStates
++ [ stringToState new ]
|> List.filter ((/=) State.Dead)
}
afnd.transitions
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
(option [ value "+", selected True ] [ text "+" ]
:: List.filterMap
(\state ->
if List.member state transition.nextStates then
Nothing
else
Just <|
option [ value (stateToString state) ]
[ text (stateToString state) ]
)
afnd.states
)
]
{- Turn an AFND into a general model -}
afndToGeneral : Automata.AFND -> Models.General
afndToGeneral =
Automata.FiniteNonDeterministic >> Models.Automaton
{- Turn a list of states into a string -}
statesToString : List State.State -> String
statesToString states =
case states of
[ State.Dead ] ->
"-"
_ ->
List.filter (\state -> state /= State.Dead) states
|> List.map stateToString
|> String.join ", "
{- Turn a state into a string -}
stateToString : State.State -> String
stateToString state =
case state of
State.Dead ->
"-"
State.Valid label ->
label
{- Read a string into a state -}
stringToState : String -> State.State
stringToState label =
if label == "-" then
State.Dead
else
State.Valid label
| 22838 | {-
View/Automata/NonDeterministic.elm
Author: <NAME>
Creation: October/2020
This file contains functions to view non deterministic automata
-}
module View.Automata.NonDeterministic exposing (viewAFND)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Models.Alphabet as Alphabet
import Models.Automata as Automata
import Models.Models as Models
import Models.State as State
import Models.Transition as Transition
import Types.Types as Types
import Utils.Utils as Utils
import View.Automata.Common as VC
import View.Styles exposing (..)
{- Given an AFND, return a table that represents it -}
viewAFND : Automata.AFND -> Html Types.Msg
viewAFND afnd =
table tableStyles
(VC.viewAutomataHeader (Alphabet.NonDeterministic afnd.alphabet)
:: getAutomatonRows afnd
)
{- Given an AFND, return a list of rows that represent the states and
transitions
-}
getAutomatonRows : Automata.AFND -> List (Html Types.Msg)
getAutomatonRows afnd =
List.map (\state -> getStateRow afnd state) afnd.states
{- Given an AFND and a State, return the row that represents the State -}
getStateRow : Automata.AFND -> State.State -> Html Types.Msg
getStateRow afnd prevState =
let
isInitial =
prevState == afnd.initialState
isFinal =
List.member prevState afnd.finalStates
prefix =
if isInitial && isFinal then
"->*"
else if isInitial then
"->"
else if isFinal then
"*"
else
""
prefixSelect =
select
[ onInput
(\new ->
case new of
"->*" ->
{ afnd
| initialState = prevState
, finalStates =
afnd.finalStates
++ [ prevState ]
|> Utils.removeDuplicates
}
|> afndToGeneral
|> Types.UpdateCurrent
"->" ->
{ afnd
| initialState = prevState
, finalStates =
List.filter ((/=) prevState)
afnd.finalStates
}
|> afndToGeneral
|> Types.UpdateCurrent
"*" ->
{ afnd
| finalStates =
afnd.finalStates
++ [ prevState ]
|> Utils.removeDuplicates
}
|> afndToGeneral
|> Types.UpdateCurrent
_ ->
{ afnd
| finalStates =
List.filter
((/=) prevState)
afnd.finalStates
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
(List.map
(\t ->
option
[ value t, selected (t == prefix) ]
[ text t ]
)
(if prevState == afnd.initialState then
[ "->*", "->" ]
else
[ "->*", "->", "*", "" ]
)
)
transitions =
Utils.getFlatOutTransitionsNonDeterministic afnd prevState
|> Utils.sortTransitionsNonDeterministic
|> Utils.swapFirstAndLast
in
tr tableRowStyles
(td tableItemStyles
[ button
[ disabled isInitial
, onClick
({ afnd
| states = List.filter ((/=) prevState) afnd.states
, finalStates =
List.filter ((/=) prevState) afnd.finalStates
, transitions =
List.filterMap
(\transition ->
if
List.member prevState
transition.nextStates
then
Just
{ transition
| nextStates =
case
transition.nextStates
|> List.filter
((/=) prevState)
of
[] ->
[ State.Dead ]
a ->
a
}
else if
transition.prevState
== prevState
then
Nothing
else
Just transition
)
afnd.transitions
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
[ text "Remover estado" ]
]
:: td tableItemStyles
[ prefixSelect
, text <| stateToString prevState
]
:: List.map
(\transition ->
viewFlatNonDeterministicTransition transition afnd
|> td tableItemStyles
)
transitions
)
{- Helper function to convert the nextState of a Transition to a String -}
viewFlatNonDeterministicTransition :
Transition.NonDeterministicTransition
-> Automata.AFND
-> List (Html Types.Msg)
viewFlatNonDeterministicTransition transition afnd =
List.map
(\state ->
select
[ onInput
(\new ->
{ afnd
| transitions =
Utils.replaceBy transition
{ transition
| nextStates =
case
Utils.replaceBy
state
(stringToState new)
transition.nextStates
|> Utils.removeDuplicates
|> List.filter
((/=) State.Dead)
of
[] ->
[ State.Dead ]
a ->
a
}
afnd.transitions
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
(List.filterMap
(\s ->
if
List.member s transition.nextStates
&& s
/= state
then
Nothing
else
Just <|
option
[ value (stateToString s)
, selected (s == state)
]
[ text (stateToString s) ]
)
(afnd.states ++ [ State.Dead ])
)
)
transition.nextStates
++ [ select
[ onInput
(\new ->
{ afnd
| transitions =
Utils.replaceBy transition
{ transition
| nextStates =
transition.nextStates
++ [ stringToState new ]
|> List.filter ((/=) State.Dead)
}
afnd.transitions
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
(option [ value "+", selected True ] [ text "+" ]
:: List.filterMap
(\state ->
if List.member state transition.nextStates then
Nothing
else
Just <|
option [ value (stateToString state) ]
[ text (stateToString state) ]
)
afnd.states
)
]
{- Turn an AFND into a general model -}
afndToGeneral : Automata.AFND -> Models.General
afndToGeneral =
Automata.FiniteNonDeterministic >> Models.Automaton
{- Turn a list of states into a string -}
statesToString : List State.State -> String
statesToString states =
case states of
[ State.Dead ] ->
"-"
_ ->
List.filter (\state -> state /= State.Dead) states
|> List.map stateToString
|> String.join ", "
{- Turn a state into a string -}
stateToString : State.State -> String
stateToString state =
case state of
State.Dead ->
"-"
State.Valid label ->
label
{- Read a string into a state -}
stringToState : String -> State.State
stringToState label =
if label == "-" then
State.Dead
else
State.Valid label
| true | {-
View/Automata/NonDeterministic.elm
Author: PI:NAME:<NAME>END_PI
Creation: October/2020
This file contains functions to view non deterministic automata
-}
module View.Automata.NonDeterministic exposing (viewAFND)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Models.Alphabet as Alphabet
import Models.Automata as Automata
import Models.Models as Models
import Models.State as State
import Models.Transition as Transition
import Types.Types as Types
import Utils.Utils as Utils
import View.Automata.Common as VC
import View.Styles exposing (..)
{- Given an AFND, return a table that represents it -}
viewAFND : Automata.AFND -> Html Types.Msg
viewAFND afnd =
table tableStyles
(VC.viewAutomataHeader (Alphabet.NonDeterministic afnd.alphabet)
:: getAutomatonRows afnd
)
{- Given an AFND, return a list of rows that represent the states and
transitions
-}
getAutomatonRows : Automata.AFND -> List (Html Types.Msg)
getAutomatonRows afnd =
List.map (\state -> getStateRow afnd state) afnd.states
{- Given an AFND and a State, return the row that represents the State -}
getStateRow : Automata.AFND -> State.State -> Html Types.Msg
getStateRow afnd prevState =
let
isInitial =
prevState == afnd.initialState
isFinal =
List.member prevState afnd.finalStates
prefix =
if isInitial && isFinal then
"->*"
else if isInitial then
"->"
else if isFinal then
"*"
else
""
prefixSelect =
select
[ onInput
(\new ->
case new of
"->*" ->
{ afnd
| initialState = prevState
, finalStates =
afnd.finalStates
++ [ prevState ]
|> Utils.removeDuplicates
}
|> afndToGeneral
|> Types.UpdateCurrent
"->" ->
{ afnd
| initialState = prevState
, finalStates =
List.filter ((/=) prevState)
afnd.finalStates
}
|> afndToGeneral
|> Types.UpdateCurrent
"*" ->
{ afnd
| finalStates =
afnd.finalStates
++ [ prevState ]
|> Utils.removeDuplicates
}
|> afndToGeneral
|> Types.UpdateCurrent
_ ->
{ afnd
| finalStates =
List.filter
((/=) prevState)
afnd.finalStates
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
(List.map
(\t ->
option
[ value t, selected (t == prefix) ]
[ text t ]
)
(if prevState == afnd.initialState then
[ "->*", "->" ]
else
[ "->*", "->", "*", "" ]
)
)
transitions =
Utils.getFlatOutTransitionsNonDeterministic afnd prevState
|> Utils.sortTransitionsNonDeterministic
|> Utils.swapFirstAndLast
in
tr tableRowStyles
(td tableItemStyles
[ button
[ disabled isInitial
, onClick
({ afnd
| states = List.filter ((/=) prevState) afnd.states
, finalStates =
List.filter ((/=) prevState) afnd.finalStates
, transitions =
List.filterMap
(\transition ->
if
List.member prevState
transition.nextStates
then
Just
{ transition
| nextStates =
case
transition.nextStates
|> List.filter
((/=) prevState)
of
[] ->
[ State.Dead ]
a ->
a
}
else if
transition.prevState
== prevState
then
Nothing
else
Just transition
)
afnd.transitions
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
[ text "Remover estado" ]
]
:: td tableItemStyles
[ prefixSelect
, text <| stateToString prevState
]
:: List.map
(\transition ->
viewFlatNonDeterministicTransition transition afnd
|> td tableItemStyles
)
transitions
)
{- Helper function to convert the nextState of a Transition to a String -}
viewFlatNonDeterministicTransition :
Transition.NonDeterministicTransition
-> Automata.AFND
-> List (Html Types.Msg)
viewFlatNonDeterministicTransition transition afnd =
List.map
(\state ->
select
[ onInput
(\new ->
{ afnd
| transitions =
Utils.replaceBy transition
{ transition
| nextStates =
case
Utils.replaceBy
state
(stringToState new)
transition.nextStates
|> Utils.removeDuplicates
|> List.filter
((/=) State.Dead)
of
[] ->
[ State.Dead ]
a ->
a
}
afnd.transitions
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
(List.filterMap
(\s ->
if
List.member s transition.nextStates
&& s
/= state
then
Nothing
else
Just <|
option
[ value (stateToString s)
, selected (s == state)
]
[ text (stateToString s) ]
)
(afnd.states ++ [ State.Dead ])
)
)
transition.nextStates
++ [ select
[ onInput
(\new ->
{ afnd
| transitions =
Utils.replaceBy transition
{ transition
| nextStates =
transition.nextStates
++ [ stringToState new ]
|> List.filter ((/=) State.Dead)
}
afnd.transitions
}
|> afndToGeneral
|> Types.UpdateCurrent
)
]
(option [ value "+", selected True ] [ text "+" ]
:: List.filterMap
(\state ->
if List.member state transition.nextStates then
Nothing
else
Just <|
option [ value (stateToString state) ]
[ text (stateToString state) ]
)
afnd.states
)
]
{- Turn an AFND into a general model -}
afndToGeneral : Automata.AFND -> Models.General
afndToGeneral =
Automata.FiniteNonDeterministic >> Models.Automaton
{- Turn a list of states into a string -}
statesToString : List State.State -> String
statesToString states =
case states of
[ State.Dead ] ->
"-"
_ ->
List.filter (\state -> state /= State.Dead) states
|> List.map stateToString
|> String.join ", "
{- Turn a state into a string -}
stateToString : State.State -> String
stateToString state =
case state of
State.Dead ->
"-"
State.Valid label ->
label
{- Read a string into a state -}
stringToState : String -> State.State
stringToState label =
if label == "-" then
State.Dead
else
State.Valid label
| elm |
[
{
"context": "{-\n Swaggy Jenkins\n Jenkins API clients generated from Swagger / O",
"end": 20,
"score": 0.9995280504,
"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.9999185801,
"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.9996535182,
"start": 240,
"tag": "USERNAME",
"value": "openapitools"
}
] | clients/elm/generated/src/Data/GithubContent.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.GithubContent exposing (GithubContent, githubContentDecoder, githubContentEncoder)
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 GithubContent =
{ name : Maybe String
, sha : Maybe String
, class : Maybe String
, repo : Maybe String
, size : Maybe Int
, owner : Maybe String
, path : Maybe String
, base64Data : Maybe String
}
githubContentDecoder : Decoder GithubContent
githubContentDecoder =
decode GithubContent
|> optional "name" (Decode.nullable Decode.string) Nothing
|> optional "sha" (Decode.nullable Decode.string) Nothing
|> optional "_class" (Decode.nullable Decode.string) Nothing
|> optional "repo" (Decode.nullable Decode.string) Nothing
|> optional "size" (Decode.nullable Decode.int) Nothing
|> optional "owner" (Decode.nullable Decode.string) Nothing
|> optional "path" (Decode.nullable Decode.string) Nothing
|> optional "base64Data" (Decode.nullable Decode.string) Nothing
githubContentEncoder : GithubContent -> Encode.Value
githubContentEncoder model =
Encode.object
[ ( "name", withDefault Encode.null (map Encode.string model.name) )
, ( "sha", withDefault Encode.null (map Encode.string model.sha) )
, ( "_class", withDefault Encode.null (map Encode.string model.class) )
, ( "repo", withDefault Encode.null (map Encode.string model.repo) )
, ( "size", withDefault Encode.null (map Encode.int model.size) )
, ( "owner", withDefault Encode.null (map Encode.string model.owner) )
, ( "path", withDefault Encode.null (map Encode.string model.path) )
, ( "base64Data", withDefault Encode.null (map Encode.string model.base64Data) )
]
| 27396 | {-
<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.GithubContent exposing (GithubContent, githubContentDecoder, githubContentEncoder)
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 GithubContent =
{ name : Maybe String
, sha : Maybe String
, class : Maybe String
, repo : Maybe String
, size : Maybe Int
, owner : Maybe String
, path : Maybe String
, base64Data : Maybe String
}
githubContentDecoder : Decoder GithubContent
githubContentDecoder =
decode GithubContent
|> optional "name" (Decode.nullable Decode.string) Nothing
|> optional "sha" (Decode.nullable Decode.string) Nothing
|> optional "_class" (Decode.nullable Decode.string) Nothing
|> optional "repo" (Decode.nullable Decode.string) Nothing
|> optional "size" (Decode.nullable Decode.int) Nothing
|> optional "owner" (Decode.nullable Decode.string) Nothing
|> optional "path" (Decode.nullable Decode.string) Nothing
|> optional "base64Data" (Decode.nullable Decode.string) Nothing
githubContentEncoder : GithubContent -> Encode.Value
githubContentEncoder model =
Encode.object
[ ( "name", withDefault Encode.null (map Encode.string model.name) )
, ( "sha", withDefault Encode.null (map Encode.string model.sha) )
, ( "_class", withDefault Encode.null (map Encode.string model.class) )
, ( "repo", withDefault Encode.null (map Encode.string model.repo) )
, ( "size", withDefault Encode.null (map Encode.int model.size) )
, ( "owner", withDefault Encode.null (map Encode.string model.owner) )
, ( "path", withDefault Encode.null (map Encode.string model.path) )
, ( "base64Data", withDefault Encode.null (map Encode.string model.base64Data) )
]
| 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.GithubContent exposing (GithubContent, githubContentDecoder, githubContentEncoder)
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 GithubContent =
{ name : Maybe String
, sha : Maybe String
, class : Maybe String
, repo : Maybe String
, size : Maybe Int
, owner : Maybe String
, path : Maybe String
, base64Data : Maybe String
}
githubContentDecoder : Decoder GithubContent
githubContentDecoder =
decode GithubContent
|> optional "name" (Decode.nullable Decode.string) Nothing
|> optional "sha" (Decode.nullable Decode.string) Nothing
|> optional "_class" (Decode.nullable Decode.string) Nothing
|> optional "repo" (Decode.nullable Decode.string) Nothing
|> optional "size" (Decode.nullable Decode.int) Nothing
|> optional "owner" (Decode.nullable Decode.string) Nothing
|> optional "path" (Decode.nullable Decode.string) Nothing
|> optional "base64Data" (Decode.nullable Decode.string) Nothing
githubContentEncoder : GithubContent -> Encode.Value
githubContentEncoder model =
Encode.object
[ ( "name", withDefault Encode.null (map Encode.string model.name) )
, ( "sha", withDefault Encode.null (map Encode.string model.sha) )
, ( "_class", withDefault Encode.null (map Encode.string model.class) )
, ( "repo", withDefault Encode.null (map Encode.string model.repo) )
, ( "size", withDefault Encode.null (map Encode.int model.size) )
, ( "owner", withDefault Encode.null (map Encode.string model.owner) )
, ( "path", withDefault Encode.null (map Encode.string model.path) )
, ( "base64Data", withDefault Encode.null (map Encode.string model.base64Data) )
]
| elm |
[
{
"context": "{-\n Swaggy Jenkins\n Jenkins API clients generated from Swagger / O",
"end": 20,
"score": 0.9983317256,
"start": 6,
"tag": "NAME",
"value": "Swaggy Jenkins"
},
{
"context": "n of the OpenAPI document: 1.1.2-pre.0\n Contact: blah@cliffano.com\n\n NOTE: This file is auto generated by the open",
"end": 174,
"score": 0.9999109507,
"start": 157,
"tag": "EMAIL",
"value": "blah@cliffano.com"
},
{
"context": "d by the openapi-generator.\n https://github.com/openapitools/openapi-generator.git\n\n DO NOT EDIT THIS FILE M",
"end": 273,
"score": 0.9996128082,
"start": 261,
"tag": "USERNAME",
"value": "openapitools"
},
{
"context": "For more info on generating Elm code, see https://eriktim.github.io/openapi-elm/\n-}\n\n\nmodule Api.Request.Ba",
"end": 393,
"score": 0.9848231077,
"start": 386,
"tag": "USERNAME",
"value": "eriktim"
}
] | clients/elm/generated/src/Api/Request/Base.elm | cliffano/jenkins-api-clients-generator | 0 | {-
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification
The version of the OpenAPI document: 1.1.2-pre.0
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.
For more info on generating Elm code, see https://eriktim.github.io/openapi-elm/
-}
module Api.Request.Base exposing
( getCrumb
)
import Api
import Api.Data
import Dict
import Http
import Json.Decode
import Json.Encode
{-| Retrieve CSRF protection token
-}
getCrumb : Api.Request Api.Data.DefaultCrumbIssuer
getCrumb =
Api.request
"GET"
"/crumbIssuer/api/json"
[]
[]
[]
Nothing
Api.Data.defaultCrumbIssuerDecoder
| 8121 | {-
<NAME>
Jenkins API clients generated from Swagger / Open API specification
The version of the OpenAPI document: 1.1.2-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.
For more info on generating Elm code, see https://eriktim.github.io/openapi-elm/
-}
module Api.Request.Base exposing
( getCrumb
)
import Api
import Api.Data
import Dict
import Http
import Json.Decode
import Json.Encode
{-| Retrieve CSRF protection token
-}
getCrumb : Api.Request Api.Data.DefaultCrumbIssuer
getCrumb =
Api.request
"GET"
"/crumbIssuer/api/json"
[]
[]
[]
Nothing
Api.Data.defaultCrumbIssuerDecoder
| true | {-
PI:NAME:<NAME>END_PI
Jenkins API clients generated from Swagger / Open API specification
The version of the OpenAPI document: 1.1.2-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.
For more info on generating Elm code, see https://eriktim.github.io/openapi-elm/
-}
module Api.Request.Base exposing
( getCrumb
)
import Api
import Api.Data
import Dict
import Http
import Json.Decode
import Json.Encode
{-| Retrieve CSRF protection token
-}
getCrumb : Api.Request Api.Data.DefaultCrumbIssuer
getCrumb =
Api.request
"GET"
"/crumbIssuer/api/json"
[]
[]
[]
Nothing
Api.Data.defaultCrumbIssuerDecoder
| elm |
[
{
"context": "B, (3CDE [FG] |\\x0D\\n\"\n\n\nonlyKeyHeader =\n \"K: CMajor\\x0D\\n| A,B, (3CDE [FG] |\\x0D\\n\"\n\n\njustTempoAndKey",
"end": 1813,
"score": 0.6911395192,
"start": 1808,
"tag": "KEY",
"value": "Major"
}
] | tests/Test/Tempo.elm | newlandsvalley/elm-abc-parser | 6 | module Test.Tempo exposing (tests)
import Test exposing (..)
import Expect exposing (..)
import Music.Tempo exposing (..)
import Test.Utils exposing (assertMoveMatches, assertIntFuncMatches)
import Result exposing (..)
import Debug exposing (..)
tests : Test
tests =
describe "tempo change"
[ test "get the tempo from header" <|
\() ->
(assertIntFuncMatches
fullHeaderHigh
getBpm
132
)
, test "get the default tempo when there's no header" <|
\() ->
(assertIntFuncMatches
noHeader
getBpm
120
)
, test "alter tempo of existing header" <|
\() ->
(assertMoveMatches
fullHeaderMed
(setBpm 132)
fullHeaderHigh
)
, test "new tempo from default of no headers" <|
\() ->
(assertMoveMatches
noHeader
(setBpm 144)
justTempoHeader
)
, test "new tempo from default of only Key header" <|
\() ->
(assertMoveMatches
onlyKeyHeader
(setBpm 84)
justTempoAndKeyHeader
)
]
fullHeaderMed =
"X: 1\x0D\nT: a title\x0D\nQ: 1/4=120\x0D\nM: 3/4\x0D\nK: CMajor\x0D\n| A,B, (3CDE [FG] |\x0D\n"
fullHeaderHigh =
"X: 1\x0D\nT: a title\x0D\nM: 3/4\x0D\nQ: 1/4=132\x0D\nK: CMajor\x0D\n| A,B, (3CDE [FG] |\x0D\n"
noHeader =
"| A,B, (3CDE [FG] |\x0D\n"
justTempoHeader =
"Q: 1/4=144\x0D\n| A,B, (3CDE [FG] |\x0D\n"
onlyKeyHeader =
"K: CMajor\x0D\n| A,B, (3CDE [FG] |\x0D\n"
justTempoAndKeyHeader =
"Q: 1/4=84\x0D\nK: CMajor\x0D\n| A,B, (3CDE [FG] |\x0D\n"
| 273 | module Test.Tempo exposing (tests)
import Test exposing (..)
import Expect exposing (..)
import Music.Tempo exposing (..)
import Test.Utils exposing (assertMoveMatches, assertIntFuncMatches)
import Result exposing (..)
import Debug exposing (..)
tests : Test
tests =
describe "tempo change"
[ test "get the tempo from header" <|
\() ->
(assertIntFuncMatches
fullHeaderHigh
getBpm
132
)
, test "get the default tempo when there's no header" <|
\() ->
(assertIntFuncMatches
noHeader
getBpm
120
)
, test "alter tempo of existing header" <|
\() ->
(assertMoveMatches
fullHeaderMed
(setBpm 132)
fullHeaderHigh
)
, test "new tempo from default of no headers" <|
\() ->
(assertMoveMatches
noHeader
(setBpm 144)
justTempoHeader
)
, test "new tempo from default of only Key header" <|
\() ->
(assertMoveMatches
onlyKeyHeader
(setBpm 84)
justTempoAndKeyHeader
)
]
fullHeaderMed =
"X: 1\x0D\nT: a title\x0D\nQ: 1/4=120\x0D\nM: 3/4\x0D\nK: CMajor\x0D\n| A,B, (3CDE [FG] |\x0D\n"
fullHeaderHigh =
"X: 1\x0D\nT: a title\x0D\nM: 3/4\x0D\nQ: 1/4=132\x0D\nK: CMajor\x0D\n| A,B, (3CDE [FG] |\x0D\n"
noHeader =
"| A,B, (3CDE [FG] |\x0D\n"
justTempoHeader =
"Q: 1/4=144\x0D\n| A,B, (3CDE [FG] |\x0D\n"
onlyKeyHeader =
"K: C<KEY>\x0D\n| A,B, (3CDE [FG] |\x0D\n"
justTempoAndKeyHeader =
"Q: 1/4=84\x0D\nK: CMajor\x0D\n| A,B, (3CDE [FG] |\x0D\n"
| true | module Test.Tempo exposing (tests)
import Test exposing (..)
import Expect exposing (..)
import Music.Tempo exposing (..)
import Test.Utils exposing (assertMoveMatches, assertIntFuncMatches)
import Result exposing (..)
import Debug exposing (..)
tests : Test
tests =
describe "tempo change"
[ test "get the tempo from header" <|
\() ->
(assertIntFuncMatches
fullHeaderHigh
getBpm
132
)
, test "get the default tempo when there's no header" <|
\() ->
(assertIntFuncMatches
noHeader
getBpm
120
)
, test "alter tempo of existing header" <|
\() ->
(assertMoveMatches
fullHeaderMed
(setBpm 132)
fullHeaderHigh
)
, test "new tempo from default of no headers" <|
\() ->
(assertMoveMatches
noHeader
(setBpm 144)
justTempoHeader
)
, test "new tempo from default of only Key header" <|
\() ->
(assertMoveMatches
onlyKeyHeader
(setBpm 84)
justTempoAndKeyHeader
)
]
fullHeaderMed =
"X: 1\x0D\nT: a title\x0D\nQ: 1/4=120\x0D\nM: 3/4\x0D\nK: CMajor\x0D\n| A,B, (3CDE [FG] |\x0D\n"
fullHeaderHigh =
"X: 1\x0D\nT: a title\x0D\nM: 3/4\x0D\nQ: 1/4=132\x0D\nK: CMajor\x0D\n| A,B, (3CDE [FG] |\x0D\n"
noHeader =
"| A,B, (3CDE [FG] |\x0D\n"
justTempoHeader =
"Q: 1/4=144\x0D\n| A,B, (3CDE [FG] |\x0D\n"
onlyKeyHeader =
"K: CPI:KEY:<KEY>END_PI\x0D\n| A,B, (3CDE [FG] |\x0D\n"
justTempoAndKeyHeader =
"Q: 1/4=84\x0D\nK: CMajor\x0D\n| A,B, (3CDE [FG] |\x0D\n"
| elm |