@@ -5,7 +5,7 @@ defmodule ComponentsGuideWeb.ColorLive do
55 defmodule State do
66 defstruct color: { :lab , 50 , 100 , - 128 }
77
8- def from_input (
8+ def decode (
99 "#" <>
1010 << r1 :: utf8 >> <>
1111 << r2 :: utf8 >> <> << g1 :: utf8 >> <> << g2 :: utf8 >> <> << b1 :: utf8 >> <> << b2 :: utf8 >>
@@ -25,6 +25,19 @@ defmodule ComponentsGuideWeb.ColorLive do
2525 % State { color: color }
2626 end
2727
28+ def decode ( :lab , input ) when is_binary ( input ) do
29+ { l , << "," :: utf8 >> <> rest } = Integer . parse ( input )
30+ { a , << "," :: utf8 >> <> rest } = Integer . parse ( rest )
31+ { b , "" } = Integer . parse ( rest )
32+
33+ % __MODULE__ { color: { :lab , l , a , b } }
34+ end
35+
36+ def encode ( % __MODULE__ { color: color } ) do
37+ { :lab , l , a , b } = color
38+ "#{ l } ,#{ a } ,#{ b } "
39+ end
40+
2841 def set_color ( state = % __MODULE__ { } , color ) , do: % { state | color: color }
2942
3043 def l ( % __MODULE__ { color: { :lab , l , _ , _ } } ) , do: l
@@ -103,7 +116,7 @@ defmodule ComponentsGuideWeb.ColorLive do
103116 end
104117
105118 def handle_params ( % { "definition" => definition } , _path , socket ) do
106- state = State . from_input ( definition )
119+ state = State . decode ( :lab , definition )
107120 { :noreply , socket |> assign ( :state , state ) }
108121 end
109122
@@ -118,11 +131,12 @@ defmodule ComponentsGuideWeb.ColorLive do
118131 b = b |> String . to_integer ( )
119132
120133 state = socket . assigns . state |> State . set_color ( { :lab , l , a , b } )
121- hex = state |> State . hex ( )
134+ encoded = State . encode ( state )
122135
136+ # TODO: throttle for Safari’s
137+ # SecurityError: Attempt to use history.replaceState() more than 100 times per 30 seconds
123138 { :noreply ,
124139 socket
125- |> assign ( :state , state )
126- |> push_patch ( to: Routes . color_path ( socket , :show , hex ) , replace: true ) }
140+ |> push_patch ( to: Routes . color_path ( socket , :lab , encoded ) , replace: true ) }
127141 end
128142end
0 commit comments