thelayouts / thelayouts / layouts_base.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
# -*- coding: utf-8 -*-

from webhelpers.html import literal

from .utils import html_params


__all__ = [
    'CannotResolveElementException', 'LayoutElement', 'CallableElement', 
    'Script', 'Container', 'Column', 'Layout', 'Row', 'FormRow', 'FormatRow',
    'ButtonPanel', 'HSpace', 'CompositeFormLine', 'Field', 'FormLine', 
    'Fieldset', 'Label', 'Text', 'ErrorList', 'HintRow', 'AllHiddenFields',
]

class CannotResolveElementException(Exception):
    def __init__(self, field):
        super(CannotResolveElementException, self).__init__(field)


class DefaultFlags(object):
    def __init__(self, **entries):
        entries = dict({
            "inline": False,
        }, **entries)
        self.__dict__.update(entries)


class LayoutElement(object):

    def __init__(self, *elements, **attrs):
        self._is_present = attrs.pop("is_present", True)
        self.element_attrs = attrs.pop("element_attrs", {})
        self.help = attrs.pop('help', None)
        self.label_text = attrs.pop("label_text", u"")
        self.attrs = attrs
        # Before elements come LayoutElements they are stored in 
        # self.unresolved_child_elements
        self.unresolved_child_elements = list(elements)
        self.resolved_child_elements = []
        # Containing form with related fields refered to by elements
        self.form = None
        self.title = None

    def is_present(self):
        """Determine if this layout element is to be rendered."""
        if callable(self._is_present):
            return self._is_present()
        return self._is_present

    def get_element_attrs(self, **attrs):
        """Get attributes intended for child layout elements."""
        element_attrs = self.element_attrs.copy()
        element_attrs.update(attrs)
        return element_attrs

    def get_help(self):
        """Get help string for this layout element."""
        return self.help

    def get_attrs(self, **attrs):
        """Get attributes of this layout elements updated by attrs if given."""
        result_attrs = self.attrs.copy()
        result_attrs.update(attrs)
        return result_attrs

    def get_form(self):
        """Get form bound to this layout element. Form binding is done by form 
        itself calling bind(form) method before rendering the whole layout tree.
        """
        return self.form

    def get_title(self):
        """Get title for this layout element."""
        return self.title

    def get_label_text(self):
        return self.label_text

    def iterate_child_elements(self):
        """Iterate child elements yielding LayoutElement instances."""
        for element in self.resolved_child_elements:
            yield element
        while self.unresolved_child_elements:
            element = self.unresolved_child_elements.pop(0)
            element = self.resolve_element(element)
            self.resolved_child_elements.append(element)
            yield element

    def bind(self, form):
        """Bind this element and it's child elements to given form."""
        self.form = form
        for element in self.iterate_child_elements():
            element.bind(form)

    def is_bound(self):
        """Check is this layout element bound to a form."""
        return self.form is not None

    def render(self, *args, **kwargs):
        """Render this layout element (if self.is_present() == True) and it's 
        child elements."""
        if not self.is_present():
            return u""
        return self.render_elements()

    def render_elements(self):
        """Render only child layout elements."""
        rendered_elements = []
        for element in self.iterate_child_elements():
            if not element.is_present():
                continue
            rendered_elements.append(
                self.render_element(element)
            )
        return literal(u"").join(rendered_elements)

    def render_element(self, element, **attrs):
        """Render given layout element applying contained element_attrs."""
        return element.render(**self.get_element_attrs())

    def render_errors(self):
        """Render errors if any for this and child layout elements."""
        html = []
        for child_element in self.iterate_child_elements():
            html.append(child_element.render_errors())
        return literal(u"").join(html)

    def resolve_element(self, element, *args, **kwargs):
        """Resolve element into LayoutElement instance.
        Arguments:
        element -- LayoutElement, basestring or callable.
        """
        if isinstance(element, LayoutElement):
            return element
        if isinstance(element, basestring):
            return self.resolve_string_element(element, *args, **kwargs)
        if callable(element):
            return self.resolve_callable_element(element, *args, **kwargs)
        return self.resolve_other_element(element, *args, **kwargs)

    def resolve_string_element(self, element, *args, **kwargs):
        """Resolve a string into Field(LayoutElement) which represents a form 
        field."""
        return Field(element, parent_layout_element=self, *args, **kwargs)

    def resolve_callable_element(self, element, *args, **kwargs):
        """Resolve a callable element into CallableElement(LayoutElement)."""
        return CallableElement(element, *args, **kwargs)

    def resolve_other_element(self, element, *args, **kwargs):
        """Resolve an element which is not any of LayoutElement, basestring or 
        callable. Throws CannotResolveElementException() by default."""
        raise CannotResolveElementException(element, *args, **kwargs)

    def get_label_text(self):
        return self.label_text

    def is_labeled(self):
        return True

    def is_inline(self):
        return False

    # def get_flags(self):
    #     return fields.Flags()

    # def get_hint_text(self):
    #     return u""

    # def get_layout_element_by_field_name(self, field_name):
    #     """ Method supports only FormLine layout elements """
    #     for element in self.iterate_child_elements():
    #         if (
    #             hasattr(element, "field_name") and
    #             element.field_name == field_name
    #         ):
    #             return element
    #     return None

    # def prepare_help_hint_data(self):
    #     help = self.get_help()
    #     title = self.get_title()
    #     if isinstance(help, dict):
    #         help_text = help.get('text', u'')
    #         help_title = help.get('title', u'')
    #         return (help_title, help_text)
    #     return title, help

    def get_element_help_html(self):
        return self.get_help()
        # if self.get_help():
        #     obj_id = "%shelp" % self.__hash__()
        #     help_title, help_text = self.prepare_help_hint_data()
        #     return h.help_hint(obj_id, obj_id, help_title, help_text)
        # return u""


