Commit 2b585407 authored by Jean-Philippe Lang's avatar Jean-Philippe Lang

SortHelper refactoring:

* multiple columns sort feature (#2871)
* CSS classes instead of an image tag to reflect the state of the column
* examples fixed (#2945)

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/trunk@2571 e93f8b46-1217-0410-a6f0-8f06a7374b81
parent 4f4d4472
# Helpers to sort tables using clickable column headers. # Helpers to sort tables using clickable column headers.
# #
# Author: Stuart Rackham <srackham@methods.co.nz>, March 2005. # Author: Stuart Rackham <srackham@methods.co.nz>, March 2005.
# Jean-Philippe Lang, 2009
# License: This source code is released under the MIT license. # License: This source code is released under the MIT license.
# #
# - Consecutive clicks toggle the column's sort order. # - Consecutive clicks toggle the column's sort order.
# - Sort state is maintained by a session hash entry. # - Sort state is maintained by a session hash entry.
# - Icon image identifies sort column and state. # - CSS classes identify sort column and state.
# - Typically used in conjunction with the Pagination module. # - Typically used in conjunction with the Pagination module.
# #
# Example code snippets: # Example code snippets:
...@@ -17,7 +18,7 @@ ...@@ -17,7 +18,7 @@
# #
# def list # def list
# sort_init 'last_name' # sort_init 'last_name'
# sort_update # sort_update %w(first_name, last_name)
# @items = Contact.find_all nil, sort_clause # @items = Contact.find_all nil, sort_clause
# end # end
# #
...@@ -28,7 +29,7 @@ ...@@ -28,7 +29,7 @@
# #
# def list # def list
# sort_init 'last_name' # sort_init 'last_name'
# sort_update # sort_update %w(first_name, last_name)
# @contact_pages, @items = paginate :contacts, # @contact_pages, @items = paginate :contacts,
# :order_by => sort_clause, # :order_by => sort_clause,
# :per_page => 10 # :per_page => 10
...@@ -45,88 +46,133 @@ ...@@ -45,88 +46,133 @@
# </tr> # </tr>
# </thead> # </thead>
# #
# - The ascending and descending sort icon images are sort_asc.png and # - Introduces instance variables: @sort_default, @sort_criteria
# sort_desc.png and reside in the application's images directory. # - Introduces param :sort
# - Introduces instance variables: @sort_name, @sort_default.
# - Introduces params :sort_key and :sort_order.
# #
module SortHelper module SortHelper
class SortCriteria
def initialize
@criteria = []
end
def available_criteria=(criteria)
unless criteria.is_a?(Hash)
criteria = criteria.inject({}) {|h,k| h[k] = k; h}
end
@available_criteria = criteria
end
def from_param(param)
@criteria = param.to_s.split(',').collect {|s| s.split(':')[0..1]}
normalize!
end
def to_param
@criteria.collect {|k,o| k + (o ? '' : ':desc')}.join(',')
end
def to_sql
sql = @criteria.collect do |k,o|
if s = @available_criteria[k]
(o ? s.to_a : s.to_a.collect {|c| "#{c} DESC"}).join(', ')
end
end.compact.join(', ')
sql.blank? ? nil : sql
end
def add!(key, asc)
@criteria.delete_if {|k,o| k == key}
@criteria = [[key, asc]] + @criteria
normalize!
end
def add(*args)
r = self.class.new.from_param(to_param)
r.add!(*args)
r
end
def first_key
@criteria.first && @criteria.first.first
end
def first_asc?
@criteria.first && @criteria.first.last
end
private
def normalize!
@criteria = @criteria.collect {|s| [s.first, (s.last == false || s.last == 'desc') ? false : true]}
@criteria = @criteria.select {|k,o| @available_criteria.has_key?(k)} if @available_criteria
@criteria.slice!(3)
self
end
end
# Initializes the default sort column (default_key) and sort order # Initializes the default sort column (default_key) and sort order
# (default_order). # (default_order).
# #
# - default_key is a column attribute name. # - default_key is a column attribute name.
# - default_order is 'asc' or 'desc'. # - default_order is 'asc' or 'desc'.
# - name is the name of the session hash entry that stores the sort state,
# defaults to '<controller_name>_sort'.
# #
def sort_init(default_key, default_order='asc', name=nil) def sort_init(default_key, default_order='asc')
@sort_name = name || params[:controller] + params[:action] + '_sort' @sort_default = "#{default_key}:#{default_order}"
@sort_default = {:key => default_key, :order => default_order}
end end
# Updates the sort state. Call this in the controller prior to calling # Updates the sort state. Call this in the controller prior to calling
# sort_clause. # sort_clause.
# sort_keys can be either an array or a hash of allowed keys # - criteria can be either an array or a hash of allowed keys
def sort_update(sort_keys) #
sort_key = params[:sort_key] def sort_update(criteria)
sort_key = nil unless (sort_keys.is_a?(Array) ? sort_keys.include?(sort_key) : sort_keys[sort_key]) sort_name = controller_name + '_' + action_name + '_sort'
sort_order = (params[:sort_order] == 'desc' ? 'DESC' : 'ASC')
if sort_key
sort = {:key => sort_key, :order => sort_order}
elsif session[@sort_name]
sort = session[@sort_name] # Previous sort.
else
sort = @sort_default
end
session[@sort_name] = sort
sort_column = (sort_keys.is_a?(Hash) ? sort_keys[sort[:key]] : sort[:key]) @sort_criteria = SortCriteria.new
@sort_clause = (sort_column.blank? ? nil : [sort_column].flatten.collect {|s| "#{s} #{sort[:order]}"}.join(',')) @sort_criteria.available_criteria = criteria
@sort_criteria.from_param(params[:sort] || session[sort_name] || @sort_default)
session[sort_name] = @sort_criteria.to_param
end end
# Returns an SQL sort clause corresponding to the current sort state. # Returns an SQL sort clause corresponding to the current sort state.
# Use this to sort the controller's table items collection. # Use this to sort the controller's table items collection.
# #
def sort_clause() def sort_clause()
@sort_clause @sort_criteria.to_sql
end end
# Returns a link which sorts by the named column. # Returns a link which sorts by the named column.
# #
# - column is the name of an attribute in the sorted record collection. # - column is the name of an attribute in the sorted record collection.
# - The optional caption explicitly specifies the displayed link text. # - the optional caption explicitly specifies the displayed link text.
# - A sort icon image is positioned to the right of the sort link. # - 2 CSS classes reflect the state of the link: sort and asc or desc
# #
def sort_link(column, caption, default_order) def sort_link(column, caption, default_order)
key, order = session[@sort_name][:key], session[@sort_name][:order] css, order = nil, default_order
if key == column
if order.downcase == 'asc' if column.to_s == @sort_criteria.first_key
icon = 'sort_asc.png' if @sort_criteria.first_asc?
css = 'sort asc'
order = 'desc' order = 'desc'
else else
icon = 'sort_desc.png' css = 'sort desc'
order = 'asc' order = 'asc'
end end
else
icon = nil
order = default_order
end end
caption = titleize(Inflector::humanize(column)) unless caption caption = column.to_s.humanize unless caption
sort_options = { :sort_key => column, :sort_order => order } sort_options = { :sort => @sort_criteria.add(column.to_s, order).to_param }
# don't reuse params if filters are present # don't reuse params if filters are present
url_options = params.has_key?(:set_filter) ? sort_options : params.merge(sort_options) url_options = params.has_key?(:set_filter) ? sort_options : params.merge(sort_options)
# Add project_id to url_options # Add project_id to url_options
url_options = url_options.merge(:project_id => params[:project_id]) if params.has_key?(:project_id) url_options = url_options.merge(:project_id => params[:project_id]) if params.has_key?(:project_id)
link_to_remote(caption, link_to_remote(caption,
{:update => "content", :url => url_options, :method => :get}, {:update => "content", :url => url_options, :method => :get},
{:href => url_for(url_options)}) + {:href => url_for(url_options),
(icon ? nbsp(2) + image_tag(icon) : '') :class => css})
end end
# Returns a table header <th> tag with a sort link for the named column # Returns a table header <th> tag with a sort link for the named column
...@@ -150,22 +196,10 @@ module SortHelper ...@@ -150,22 +196,10 @@ module SortHelper
# </th> # </th>
# #
def sort_header_tag(column, options = {}) def sort_header_tag(column, options = {})
caption = options.delete(:caption) || titleize(Inflector::humanize(column)) caption = options.delete(:caption) || column.to_s.humanize
default_order = options.delete(:default_order) || 'asc' default_order = options.delete(:default_order) || 'asc'
options[:title]= l(:label_sort_by, "\"#{caption}\"") unless options[:title] options[:title] = l(:label_sort_by, "\"#{caption}\"") unless options[:title]
content_tag('th', sort_link(column, caption, default_order), options) content_tag('th', sort_link(column, caption, default_order), options)
end end
private
# Return n non-breaking spaces.
def nbsp(n)
'&nbsp;' * n
end
# Return capitalized title.
def titleize(title)
title.split.map {|w| w.capitalize }.join(' ')
end
end end
...@@ -142,6 +142,10 @@ table p {margin:0;} ...@@ -142,6 +142,10 @@ table p {margin:0;}
.odd {background-color:#f6f7f8;} .odd {background-color:#f6f7f8;}
.even {background-color: #fff;} .even {background-color: #fff;}
a.sort { padding-right: 16px; background-position: 100% 50%; background-repeat: no-repeat; }
a.sort.asc { background-image: url(../images/sort_asc.png); }
a.sort.desc { background-image: url(../images/sort_desc.png); }
.highlight { background-color: #FCFD8D;} .highlight { background-color: #FCFD8D;}
.highlight.token-1 { background-color: #faa;} .highlight.token-1 { background-color: #faa;}
.highlight.token-2 { background-color: #afa;} .highlight.token-2 { background-color: #afa;}
......
# Redmine - project management software
# Copyright (C) 2006-2009 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require File.dirname(__FILE__) + '/../../test_helper'
class SortHelperTest < HelperTestCase
include SortHelper
def test_default_sort_clause_with_array
sort_init 'attr1', 'desc'
sort_update(['attr1', 'attr2'])
assert_equal 'attr1 DESC', sort_clause
end
def test_default_sort_clause_with_hash
sort_init 'attr1', 'desc'
sort_update({'attr1' => 'table1.attr1', 'attr2' => 'table2.attr2'})
assert_equal 'table1.attr1 DESC', sort_clause
end
def test_params_sort
@sort_param = 'attr1,attr2:desc'
sort_init 'attr1', 'desc'
sort_update({'attr1' => 'table1.attr1', 'attr2' => 'table2.attr2'})
assert_equal 'table1.attr1, table2.attr2 DESC', sort_clause
assert_equal 'attr1,attr2:desc', @session['foo_bar_sort']
end
def test_invalid_params_sort
@sort_param = 'attr3'
sort_init 'attr1', 'desc'
sort_update({'attr1' => 'table1.attr1', 'attr2' => 'table2.attr2'})
assert_nil sort_clause
assert_equal '', @session['foo_bar_sort']
end
def test_invalid_order_params_sort
@sort_param = 'attr1:foo:bar,attr2'
sort_init 'attr1', 'desc'
sort_update({'attr1' => 'table1.attr1', 'attr2' => 'table2.attr2'})
assert_equal 'table1.attr1, table2.attr2', sort_clause
assert_equal 'attr1,attr2', @session['foo_bar_sort']
end
private
def controller_name; 'foo'; end
def action_name; 'bar'; end
def params; {:sort => @sort_param}; end
def session; @session ||= {}; end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment