;]
[askyou.git] / lib / redmine / menu_manager.rb
blob4094a9c14ec4bcc94c424842f11fc7d01c922aee
1 # redMine - project management software
2 # Copyright (C) 2006-2007  Jean-Philippe Lang
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 require 'tree' # gem install rubytree
20 # Monkey patch the TreeNode to add on a few more methods :nodoc:
21 module TreeNodePatch
22   def self.included(base)
23     base.class_eval do
24       attr_reader :last_items_count
25       
26       alias :old_initilize :initialize
27       def initialize(name, content = nil)
28         old_initilize(name, content)
29         @last_items_count = 0
30         extend(InstanceMethods)
31       end
32     end
33   end
34   
35   module InstanceMethods
36     # Adds the specified child node to the receiver node.  The child node's
37     # parent is set to be the receiver.  The child is added as the first child in
38     # the current list of children for the receiver node.
39     def prepend(child)
40       raise "Child already added" if @childrenHash.has_key?(child.name)
42       @childrenHash[child.name]  = child
43       @children = [child] + @children
44       child.parent = self
45       return child
47     end
49     # Adds the specified child node to the receiver node.  The child node's
50     # parent is set to be the receiver.  The child is added at the position
51     # into the current list of children for the receiver node.
52     def add_at(child, position)
53       raise "Child already added" if @childrenHash.has_key?(child.name)
55       @childrenHash[child.name]  = child
56       @children = @children.insert(position, child)
57       child.parent = self
58       return child
60     end
62     def add_last(child)
63       raise "Child already added" if @childrenHash.has_key?(child.name)
65       @childrenHash[child.name]  = child
66       @children <<  child
67       @last_items_count += 1
68       child.parent = self
69       return child
71     end
73     # Adds the specified child node to the receiver node.  The child node's
74     # parent is set to be the receiver.  The child is added as the last child in
75     # the current list of children for the receiver node.
76     def add(child)
77       raise "Child already added" if @childrenHash.has_key?(child.name)
79       @childrenHash[child.name]  = child
80       position = @children.size - @last_items_count
81       @children.insert(position, child)
82       child.parent = self
83       return child
85     end
87     # Wrapp remove! making sure to decrement the last_items counter if
88     # the removed child was a last item
89     def remove!(child)
90       @last_items_count -= +1 if child && child.last
91       super
92     end
95     # Will return the position (zero-based) of the current child in
96     # it's parent
97     def position
98       self.parent.children.index(self)
99     end
100   end
102 Tree::TreeNode.send(:include, TreeNodePatch)
104 module Redmine
105   module MenuManager
106     class MenuError < StandardError #:nodoc:
107     end
108     
109     module MenuController
110       def self.included(base)
111         base.extend(ClassMethods)
112       end
114       module ClassMethods
115         @@menu_items = Hash.new {|hash, key| hash[key] = {:default => key, :actions => {}}}
116         mattr_accessor :menu_items
117         
118         # Set the menu item name for a controller or specific actions
119         # Examples:
120         #   * menu_item :tickets # => sets the menu name to :tickets for the whole controller
121         #   * menu_item :tickets, :only => :list # => sets the menu name to :tickets for the 'list' action only
122         #   * menu_item :tickets, :only => [:list, :show] # => sets the menu name to :tickets for 2 actions only
123         #   
124         # The default menu item name for a controller is controller_name by default
125         # Eg. the default menu item name for ProjectsController is :projects
126         def menu_item(id, options = {})
127           if actions = options[:only]
128             actions = [] << actions unless actions.is_a?(Array)
129             actions.each {|a| menu_items[controller_name.to_sym][:actions][a.to_sym] = id}
130           else
131             menu_items[controller_name.to_sym][:default] = id
132           end
133         end
134       end
135       
136       def menu_items
137         self.class.menu_items
138       end
139       
140       # Returns the menu item name according to the current action
141       def current_menu_item
142         @current_menu_item ||= menu_items[controller_name.to_sym][:actions][action_name.to_sym] ||
143                                  menu_items[controller_name.to_sym][:default]
144       end
145       
146       # Redirects user to the menu item of the given project
147       # Returns false if user is not authorized
148       def redirect_to_project_menu_item(project, name)
149         item = Redmine::MenuManager.items(:project_menu).detect {|i| i.name.to_s == name.to_s}
150         if item && User.current.allowed_to?(item.url, project) && (item.condition.nil? || item.condition.call(project))
151           redirect_to({item.param => project}.merge(item.url))
152           return true
153         end
154         false
155       end
156     end
157     
158     module MenuHelper
159       # Returns the current menu item name
160       def current_menu_item
161         @controller.current_menu_item
162       end
163       
164       # Renders the application main menu
165       def render_main_menu(project)
166         render_menu((project && !project.new_record?) ? :project_menu : :application_menu, project)
167       end
168       
169       def display_main_menu?(project)
170         menu_name = project && !project.new_record? ? :project_menu : :application_menu
171         Redmine::MenuManager.items(menu_name).size > 1 # 1 element is the root
172       end
174       def render_menu(menu, project=nil)
175         links = []
176         menu_items_for(menu, project) do |node|
177           links << render_menu_node(node, project)
178         end
179         links.empty? ? nil : content_tag('ul', links.join("\n"))
180       end
182       def render_menu_node(node, project=nil)
183         if node.hasChildren? || !node.child_menus.nil?
184           return render_menu_node_with_children(node, project)
185         else
186           caption, url, selected = extract_node_details(node, project)
187           return content_tag('li',
188                                render_single_menu_node(node, caption, url, selected))
189         end
190       end
192       def render_menu_node_with_children(node, project=nil)
193         caption, url, selected = extract_node_details(node, project)
195         html = returning [] do |html|
196           html << '<li>'
197           # Parent
198           html << render_single_menu_node(node, caption, url, selected)
200           # Standard children
201           standard_children_list = returning "" do |child_html|
202             node.children.each do |child|
203               child_html << render_menu_node(child, project)
204             end
205           end
207           html << content_tag(:ul, standard_children_list, :class => 'menu-children') unless standard_children_list.empty?
209           # Unattached children
210           unattached_children_list = render_unattached_children_menu(node, project)
211           html << content_tag(:ul, unattached_children_list, :class => 'menu-children unattached') unless unattached_children_list.blank?
213           html << '</li>'
214         end
215         return html.join("\n")
216       end
218       # Returns a list of unattached children menu items
219       def render_unattached_children_menu(node, project)
220         return nil unless node.child_menus
222         returning "" do |child_html|
223           unattached_children = node.child_menus.call(project)
224           # Tree nodes support #each so we need to do object detection
225           if unattached_children.is_a? Array
226             unattached_children.each do |child|
227               child_html << content_tag(:li, render_unattached_menu_item(child, project)) 
228             end
229           else
230             raise MenuError, ":child_menus must be an array of MenuItems"
231           end
232         end
233       end
235       def render_single_menu_node(item, caption, url, selected)
236         link_to(h(caption), url, item.html_options(:selected => selected))
237       end
239       def render_unattached_menu_item(menu_item, project)
240         raise MenuError, ":child_menus must be an array of MenuItems" unless menu_item.is_a? MenuItem
242         if User.current.allowed_to?(menu_item.url, project)
243           link_to(h(menu_item.caption),
244                   menu_item.url,
245                   menu_item.html_options)
246         end
247       end
248       
249       def menu_items_for(menu, project=nil)
250         items = []
251         Redmine::MenuManager.items(menu).root.children.each do |node|
252           if allowed_node?(node, User.current, project)
253             if block_given?
254               yield node
255             else
256               items << node  # TODO: not used?
257             end
258           end
259         end
260         return block_given? ? nil : items
261       end
263       def extract_node_details(node, project=nil)
264         item = node
265         url = case item.url
266         when Hash
267           project.nil? ? item.url : {item.param => project}.merge(item.url)
268         when Symbol
269           send(item.url)
270         else
271           item.url
272         end
273         caption = item.caption(project)
274         return [caption, url, (current_menu_item == item.name)]
275       end
277       # Checks if a user is allowed to access the menu item by:
278       #
279       # * Checking the conditions of the item
280       # * Checking the url target (project only)
281       def allowed_node?(node, user, project)
282         if node.condition && !node.condition.call(project)
283           # Condition that doesn't pass
284           return false
285         end
287         if project
288           return user && user.allowed_to?(node.url, project)
289         else
290           # outside a project, all menu items allowed
291           return true
292         end
293       end
294     end
295     
296     class << self
297       def map(menu_name)
298         @items ||= {}
299         mapper = Mapper.new(menu_name.to_sym, @items)
300         if block_given?
301           yield mapper
302         else
303           mapper
304         end
305       end
306       
307       def items(menu_name)
308         @items[menu_name.to_sym] || Tree::TreeNode.new(:root, {})
309       end
310     end
311     
312     class Mapper
313       def initialize(menu, items)
314         items[menu] ||= Tree::TreeNode.new(:root, {})
315         @menu = menu
316         @menu_items = items[menu]
317       end
318       
319       @@last_items_count = Hash.new {|h,k| h[k] = 0}
320       
321       # Adds an item at the end of the menu. Available options:
322       # * param: the parameter name that is used for the project id (default is :id)
323       # * if: a Proc that is called before rendering the item, the item is displayed only if it returns true
324       # * caption that can be:
325       #   * a localized string Symbol
326       #   * a String
327       #   * a Proc that can take the project as argument
328       # * before, after: specify where the menu item should be inserted (eg. :after => :activity)
329       # * parent: menu item will be added as a child of another named menu (eg. :parent => :issues)
330       # * children: a Proc that is called before rendering the item. The Proc should return an array of MenuItems, which will be added as children to this item.
331       #   eg. :children => Proc.new {|project| [Redmine::MenuManager::MenuItem.new(...)] }
332       # * last: menu item will stay at the end (eg. :last => true)
333       # * html_options: a hash of html options that are passed to link_to
334       def push(name, url, options={})
335         options = options.dup
337         if options[:parent]
338           subtree = self.find(options[:parent])
339           if subtree
340             target_root = subtree
341           else
342             target_root = @menu_items.root
343           end
345         else
346           target_root = @menu_items.root
347         end
349         # menu item position
350         if first = options.delete(:first)
351           target_root.prepend(MenuItem.new(name, url, options))
352         elsif before = options.delete(:before)
354           if exists?(before)
355             target_root.add_at(MenuItem.new(name, url, options), position_of(before))
356           else
357             target_root.add(MenuItem.new(name, url, options))
358           end
360         elsif after = options.delete(:after)
362           if exists?(after)
363             target_root.add_at(MenuItem.new(name, url, options), position_of(after) + 1)
364           else
365             target_root.add(MenuItem.new(name, url, options))
366           end
367           
368         elsif options[:last] # don't delete, needs to be stored
369           target_root.add_last(MenuItem.new(name, url, options))
370         else
371           target_root.add(MenuItem.new(name, url, options))
372         end
373       end
374       
375       # Removes a menu item
376       def delete(name)
377         if found = self.find(name)
378           @menu_items.remove!(found)
379         end
380       end
382       # Checks if a menu item exists
383       def exists?(name)
384         @menu_items.any? {|node| node.name == name}
385       end
387       def find(name)
388         @menu_items.find {|node| node.name == name}
389       end
391       def position_of(name)
392         @menu_items.each do |node|
393           if node.name == name
394             return node.position
395           end
396         end
397       end
398     end
399     
400     class MenuItem < Tree::TreeNode
401       include Redmine::I18n
402       attr_reader :name, :url, :param, :condition, :parent, :child_menus, :last
403       
404       def initialize(name, url, options)
405         raise ArgumentError, "Invalid option :if for menu item '#{name}'" if options[:if] && !options[:if].respond_to?(:call)
406         raise ArgumentError, "Invalid option :html for menu item '#{name}'" if options[:html] && !options[:html].is_a?(Hash)
407         raise ArgumentError, "Cannot set the :parent to be the same as this item" if options[:parent] == name.to_sym
408         raise ArgumentError, "Invalid option :children for menu item '#{name}'" if options[:children] && !options[:children].respond_to?(:call)
409         @name = name
410         @url = url
411         @condition = options[:if]
412         @param = options[:param] || :id
413         @caption = options[:caption]
414         @html_options = options[:html] || {}
415         # Adds a unique class to each menu item based on its name
416         @html_options[:class] = [@html_options[:class], @name.to_s.dasherize].compact.join(' ')
417         @parent = options[:parent]
418         @child_menus = options[:children]
419         @last = options[:last] || false
420         super @name.to_sym
421       end
422       
423       def caption(project=nil)
424         if @caption.is_a?(Proc)
425           c = @caption.call(project).to_s
426           c = @name.to_s.humanize if c.blank?
427           c
428         else
429           if @caption.nil?
430             l_or_humanize(name, :prefix => 'label_')
431           else
432             @caption.is_a?(Symbol) ? l(@caption) : @caption
433           end
434         end
435       end
436       
437       def html_options(options={})
438         if options[:selected]
439           o = @html_options.dup
440           o[:class] += ' selected'
441           o
442         else
443           @html_options
444         end
445       end
446     end    
447   end