Exemplo n.º 1
0
    def calculateDefaultSkin(self, context):
        if self.isGrouped:
            frm = tags.invisible
            butt = ""
            fld = tags.invisible
        else:
            frm = tags.form(
                id=slot("form-id"),
                name=slot("form-id"),
                action=slot("form-action"),
                method="post",
                enctype="multipart/form-data",
                **{"accept-charset": "utf-8"}
            )
            butt = slot("form-button")
            fld = tags.fieldset[tags.input(type="hidden", name="_charset_")]

        ## Provide default skin since no skin was provided for us.
        context.tag.clear()[
            frm[
                fld[
                    tags.legend(_class="freeform-form-label")[slot("form-label")],
                    tags.div(_class="freeform-form-description")[slot("form-description")],
                    tags.div(_class="freeform-form-error")[slot("form-error")],
                    slot("form-arguments"),
                    butt,
                ]
            ]
        ]
    def rend(self, context, data):
        if data.getAttribute('invisible'):
            return ''

        context.remember(data, iformless.IBinding)

        if self.needsSkin or not context.tag.children:
            self.calculateDefaultSkin(context)

        self.fillForm(context, data)
        context.fillSlots('form-label', data.label)
        context.fillSlots('form-description', data.description)
        context.fillSlots(
            'form-arguments',
            list(self.generateArguments(context, data.getArgs())))

        if not self.isGrouped:
            try:
                button_pattern = context.tag.onePattern('form-button')
            except NodeNotFound:
                button_pattern = invisible[slot('input')]

            button_pattern.fillSlots(
                'input',
                input(type='submit',
                      value=data.action or data.label,
                      name=data.name,
                      class_="freeform-button"))

            context.fillSlots('form-button', button_pattern)

        return context.tag(key=None)
Exemplo n.º 3
0
    def rend(self, context, data):
        if data.getAttribute('invisible'):
            return ''

        context.remember(data, iformless.IBinding)

        if self.needsSkin or not context.tag.children:
            self.calculateDefaultSkin(context)

        self.fillForm(context, data)
        context.fillSlots( 'form-label', data.label )
        context.fillSlots( 'form-description', data.description )
        context.fillSlots( 'form-arguments', list(self.generateArguments(context, data.getArgs())))

        if not self.isGrouped:
            try:
                button_pattern = context.tag.onePattern( 'form-button' )
            except NodeNotFound:
                button_pattern = tags.invisible[ slot('input') ]

            button_pattern.fillSlots( 'input', tags.input(type='submit', value=data.action or data.label, name=data.name, class_="freeform-button") )

            context.fillSlots( 'form-button', button_pattern )

        return context.tag(key=None)
Exemplo n.º 4
0
    def startElementNS(self, ns_and_name, qname, attrs):

        ns, name = ns_and_name
        if ns == nevow.namespace:
            if name == 'invisible':
                name = ''
            elif name == 'slot':
                el = slot(attrs[(None, 'name')])
                self.stack.append(el)
                self.current.append(el)
                self.current = el.children
                return

        attrs = dict(attrs)
        specials = {}
        attributes = self.attributeList
        directives = self.directiveMapping
        for k, v in attrs.items():
            att_ns, nons = k
            if att_ns != nevow.namespace:
                continue
            if nons in directives:
                ## clean this up by making the names more consistent
                specials[directives[nons]] = directive(v)
                del attrs[k]
            if nons in attributes:
                specials[nons] = v
                del attrs[k]

        no_ns_attrs = {}
        for (attrNs, attrName), v in attrs.items():
            nsPrefix = self.prefixMap.get(attrNs)
            if nsPrefix is None:
                no_ns_attrs[attrName] = v
            else:
                no_ns_attrs['%s:%s' % (nsPrefix, attrName)] = v

        if ns == nevow.namespace and name == 'attr':
            if not self.stack:
                # TODO: define a better exception for this?
                raise AssertionError('<nevow:attr> as top-level element')
            if 'name' not in no_ns_attrs:
                # TODO: same here
                raise AssertionError('<nevow:attr> requires a name attribute')
            el = Tag('', specials=specials)
            self.stack[-1].attributes[no_ns_attrs['name']] = el
            self.stack.append(el)
            self.current = el.children
            return

        # Apply any xmlns attributes
        if self.xmlnsAttrs:
            no_ns_attrs.update(dict(self.xmlnsAttrs))
            self.xmlnsAttrs = []

        el = Tag(name, attributes=dict(no_ns_attrs), specials=specials)
        self.stack.append(el)
        self.current.append(el)
        self.current = el.children
