Files
labelmaker/lib/labelmaker_web/tools.ex
2025-05-16 16:44:12 -04:00

65 lines
2.0 KiB
Elixir

defmodule LabelmakerWeb.Tools do
# for the ~p sigil
use Phoenix.VerifiedRoutes,
endpoint: LabelmakerWeb.Endpoint,
router: LabelmakerWeb.Router,
statics: LabelmakerWeb.static_paths()
alias LabelmakerWeb.Constants
def process_parameters(parameters) do
# ensure our defaults are in place to cover any missing parameters
%{"label" => label, "size" => size} =
Constants.defaults()
|> Map.new(fn {k, v} -> {Atom.to_string(k), v} end)
|> Map.merge(parameters)
link = ~p"/#{label}?#{Map.take(parameters, ["color", "font", "outline", "size"])}"
line_breaks = Regex.scan(~r/#{Regex.escape("\\n")}/, label) |> length()
size = String.to_integer(size)
parameters =
parameters
|> Map.take(Constants.permitted_keys())
|> Map.new(fn {k, v} -> {String.to_atom(k), v} end)
|> Enum.map(fn
{:font, font} ->
{:font, Constants.font_map()[String.downcase(font)]}
{:label, label} ->
if String.length(label) > Constants.max_label_length(),
do: {:label, String.slice(label, 0, Constants.max_label_length() + 1)},
else: {:label, label}
{:link, _} ->
{:link, link}
{:preview_height, _} ->
{:preview_height, size + size * line_breaks}
{:preview_text, _} ->
{:preview_text, String.split(label, "\\n")}
pair ->
pair
end)
|> Enum.filter(fn
{:color, color} -> color in Constants.colors()
{:font, font} -> font in Map.values(Constants.font_map())
{:outline, outline} -> outline in Constants.outlines()
{:size, size} -> size in Constants.sizes()
_ -> true
end)
|> Map.new()
Map.merge(Constants.defaults(), parameters)
end
def outline(_, error: true), do: outline(Constants.danger(), false)
def outline("none", _error), do: ""
def outline(color, _error),
do:
"text-shadow: -1px -1px 0 #{color}, 1px -1px 0 #{color}, -1px 1px 0 #{color}, 1px 1px 0 #{color};"
end