adrienpoly / motion

Reactive frontend UI components for Rails in pure Ruby

Home Page:https://github.com/unabridged/motion

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Motion

Gem Version npm version Build Status Maintainability Test Coverage Ruby Code Style JavaScript Code Style

Motion allows you to build reactive, real-time frontend UI components in your Rails application using pure Ruby.

  • Plays nicely with the Rails monolith you have.
  • Peacefully coexists with your existing tech: Strong Parameters, Turbolinks, Trix, React, Vue, etc.
  • Real-time frontend UI updates from frontend user interaction AND server-side updates.
  • Leans on ActionCable and ViewComponent for the heavy lifting.
  • No more frontend models, stores, or syncing; your source of truth is the database you already have.
  • No JavaScript required!

Installation

Motion has Ruby and JavaScript parts, execute both of these commands:

bundle add motion
yarn add @unabridged/motion

You will also need a view component library. Any view component library that implements the new render_in interface that landed in Rails 6.1 should be compatible, but Motion is actively developed and tested against Github's ViewComponent.

Motion communicates over and therefore requires ActionCable.

After installing all libraries, run the install script:

bin/rails g motion:install

This will install 2 files, both of which you are free to leave alone.

How does it work?

Motion allows you to mount special DOM elements (henceforth "Motion components") in your standard Rails views that can be real-time updated from frontend interactions, backend state changes, or a combination of both. This is similar to something like Stimulus Reflex in a few ways:

  • Websockets Communication - Communication with your Rails backend is performed via ActionCable
  • No Full Page Reload - The current page for a user is updated in place.
  • Fast DOM Diffing - DOM diffing is performed when replacing existing content with new content.
  • Server Triggered Events - Server-side events can trigger updates to arbitrarily many components via WebSocket channels.

However Motion has a fundamentally different architecture than Stimulus Reflex and is much more like Phoenix LiveView (and even React!) in some key ways:

  • Partial Page Replacement - Motion does not use full page replacement, but rather replaces only the component on the page with new HTML, DOM diffed for performance.
  • Encapsulated, consistent stateful components - Components have continuous internal state that persists and updates. This means each time a component changes, new rendered HTML is generated and can replace what was there before.
  • Blazing Fast - Communication does not have to go through the full Rails router and controller stack. No changes to your routing or controller are required to get the full functionality of Motion.

Frontend interactions

Frontend interactions can update your Motion components using standard JavaScript events that you're already familiar with: change, blur, form submission, and more. You can invoke Motion actions manually using JavaScript if you need to.

The primary way to handle user interactions on the frontend is by using map_motion:

class MyComponent < ViewComponent::Base
  include Motion::Component

  attr_reader :total

  def initialize(total: 0)
    @total = 0
  end

  map_motion :add

  def add
    @total += 1
  end
end

To invoke this motion on the frontend, add data-motion='add' to your component's template:

<div>
  <span><%= total %></span>
  <%= button_tag "Increment", data: { motion: "add" } %>
</div>

This component can be included on your page the same as always with ViewComponent:

<%= render MyComponent.new(total: 5) %>

Every time the "Increment" button is clicked, MyComponent will call the add method, re-render your component and send it back to the frontend to replace the existing DOM. All invocations of mapped motions will cause the component to re-render, and unchanged rendered HTML will not perform any changes.

Backend interactions

Backend changes can be streamed to your Motion components in 2 steps.

  1. Broadcast changes using ActionCable after an event you care about:
class Todo < ApplicationModel
  after_commit :broadcast_created, on: :create

  def broadcast_created
    ActionCable.server.broadcast("todos:created", id)
  end
end
  1. Configure your Motion component to listen to an ActionCable channel:
class MyComponent < ViewComponent::Base
  include Motion::Component

  stream_from "todos:created", :handle_created

  def initialize
    @todos = Todo.all.to_a
  end

  def handle_created
    @todos = Todo.all.to_a
  end
end

This will cause any user that has a page open with MyComponent mounted on it to re-render that component's portion of the page.

All invocations of stream_from connected methods will cause the component to re-render everywhere, and unchanged rendered HTML will not perform any changes.

Motion::Event and Motion::Element

Methods that are mapped using map_motion accept an event parameter which is a Motion::Event. This object has a target attribute which is a Motion::Element, the element in the DOM that triggered the motion. Useful state and attributes can be extracted from these objects, including value, selected, checked, form state, data attributes, and more.

  map_motion :example

  def example(event)
    event.type # => "change"
    event.name # alias for type

    element = event.target # => Motion::Element instance
    element.tag_name # => "input"
    element.value # => "5"
    element[:value] # hash lookup version, works for all attributes
    element.attributes # { class: "col-xs-12", ... }

    # DOM element with data-field="..."
    element.data[:field]

    # ActionController::Parameters instance with all form params. Also
    # available on Motion::Event objects for convenience.
    element.form_data
  end

See the code for full API for Event and Element.

Limitations

  • Due to the way that your components are replaced on the page, Motion ViewComponents templates are limited to a single top-level DOM element. If you have multiple DOM elements in your template at the top level, you must wrap them in a single element. This is a similar limitation that React enforced until React.Fragment appeared and is for a very similar reason.

Roadmap

Broadly speaking, these initiatives are on our roadmap:

  • Enhanced documentation and usage examples
  • Support more ViewComponent-like libraries
  • Support communication via AJAX instead of (or in addition to) websockets

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/unabridged/motion.

License

The gem is available as open source under the terms of the MIT License.

About

Reactive frontend UI components for Rails in pure Ruby

https://github.com/unabridged/motion

License:MIT License


Languages

Language:Ruby 80.6%Language:JavaScript 18.5%Language:HTML 0.7%Language:Shell 0.2%