Skip to content
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
5 changes: 4 additions & 1 deletion lib/lavash/chip_set.ex
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,14 @@ defmodule Lavash.ChipSet do
template do
~H"""
<div class="flex flex-wrap gap-2">
<%!-- data-lavash-member is auto-injected from the class
expression: prop-ref branches become an interpolated
directive, and the loop-var value rides phx-value-val
(#129) --%>
<button
:for={value <- @values}
type="button"
class={if value in (@selected || []), do: @active_class, else: @inactive_class}
data-lavash-member={"selected|#{@active_class}|#{@inactive_class}"}
phx-click="toggle"
phx-value-val={value}
>
Expand Down
96 changes: 78 additions & 18 deletions lib/lavash/optimistic/data_attr_transformer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,13 @@ defmodule Lavash.Optimistic.DataAttrTransformer do
`data-lavash-member-value="x"` injected when `:selected` is an
optimistic array field.

Also matched (#129): the nil-safe list (`value in (@selected ||
[])`), prop-ref class branches (`do: @active_class` — the
directive becomes an interpolated expression resolved at render),
and a loop-variable value — which injects no `member-value` and
requires the element to carry `phx-value-val`, the per-row value
the JS reads inside `:for` loops (the ChipSet shape).

### 7. Reactive attribute derives

For any attr listed in `metadata[:attr_derives]` (computed by
Expand Down Expand Up @@ -530,21 +537,54 @@ defmodule Lavash.Optimistic.DataAttrTransformer do
attrs
else
with {:expr, expr, _meta} <- AttrHelpers.get_attr_value(attrs, "class"),
{:ok, value_str, field_name, true_str, false_str} <- parse_membership_class_if(expr),
{:ok, member_value, field_name, true_cls, false_cls} <-
parse_membership_class_if(expr),
field_atom = safe_existing_atom(field_name),
true <- not is_nil(field_atom),
true <- is_map_key(metadata[:optimistic_fields] || %{}, field_atom) do
directive = "#{field_name}|#{true_str}|#{false_str}"

attrs
|> AttrHelpers.add_attr_if_missing("data-lavash-member", {:string, directive})
|> AttrHelpers.add_attr_if_missing("data-lavash-member-value", {:string, value_str})
true <- is_map_key(metadata[:optimistic_fields] || %{}, field_atom),
{:ok, attrs} <- add_member_value(attrs, member_value) do
AttrHelpers.add_attr_if_missing(
attrs,
"data-lavash-member",
member_directive(field_name, true_cls, false_cls)
)
else
_ -> attrs
end
end
end

# Literal member values ride data-lavash-member-value; a loop
# variable (the ChipSet shape — `value in @selected` inside :for)
# can't be injected statically, so the element must already carry
# phx-value-val, which the JS reads as the per-row value (#129).
defp add_member_value(attrs, {:literal, value_str}) do
{:ok,
AttrHelpers.add_attr_if_missing(attrs, "data-lavash-member-value", {:string, value_str})}
end

defp add_member_value(attrs, :loop_var) do
if AttrHelpers.has_attr?(attrs, "phx-value-val"), do: {:ok, attrs}, else: :error
end

# Literal class branches produce a static directive; prop-ref
# branches (`do: @active_class`) produce an interpolated expression
# attr so the directive resolves at render time (#129).
defp member_directive(field_name, true_cls, false_cls) do
if match?({:literal, _}, true_cls) and match?({:literal, _}, false_cls) do
{:literal, t} = true_cls
{:literal, f} = false_cls
{:string, "#{field_name}|#{t}|#{f}"}
else
{:expr,
~s("#{field_name}|" <> #{member_cls_source(true_cls)} <> "|" <> #{member_cls_source(false_cls)}),
%{line: 0, column: 0}}
end
end

defp member_cls_source({:literal, s}), do: inspect(s)
defp member_cls_source({:prop, name}), do: "(@#{name} || \"\")"

# ============================================
# Pattern 7: reactive attribute derives
# ============================================
Expand Down Expand Up @@ -626,15 +666,11 @@ defmodule Lavash.Optimistic.DataAttrTransformer do
defp parse_membership_class_if(source) do
case Code.string_to_quoted(source) do
{:ok,
{:if, _,
[
{:in, _, [value_ast, {:@, _, [{field, _, ctx}]}]},
[do: true_branch, else: false_branch]
]}}
when is_atom(field) and is_atom(ctx) ->
with {:ok, val} <- as_member_value(value_ast),
{:ok, t} <- as_class_string(true_branch),
{:ok, f} <- as_class_string(false_branch) do
{:if, _, [{:in, _, [value_ast, selected_ast]}, [do: true_branch, else: false_branch]]}} ->
with {:ok, field} <- member_field(selected_ast),
{:ok, val} <- as_member_value(value_ast),
{:ok, t} <- as_member_class(true_branch),
{:ok, f} <- as_member_class(false_branch) do
{:ok, val, Atom.to_string(field), t, f}
end

Expand All @@ -643,12 +679,36 @@ defmodule Lavash.Optimistic.DataAttrTransformer do
end
end

# `value in @selected` and the nil-safe `value in (@selected || [])`
defp member_field({:@, _, [{field, _, ctx}]}) when is_atom(field) and is_atom(ctx),
do: {:ok, field}

defp member_field({:||, _, [{:@, _, [{field, _, ctx}]}, []]})
when is_atom(field) and is_atom(ctx),
do: {:ok, field}

defp member_field(_), do: :error

# Class branches: string literals, or prop refs like @active_class
# (resolved at render time via an interpolated directive)
defp as_member_class({:@, _, [{name, _, ctx}]}) when is_atom(name) and is_atom(ctx),
do: {:ok, {:prop, name}}

defp as_member_class(branch) do
with {:ok, s} <- as_class_string(branch), do: {:ok, {:literal, s}}
end

defp as_class_string(s) when is_binary(s), do: {:ok, s}
defp as_class_string(nil), do: {:ok, ""}
defp as_class_string(_), do: :error

defp as_member_value(s) when is_binary(s), do: {:ok, s}
defp as_member_value(a) when is_atom(a), do: {:ok, Atom.to_string(a)}
defp as_member_value(s) when is_binary(s), do: {:ok, {:literal, s}}

# A bare lowercase variable (no @) is a :for loop binding — the
# per-row value must come from phx-value-val at runtime (#129)
defp as_member_value({name, _, ctx}) when is_atom(name) and is_atom(ctx), do: {:ok, :loop_var}

defp as_member_value(a) when is_atom(a), do: {:ok, {:literal, Atom.to_string(a)}}
defp as_member_value(_), do: :error

defp optimistic_boolean?(field_atom, metadata) do
Expand Down
56 changes: 56 additions & 0 deletions test/lavash/template/token_transformer_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,62 @@ defmodule Lavash.Template.TokenTransformerTest do
end
end

describe "class member injection — ChipSet shapes (#129)" do
test "loop-var value + prop-ref branches + nil-safe list" do
tokens = [
tag("button", [
expr_attr(
"class",
"if value in (@selected || []), do: @active_class, else: @inactive_class"
),
expr_attr("phx-value-val", "value")
])
]

metadata = optimistic_metadata([{:selected, :list}])
[{:block, :tag, "button", attrs, _, _, _}] = transform(tokens, metadata)

expected_directive =
"\"selected|\" <> (@active_class || \"\") <> \"|\" <> (@inactive_class || \"\")"

assert {"data-lavash-member", {:expr, ^expected_directive, _}, _} =
Enum.find(attrs, &match?({"data-lavash-member", _, _}, &1))

# loop-var value rides phx-value-val — no member-value injected
refute Enum.any?(attrs, &match?({"data-lavash-member-value", _, _}, &1))
end

test "loop-var value WITHOUT phx-value-val gets no injection" do
tokens = [
tag("button", [
expr_attr("class", "if value in @selected, do: \"on\", else: \"off\"")
])
]

metadata = optimistic_metadata([{:selected, :list}])
[{:block, :tag, "button", attrs, _, _, _}] = transform(tokens, metadata)

refute Enum.any?(attrs, &match?({"data-lavash-member", _, _}, &1))
end

test "literal value and classes still inject the static directive" do
tokens = [
tag("span", [
expr_attr("class", "if \"x\" in @items, do: \"sel\", else: \"unsel\"")
])
]

metadata = optimistic_metadata([{:items, :list}])
[{:block, :tag, "span", attrs, _, _, _}] = transform(tokens, metadata)

assert {"data-lavash-member", {:string, "items|sel|unsel", _}, _} =
Enum.find(attrs, &match?({"data-lavash-member", _, _}, &1))

assert {"data-lavash-member-value", {:string, "x", _}, _} =
Enum.find(attrs, &match?({"data-lavash-member-value", _, _}, &1))
end
end

# ============================================
# phx-target injection
# ============================================
Expand Down
Loading