PhiaUiDesign.Codegen.AttrFormatter (phia_ui v0.1.17)

Copy Markdown View Source

Formats Elixir values for HEEx template attributes.

Handles the mapping between in-memory attr values and their HEEx text representation. Phoenix function component attrs use the Elixir atom name directly (underscores), so :variant becomes variant=....

Special rules:

  • nil values are omitted (returns nil).
  • true booleans emit the bare attr name: disabled.
  • false booleans are omitted.
  • Atoms are wrapped in curlies: variant={:destructive}.
  • Strings are double-quoted: label="Save".
  • Numbers are wrapped in curlies: count={3}.
  • Lists and maps use inspect/1 inside curlies.
  • The :class attr always renders as a plain HTML string attribute.

Summary

Functions

Format a single attr key-value pair for HEEx output.

Format a map of attrs into a single space-separated string suitable for insertion into an opening HEEx tag.

Functions

format(key, value)

@spec format(atom(), term()) :: String.t() | nil

Format a single attr key-value pair for HEEx output.

Returns the formatted attribute string, or nil if the attr should be omitted from the output (nil value, false boolean).

Examples

iex> AttrFormatter.format(:disabled, true)
"disabled"

iex> AttrFormatter.format(:variant, :destructive)
"variant={:destructive}"

iex> AttrFormatter.format(:label, "Save")
~s(label="Save")

iex> AttrFormatter.format(:hidden, false)
nil

iex> AttrFormatter.format(:tooltip, nil)
nil

format_attrs(attrs)

@spec format_attrs(map()) :: String.t()

Format a map of attrs into a single space-separated string suitable for insertion into an opening HEEx tag.

Keys are sorted alphabetically for deterministic output.

Examples

iex> AttrFormatter.format_attrs(%{variant: :outline, disabled: true})
"disabled variant={:outline}"

iex> AttrFormatter.format_attrs(%{})
""