Current section

Files

Jump to
sprocket src sprocket@hooks@state.erl
Raw

src/sprocket@hooks@state.erl

-module(sprocket@hooks@state).
-compile([no_auto_import, nowarn_unused_vars]).
-export([state/3]).
-spec state(
sprocket@context:context(),
MSY,
fun((sprocket@context:context(), MSY, fun((MSY) -> nil)) -> {sprocket@context:context(),
list(sprocket@context:element())})
) -> {sprocket@context:context(), list(sprocket@context:element())}.
state(Ctx, Initial, Cb) ->
{context, _, _, _, Render_update, Update_hook, _} = Ctx,
Init_state = fun() ->
{state,
sprocket@internal@utils@unique:new(),
gleam@dynamic:from(Initial)}
end,
_assert_subject = sprocket@context:fetch_or_init_hook(Ctx, Init_state),
{Ctx@1, {state, Hook_id, Value}, _} = case _assert_subject of
{_, {state, _, _}, _} -> _assert_subject;
_assert_fail ->
erlang:error(#{gleam_error => let_assert,
message => <<"Assertion pattern match failed"/utf8>>,
value => _assert_fail,
module => <<"sprocket/hooks/state"/utf8>>,
function => <<"state"/utf8>>,
line => 16})
end,
Setter = fun(Value@1) ->
Update_hook(Hook_id, fun(Hook) -> case Hook of
{state, Id, _} when Id =:= Hook_id ->
{state, Id, gleam@dynamic:from(Value@1)};
_ ->
sprocket@internal@exceptions:throw_on_unexpected_hook_result(
Hook
)
end end),
Render_update()
end,
Cb(Ctx@1, gleam@dynamic:unsafe_coerce(Value), Setter).