Coder Social home page Coder Social logo

clearwater's Introduction

clearwater

Quality Build Downloads Issues License Version

Clearwater is a rich front-end framework for building fast, reasonable, and easily composable browser applications in Ruby. It renders to a virtual DOM and applies the virtual DOM to the browser's actual DOM to update only what has changed on the page.

Installing

Add these lines to your application's Gemfile:

gem 'clearwater', '~> 1.0.0.rc1'
gem 'opal-rails', github: 'opal/opal-rails' # Only needed for Rails apps

The github dependency is so that it will install Opal 0.9, which has much better performance than Opal 0.8.

Using

Clearwater has three distinct parts:

  1. The component: the presenter and template engine
  2. The router: the dispatcher and control
  3. The application: the "Go" button

The Component

class Blog
  # All components need a set of behavior, but don't worry it's not a massive list.
  include Clearwater::Component

  # This method needs to return a virtual-DOM element using the element DSL.
  def render
    main([
      Articles.new,
      Biography.new,
    ])
  end
end

While we use two components in this example, you can use all of these as well:

# <main id="foo">
#   <h1>Heading</h1>
#   <article>hello!</article>
# </main>
def render
  main({ id: 'foo' }, [
    h1('Heading'),
    article('hello!'),
  ])
end

# <main>Hello, world!</main>
def render
  main('Hello, world!')
end

# <main>123</main>
def render
  main(123)
end

# <main></main>
def render
  main
end

The Router

router = Clearwater::Router.new do
  # A route with a block contains subordinate routes
  route 'blog' => Blog.new do # /blog
    route 'new_article' => NewArticle.new # /blog/new_article

    # This path contains a dynamic segment. Inside this component, you can use
    # router.params[:article_id] to return the value for this segment of the
    # URL. So for "/articles/123", router.params[:article_id] would be "123".
    route ':article_id' => ArticleReader.new # /blog/123
  end
end

Using with Rails

You can also use Clearwater as part of the Rails asset pipeline. First create your Clearwater application (replace app/assets/application.js with this file):

# file: app/assets/javascripts/application.rb
require 'opal' # Not necessary if you load Opal from a CDN
require 'clearwater'

class Layout
  include Clearwater::Component

  def render
    h1('Hello, world!')
  end
end

app = Clearwater::Application.new(component: Layout.new)
app.call

Then, in app/views/layouts/application.html.erb:

<!DOCTYPE html>
<html>
  <!-- snip -->

  <body>
    <!--
      We load the JS in the body tag to ensure the element exists so we can
      render to it. Otherwise, we need to use events on the document before we
      instantiate and call the Clearwater app. And that's no fun.
    -->
    <%= javascript_include_tag 'application' %>
  </body>
</html>

Then just create a root route that renders a blank template and refresh the page. You should see "Hello, world!" in big, bold letters. Congrats! You've built your first Clearwater app on Rails!

Example app

require 'opal'
require 'clearwater'
require 'ostruct'

class Layout
  include Clearwater::Component

  def render
    div({ id: 'app' }, [
      header({ class_name: 'main-header' }, [
        h1('Hello, world!'),
      ]),
      outlet, # This is what renders subordinate routes
    ])
  end
end

class Articles
  include Clearwater::Component

  def render
    div({ id: 'articles-container '}, [
      input({ class_name: 'search-articles', onkeyup: method(:search) }),
      ul({ id: 'articles-index' }, articles.map { |article|
        ArticlesListItem.new(article)
      }),
      outlet, # This is what renders subordinate routes (e.g. Article)
    ])
  end

  def articles
    @articles ||= MyStore.fetch_articles

    if @query
      @articles.select { |article| article.match?(@query) }
    else
      @articles
    end
  end

  def search(event)
    @query = event.target.value
    call # Rerender the app
  end
end

class ArticlesListItem
  include Clearwater::Component

  attr_reader :article

  def initialize(article)
    @article = article
  end

  def render
    # Note the "key" key in this hash. This is a hint to the virtual DOM that
    # if this node is moved around, it can still reuse the same element.
    li({ key: article.id, class_name: 'article' }, [
      # The Link component will rerender the app for the new URL on click
      Link.new({ href: "/articles/#{article.id}" }, article.title),
      time({ class_name: 'timestamp' }, article.timestamp.strftime('%m/%d/%Y')),
    ])
  end
end

class Article
  include Clearwater::Component

  def render
    # In addition to using HTML5 tag names as methods, you can use the `tag`
    # method with a query selector to generate a tag with those attributes.
    tag('article.selected-article', nil, [
      h1({ class_name: 'article-title' }, article.title),
      time({ class_name: 'article-timestamp' }, article.timestamp.strftime('%m-%d-%Y')),
      section({ class_name: 'article-body' }, article.body),
    ])
  end

  def article
    # params[:article_id] is the section of the URL that contains what would be
    # the `:article_id` parameter in the router below.
    MyStore.article(params[:article_id])
  end

  def match? query
    query.split.all? { |token|
      title.include?(token) || body.include?(token)
    }
  end
end

module MyStore
  extend self
  DB = 5.times.map do |n|
    OpenStruct.new(id: n, timestamp: Time.new, title: "Random thoughts n.#{n}", body: 'Some deep stuff')
  end

  def fetch_articles
    DB
  end

  def article(id)
    id = id.to_i
    DB.find {|a| a.id == id}
  end
end

router = Clearwater::Router.new do
  route 'articles' => Articles.new do
    route ':article_id' => Article.new
  end
end

MyApp = Clearwater::Application.new(
  component: Layout.new,
  router: router,
  element: Bowser.document.body # This is the default target element
)

MyApp.call # Render the app.

Contributing

  1. Fork it
  2. Branch it
  3. Hack it
  4. Save it
  5. Commit it
  6. Push it
  7. Pull-request it

License

Copyright (c) 2014-2015 Jamie Gaskins

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

clearwater's People

Contributors

jgaskins avatar jasnow avatar devonestes avatar elia avatar ferdinandrosario avatar

Watchers

 avatar  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.