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

New variant for tags-mode #78

Merged
merged 11 commits into from
Dec 27, 2024
5 changes: 3 additions & 2 deletions lib/live_select.ex
Original file line number Diff line number Diff line change
Expand Up @@ -370,9 +370,10 @@ defmodule LiveSelect do
~S(an id to assign to the component. If none is provided, `#{form_name}_#{field}_live_select_component` will be used)

attr :mode, :atom,
values: [:single, :tags],
values: [:single, :tags, :quick_tags],
default: Component.default_opts()[:mode],
doc: "either `:single` (for single selection), or `:tags` (for multiple selection using tags)"
doc:
"either `:single` (for single selection), `:tags` (for multiple selection using tags), or :quick_tags (tags mode but can select multiple at a time)"

attr :options, :list,
doc:
Expand Down
68 changes: 62 additions & 6 deletions lib/live_select/component.ex
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ defmodule LiveSelect.Component do
none: []
]

@modes ~w(single tags)a
@modes ~w(single tags quick_tags)a

@impl true
def mount(socket) do
Expand Down Expand Up @@ -429,25 +429,48 @@ defmodule LiveSelect.Component do

defp maybe_select(%{assigns: %{active_option: -1}} = socket, _extra_params), do: socket

defp maybe_select(
%{assigns: %{active_option: active_option, options: options, selection: selection}} =
socket,
extra_params
)
when active_option >= 0 do
option = Enum.at(options, active_option)

if already_selected?(option, selection) do
pos = get_selection_index(option, selection)
unselect(socket, pos)
else
select(socket, Enum.at(options, active_option), extra_params)
ringvold marked this conversation as resolved.
Show resolved Hide resolved
end
end

defp maybe_select(socket, extra_params) do
select(socket, Enum.at(socket.assigns.options, socket.assigns.active_option), extra_params)
end

defp get_selection_index(option, selection) do
Enum.find_index(selection, fn %{label: label} -> label == option.label end)
end

defp select(socket, selected, extra_params) do
selection =
case socket.assigns.mode do
:tags ->
socket.assigns.selection ++ [selected]

:quick_tags ->
socket.assigns.selection ++ [selected]

_ ->
[selected]
ringvold marked this conversation as resolved.
Show resolved Hide resolved
end

socket
|> assign(
active_option: -1,
active_option: if(quick_tags_mode?(socket), do: socket.assigns.active_option, else: -1),
selection: selection,
hide_dropdown: true
hide_dropdown: not quick_tags_mode?(socket)
)
|> maybe_save_selection()
|> client_select(Map.merge(%{input_event: true}, extra_params))
Expand Down Expand Up @@ -521,7 +544,7 @@ defmodule LiveSelect.Component do
List.wrap(normalize_selection_value(value, options ++ current_selection, value_mapper))
end

defp update_selection(value, current_selection, options, :tags, value_mapper) do
defp update_selection(value, current_selection, options, _mode, value_mapper) do
value = if Enumerable.impl_for(value), do: value, else: [value]

Enum.map(value, &normalize_selection_value(&1, options ++ current_selection, value_mapper))
Expand Down Expand Up @@ -664,8 +687,16 @@ defmodule LiveSelect.Component do

defp encode(value), do: Jason.encode!(value)

defp already_selected?(option, selection) do
option.label in Enum.map(selection, & &1.label)
def already_selected?(idx, selection) when is_integer(idx) do
Enum.at(selection, idx) != nil
end
ringvold marked this conversation as resolved.
Show resolved Hide resolved

def already_selected?(option, selection) do
Enum.any?(selection, fn item -> item.label == option.label end)
end
ringvold marked this conversation as resolved.
Show resolved Hide resolved

defp quick_tags_mode?(socket) do
socket.assigns.mode == :quick_tags
end