Exemplo n.º 5
0
    def startElementNS(self, ns_and_name, qname, attrs):

        ns, name = ns_and_name
        if ns == nevow.namespace:
            if name == 'invisible':
                name = ''
            elif name == 'slot':
                el = slot(attrs[(None,'name')])
                self.stack.append(el)
                self.current.append(el)
                self.current = el.children
                return
        
        attrs = dict(attrs)
        specials = {}
        attributes = self.attributeList
        directives = self.directiveMapping
        for k, v in attrs.items():
            att_ns, nons = k
            if att_ns != nevow.namespace:
                continue
            if nons in directives:
                ## clean this up by making the names more consistent
                specials[directives[nons]] = directive(v)
                del attrs[k]
            if nons in attributes:
                specials[nons] = v
                del attrs[k]

        no_ns_attrs = {}
        for (attrNs, attrName), v in attrs.items():
            nsPrefix = self.prefixMap.get(attrNs)
            if nsPrefix is None:
                no_ns_attrs[attrName] = v
            else:
                no_ns_attrs['%s:%s'%(nsPrefix,attrName)] = v

        if ns == nevow.namespace and name == 'attr':
            if not self.stack:
                # TODO: define a better exception for this?
                raise AssertionError( '<nevow:attr> as top-level element' )
            if 'name' not in no_ns_attrs:
                # TODO: same here
                raise AssertionError( '<nevow:attr> requires a name attribute' )
            el = Tag('', specials=specials)
            self.stack[-1].attributes[no_ns_attrs['name']] = el
            self.stack.append(el)
            self.current = el.children
            return

        # Apply any xmlns attributes
        if self.xmlnsAttrs:
            no_ns_attrs.update(dict(self.xmlnsAttrs))
            self.xmlnsAttrs = []

        el = Tag(name, attributes=dict(no_ns_attrs), specials=specials)
        self.stack.append(el)
        self.current.append(el)
        self.current = el.children
Exemplo n.º 6
0
def MicroDomElementSerializer(element, context):
    directiveMapping = {
        'render': 'render',
        'data': 'data',
        'macro': 'macro',
    }
    attributeList = [
        'pattern',
        'key',
    ]

    name = element.tagName
    if name.startswith('nevow:'):
        _, name = name.split(':')
        if name == 'invisible':
            name = ''
        elif name == 'slot':
            return slot(element.attributes['name'])[precompile(
                serialize(element.childNodes, context), context)]

    attrs = dict(element.attributes)  # get rid of CaseInsensitiveDict
    specials = {}
    attributes = attributeList
    directives = directiveMapping
    for k, v in list(attrs.items()):
        # I know, this is totally not the way to do xml namespaces but who cares right now
        ## I'll fix it later -dp
        ### no you won't *I'll* fix it later -glyph
        if isinstance(k, tuple):
            if k[0] != 'http://nevow.com/ns/nevow/0.1':
                continue
            else:
                nons = k[1]
        elif not k.startswith('nevow:'):
            continue
        else:
            _, nons = k.split(':')
        if nons in directives:
            ## clean this up by making the names more consistent
            specials[directives[nons]] = directive(v)
            del attrs[k]
        if nons in attributes:
            specials[nons] = v
            del attrs[k]

    # TODO: there must be a better way than this ...
    # Handle any nevow:attr elements. If we don't do it now then this tag will
    # be serialised and it will too late.
    childNodes = []
    for child in element.childNodes:
        if getattr(child, 'tagName', None) == 'nevow:attr':
            attrs[child.attributes['name']] = child.childNodes
        else:
            childNodes.append(child)

    tag = Tag(name, attributes=attrs, children=childNodes, specials=specials)

    return serialize(tag, context)
Exemplo n.º 7
0
        class R(rend.Page):
            def data_numbers(context, data):
                return [
                    ['one', 'un/une'],
                    ['two', 'deux'],
                    ['three', 'trois'],
                ]

            def render_row(context, data):
                context.fillSlots('english', data[0])
                context.fillSlots('french', data[1])
                return context.tag

            tags = table(data=data_numbers, render=directive('sequence'))[
                tr(pattern='header')[th['English'], th['French']],
                tr(pattern='item', render=render_row)[td[slot('english')],
                                                      td[slot('french')]], ]

            docFactory = loaders.stan(tags)