class CallableElement(LayoutElement):
    """Layout element just calling it's element as callable providing given 
    arguments."""

    def __init__(
        self, element, element_args=tuple(), element_kwargs={}, **kwargs
    ):
        """
        Arguments:
        element -- a callable which is to be called when rendering. Signature of
        calling given element is following: element(form, *args, **kwargs),
            where `form` is a bound form.
        element_args -- a list of arguments which are to be passed to given
            element.
        element_kwargs -- a list of keyword arguments which are to be passed to
            given element.
        """
        assert callable(element)
        super(CallableElement, self).__init__(**kwargs)
        self.element = element
        self.element_args = element_args
        self.element_kwargs = element_kwargs

    def render(self):
        """Call the callable element and return results of the call."""
        return self.element(
            self.form, *self.element_args, **self.element_kwargs
        )


class Script(CallableElement):
    """Alias for CallableElement."""
    pass


class Container(LayoutElement):
    """Represents a collection of elements surrounded with additional markup."""
    
    def render(self, **kwargs):
        """Render child elements within a  container."""
        return literal(u"").join((
            self.render_container_start(**self.get_element_attrs()),
            self.render_elements(),
            self.render_container_end(),
        ))
        
    def render_container_start(self, **kwargs):
        """Render start of a container."""
        return literal(u'<div %s>') % (
            html_params(**self.attrs),
        )

    def render_container_end(self):
        """Render end of container."""
        return literal(u'</div>')


class Column(Container):
    """Renders child elements in a column."""

    def render_element(self, element, **attrs):
        """Render given child element so it is displayed in column with others.
        """
        return literal(u"<div %s>%s</div>") % (
            html_params(**attrs), element.render()
        )


class Layout(Column):
    """Alias for Column."""
    pass


class Row(Container):
    """Renders child elements in a row."""

    def render_element(self, element, **attrs):
        """Render given element so it's displayed in row with others."""
        attrs = attrs.copy()
        attrs['style'] = attrs.get('style', '') + 'float: left;';
        return literal(u"<div %s>%s</div>") % (
            html_params(**attrs), element.render()
        )

    def render_container_end(self):
        """Render container end in a different way Container does."""
        return literal(u"").join((
            literal(u"<div style='clear: both;'></div>"),
            super(Row, self).render_container_end(),
        ))