defp next_selectable(%{
Expand All @@ -676,6 +707,18 @@ defmodule LiveSelect.Component do
when max_selectable > 0 and length(selection) >= max_selectable,
do: active_option

defp next_selectable(%{
options: options,
active_option: active_option,
mode: :quick_tags
}) do
options
|> Enum.with_index()
|> Enum.reject(fn {opt, _} -> active_option == opt end)
|> Enum.map(fn {_, idx} -> idx end)
|> Enum.find(active_option, &(&1 > active_option))
end
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is unnecessary code duplication IMO. All you need to do is change like 717 to something like:

|> Enum.reject(fn {opt, _} -> active_option == opt || (mode != :quick_tags && already_selected?(opt, selection)) end)

and you have a version that works for both :quick_tags and non-:quick_tags modes :)


defp next_selectable(%{options: options, active_option: active_option, selection: selection}) do
options
|> Enum.with_index()
Expand All @@ -692,6 +735,19 @@ defmodule LiveSelect.Component do
when max_selectable > 0 and length(selection) >= max_selectable,
do: active_option

defp prev_selectable(%{
options: options,
active_option: active_option,
mode: :quick_tags
}) do
options
|> Enum.with_index()
|> Enum.reverse()
|> Enum.reject(fn {opt, _} -> active_option == opt end)
|> Enum.map(fn {_, idx} -> idx end)
|> Enum.find(active_option, &(&1 < active_option || active_option == -1))
end

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is unnecessary code duplication IMO. All you need to do is change like 746 to something like:

|> Enum.reject(fn {opt, _} -> active_option == opt || (mode != :quick_tags && already_selected?(opt, selection)) end)

and you have a version that works for both :quick_tags and non-:quick_tags modes :)

defp prev_selectable(%{options: options, active_option: active_option, selection: selection}) do
options
|> Enum.with_index()
Expand Down
20 changes: 12 additions & 8 deletions lib/live_select/component.html.heex
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@
data-field={@field.id}
data-debounce={@debounce}
>
<%= if @mode == :tags && Enum.any?(@selection) do %>
<div class={
class(@style, :tags_container, @tags_container_class, @tags_container_extra_class)
}>
<div class={class(@style, :tags_container, @tags_container_class, @tags_container_extra_class)}>
<%= if (@mode == :tags || @mode == :quick_tags) && Enum.any?(@selection) do %>
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer @mode in [:tags, :quick_tags] , I think it's more readable (nitpick, I know)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree!

<%= for {option, idx} <- Enum.with_index(@selection) do %>
<div class={class(@style, :tag, @tag_class, @tag_extra_class)}>
<%= if @tag == [] do %>
Expand Down Expand Up @@ -40,8 +38,9 @@
</button>
</div>
<% end %>
</div>
<% end %>
<% end %>
</div>

<div>
<%= text_input(@field.form, @text_input_field,
class:
Expand Down Expand Up @@ -122,12 +121,17 @@
)
)
}
data-idx={unless already_selected?(option, @selection), do: idx}
data-idx={
if @mode == :quick_tags or not already_selected?(option, @selection), do: idx
}
>
<%= if @option == [] do %>
<%= option.label %>
<% else %>
<%= render_slot(@option, option) %>
<%= render_slot(
@option,
Map.merge(option, %{selected: already_selected?(option, @selection)})
) %>
<% end %>
</div>
</li>
Expand Down
94 changes: 80 additions & 14 deletions lib/support/live_select_web/live/showcase_live.ex
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,15 @@ defmodule LiveSelectWeb.ShowcaseLive do
field(:allow_clear, :boolean)
field(:debounce, :integer, default: Component.default_opts()[:debounce])
field(:disabled, :boolean)
field(:custom_option_html, :boolean)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love that you went out of the way to create this toggle to show how to style the options as checkboxes!

Can we please rename it to something more specific like "Options styles as checkboxes" ?

field(:max_selectable, :integer, default: Component.default_opts()[:max_selectable])
field(:user_defined_options, :boolean)
field(:mode, Ecto.Enum, values: [:single, :tags], default: Component.default_opts()[:mode])

field(:mode, Ecto.Enum,
values: [:single, :tags, :quick_tags],
default: Component.default_opts()[:mode]
)

field(:new, :boolean, default: true)
field(:placeholder, :string, default: "Search for a city")
field(:search_delay, :integer, default: 10)
Expand All @@ -93,6 +99,7 @@ defmodule LiveSelectWeb.ShowcaseLive do
:allow_clear,
:debounce,
:disabled,
:custom_option_html,
:max_selectable,
:user_defined_options,
:mode,
Expand All @@ -119,7 +126,7 @@ defmodule LiveSelectWeb.ShowcaseLive do
default_opts = Component.default_opts()

settings
|> Map.drop([:search_delay, :new, :selection])
|> Map.drop([:search_delay, :new, :selection, :custom_option_html])
|> Map.from_struct()
|> then(
&if is_nil(&1.style) do
Expand All @@ -134,6 +141,19 @@ defmodule LiveSelectWeb.ShowcaseLive do
(settings.mode != :single && option == :allow_clear)
end)
|> Keyword.new()
|> then(&maybe_set_classes_for_multiselect/1)
end

