"""An expandable/collapsible box of wiki content.

Can by styled with the css classes 'expander', 'open', 'closed'.
Additional css classes can be added with a 'class' parameter.
The title can use inline wiki format.

Example:
{{{#!Expander title='An Outrageous Claim' state=open
An in detail elaboration of this outrageous claim, using full wiki syntax.
}}}
"""
from string import Template
from genshi.builder import tag
from trac.wiki.macros import WikiMacroBase
from trac.wiki import format_to_html, format_to_oneliner

t = Template('$state expander$extra')
s = Template('display: $display')
script = ("s=nextSibling.style.display=='none';nextSibling.style.display=s?'block':'none';"
          "c = parentNode.getAttribute('class');"
          "parentNode.setAttribute('class',c.replace(s?/^closed/:/^open/,s?'open':'closed'))")


class ExpanderMacro(WikiMacroBase):

    def expand_macro(self, formatter, name, content, args):
        cssclass = args.get('class', None)
        cssclass = (cssclass and ' ' + cssclass) or ''
        title = args.get('title', 'Title')
        state = args.get('state', 'closed')
        display = state == 'closed' and 'none' or 'block'
        return tag.div(tag.h6(format_to_oneliner(self.env, formatter.context, title),
                              onclick=script),
                       tag.div(format_to_html(self.env, formatter.context, content),
                               style=s.substitute(display=display)),
                       class_=t.substitute(state=state, extra=cssclass))

