Giter Site home page Giter Site logo

phx_component_helpers's Introduction

PhxComponentHelpers

github codecov Hex pm

๐Ÿ‘‰ Demonstration & Code samples

Presentation

PhxComponentHelpers provides helper functions meant to be used within Phoenix LiveView to make your components more configurable and extensible from templates.

It provides the following features:

  • set HTML, data or phx attributes from component assigns
  • set a bunch of attributes at once with any custom prefix such as @click or x-bind: (for alpinejs users)
  • validate mandatory attributes
  • set and extend CSS classes from component assigns
  • forward a subset of assigns to child components

Motivation

Writing a library of stateless components is a great way to improve consistency in both your UI and code and also to get a significant productivity boost.

The best components can be used as-is without any further configuration, but are versatile enough to be customized from templates or higher level components.

Writing such components is not difficult, but involves a lot of boilerplate code. PhxComponentHelpers is here to alleviate the pain.

Example

A lot of code samples are available on this site, but basically PhxComponentHelpers allows you to write components as such:

defmodule Forms.Button do
  use Phoenix.Component
  import PhxComponentHelpers

  def button(assigns) do
    assigns =
      assigns
      |> extend_class("bg-blue-700 hover:bg-blue-900 ...")
      |> set_attributes([:type, :id, :label], required: [:id])
      |> set_phx_attributes()

    ~H"""
    <button {@heex_id} {@heex_type} {@heex_phx_attributes} {@heex_class}>
      <%= @label %>
    </button>
    """
  end
end

From templates, it looks like this:

<.form id="form" phx-submit="form_submit" class="divide-none">

  <.input_group>
    <.label for="name" label="Name"/>
    <.text_input name="name" value={@my.name}/>
  </.input_group>

  <.button_group class="pt-2">
    <.button type="submit" phx-click="btn-click" label="Save"/>
  </.button_group>

</.form>

How does it play with the PETAL stack?

PETAL stands for Phoenix - Elixir - TailwindCSS - Alpine.js - LiveView. In recent months it has become quite popular in the Elixir ecosystem and PhxComponentHelpers is meant to fit in.

  • TailwindCSS provides a new way to structure CSS, but keeping good HTML hygiene requires to rely on a component-oriented library.
  • Alpine.js is the Javascript counterpart of Tailwind. It lets you define dynamic behaviour right from your templates using HTML attributes.

The point of developing good components is to provide strong defaults in the component so that they can be used as-is, but also to let these defaults be overridden right from the templates.

Here is the definition of a typical Form button, with Tailwind & Alpine:

defmodule Forms.Button do
  use Phoenix.Component
  import PhxComponentHelpers

  @css_class "inline-flex items-center justify-center p-3 w-5 h-5 border \
              border-transparent text-2xl leading-4 font-medium rounded-md \
              text-white bg-primary hover:bg-primary-hover"

  def button(assigns) do
    assigns =
      assigns
      |> extend_class(@css_class)
      |> set_phx_attributes()
      |> set_prefixed_attributes(["@click", "x-bind:"],
        into: :alpine_attributes,
        required: ["@click"]
      )

    ~H"""
    <button type="button" {@heex_class} {@heex_alpine_attributes} {@heex_phx_attributes}>
      <%= render_block(@inner_block) %>
    </button>
    """
  end
end

Then in your html.heex template you can imagine the following code, providing @click behaviour and overriding just the few tailwind css classes you need (only p-*, w-* and h-* will be replaced). No phx behaviour here, but it's ok, it won't break ;-)

<.button class="!p-* p-0 !w-* w-7 !h-* h-7" "@click"="$dispatch('closeslideover')">
  <.icon icon={:plus_circle}/>
</.button>

Forms

This library also provides Phoenix.HTML.Form related functions so you can easily write your own my_form_for function with your css defaults.

def my_form_for(options) when is_list(options) do
  options
  |> extend_form_class("mt-4 space-y-2")
  |> Phoenix.LiveView.Helpers.form()
end

Then you only need to use PhxComponentHelpers.set_form_attributes/1 within your own form components in order to fetch names & values from the form. Your template will then look like this:

<.my_form_for let={f} for={@changeset} phx-submit="form_submit" class="divide-none">
  <.input_group>
    <.label form={f} field={:name} label="Name"/>
    <.text_input form={f} field={:name}/>
  </.input_group>

  <.button_group class="pt-2">
    <.button type="submit" label="Save"/>
  </.button_group>