defp maybe_set_classes_for_multiselect(opts) do
if LiveSelectWeb.ShowcaseLive.quick_tags?(opts[:mode]) do
Keyword.put(
opts,
:selected_option_class,
"cursor-pointer font-bold hover:bg-gray-400 rounded"
)
else
opts
end
ringvold marked this conversation as resolved.
Show resolved Hide resolved
end

def has_style_errors?(%Ecto.Changeset{errors: errors}) do
Expand Down Expand Up @@ -240,20 +260,55 @@ defmodule LiveSelectWeb.ShowcaseLive do
assigns = assign(assigns, opts: opts, format_value: format_value)

~H"""
<div>
<span class="text-success">&lt;.live_select</span>
<br />&nbsp;&nbsp; <span class="text-success">field</span>=<span class="text-info">&#123;my_form[:city_search]&#125;</span>
<%= for {key, value} <- @opts, !is_nil(value) do %>
<%= if value == true do %>
<br />&nbsp;&nbsp; <span class="text-success">{key}</span>
<% else %>
<br />&nbsp;&nbsp; <span class="text-success"><%= key %></span>=<span class="text-info"><%= @format_value.(value) %></span>
<%= if @custom_option_html do %>
<div>
<span class="text-success">&lt;.live_select</span>
<br />&nbsp;&nbsp; <span class="text-success">field</span>=<span class="text-info">&#123;my_form[:city_search]&#125;</span>
<%= for {key, value} <- @opts, !is_nil(value) do %>
<%= if value == true do %>
<br />&nbsp;&nbsp; <span class="text-success">{key}</span>
<% else %>
<br />&nbsp;&nbsp; <span class="text-success"><%= key %></span>=<span class="text-info"><%= @format_value.(value) %></span>
<% end %>
<% end %>
<% end %>
<span class="text-success">/&gt;</span>
</div>
<br /><span class="text-success">&gt;</span>

<br />&nbsp;&nbsp; <span class="text-success">
&lt;:option :let</span>=<span class="text-info">&#123;%&#123;label: label, value: value, selected: selected&#125;&#125;</span>
<span class="text-success">
&gt;
</span>
<br /><%= indent(2) %> <span class="text-success">&lt;div class</span>=<span class="text-info">"flex justify-content items-center"&gt;</span>
<br /><%= indent(3) %> <span class="text-success">&lt;input</span>
<br /><%= indent(4) %> <span class="text-success">class</span>=<span class="text-info">"rounded w-4 h-4 mr-3 border border-border"</span>
<br /><%= indent(4) %> <span class="text-success">type</span>=<span class="text-info">"checkbox"</span>
<br /><%= indent(4) %> <span class="text-success">checked</span>=<span class="text-info">&#123;selected&#125;</span>
<br /><%= indent(3) %> <span class="text-success">/&gt;</span>
<br /><%= indent(4) %> <span class="text-success">&lt;span class</span>=<span class="text-info">"text-sm"&gt;&lt;&#37;= label &#37;&gt;</span>
<br /><%= indent(2) %> <span class="text-success">&lt;/div&gt;</span>
<br /><%= indent(1) %> <span class="text-success">&lt;/:option&gt;</span>
<br /><span class="text-success">&lt;.live_select/&gt;</span>
</div>
<% else %>
<div>
<span class="text-success">&lt;.live_select</span>
<br />&nbsp;&nbsp; <span class="text-success">field</span>=<span class="text-info">&#123;my_form[:city_search]&#125;</span>
<%= for {key, value} <- @opts, !is_nil(value) do %>
<%= if value == true do %>
<br />&nbsp;&nbsp; <span class="text-success">{key}</span>
<% else %>
<br />&nbsp;&nbsp; <span class="text-success"><%= key %></span>=<span class="text-info"><%= @format_value.(value) %></span>
<% end %>
<% end %>
<span class="text-success">/&gt;</span>
</div>
<% end %>
"""
end

defp indent(amount) do
raw(for _ <- 1..amount, do: "&nbsp;&nbsp;&nbsp;")
end
end

@impl true
Expand Down Expand Up @@ -300,9 +355,16 @@ defmodule LiveSelectWeb.ShowcaseLive do
{:ok, settings} ->
socket.assigns