class FormRow(Row):

    def __init__(self, *elements, **attrs):
        super(FormRow, self).__init__(*elements, **attrs)
        self.element_attrs['style'] = self.element_attrs.get(
            'style', 'margin-right: 5px;'
        )


class FormatRow(Row):

    def __init__(self, format_text, elements_dict, **attrs):
        self.format_text = format_text
        element_ids, elements = zip(*elements_dict.iteritems())
        super(FormatRow, self).__init__(*elements, **attrs)
        self.elements_dict = {}
        for key, element in zip(element_ids, self.iterate_child_elements()):
            self.elements_dict[key] = element

    def render_elements(self):
        return self.format_text % dict(
            (k, el.render()) for k, el in self.elements_dict.iteritems())


class ButtonPanel(Row):

    def __init__(self, *elements, **attrs):
        super(ButtonPanel, self).__init__(*elements, **attrs)
        self.element_attrs['class_'] = self.element_attrs.get(
            'class_', 'submit-buttons'
        )


class HSpace(LayoutElement):

    def __init__(self, margin_right=u'10px', *elements, **attrs):
        super(HSpace, self).__init__(*elements, **attrs)
        self.margin_right = margin_right

    def render(self, **kwargs):
        return literal(u"""
            <span style="margin-right: %(margin_right)s;">&#160;</span>
        """) % dict(
            margin_right=self.margin_right
        )


class CompositeFormLine(LayoutElement):

    def __init__(
        self, element, hint_text=None, warning_text=None, required=None, 
        **attrs
    ):
        element = self.resolve_element(
            element, hint_text=hint_text, warning_text=warning_text, 
            required=required
        )
        super(CompositeFormLine, self).__init__(element, **attrs)
        self.hint_text = hint_text
        self.warning_text = warning_text
        self.required = required

    def get_title(self):
        return self.get_label_text()

    def get_label_class(self, element):
        if self.required or element.get_flags().required:
            return "required"
        return ""

    def get_label_html(self, element):
        if not element.is_labeled():
            return self.get_label_text()
        return self.get_element_label(element)

    def get_element_label(self, element):
        return self.get_label_text() or element.get_label_text()

    def get_hint_text(self):
        return self.hint_text

    def get_hint_html(self, element):
        if self.get_hint_text():
            element = self
        if element.get_hint_text():
            hint_html = literal(u'<span class="text-hint">%s</span>') % (
                element.get_hint_text(),
            )
        else:
            hint_html = u''
        return hint_html

    def get_warning_html(self):
        return h.warn(self.warning_text) if self.warning_text else u''

    def get_attrs(self, **kwargs):
        attrs = self.attrs.copy()
        attrs.update(kwargs)
        attrs.setdefault('class_', 'form-line')
        return attrs

    def render_element(self, element, **kwargs):
        if element.is_inline():
            return super(CompositeFormLine, self).render_element(
                element, **kwargs
            )
        return literal("""
            <div %(attrs)s>
                <span class="label">
                    <label class="%(label_class)s">%(label)s</label>
                    %(help)s
                </span>
                <div class="form-inputs">
                    %(element)s
                    %(hint)s
                    %(warning)s
                </div>
            </div>
        """) % dict(
            attrs=html_params(**self.get_attrs(**kwargs)),
            label_class=self.get_label_class(element),
            label=self.get_label_html(element),
            help=self.get_element_help(element),
            element=super(CompositeFormLine, self).render_element(element),
            hint=self.get_hint_html(element),
            warning=self.get_warning_html(),
        )

    def get_element_help(self, element):
        if self.get_help():
            element = self
        if not element.get_help():
            return u''
        return element.get_element_help_html()


