Coder Social home page Coder Social logo

matt-yorkley / futurism Goto Github PK

View Code? Open in Web Editor NEW

This project forked from stimulusreflex/futurism

0.0 0.0 0.0 867 KB

Lazy-load Rails partials via CableReady

License: MIT License

Emacs Lisp 0.24% Ruby 80.03% JavaScript 9.25% CSS 2.22% HTML 8.15% Shell 0.11%

futurism's Introduction

Futurism

Twitter follow

All Contributors

Lazy-load Rails partials via CableReady

๐Ÿšจ BREAKING CHANGE: With v1.0, futurism has been transferred to the stimulusreflex organization. Please update your npm package to @stimulus_reflex/futurism accordingly ๐Ÿšจ

birmingham-museums-trust-GrvC6MI-z4w-unsplash

Photo by Birmingham Museums Trust on Unsplash

Table of Contents

Facts

  • only one dependency: CableReady
  • bundle size (without CableReady) is around ~2.46kB

Browser Support

  • Chrome v67+ (v54+ via Polyfill)
  • Firefox v63+
  • Edge v79+
  • Safari v10.1+ via Polyfill
  • iOS Safari & Chrome v10.3+ via Polyfill

Caniuse

Usage

with a helper in your template

<%= futurize @posts, extends: :div do %>
  <!-- placeholder -->
<% end %>

