""" the ``Node`` class to build navigation tree. """ import json import locale from .directsvc import JSONEncoder from gluon import current class Node(object): """The *node* is the key element of the navigation tree. It contains children (leaves) which are associated to widgets. The widget will be display on the panel of the *Viewport*. Args: text (str): name of the node appearing in the viewport navigation tree. Attributes: text (str): name of the node children (list): list of children hidden (list): list of children to be hidden """ def __init__(self, text): self.text = text self.children = [] self.hidden = [] def add_child(self, text, cfg): """Add a child (leaf) to the node. Args: text (str): the name of the leaf cfg (dict): the Ext JS configuration options defining the widget associated to the leaf """ di = {"cfg": json.dumps(cfg, cls=JSONEncoder), "leaf": True, "text": text} self.children.append(di) def add_children(self, leaves, func=None, hidden=[]): """Add children (leaves) to the node. Args: leaves (list): names of the leaves func (function): function mapping the leaf name to the Ext JS configuration options dictionary. The latter defines the associated widget. hidden (list): list of children to be ignored. Note: * Leaf names are translated in the current language * Leaf names are sorted in alphabetic order """ # translator T = current.T # translate and order leaves in alphabetic order # according to local setting cvt = {} for el in leaves: # NOTE: str is required to force the translation when lazyT is on cvt[str(T(el))] = el translate_leaves = list(cvt.keys()) translate_leaves.sort() # fill the node with its children for tr_leaf in translate_leaves: leaf = cvt[tr_leaf] if leaf in hidden: continue self.add_child(tr_leaf, func(leaf)) def get_node(self): """Get the dictionary defining the node. Returns: dict: * **text** (str): name of the node * **children** (list): list of leaves. Each element is a dictionary with three keys: * **cfg** (dict): configuration for the widgets associated to the leaf. * **leave** (bool): always ``True``. * **text** (str): name of the leaf """ return {"text": self.text, "children": self.children} def sort_children(self): """sort children according to alphabetical order. """ di = {} for child in self.children: di[child["text"]] = child names = list(di.keys()) names.sort(cmp=locale.strcoll) self.children = [] for name in names: self.children.append(di[name])