class Field(LayoutElement):

    def __init__(self, field_name, hint_text=None, warning_text=None, **attrs):
        super(Field, self).__init__(**attrs)
        self.name = field_name
        self.hint_text = hint_text
        self.warning_text = warning_text

    def get_title(self):
        return self.get_label_text()

    @property
    def id(self):
        return getattr(self.form, self.name).id

#    @property
#    def name(self):
#        return getattr(self.form, self.name).name

    @property
    def form_field(self):
        # TODO: To be removed
        return self.get_form_field()

    def get_form_field(self):
        return getattr(self.form, self.name)

    def get_flags(self):
        return self.form_field.flags

    def get_label_text(self):
        return self.label_text or self.form_field.label.text

    @property
    def errors(self):
        return self.get_errors()

    def get_errors(self):
        return self.form_field.errors

    def get_hint_text(self):
        return (
            self.hint_text or
            getattr(self.form, 'hints', {}).get(self.name, u'')
        )

    @property
    def inline_hint_text(self):
        return getattr(self.form, 'inline_hints', {}).get(self.name, u'')

    def get_help(self):
        return self.help or getattr(self.form, 'helps', {}).get(self.name, u'')

    def render(self, **kwargs):
        if not self.is_present():
            return ""
        attrs = self.get_attrs(**kwargs)
        return literal(u"").join((
            self.get_form_field()(),
            self.render_errors(),
        ))

    def render_errors(self):
        return ErrorList(self.id, self.errors).render()

    def is_labeled(self):
        return not self.is_boolean_field()

    def is_boolean_field(self):
        # TODO: To be implemented
        #return isinstance(form_field, fields.BooleanField)
        return False

    def is_hidden_field(self):
        # TODO: To be implemented
        # return isinstance(form_field, fields.HiddenField)
        return False

    def is_inline(self):
        return self.get_flags().inline


class FormLine(CompositeFormLine):

    def __init__(
        self, field_name, hint_text=None, warning_text=None, label_text=None,
        **attrs
    ):
        super(FormLine, self).__init__(
            field_name, hint_text=hint_text, warning_text=warning_text,
            label_text=label_text, **attrs
        )

    def render_element(self, field_element, **kwargs):
        if field_element.is_hidden_field():
            return field_element.render(**self.element_attrs)
        if not field_element.is_inline():
            self._set_field_inline_hint(field_element)
        return super(FormLine, self).render_element(field_element, **kwargs)

    def _set_field_inline_hint(self, field_element):
        if not hasattr(field_element, 'inline_hint_text') or not field_element.inline_hint_text:
            return u''

        hint = field_element.inline_hint_text.strip().replace('\n', '\\')

        help_js = u"""$("#%(field_id)s").defaultValue();""" % dict(
            field_id = field_element.id
        )
        field_element.attrs['rel'] = hint
        h.add_on_dom_ready(help_js, inline=False, jslib=u'jquery')
        h.add_import('jquery', 'defaultvalue')


class Fieldset(Column):

    def __init__(self, *elements, **attrs):
        self.legend = attrs.pop('legend', u"")
        self.collapsed = attrs.pop("collapsed", False)
        super(Fieldset, self).__init__(*elements, **attrs)

    def get_title(self):
        return self.legend

    def resolve_string_element(self, element, *args, **kwargs):
        return FormLine(element, *args, **kwargs)

    def render_container_start(self, **kwargs):
        attrs = self.get_attrs(**kwargs)
        html = []
        if self.collapsed:
            link_attrs = html_params(
                href='javascript:void(0)', class_='collapse-link',
                onclick='jQuery(this).hide().next().show("fast")'
            )
            html.append(literal(
                u'<a %s><span class="collapse-icon"></span><span class="collapse-text">%s</span></a>') % (
                    link_attrs, self.legend
                )
            )
            if 'style' in attrs:
                attrs['style'] += '; display: none;'
            else:
                attrs['style'] = 'display: none;'
        html.append(literal(u'<fieldset %s>') % html_params(**attrs))
        if self.legend:
            help_html = self.get_element_help_html()
            html.append(literal(u'<legend>%s %s</legend>') % (self.legend, help_html))
        return literal(u'\n').join(html)

    def render_container_end(self):
        return literal(u'</fieldset>')


