Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a function that creates a color from a hexadecimal string. #229

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 139 additions & 0 deletions src/Element.elm
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,145 @@ toRgb (Internal.Rgba r g b a) =
}



{- Create a color from a Hexadecimal string -}


hex : String -> Color
hex hexCode =
let
hexCharToInt : Char -> Maybe Int
hexCharToInt char =
let
validChars =
"0123456789abcdef"

indexedList =
List.indexedMap Tuple.pair <| String.toList validChars

searchResult =
List.head <|
List.filter
(\( _, value ) -> value == char)
indexedList
in
case searchResult of
Nothing ->
Nothing

Just ( integer, _ ) ->
Just integer

tupleIt : String -> Maybe ( Char, Char )
tupleIt str =
let
list =
String.toList <| String.toLower str

head =
List.head list

last =
List.head <| List.reverse list
in
case head of
Nothing ->
Nothing

Just first ->
case last of
Nothing ->
Nothing

Just second ->
Just ( first, second )

charTupToIntTup : Maybe ( Char, Char ) -> Maybe ( Int, Int )
charTupToIntTup charTup =
case charTup of
Nothing ->
Nothing

Just ( tupA, tupB ) ->
let
mbyA =
hexCharToInt tupA

mbyB =
hexCharToInt tupB
in
case mbyA of
Nothing ->
Nothing

Just a ->
case mbyB of
Nothing ->
Nothing

Just b ->
Just ( a, b )

toBase10 : Maybe ( Int, Int ) -> Maybe Int
toBase10 tuple =
case tuple of
Nothing ->
Nothing

Just ( a, b ) ->
Just (a * 16 + b)

firstChar =
List.head <| String.toList hexCode

maybeR =
toBase10 <|
charTupToIntTup <|
tupleIt <|
String.slice 1 3 hexCode

maybeG =
toBase10 <|
charTupToIntTup <|
tupleIt <|
String.slice 3 5 hexCode

maybeB =
toBase10 <|
charTupToIntTup <|
tupleIt <|
String.slice 5 7 hexCode

failColor =
rgb255 255 0 0
in
if String.length hexCode == 7 then
case firstChar of
Just '#' ->
case maybeR of
Nothing ->
failColor

Just r ->
case maybeG of
Nothing ->
failColor

Just g ->
case maybeB of
Nothing ->
failColor

Just b ->
rgb255 r g b

_ ->
failColor

else
failColor


{-| The basic building block of your layout.

howdy : Element msg
Expand Down