Exemplo n.º 8
0
def MicroDomElementSerializer(element, context):
    directiveMapping = {
        'render': 'render',
        'data': 'data',
        'macro': 'macro',
    }
    attributeList = [
        'pattern', 'key',
    ]

    name = element.tagName
    if name.startswith('nevow:'):
        _, name = name.split(':')
        if name == 'invisible':
            name = ''
        elif name == 'slot':
            return slot(element.attributes['name'])[
                precompile(serialize(element.childNodes, context), context)]
    
    attrs = dict(element.attributes) # get rid of CaseInsensitiveDict
    specials = {}
    attributes = attributeList
    directives = directiveMapping
    for k, v in attrs.items():
        # I know, this is totally not the way to do xml namespaces but who cares right now
        ## I'll fix it later
        if not k.startswith('nevow:'):
            continue
        _, nons = k.split(':')
        if nons in directives:
            ## clean this up by making the names more consistent
            specials[directives[nons]] = directive(v)
            del attrs[k]
        if nons in attributes:
            specials[nons] = v
            del attrs[k]
            
    # TODO: there must be a better way than this ...
    # Handle any nevow:attr elements. If we don't do it now then this tag will
    # be serialised and it will too late.
    childNodes = []
    for child in element.childNodes:
        if getattr(child,'tagName',None) == 'nevow:attr':
            attrs[child.attributes['name']] = child.childNodes
        else:
            childNodes.append(child)

    tag = Tag(
            name,
            attributes=attrs,
            children=childNodes,
            specials=specials
            )

    return serialize(tag, context)
class ChoiceRenderer(BaseInputRenderer):
    default_select = select(
        id=slot('id'), name=slot('name'), render=directive('sequence'))[option(
            pattern="item", value=valToKey,
            render=isSelected)[lambda c, d: iformless.ITyped(c).stringify(d)]]

    def input(self, context, slot, data, name, value):
        tv = data.typedValue
        choices = tv.choices

        if value:
            context.remember(value, csv)
        else:
            context.remember('', csv)

        try:
            selector = context.tag.patternGenerator('selector')
        except NodeNotFound:
            selector = self.default_select

        return selector(data=choices)
Exemplo n.º 10
0
def MicroDomElementSerializer(element, context):
    directiveMapping = {"render": "render", "data": "data", "macro": "macro"}
    attributeList = ["pattern", "key"]

    name = element.tagName
    if name.startswith("nevow:"):
        _, name = name.split(":")
        if name == "invisible":
            name = ""
        elif name == "slot":
            return slot(element.attributes["name"])[precompile(serialize(element.childNodes, context), context)]

    attrs = dict(element.attributes)  # get rid of CaseInsensitiveDict
    specials = {}
    attributes = attributeList
    directives = directiveMapping
    for k, v in attrs.items():
        # I know, this is totally not the way to do xml namespaces but who cares right now
        ## I'll fix it later -dp
        ### no you won't *I'll* fix it later -glyph
        if isinstance(k, tuple):
            if k[0] != "http://nevow.com/ns/nevow/0.1":
                continue
            else:
                nons = k[1]
        elif not k.startswith("nevow:"):
            continue
        else:
            _, nons = k.split(":")
        if nons in directives:
            ## clean this up by making the names more consistent
            specials[directives[nons]] = directive(v)
            del attrs[k]
        if nons in attributes:
            specials[nons] = v
            del attrs[k]

    # TODO: there must be a better way than this ...
    # Handle any nevow:attr elements. If we don't do it now then this tag will
    # be serialised and it will too late.
    childNodes = []
    for child in element.childNodes:
        if getattr(child, "tagName", None) == "nevow:attr":
            attrs[child.attributes["name"]] = child.childNodes
        else:
            childNodes.append(child)

    tag = Tag(name, attributes=attrs, children=childNodes, specials=specials)

    return serialize(tag, context)
Exemplo n.º 11
0
        class Page(rend.Page):
            docFactory = loaders.stan(
                html(render=directive("template"))[body[
                    p(render=directive("before")), p[slot(name="maincontent")],
                    p(render=directive("after")), ], ])

            def render_before(self, context, data):
                return context.tag["before"]

            def render_template(self, context, data):
                context.fillSlots('maincontent', Fragment())
                return context.tag

            def render_after(self, context, data):
                return context.tag["after"]
Exemplo n.º 12
0
def MicroDomElementSerializer(element, context):
    directiveMapping = {
        'render': 'render',
        'data': 'data',
        'macro': 'macro',
    }
    attributeList = [
        'pattern', 'key',
    ]
    name = element.tagName
    if name.startswith('nevow:'):
        _, name = name.split(':')
        if name == 'invisible':
            name = ''
        elif name == 'slot':
            return slot(element.attributes['name'])[
                precompile(serialize(element.childNodes, context), context)]
    attrs = dict(element.attributes) # get rid of CaseInsensitiveDict
    specials = {}
    attributes = attributeList
    directives = directiveMapping
    for k, v in attrs.items():
        if not k.startswith('nevow:'):
            continue
        _, nons = k.split(':')
        if nons in directives:
            specials[directives[nons]] = directive(v)
            del attrs[k]
        if nons in attributes:
            specials[nons] = v
            del attrs[k]
    childNodes = []
    for child in element.childNodes:
        if getattr(child,'tagName',None) == 'nevow:attr':
            attrs[child.attributes['name']] = child.childNodes
        else:
            childNodes.append(child)
    tag = Tag(
            name,
            attributes=attrs,
            children=childNodes,
            specials=specials
            )
    return serialize(tag, context)