custom <futurism-element>s (in the form of a <div> or a <tr is="futurism-table-row"> are rendered. Those custom elements have an IntersectionObserver attached that will send a signed global id to an ActionCable channel (FuturismChannel) which will then replace the placeholders with the actual resource partial.

With that method, you could lazy load every class that has to_partial_path defined (ActiveModel has by default).

You can pass the placeholder as a block:

<%= futurize @posts, extends: :tr do %>
  <td class="placeholder"></td>
<% end %>

aa601dec1930151f71dbf0d6b02b61c9

You can also omit the placeholder, which falls back to eager loading.

API

Currently there are two ways to call futurize, designed to wrap render's behavior:

Resource

You can pass a single ActiveRecord or an ActiveRecord::Relation to futurize, just as you would call render:

<%= futurize @posts, extends: :tr do %>
  <td class="placeholder"></td>
<% end %>

Partial Path

Remember that you can override the partial path in you models, like so:

class Post < ApplicationRecord
  def to_partial_path
    "home/post"
  end
end

That way you get maximal flexibility when just specifying a single resource.

Explicit Partial

Call futurize with a partial keyword:

<%= futurize partial: "items/card", locals: {card: @card}, extends: :div do %>
  <div class="spinner"></div>
<% end %>

You can also use the shorthand syntax:

<%= futurize "items/card", card: @card, extends: :div do %>
  <div class="spinner"></div>
<% end %>

Collections

Collection rendering is also possible:

<%= futurize partial: "items/card", collection: @cards, extends: :div do %>
  <div class="spinner"></div>
<% end %>

Specifying Controller to Render

You can also pass in the controller that will be used to render the partial.

<%= futurize partial: "items/card", collection: @cards, controller: MyController, extends: :div do %>
  <div class="spinner"></div>
<% end %>

By default (i.e. not passing in a value), futurize will use ApplicationController, but you may override by setting the Futurism default controller in an initializer, for example config/initializers/futurism.rb.

Futurism.default_controller = "MyController" # to avoid the controller from trying to autoload at boot, provide as a string

HTML Options

You can pass a hash of attribute/value pairs which will be mixed into the HTML markup for the placeholder element. This is important for layouts that require elements to have dimensionality. For example, many scripts calculate size based on element height and width. This option ensures that your elements have integrity, even if they are gone before you see them.

<%= futurize @posts, extends: :tr, html_options: {style: "width: 50px; height: 50px;"} do %>
  <td class="placeholder"></td>
<% end %>

This will output the following:

<tr style="width: 50px; height: 50px;">
  <td class="placeholder"></td>
</tr>

Eager Loading

It may sound surprising to support eager loading in a lazy loading library ๐Ÿ˜‚, but there's a quite simple use case:

Suppose you have some hidden interactive portion of your page, like a tab or dropdown. You don't want its content to block the initial page load, but once that is done, you occasionally don't want to wait for the element to become visible and trigger the IntersectionObserver, you want to lazy load its contents right after it's added to the DOM.

Futurism makes that dead simple:

<%= futurize 'some_tab', eager: true, extends: :tr do %>
  <div class="placeholder"</td>
<% end %>

Bypassing

In some rare cases, e.g. when combined with CableReady's async updates_for mechanism, you'll want to bypass futurism entirely and fall back to native rendering. You can do this by passing an unless option:

<%= futurize 'some_tab', unless: bypass_futurism?, extends: :tr do %>
  <div class="placeholder"</td>
<% end %>

Internally, this works the same as bypassing futurism in tests

Broadcast Partials Individually

Futurism's default behavior is to broadcast partials as they are generated in batches:

On the client side, IntersectionObserver events are triggered in a debounced fashion, so several renders are performed on the server for each of those events. By default, futurism will group those to a single broadcast call (to save server CPU time).

For collections, however, you can opt into individual broadcasts by specifying broadcast_each: true in your helper usage:

<%= futurize @posts, broadcast_each: true, extends: :tr do %>
  <div class="placeholder"</td>
<% end %>

Contextual Placeholder Arguments

For individual models or arbitrary collections, you can pass record and index to the placeholder block as arguments:

<%= futurize @post, extends: :div do |post| %>
  <div><%= post.title %></div>
<% end %>
<%= futurize @posts, extends: :tr do |post, index| %>
  <td><%= index + 1 %></td><td><%= post.title %></td>
<% end %>
<%= futurize partial: "users/user", collection: users, extends: "tr" do |user, index| %>
  <td><%= index + 1 %></td><td><%= user.name %></td>
<% end >

Events

Once your futurize element has been rendered, the futurize:appeared custom event will be called.

Installation

Add this line to your application's Gemfile:

gem 'futurism'

And then execute:

$ bundle

To copy over the javascript files to your application, run

$ bin/rails futurism:install

! Note that the installer will run yarn add @stimulus_reflex/futurism for you !

Manual Installation

After bundle, install the Javascript library:

$ bin/yarn add @stimulus_reflex/futurism

In your app/javascript/channels/index.js, add the following

import * as Futurism from '@stimulus_reflex/futurism'

import consumer from './consumer'

Futurism.initializeElements()
Futurism.createSubscription(consumer)

Authentication

For authentication, you can rely on ActionCable identifiers, for example, if you use Devise:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = env["warden"].user || reject_unauthorized_connection
    end
  end
end

The Stimulus Reflex Docs have an excellent section about all sorts of authentication.

Testing

In Rails system tests there is a chance that flaky errors will occur due to Capybara not waiting for the placeholder elements to be replaced. To overcome this, add the flag

Futurism.skip_in_test = true

to an initializer, for example config/initializers/futurism.rb.

Gotchas

ActiveStorage URLs aren't correct in development

Out of the box, Rails will prefix generated urls with http://example.org rather than http://localhost, much like ActionMailer. To amend this, add

  # config/environments/development.rb
  config.action_controller.default_url_options = {host: "localhost", port: 3000}

  # config/environments/production.rb
  config.action_controller.default_url_options = {host: "mysite.com"}

to your environments.

Contributing

Get local environment setup

Below are a set of instructions that may help you get a local development environment working

# Get the gem/npm package source locally
git clone futurism
cd futurism/javascript
yarn install # install all of the npm package's dependencies
yarn link # set the local machine's futurism npm package's lookup to this local path

# Setup a sample project, use the information below directly or use your own project
git clone https://github.com/leastbad/stimulus_reflex_harness.git
cd stimulus_reflex_harness
git checkout futurism
# Edit Gemfile to point point to local gem (e.g. `gem "futurism", path: "../futurism"`)
# yarn link @stimulus_reflex/futurism


# Do your work, Submit PR, Profit!


# To stop using your local version of futurism
# change your Gemfile back to the published (e.g. `gem "futurism"`)
cd path/to/futurism/javascript
# Stop using the local npm package
yarn unlink

# Instruct your project to reinstall the published version of the npm package
cd path/to/project
yarn install --force

Release

  1. Update the version numbers in javascript/package.json and lib/futurism/version.rb
  2. git commit -m "Bump version to x.x.x"
  3. Run bundle exec rake build
  4. Run bundle exec rake release
  5. cd javascript && npm publish --access public

License

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

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Julian Rubisch

๐Ÿ’ป

darkrubyist

๐Ÿ’ป ๐Ÿ“–

Konnor Rogers

๐Ÿ’ป

Andrew Mason

๐Ÿšง

Chris Oliver

๐Ÿ’ป ๐Ÿ‘€

leastbad

๐Ÿ’ป ๐Ÿ‘€

M. E. Patterson

๐Ÿ›

Stephen Margheim

๐Ÿ’ป

Hassanin Ahmed

๐Ÿ’ป

Marco Roth

๐Ÿ’ป

Viedit com

๐Ÿ“–

Scott Barrow

๐Ÿ’ป

Dom Christie

๐Ÿ‘€

Ricky Chilcott

๐Ÿ‘€

mansakondo

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

futurism's People

Contributors

allcontributors[bot] avatar dependabot[bot] avatar dorianmariecom avatar fractaledmind avatar julianrubisch avatar konnorrogers avatar leastbad avatar mansakondo avatar marcoroth avatar nachiket87 avatar rickychilcott avatar sas1ni69 avatar scottbarrow avatar vieditcom avatar

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.