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

Allow any term to be used as tag in Kino.Control.tagged_stream/1 #485

Merged
merged 1 commit into from
Dec 26, 2024
Merged
Show file tree
Hide file tree
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
8 changes: 5 additions & 3 deletions lib/kino/control.ex
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,8 @@ defmodule Kino.Control do
@doc """
Same as `stream/1`, but attaches custom tag to every stream item.

Tags can be arbitrary terms.

## Example

button = Kino.Control.button("Hello")
Expand All @@ -414,17 +416,17 @@ defmodule Kino.Control do
#=> {:hello, %{origin: "client1", type: :click}}
#=> {:check, %{origin: "client1", type: :change, value: true}}
"""
@spec tagged_stream(keyword(event_source())) :: Enumerable.t()
@spec tagged_stream(list({tag :: term(), event_source()})) :: Enumerable.t()
def tagged_stream(entries) when is_list(entries) do
{tagged_topics, tagged_intervals} =
for entry <- entries, reduce: {[], []} do
{tagged_topics, tagged_intervals} ->
case entry do
{tag, source} when is_atom(tag) ->
{_tag, source} ->
assert_stream_source!(source)

_other ->
raise ArgumentError, "expected a keyword list, got: #{inspect(entries)}"
raise ArgumentError, "expected a list of 2-element tuples, got: #{inspect(entries)}"
end

{tag, source} = entry
Expand Down
12 changes: 11 additions & 1 deletion test/kino/control_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ defmodule Kino.ControlTest do

describe "tagged_stream/1" do
test "raises on invalid argument" do
assert_raise ArgumentError, "expected a keyword list, got: [0]", fn ->
assert_raise ArgumentError, "expected a list of 2-element tuples, got: [0]", fn ->
Kino.Control.tagged_stream([0])
end

Expand All @@ -191,6 +191,16 @@ defmodule Kino.ControlTest do
|> Enum.take(2)

assert Enum.sort(events) == [{:click, %{origin: "client1"}}, {:name, %{origin: "client2"}}]

events =
[{{:click, "button"}, button}, {{:name, "text"}, input}]
|> Kino.Control.tagged_stream()
|> Enum.take(2)

assert Enum.sort(events) == [
{{:click, "button"}, %{origin: "client1"}},
{{:name, "text"}, %{origin: "client2"}}
]
end
end

Expand Down
Loading