Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add permalinks example #26

Merged
merged 21 commits into from Jun 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.yml
Expand Up @@ -2,3 +2,4 @@ globals:
alert: readonly
location: readonly
performance: readonly
history: readonly
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -32,3 +32,4 @@ yarn-debug.log*
.tmuxinator.yml
.env
.solargraph.yml
*~
15 changes: 15 additions & 0 deletions app/controllers/permalinks_controller.rb
@@ -0,0 +1,15 @@
# frozen_string_literal: true

class PermalinksController < ApplicationController
def show
@categories = Restaurant.select(:category).distinct.order(:category).map(&:category)

unless @stimulus_reflex
session[:category] = params[:category] || ""
session[:rating] = params[:rating] || ""
session[:price] = params[:price] || ""
end

@restaurants = Restaurant.category(session[:category]).stars(session[:rating]).price(session[:price])
end
end
3 changes: 2 additions & 1 deletion app/helpers/demos_helper.rb
Expand Up @@ -8,6 +8,7 @@ def demos
calendar
geo_selector
gravatar
permalink
reverse_text
tabular
todo
Expand All @@ -33,7 +34,7 @@ def file_timestamps(filepaths = [])

def file_lines(filepath)
lines = File.open(Rails.root.join(filepath)).readlines
lines.reject! { |line| line.to_s.strip =~ /\A(#|\/|\*|\<--)/ }
lines.reject! { |line| line.to_s.strip =~ /\A(#|\/|\*|<--)/ }
lines.shift while lines.first.blank?
lines.pop while lines.last.blank?
lines
Expand Down
50 changes: 50 additions & 0 deletions app/javascript/controllers/permalink_controller.js
@@ -0,0 +1,50 @@
import { camelize } from 'inflected'

import ApplicationController from './application_controller'

/* This is the custom StimulusReflex controller for PermalinkReflex.
* Learn more at: https://docs.stimulusreflex.com
*/

export default class extends ApplicationController {
filter (e) {
this.stimulate('PermalinkReflex#filter', e.target)
}

beforeReflex (element) {
if (element.type === 'checkbox') {
this.data.set(
element.name,
Array.from(document.querySelectorAll(`input[name=${element.name}]`))
.filter(e => e.checked)
.map(e => e.value)
.join(',')
)
} else {
this.data.set(element.name, element.value)
}
}

afterReflex (element, reflex, error) {
if (!error) {
const camelizedIdentifier = camelize(this.identifier, false)
const params = new URLSearchParams(window.location.search.slice(1))
Object.keys(Object.assign({}, this.element.dataset))
.filter(attr => attr.startsWith(camelizedIdentifier))
.forEach(attr => {
const paramName = attr.slice(camelizedIdentifier.length).toLowerCase()
const paramValue = this.data.get(paramName)
paramValue.length
? params.set(paramName, paramValue)
: params.delete(paramName)
})
const qs = params
.toString()
.replace(/%28/g, '(')
.replace(/%29/g, ')')
.replace(/%2C/g, ',')
const query = qs.length ? '?' : ''
history.pushState({}, '', `${window.location.pathname}${query}${qs}`)
}
}
}
1 change: 1 addition & 0 deletions app/javascript/stylesheets/application.scss
Expand Up @@ -15,3 +15,4 @@ $info: #1181b2;
@import 'snake';
@import 'validation';
@import 'todo';
@import 'permalinks';
4 changes: 4 additions & 0 deletions app/javascript/stylesheets/permalinks.scss
@@ -0,0 +1,4 @@
.hover_white:hover.active {
color: #44449b !important;
background-color: red !important;
}
3 changes: 3 additions & 0 deletions app/models/restaurant.rb
Expand Up @@ -19,4 +19,7 @@ class Restaurant < ApplicationRecord
where(arel_table[:name].matches("%#{query}%"))
.or(where(arel_table[:category].matches("%#{query}%")))
}
scope :category, ->(category) { where(category: category) if category.present? }
scope :stars, ->(stars) { where(stars: stars..) if stars.present? }
scope :price, ->(price) { where(price: price.split(",")) if price.present? }
end
2 changes: 1 addition & 1 deletion app/reflexes/gravatar_reflex.rb
Expand Up @@ -3,7 +3,7 @@
class GravatarReflex < ApplicationReflex
def perform
email = element[:value]
return unless %r{[^@]+@[^\.]+\..+}.match?(email)
return unless %r{[^@]+@[^.]+\..+}.match?(email)
email_md5 = Digest::MD5.hexdigest(email.downcase.strip)
@gravatar_image_url = "https://www.gravatar.com/avatar/#{email_md5}"
end
Expand Down
7 changes: 7 additions & 0 deletions app/reflexes/permalink_reflex.rb
@@ -0,0 +1,7 @@
# frozen_string_literal: true

class PermalinkReflex < ApplicationReflex
def filter
session[element[:name].to_sym] = element.value
end
end
56 changes: 56 additions & 0 deletions app/views/permalinks/_demo.html.erb
@@ -0,0 +1,56 @@
<div class="form-row mb-4" data-controller="permalink" data-permalink-category="<%= session[:category] %>" data-permalink-rating="<%= session[:rating] %>" data-permalink-price="<%= session[:price] %>">
<div class="col-3 offset-3">
<%= label_tag "rating" %>
<%= select_tag "rating",
options_for_select((1..5), session[:rating]),
include_blank: true,
class: "form-control",
data: { action: "change->permalink#filter",
reflex_root: "#search-results" } %>
</div>
<div class="col-3">
<%= label_tag "category" %>
<%= select_tag "category",
options_for_select(@categories, session[:category]),
include_blank: true,
class: "form-control",
data: { action: "change->permalink#filter",
reflex_root: "#search-results" } %>
</div>
<div class="col-3">
<%= label_tag "price", "Price", class: "d-block" %>
<div class="btn-group btn-group-toggle" id="price-button-group">
<% {'$' => 1, '$$' => 2, '$$$' => 3}.each do |key, value| %>
<%= label_tag '', class: "btn btn-outline-primary hover_white #{'active' if session[:price]&.include?(value.to_s)}" do %>
<%= check_box_tag 'price', value, session[:price]&.include?(value.to_s), id: "price-#{value}", class: "", data: { action: "click->permalink#filter",
reflex_root: "#search-results,#price-button-group"} %>
<%= key %>
<% end %>
<% end %>
</div>
</div>
</div>

<div id="search-results">
<table class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th style="width:25%" class="text-white">Name</th>
<th style="width:25%" class="text-white">Rating </th>
<th style="width:25%" class="text-white">Category</th>
<th style="width:25%" class="text-white">Price</th>
</tr>
</thead>

<tbody>
<% @restaurants.each do |restaurant| %>
<tr>
<td><%= restaurant.name %></td>
<td><%= "★" * restaurant.stars %></td>
<td><%= restaurant.category %></td>
<td><%= "$" * restaurant.price %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
24 changes: 24 additions & 0 deletions app/views/permalinks/show.html.erb
@@ -0,0 +1,24 @@
<%= content_for :demo_title, "Permalink" %>
<%= content_for :demo_summary, "Update the browser URL after filtering" %>
<%= render_demo "/permalinks/demo" %>

<%= render_explanation do %>
<p>

</p>
<p>
<ul>
<li>Uses stimulus' Data API for managing the client side state</li>
<li>Updates the browser <code>history</code> using <code>pushState</code> in an <code>afterReflex</code> - so you always have a permalink in the browser bar representing the current state</li>
<li>No need to build an API layer that returns JSON.</li>
<li>The permalink is picked up when the controller is loaded in a non-stimulus-reflex request (i.e. <code>@stimulus_reflex</code> is false.</li>
</ul>
</p>
<% end %>

<%= render_gists(
"app/views/permalinks/_demo.html.erb",
"app/javascript/controllers/permalink_controller.js",
"app/controllers/permalinks_controller.rb",
"app/reflexes/permalink_reflex.rb"
) %>
1 change: 1 addition & 0 deletions config/routes.rb
Expand Up @@ -8,6 +8,7 @@
resource :chat, only: [:show]
resource :geo_selector, only: [:show]
resource :gravatar, only: [:show]
resource :permalink, only: [:show]
resource :reverse_text, only: [:show]
resource :snake, only: [:show]
resource :tabular, only: [:show]
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -9,6 +9,7 @@
"@rails/webpacker": "^5.0.1",
"bootstrap": "^4.3.1",
"cable_ready": "4.3.0-pre1",
"inflected": "^2.0.4",
"lodash-es": "^4.17.15",
"popper.js": "^1.16.0",
"pygments-rouge-css": "^0.1.0",
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Expand Up @@ -4305,6 +4305,11 @@ infer-owner@^1.0.3, infer-owner@^1.0.4:
resolved "https://registry.yarnpkg.com/infer-owner/-/infer-owner-1.0.4.tgz#c4cefcaa8e51051c2a40ba2ce8a3d27295af9467"
integrity sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==

inflected@^2.0.4:
version "2.0.4"
resolved "https://registry.yarnpkg.com/inflected/-/inflected-2.0.4.tgz#323770961ccbe992a98ea930512e9a82d3d3ef77"
integrity sha512-HQPzFLTTUvwfeUH6RAGjD8cHS069mBqXG5n4qaxX7sJXBhVQrsGgF+0ZJGkSuN6a8pcUWB/GXStta11kKi/WvA==

inflight@^1.0.4:
version "1.0.6"
resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"
Expand Down