Exemplo n.º 13
0
 def calculateDefaultSkin(self, context):
     if self.isGrouped:
         frm = invisible
         butt = ''
         fld = invisible
     else:
         frm = form(
             id=slot('form-id'),
             name=slot('form-id'),
             action=slot('form-action'),
             method="post",
             enctype="multipart/form-data",
             **{'accept-charset':'utf-8'}
             )
         butt = slot('form-button')
         fld = fieldset[input(type='hidden', name='_charset_')]
     context.tag.clear()[
         frm[fld[legend(_class="freeform-form-label")[ slot('form-label') ],
                 div(_class="freeform-form-description")[slot('form-description')],
                 div(_class="freeform-form-error")[ slot('form-error') ],
                 slot('form-arguments'), butt ]]]
    def calculateDefaultSkin(self, context):
        if self.isGrouped:
            frm = invisible
            butt = ''
            fld = invisible
        else:
            frm = form(id=slot('form-id'),
                       name=slot('form-id'),
                       action=slot('form-action'),
                       method="post",
                       enctype="multipart/form-data",
                       **{'accept-charset': 'utf-8'})
            butt = slot('form-button')
            fld = fieldset[input(type='hidden', name='_charset_')]

        ## Provide default skin since no skin was provided for us.
        context.tag.clear()[frm[fld[
            legend(_class="freeform-form-label")[slot('form-label')],
            div(_class="freeform-form-description")[slot('form-description')],
            div(_class="freeform-form-error")[slot('form-error')],
            slot('form-arguments'), butt]]]
Exemplo n.º 15
0
            content_pattern = context.tag.patternGenerator( 'binding' )
        except NodeNotFound:
            content_pattern = freeformDefaultContentPattern

        context.fillSlots(
            'form-arguments',
            content_pattern(
                data=data, render=typedRenderer, key=data.name))

        context.fillSlots('form-button', subm)

        return context.tag


freeformDefaultContentPattern = tags.invisible[
    tags.label(_class="freeform-label", _for=slot('id'))[ slot('label') ],
    tags.span(_class="freeform-input")[ slot('input') ],
    tags.div(_class="freeform-error")[ slot('error') ],
    tags.div(_class="freeform-description")[tags.label(_for=slot('id'))[ slot('description') ]]].freeze()


class MethodBindingRenderer(BaseBindingRenderer):
    def rend(self, context, data):
        if data.getAttribute('invisible'):
            return ''

        context.remember(data, iformless.IBinding)

        if self.needsSkin or not context.tag.children:
            self.calculateDefaultSkin(context)
Exemplo n.º 16
0
            content_pattern = context.tag.patternGenerator( 'binding' )
        except NodeNotFound:
            content_pattern = freeformDefaultContentPattern

        context.fillSlots(
            'form-arguments',
            content_pattern(
                data=data, render=typedRenderer, key=data.name))

        context.fillSlots('form-button', subm)

        return context.tag


freeformDefaultContentPattern = tags.invisible[
    tags.label(_class="freeform-label", _for=slot('id'))[ slot('label') ],
    tags.span(_class="freeform-input")[ slot('input') ],
    tags.div(_class="freeform-error")[ slot('error') ],
    tags.div(_class="freeform-description")[tags.label(_for=slot('id'))[ slot('description') ]]].freeze()


class MethodBindingRenderer(BaseBindingRenderer):
    def rend(self, context, data):
        if data.getAttribute('invisible'):
            return ''

        context.remember(data, iformless.IBinding)

        if self.needsSkin or not context.tag.children:
            self.calculateDefaultSkin(context)