</.my_form_for>

Compared to Surface

Surface is a library built on top of Phoenix LiveView. Surface is much more ambitious and complex than PhxComponentHelpers (which obviously isn't a framework, just helpers ...).

Surface really changes the way you code user interfaces and components (you almost won't be using HTML templates anymore) whereas PhxComponentHelpers is just some syntactic sugar to help you use raw phoenix_live_view.

Documentation

Available on https://hexdocs.pm

Installation

Add the following to your mix.exs.

def deps do
  [
    {:phx_component_helpers, "~> 1.4.0"},
    {:jason, "~> 1.0"} # only required if you want to use json encoding options
  ]
end

phx_component_helpers's People

Contributors

cblavier avatar dsrees avatar jon4syth avatar seb3s avatar thenrio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

phx_component_helpers's Issues

extend_class removes all sibling selector variants, even when they don't conflict with default classes

Expected Behavior

When calling extend_class with a function that returns sibling selector variant classes (i.e. peer-* and group-* type classes) only the classes that conflict with the default classes would be overwritten.
E.g.

%{class: "peer-checked:bg-indigo-500"}
|> extend_class(fn _assigns -> "peer-checked:bg-red-500 peer-focus:ring-2" end)

%{class: "peer-checked:bg-indigo-500 peer-focus:ring-2"}

Actual Behavior

%{class: "peer-checked:bg-indigo-500"}
|> extend_class(fn _assigns -> "peer-checked:bg-red-500 peer-focus:ring-2" end)

# note that "peer-focus:ring-2" is removed erroneously
%{class: "peer-checked:bg-indigo-500"}

Thanks for the awesome library!

order of "forward_assigns" kills other assigns

|> forward_assigns(merge: %{foo: "bar"})
|> extend_class(@css_table)
works

|> extend_class(@css_table)
|> forward_assigns(merge: %{foo: "bar"})
just leaves :foo as assigns

bug or hidden feature?

Update extend_class to accept a list of default classes

In Phoenix, you can pass a list to class and it will resolve a single class string. It would be great to support this functionality as well in extend_class/3

# Phoenix example
<span class={[
    "text-sm font-semibold",
    @important && "uppercase",
    if Enum.empty(@errors, do: "text-gray-900", else: "text-red-600"
]}>


# extend_class example
PhxComponentHelpers.extend_class(
        assigns,
        [
            "text-sm font-semibold",
            @important && "uppercase",
            if Enum.empty(@errors, do: "text-gray-900", else: "text-red-600"
        ]
      )

I was going to work on this, but wanted to open an issue and get some feedback before continuing. I noticed there's not much activity in the library (it's such a simple API that doesn't need much modification) so wanted to check the pulse before opening a PR. Thanks

Class states defaults

Component:

defmodule MyAppWeb.Components.Button do
  use MyAppWeb, :component
  import PhxComponentHelpers

  @button_class "leading-6 rounded-full px-6 py-3 border border-orange-500 bg-orange-500 focus:outline focus:outline-2 focus:outline-orange-500/50"
  @label_class "text-medium text-white"

  def button(assigns) do
    assigns
    |> set_attributes([:label, :router], required: [:label, :router])
    |> extend_class(@button_class, attribute: :button_class)
    |> extend_class(@label_class, attribute: :label_class)
    |> render()
  end

  defp render(assigns) do
    ~H"""
    <%= live_patch [{:to, @router} | @heex_button_class] do %>
      <span {@heex_label_class}><%= @label %></span>
    <% end %>
    """
  end
end

Call component

<.button
  label="Button text"
  router="#"
  button_class="bg-indigo-500 border-indigo-100 focus:outline-indigo-500/50"
/>

Render

<a class="py-3 px-6 rounded-full leading-6 bg-indigo-500 border-indigo-100 focus:outline-indigo-500/50" data-phx-link="patch" data-phx-link-state="push" href="#">
  <span class="text-white text-medium">Button text</span>
</a>

Expected

<a class="py-3 px-6 rounded-full leading-6 bg-indigo-500 border-indigo-100 focus:outline focus:outline-2 focus:outline-indigo-500/50" data-phx-link="patch" data-phx-link-state="push" href="#">
  <span class="text-white text-medium">Button text</span>
</a>

I don't know why removes the classes focus:outline focus:outline-2

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.