class Label(LayoutElement):

    def __init__(self, text, for_, required=False, **attrs):
        super(Label, self).__init__(**attrs)
        self.text = text
        self.for_ = for_
        self.required = required

    def render(self, **kwargs):
        text = self.text
        kwargs.setdefault('class_', 'label')

        return literal(u"""
            <span %(params)s>
                <label %(label_params)s>
                    %(text)s
                </label>
                %(help)s
            </span>
        """) % dict(
            params=html_params(**kwargs),
            label_params=html_params(
                class_='required' if self.required else '', for_=self.for_
            ),
            text=self.text,
            help=self.get_element_help_html(),
        )


class Text(LayoutElement):

    def __init__(self, text, **attrs):
        super(Text, self).__init__(**attrs)
        self.text = text

    def render(self, **kwargs):
        return literal(u"""
            <span %(params)s>%(text)s</span>
        """) % dict(
            params=html_params(**self.attrs),
            text=self.text,
        )


class ErrorList(object):

    def __init__(self, field_id, errors):
        self.field_id = field_id
        self.errors = errors

    def _error(self, error=u'', **kwargs):
        return literal(u'<span %s>%s</span>') % (html_params(**kwargs), error)

    def render(self):
        css_classes = []
        if not self.errors:
            css_classes.append('hidden')
        html = [self._error(
            id='%s_error_icon' % self.field_id, 
            class_=' '.join(css_classes + ['error-icon'])
        )]
        if self.errors:
            if isinstance(self.errors, dict):
                self.errors = self.errors.values()
                if len(self.errors) > 0 and isinstance(self.errors[0], (list, tuple)):
                    html.pop()
                    self.errors = []
            for error in self.errors:
                if isinstance(error, (list, tuple)):
                    error = '\n'.join(error)
                html.append(self._error(
                    error, id='%s_error' % self.field_id, 
                    class_=' '.join(css_classes + ['error'])
                ))
        else:
            html.append(
                self._error(
                    id='%s_error' % self.field_id, 
                    class_=' '.join(css_classes + ['error'])
                )
            )
        return literal(u'\n').join(html)


class HintRow(LayoutElement):

    def __init__(
        self, name, hint=None, class_="fancy-hint", style="", id=None, 
        _form=None, base_class="form-line", **attrs
    ):
        super(HintRow, self).__init__(_form=_form, **attrs)
        self.name = name
        self.hint = hint
        self.class_ = class_
        self.style = style
        self.id = id if id else name+"-hint"
        self.base_class = base_class

    def render(self, **kwargs):
        if not self.hint:
            return
        border_radius = "border-radius-cabinet" if h.is_cabinet() or h.is_cabinet_user() else "border-radius-port"
        class_ = self.class_+" "+kwargs.get("class_", "")+" "+border_radius
        style = literal(u'style="%s"') % self.style if self.style else ""
        return literal(u'<div class="%(base_class)s" id="%(id)s_line" %(style)s><div id="%(id)s" class="%(class_)s">%(hint)s</div></div>') % dict(
            class_ = class_,
            style = style,
            id = self.id,
            hint = self.hint,
            base_class = self.base_class
        )


class AllHiddenFields(LayoutElement):

    def render(self, **kwargs):
        if 'style' in kwargs:
            kwargs['style'] = '%s; %s' % (kwargs['style'], 'display: none;')
        else:
            kwargs['style'] = 'display: none;'

        output = [literal(u'<div %s>') % html_params(**kwargs)]
        for field in self.form:
            if isinstance(field, fields.HiddenField):
                output.append(field(**self.element_attrs))
        output.append(literal(u'</div>'))
        return literal(u'\n').join(output)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.