Exemplo n.º 17
0
    def startElementNS(self, ns_and_name, qname, attrs):

        filename = self.sourceFilename
        lineNumber = self.locator.getLineNumber()
        columnNumber = self.locator.getColumnNumber()

        ns, name = ns_and_name
        if ns == nevow.namespace:
            if name == 'invisible':
                name = ''
            elif name == 'slot':
                try:
                    # Try to get the default value for the slot
                    default = attrs[(None, 'default')]
                except KeyError:
                    # If there wasn't one, then use None to indicate no
                    # default.
                    default = None
                el = slot(
                    attrs[(None, 'name')], default=default,
                    filename=filename, lineNumber=lineNumber,
                    columnNumber=columnNumber)
                self.stack.append(el)
                self.current.append(el)
                self.current = el.children
                return

        attrs = dict(attrs)
        specials = {}
        attributes = self.attributeList
        directives = self.directiveMapping
        for k, v in list(attrs.items()):
            att_ns, nons = k
            if att_ns != nevow.namespace:
                continue
            if nons in directives:
                ## clean this up by making the names more consistent
                specials[directives[nons]] = directive(v)
                del attrs[k]
            if nons in attributes:
                specials[nons] = v
                del attrs[k]

        no_ns_attrs = {}
        for (attrNs, attrName), v in list(attrs.items()):
            nsPrefix = self.prefixMap.get(attrNs)
            if nsPrefix is None:
                no_ns_attrs[attrName] = v
            else:
                no_ns_attrs['%s:%s'%(nsPrefix,attrName)] = v

        if ns == nevow.namespace and name == 'attr':
            if not self.stack:
                # TODO: define a better exception for this?
                raise AssertionError( '<nevow:attr> as top-level element' )
            if 'name' not in no_ns_attrs:
                # TODO: same here
                raise AssertionError( '<nevow:attr> requires a name attribute' )
            el = Tag('', specials=specials, filename=filename,
                     lineNumber=lineNumber, columnNumber=columnNumber)
            self.stack[-1].attributes[no_ns_attrs['name']] = el
            self.stack.append(el)
            self.current = el.children
            return

        # Apply any xmlns attributes
        if self.xmlnsAttrs:
            no_ns_attrs.update(dict(self.xmlnsAttrs))
            self.xmlnsAttrs = []

        # Add the prefix that was used in the parsed template for non-Nevow
        # namespaces (which Nevow will consume anyway).
        if ns != nevow.namespace and ns is not None:
            prefix = self.prefixMap[ns]
            if prefix is not None:
                name = '%s:%s' % (self.prefixMap[ns],name)
        el = Tag(
            name, attributes=dict(no_ns_attrs), specials=specials,
            filename=filename, lineNumber=lineNumber,
            columnNumber=columnNumber)
        self.stack.append(el)
        self.current.append(el)
        self.current = el.children
Exemplo n.º 18
0
        context.fillSlots("form-description", "")

        try:
            content_pattern = context.tag.patternGenerator("binding")
        except NodeNotFound:
            content_pattern = freeformDefaultContentPattern

        context.fillSlots("form-arguments", content_pattern(data=data, render=typedRenderer, key=data.name))

        context.fillSlots("form-button", subm)

        return context.tag


freeformDefaultContentPattern = tags.invisible[
    tags.label(_class="freeform-label", _for=slot("id"))[slot("label")],
    tags.span(_class="freeform-input")[slot("input")],
    tags.div(_class="freeform-error")[slot("error")],
    tags.div(_class="freeform-description")[tags.label(_for=slot("id"))[slot("description")]],
].freeze()


class MethodBindingRenderer(BaseBindingRenderer):
    def rend(self, context, data):
        if data.getAttribute("invisible"):
            return ""

        context.remember(data, iformless.IBinding)

        if self.needsSkin or not context.tag.children:
            self.calculateDefaultSkin(context)
class RadioRenderer(ChoiceRenderer):
    default_select = span(id=slot('id'), render=directive('sequence'))[div(
        pattern="item", _class="freeform-radio-option")[input(
            type="radio", name=slot('name'), value=valToKey,
            render=isChecked)[lambda c, d: iformless.ITyped(c).stringify(d)]]]
        try:
            content_pattern = context.tag.patternGenerator('binding')
        except NodeNotFound:
            content_pattern = freeformDefaultContentPattern

        context.fillSlots(
            'form-arguments',
            content_pattern(data=data, render=typedRenderer, key=data.name))

        context.fillSlots('form-button', subm)

        return context.tag


freeformDefaultContentPattern = invisible[
    label(_class="freeform-label", _for=slot('id'))[slot('label')],
    span(_class="freeform-input")[slot('input')],
    div(_class="freeform-error")[slot('error')],
    div(_class="freeform-description")[label(
        _for=slot('id'))[slot('description')]]].freeze()


class MethodBindingRenderer(BaseBindingRenderer):
    def rend(self, context, data):
        if data.getAttribute('invisible'):
            return ''

        context.remember(data, iformless.IBinding)

        if self.needsSkin or not context.tag.children:
            self.calculateDefaultSkin(context)