attrs =
if settings.mode == :quick_select do
%{selected_option_class: "cursor-pointer font-bold hover:bg-gray-400 rounded"}
else
%{}
end

socket =
socket
|> assign(:settings_form, Settings.changeset(settings, %{}) |> to_form)
|> assign(:settings_form, Settings.changeset(settings, attrs) |> to_form)
Copy link
Owner

@maxmarcon maxmarcon Dec 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: let's remove this code and all other changes in this file related to the selected_option_class override, and add this:

params =
      if params["mode"] == "quick_tags" do
        Map.put_new(
          params,
          "selected_option_class",
          "cursor-pointer font-bold hover:bg-gray-400 rounded"
        )
      else
        params
      end

just before we create the changeset. Advantages:

  1. simpler
  2. more transparent, as the user will see the classes in the UI's styling options
  3. the user can override these default classes if they want to

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, what I had done was kind of a hack to just to make it work.
This is nice, but it seems to not reset when you change back to tags mode.
Maybe do a reset of selected_option_class in the else clause or just let it be?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think just let it be, at least for now. I mean if the user changes the style while in quick_tags mode you don't want it to be reset when you change back to tags mode... the user will lose what they entered.

I guess for now this is the best we can do, we can come up with a better way later :)

|> update(:schema_module, fn _, %{settings_form: settings_form} ->
if settings_form[:mode].value == :single, do: CitySearchSingle, else: CitySearchMany
end)
Expand Down Expand Up @@ -489,6 +551,10 @@ defmodule LiveSelectWeb.ShowcaseLive do
{:noreply, socket}
end

def quick_tags?(mode) do
mode == :quick_tags
end

defp value_mapper(%City{name: name} = value), do: %{label: name, value: Map.from_struct(value)}

defp value_mapper(value), do: value
Expand Down
30 changes: 26 additions & 4 deletions lib/support/live_select_web/live/showcase_live.html.heex
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
<div class="flex flex-wrap p-5 gap-2">
<div class="form-control max-w-sm">
{label(@settings_form, :mode, "Mode:", class: "label label-text font-semibold")}
{select(@settings_form, :mode, [:single, :tags],
{select(@settings_form, :mode, [:single, :tags, :quick_tags],
class: "select select-sm select-bordered text-xs"
)}
</div>
Expand Down Expand Up @@ -71,6 +71,10 @@
<span class="label-text mr-1">Disabled:&nbsp;</span>
{checkbox(@settings_form, :disabled, class: "toggle")}
<% end %>
<%= label class: "label cursor-pointer" do %>
<span class="label-text mr-1">Custom option HTML:&nbsp;</span>
<%= checkbox(@settings_form, :custom_option_html, class: "toggle") %>
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I love that you went out of the way to create this toggle to show how to style the options as checkboxes!

Can we please rename it to something more specific like "Options styles as checkboxes" ?

<% end %>
</div>
<div class="form-control max-w-sm">
{label(@settings_form, :search_delay, "Search delay in ms:",
Expand Down Expand Up @@ -286,7 +290,22 @@
field={@live_select_form[:city_search]}
value_mapper={&value_mapper/1}
{live_select_assigns(@settings_form.source)}
/>
>
<:option :let={%{label: label, value: _value, selected: selected}}>
<%= if @settings_form[:custom_option_html].value do %>
<div class="flex justify-content items-center">
<input
class="rounded w-4 h-4 mr-3 border border-border"
type="checkbox"
checked={selected}
/>
<span class="text-sm"><%= label %></span>
</div>
<% else %>
<%= label %>
<% end %>
</:option>
</.live_select>
</div>
<div class="flex flex-col gap-y-1">
{submit("Submit",
Expand All @@ -310,7 +329,7 @@
</div>

<div
class="w-full md:w-2/3 mt-5 relative border-info border rounded-lg p-2"
class="w-full md:w-2/3 mt-5 mb-5 relative border-info border rounded-lg p-2"
id="live-select-code"
>
<div
Expand All @@ -326,7 +345,10 @@
<.copy_to_clipboard_icon />
</button>
</div>
<Render.live_select opts={Settings.live_select_opts(@settings_form.data, true)} />
<Render.live_select
custom_option_html={@settings_form[:custom_option_html].value}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the argument of the function component should also be renamed to options_styled_as_checkboxes

opts={Settings.live_select_opts(@settings_form.data, true)}
/>
</div>
</div>
</div>
Expand Down
Loading
Loading