Initial commit of the new class based and menu based navigation system

This commit is contained in:
Roberto Rosario
2015-04-03 07:09:51 -04:00
parent 192069462f
commit 0246068cd0
27 changed files with 399 additions and 485 deletions

View File

@@ -0,0 +1 @@
from .classes import Link, Menu # NOQA

View File

@@ -2,7 +2,6 @@ from __future__ import unicode_literals
object_navigation = {}
model_list_columns = {}
top_menu_entries = []
def register_links(src, links, menu_name=None, position=None):
@@ -28,31 +27,6 @@ def register_links(src, links, menu_name=None, position=None):
object_navigation[menu_name][src]['links'].extend(links)
def register_top_menu(name, link, position=None):
"""
Register a new menu entry for the main menu displayed at the top
of the page
"""
entry = {'link': link, 'name': name}
if position is not None:
entry['position'] = position
top_menu_entries.insert(position, entry)
else:
length = len(top_menu_entries)
entry['position'] = length
top_menu_entries.append(entry)
sort_menu_entries()
return entry
def sort_menu_entries():
global top_menu_entries
top_menu_entries = sorted(top_menu_entries, key=lambda k: (k['position'] < 0, k['position']))
def register_model_list_columns(model, columns):
"""
Define which columns will be displayed in the generic list template

View File

@@ -5,6 +5,7 @@ import logging
import urllib
import urlparse
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import NoReverseMatch, resolve, reverse
from django.template import VariableDoesNotExist, Variable
from django.utils.encoding import smart_str, smart_unicode
@@ -12,34 +13,125 @@ from django.utils.http import urlencode, urlquote
from django.utils.text import unescape_string_literal
from django.utils.translation import ugettext_lazy as _
from permissions.models import Permission
logger = logging.getLogger(__name__)
class ResolvedLink(object):
active = False
url = '#'
description = None
icon = None
text = _('Unnamed link')
url = '#'
class Menu(object):
_registry = {}
@classmethod
def get(cls, name):
return cls._registry[name]
def __init__(self, name):
if name in self.__class__._registry:
raise Exception('A menu with this name already exists')
self.name = name
self.bound_links = {}
self.__class__._registry[name] = self
def bind_links(self, links, sources=None, position=0):
"""
Associate a link to a model, a view, or an url inside this menu
"""
if sources:
for source in sources:
source_links = self.bound_links.setdefault(source, [])
source_links.extend(links)
else:
# Unsourced links display always
source_links = self.bound_links.setdefault(None, [])
source_links.extend(links)
def resolve(self, context):
result = []
request = Variable('request').resolve(context)
current_path = request.META['PATH_INFO']
# Get sources: view name, view objects
current_view = resolve(current_path).view_name
resolved_navigation_object_list = []
navigation_object_list = context.get('navigation_object_list', [{'object': 'object'}])
# Multiple objects
for navigation_object in navigation_object_list:
try:
resolved_navigation_object_list.append(Variable(navigation_object['object']).resolve(context))
except VariableDoesNotExist:
pass
# Main menu links
for link in self.bound_links.get(None, []):
result.append(link.resolve(context))
for resolved_navigation_object in resolved_navigation_object_list:
for source, links in self.bound_links.iteritems():
if inspect.isclass(source) and isinstance(resolved_navigation_object, source) or Combined(obj=type(resolved_navigation_object), view=current_view) == source:
for link in links:
result.append(link.resolve(context))
#break # No need for further content object match testing
return result
class Link(object):
bound_links = {}
@classmethod
def bind_links(cls, sources, links, menu_name=None, position=0):
"""
Associate a link to a model, a view, or an url
"""
cls.bound_links.setdefault(menu_name, {})
def resolve_template_variable(cls, context, name):
try:
for source in sources:
cls.bound_links[menu_name].setdefault(source, {'links': []})
try:
cls.bound_links[menu_name][source]['links'].extend(links)
except TypeError:
# Try to see if links is a single link
cls.bound_links[menu_name][source]['links'].append(links)
return unescape_string_literal(name)
except ValueError:
#return Variable(name).resolve(context)
#TODO: Research if should return always as a str
return str(Variable(name).resolve(context))
except TypeError:
raise Exception('The bind_links source argument must be a list, even for single element sources.')
return name
@classmethod
def resolve_arguments(cls, context, src_args):
args = []
kwargs = {}
if isinstance(src_args, list):
for i in src_args:
try:
# Try to execute as a function
val = i(context=context)
except TypeError:
val = Link.resolve_template_variable(context, i)
if val:
args.append(val)
else:
args.append(val)
elif isinstance(src_args, dict):
for key, value in src_args.items():
try:
# Try to execute as a function
val = i(context=context)
except TypeError:
val = Link.resolve_template_variable(context, value)
if val:
kwargs[key] = val
else:
kwargs[key] = val
else:
val = Link.resolve_template_variable(context, src_args)
if val:
args.append(val)
return args, kwargs
def __init__(self, text, view, klass=None, args=None, icon=None,
permissions=None, condition=None, conditional_disable=None,
@@ -60,89 +152,67 @@ class Link(object):
self.keep_query = keep_query
self.conditional_highlight = conditional_highlight # Used by dynamic sources
def resolve(self, context, request=None, current_path=None, current_view=None, resolved_object=None):
# Don't calculate these if passed in an argument
request = request or Variable('request').resolve(context)
current_path = current_path or request.META['PATH_INFO']
if not current_view:
match = resolve(current_path)
if match.namespace:
current_view = '{}:{}'.format(match.namespace, match.url_name)
else:
current_view = match.url_name
def resolve(self, context):
request = Variable('request').resolve(context)
current_path = request.META['PATH_INFO']
current_view = resolve(current_path).view_name
# Preserve unicode data in URL query
previous_path = smart_unicode(urllib.unquote_plus(smart_str(request.get_full_path()) or smart_str(request.META.get('HTTP_REFERER', reverse('main:home')))))
query_string = urlparse.urlparse(previous_path).query
parsed_query_string = urlparse.parse_qs(query_string)
logger.debug('condition: %s', self.condition)
if resolved_object:
context['resolved_object'] = resolved_object
if self.permissions:
try:
Permission.objects.check_permissions(request.user, self.permissions)
except PermissionDenied:
return None
# Check to see if link has conditional display
if self.condition:
self.condition_result = self.condition(context)
else:
self.condition_result = True
if not self.condition(context):
return None
logger.debug('self.condition_result: %s', self.condition_result)
#logger.debug('self.condition_result: %s', self.condition_result)
if self.condition_result:
resolved_link = ResolvedLink()
resolved_link.text = self.text
resolved_link.icon = self.icon
resolved_link.permissions = self.permissions
resolved_link.condition_result = self.condition_result
resolved_link = ResolvedLink()
resolved_link.text = self.text
resolved_link.icon = self.icon
resolved_link.description = self.description
#resolved_link.permissions = self.permissions
#resolved_link.condition_result = self.condition_result
try:
#args, kwargs = resolve_arguments(context, self.get('args', {}))
args, kwargs = Link.resolve_arguments(context, self.args)
except VariableDoesNotExist:
args = []
kwargs = {}
#django/template/defaulttags.py
if self.view:
if not self.dont_mark_active:
resolved_link.active = self.view == current_view
#class URLNode(Node):
try:
if kwargs:
resolved_link.url = reverse(self.view, kwargs=kwargs)
else:
resolved_link.url = reverse(self.view, args=args)
if self.keep_query:
resolved_link.url = '%s?%s' % (urlquote(resolved_link.url), urlencode(parsed_query_string, doseq=True))
#def __init__(self, view_name, args, kwargs, asvar):
# self.view_name = view_name
# self.args = args
# self.kwargs = kwargs
# self.asvar = asvar
# def render(self, context):
except NoReverseMatch, exc:
resolved_link.url = '#'
resolved_link.error = exc
elif self.url:
if not self.dont_mark_active:
resolved_link.url.active = self.url == current_path
try:
args, kwargs = Link.resolve_arguments(context, self.args)
except VariableDoesNotExist:
args = []
kwargs = {}
if kwargs:
resolved_link.url = self.url % kwargs
else:
resolved_link.url = self.url % args
if self.keep_query:
resolved_link.url = '%s?%s' % (urlquote(resolved_link.url), urlencode(parsed_query_string, doseq=True))
if not self.dont_mark_active:
resolved_link.active = self.view == current_view
try:
if kwargs:
resolved_link.url = reverse(self.view, kwargs=kwargs)
else:
resolved_link.active = False
resolved_link.url = reverse(self.view, args=args)
if self.keep_query:
resolved_link.url = '%s?%s' % (urlquote(resolved_link.url), urlencode(parsed_query_string, doseq=True))
if self.conditional_highlight:
resolved_link.active = self.conditional_highlight(context)
except NoReverseMatch, exc:
resolved_link.url = '#'
resolved_link.error = exc
if self.conditional_disable:
resolved_link.disabled = self.conditional_disable(context)
else:
resolved_link.disabled = False
# TODO: add tree base main menu support to auto activate parent links
return resolved_link
return resolved_link
'''
@classmethod
def get_context_navigation_links(cls, context, menu_name=None, links_dict=None):
request = Variable('request').resolve(context)
@@ -237,52 +307,92 @@ class Link(object):
objects[resolved_object]['label'] = object_label
return objects
'''
@classmethod
def resolve_template_variable(cls, context, name):
try:
return unescape_string_literal(name)
except ValueError:
#return Variable(name).resolve(context)
#TODO: Research if should return always as a str
return str(Variable(name).resolve(context))
except TypeError:
return name
'''
def resolve(self, context, request=None, current_path=None, current_view=None, resolved_object=None):
# Don't calculate these if passed in an argument
request = request or Variable('request').resolve(context)
current_path = current_path or request.META['PATH_INFO']
if not current_view:
match = resolve(current_path)
if match.namespace:
current_view = '{}:{}'.format(match.namespace, match.url_name)
else:
current_view = match.url_name
@classmethod
def resolve_arguments(cls, context, src_args):
args = []
kwargs = {}
# Preserve unicode data in URL query
previous_path = smart_unicode(urllib.unquote_plus(smart_str(request.get_full_path()) or smart_str(request.META.get('HTTP_REFERER', reverse('main:home')))))
query_string = urlparse.urlparse(previous_path).query
parsed_query_string = urlparse.parse_qs(query_string)
if isinstance(src_args, list):
for i in src_args:
try:
# Try to execute as a function
val = i(context=context)
except TypeError:
val = Link.resolve_template_variable(context, i)
if val:
args.append(val)
else:
args.append(val)
elif isinstance(src_args, dict):
for key, value in src_args.items():
try:
# Try to execute as a function
val = i(context=context)
except TypeError:
val = Link.resolve_template_variable(context, value)
if val:
kwargs[key] = val
else:
kwargs[key] = val
logger.debug('condition: %s', self.condition)
if resolved_object:
context['resolved_object'] = resolved_object
# Check to see if link has conditional display
if self.condition:
self.condition_result = self.condition(context)
else:
val = Link.resolve_template_variable(context, src_args)
if val:
args.append(val)
self.condition_result = True
return args, kwargs
logger.debug('self.condition_result: %s', self.condition_result)
if self.condition_result:
resolved_link = ResolvedLink()
resolved_link.text = self.text
resolved_link.icon = self.icon
resolved_link.permissions = self.permissions
resolved_link.condition_result = self.condition_result
try:
#args, kwargs = resolve_arguments(context, self.get('args', {}))
args, kwargs = Link.resolve_arguments(context, self.args)
except VariableDoesNotExist:
args = []
kwargs = {}
if self.view:
if not self.dont_mark_active:
resolved_link.active = self.view == current_view
try:
if kwargs:
resolved_link.url = reverse(self.view, kwargs=kwargs)
else:
resolved_link.url = reverse(self.view, args=args)
if self.keep_query:
resolved_link.url = '%s?%s' % (urlquote(resolved_link.url), urlencode(parsed_query_string, doseq=True))
except NoReverseMatch, exc:
resolved_link.url = '#'
resolved_link.error = exc
elif self.url:
if not self.dont_mark_active:
resolved_link.url.active = self.url == current_path
if kwargs:
resolved_link.url = self.url % kwargs
else:
resolved_link.url = self.url % args
if self.keep_query:
resolved_link.url = '%s?%s' % (urlquote(resolved_link.url), urlencode(parsed_query_string, doseq=True))
else:
resolved_link.active = False
if self.conditional_highlight:
resolved_link.active = self.conditional_highlight(context)
if self.conditional_disable:
resolved_link.disabled = self.conditional_disable(context)
else:
resolved_link.disabled = False
# TODO: add tree base main menu support to auto activate parent links
return resolved_link
'''
class ModelListColumn(object):
_model_list_columns = {}

View File

@@ -15,270 +15,46 @@ from django.utils.text import unescape_string_literal
from common.utils import urlquote
from ..api import object_navigation, top_menu_entries
from ..api import object_navigation
from ..classes import Menu
from ..forms import MultiItemForm
register = Library()
class TopMenuNavigationNode(Node):
def render(self, context):
request = Variable('request').resolve(context)
current_path = request.META['PATH_INFO']
current_view = resolve(current_path).view_name
all_menu_links = [entry.get('link', {}) for entry in top_menu_entries]
menu_links = resolve_links(context, all_menu_links, current_view, current_path)
context['menu_links'] = menu_links
return ''
@register.assignment_tag(takes_context=True)
def get_top_menu_links(context):
return Menu.get('main menu').resolve(context=context)
@register.tag
def get_top_menu_links(parser, token):
return TopMenuNavigationNode()
@register.assignment_tag(takes_context=True)
def get_object_facet_links(context):
return Menu.get('object facet').resolve(context=context)
def resolve_arguments(context, src_args):
args = []
kwargs = {}
if isinstance(src_args, list):
for i in src_args:
val = resolve_template_variable(context, i)
if val:
args.append(val)
elif isinstance(src_args, dict):
for key, value in src_args.items():
val = resolve_template_variable(context, value)
if val:
kwargs[key] = val
else:
val = resolve_template_variable(context, src_args)
if val:
args.append(val)
@register.assignment_tag(takes_context=True)
def get_action_links(context):
result = []
return args, kwargs
for menu_name in ['object menu', 'sidebar menu', 'secondary menu']:
links = Menu.get(name=menu_name).resolve(context)
if links:
result.append(links)
def resolve_links(context, links, current_view, current_path, parsed_query_string=None):
"""
Express a list of links from definition to final values
"""
context_links = []
for link in links:
# Check to see if link has conditional display
if 'condition' in link:
condition_result = link['condition'](context)
else:
condition_result = True
if condition_result:
new_link = copy.copy(link)
try:
args, kwargs = resolve_arguments(context, link.get('args', {}))
except VariableDoesNotExist:
args = []
kwargs = {}
if 'view' in link:
if not link.get('dont_mark_active', False):
new_link['active'] = link['view'] == current_view
try:
if kwargs:
new_link['url'] = reverse(link['view'], kwargs=kwargs)
else:
new_link['url'] = reverse(link['view'], args=args)
if link.get('keep_query', False):
try:
for key in link.get('remove_from_query', []):
del parsed_query_string[key]
except KeyError:
# We were asked to remove a key not found in the
# query string, that is not fatal
pass
new_link['url'] = urlquote(new_link['url'], parsed_query_string)
except NoReverseMatch as exception:
new_link['url'] = '#'
new_link['error'] = exception
elif 'url' in link:
if not link.get('dont_mark_active', False):
new_link['active'] = link['url'] == current_path
if kwargs:
new_link['url'] = link['url'] % kwargs
else:
new_link['url'] = link['url'] % args
if link.get('keep_query', False):
try:
for key in link.get('remove_from_query', []):
del parsed_query_string[key]
except KeyError:
# We were asked to remove a key not found in the
# query string, that is not fatal
pass
new_link['url'] = urlquote(new_link['url'], parsed_query_string)
else:
new_link['active'] = False
if 'conditional_highlight' in link:
new_link['active'] = link['conditional_highlight'](context)
if 'conditional_disable' in link:
new_link['disabled'] = link['conditional_disable'](context)
else:
new_link['disabled'] = False
context_links.append(new_link)
return context_links
def get_navigation_object(context, object_name=None):
if not object_name:
try:
object_name = Variable('navigation_object_name').resolve(context)
except VariableDoesNotExist:
object_name = 'object'
try:
obj = Variable(object_name).resolve(context)
except VariableDoesNotExist:
obj = None
return obj, object_name
def _get_object_navigation_links(context, menu_name=None, links_dict=object_navigation, obj=None, object_name=None):
request = Variable('request').resolve(context)
current_path = request.META['PATH_INFO']
current_view = resolve(current_path).view_name
context_links = []
# Don't fudge with the original global dictionary
links_dict = links_dict.copy()
# Preserve unicode data in URL query
previous_path = smart_unicode(urllib.unquote_plus(smart_str(request.get_full_path()) or smart_str(request.META.get('HTTP_REFERER', reverse('main:home')))))
query_string = urlparse.urlparse(previous_path).query
parsed_query_string = urlparse.parse_qs(query_string)
try:
# Check for an inject temporary navigation dictionary
temp_navigation_links = Variable('extra_navigation_links').resolve(context)
except VariableDoesNotExist:
pass
else:
if temp_navigation_links:
links_dict.update(temp_navigation_links)
# Match view links
try:
links = links_dict[menu_name][current_view]['links']
for link in resolve_links(context, links, current_view, current_path, parsed_query_string):
context_links.append(link)
except KeyError:
pass
if not obj:
obj, object_name = get_navigation_object(context, object_name=object_name)
# Match context navigation object links
for source, data in links_dict[menu_name].items():
if inspect.isclass(source) and isinstance(obj, source):
for link in resolve_links(context, data['links'], current_view, current_path, parsed_query_string):
context_links.append(link)
break
return context_links
def resolve_template_variable(context, name):
try:
return unescape_string_literal(name)
except ValueError:
# return Variable(name).resolve(context)
# TODO: Research if should return always as a str
return str(Variable(name).resolve(context))
except TypeError:
return name
class GetNavigationLinks(Node):
def __init__(self, menu_name=None, links_dict=object_navigation, var_name='object_navigation_links'):
self.menu_name = menu_name
self.links_dict = links_dict
self.var_name = var_name
def render(self, context):
menu_name = resolve_template_variable(context, self.menu_name)
context[self.var_name] = _get_object_navigation_links(context, menu_name, links_dict=self.links_dict)
obj, object_name = get_navigation_object(context)
context['navigation_object'] = obj
return ''
@register.tag
def get_object_navigation_links(parser, token):
tag_name, arg = token.contents.split(None, 1)
m = re.search(r'("?\w+"?)?.?as (\w+)', arg)
if not m:
raise TemplateSyntaxError('%r tag had invalid arguments' % tag_name)
menu_name, var_name = m.groups()
return GetNavigationLinks(menu_name=menu_name, var_name=var_name)
@register.inclusion_tag('navigation/generic_navigation.html', takes_context=True)
def object_navigation_template(context):
new_context = copy.copy(context)
new_context.update({
'horizontal': True,
'object_navigation_links': _get_object_navigation_links(context)
})
return new_context
return result
@register.simple_tag(takes_context=True)
def get_multi_item_links_form(context, object_list=None):
if object_list:
first_object = object_list[0]
else:
first_object = None
actions = [(link['url'], link['text']) for link in _get_object_navigation_links(context, menu_name='multi_item_links', obj=first_object)]
def get_multi_item_links_form(context, object_list):
first_object = object_list[0]
actions = []#(link.url, link.text) for link in Menu.get('multi items').resolve(context=context, obj=first_object)]
form = MultiItemForm(actions=actions)
context.update({'multi_item_form': form, 'multi_item_actions': actions})
return ''
def get_navigation_links(context, menu_name=None, links_dict=object_navigation, object_name=None):
return _get_object_navigation_links(context=context, menu_name=menu_name, links_dict=links_dict, object_name=object_name)
@register.assignment_tag(takes_context=True)
def get_contextual_links(context):
result = []
def get_object_links(context):
return Menu.get('object menu').resolve(context=context)
navigation_object_list = context.get('navigation_object_list', [])
if navigation_object_list:
for navigation_object in context.get('navigation_object_list', []):
links = get_navigation_links(context, object_name=navigation_object['object'])
if links:
result.append(links)
else:
links = get_navigation_links(context)
if links:
result.append(links)
links = get_navigation_links(context, menu_name='sidebar')
if links:
result.append(links)
links = get_navigation_links(context, menu_name='secondary_menu')
if links:
result.append(links)
return result