Esempio n. 1
0
    def _get_element(self, **kwargs) -> htmler.Input:
        """Render the widget
        :param **kwargs:
        """
        inp = htmler.Input(
            type=self._type,
            id=self._uid,
            name=self._name,
            css='form-control',
            autocomplete=self._autocomplete,
            placeholder=self._placeholder,
            required=self._required
        )

        value = self.get_val()
        if value:
            inp.set_attr('value', value)

        if not self._enabled:
            inp.set_attr('disabled', 'true')

        if self._min_length:
            inp.set_attr('minlength', self._min_length)

        if self._max_length:
            inp.set_attr('maxlength', self._max_length)

        if self._prepend or self._append:
            group = htmler.Div(css='input-group')
            if self._prepend:
                prepend = group.append_child(htmler.Div(css='input-group-addon input-group-prepend'))
                prepend.append_child(htmler.Div(self._prepend, css='input-group-text'))
            group.append_child(inp)
            if self._append:
                append = group.append_child(htmler.Div(css='input-group-addon input-group-append'))
                append.append_child(htmler.Div(self._append, css='input-group-text'))
            inp = group

        if self._inputmask:
            inp.set_attr('data_inputmask', ','.join(["'{}': '{}'".format(k, v) for k, v in self._inputmask.items()]))

        return inp
Esempio n. 2
0
    def _get_element(self, **kwargs) -> htmler.Element:
        """Hook
        """
        em = htmler.TagLessElement()

        if len(self._header):
            header = htmler.Div(self._header, css='card-header panel-heading')
            header.add_css(self._header_css)
            em.append_child(header)

        body = em.append_child(htmler.Div(
            css='card-body panel-body children'))  # type: htmler.Element
        body.add_css(self._body_css)

        if len(self._footer):
            footer = htmler.Div(self._footer, css='card-footer panel-footer')
            footer.add_css(self._footer_css)
            em.append_child(footer)

        return em
Esempio n. 3
0
    def _get_element(self, **kwargs) -> htmler.Element:
        """Get HTML element of the widget
        """
        div = htmler.Div(css=self._box_type, data_pub_id=self._pub_id)

        if self._url:
            div.set_attr('data_url', self._url)
        if self._title:
            div.set_attr('data_title', self._title)

        return div
Esempio n. 4
0
    def _get_element(self, **kwargs) -> htmler.Element:
        """Get widget's HTML element
        """
        # Root element
        r = htmler.TagLessElement()

        # Append toolbar
        r.append_child(self._toolbar)

        r.append_child(htmler.Div(css='widget-component'))

        return r
Esempio n. 5
0
 def _get_embed(self, url: str) -> htmler.Element:
     """Get player embed code.
     """
     if 'youtube.com' in url or 'youtu.be' in url:
         return self._get_embed_youtube(url)
     elif 'facebook.com' in url:
         return self._get_embed_facebook(url)
     elif 'vimeo.com' in url:
         return self._get_embed_vimeo(url)
     elif 'rutube.ru' in url:
         return self._get_embed_rutube(url)
     else:
         return htmler.Div('Not implemented.')
Esempio n. 6
0
    def _get_element(self, **kwargs) -> htmler.Element:
        self.data.update({
            'value':
            json.dumps([u.uid for u in (self.value or [])]),
            'max_slots':
            self._max_slots,
            'modal_title':
            self._modal_title,
            'modal_ok_button_caption':
            self._modal_ok_button_caption,
            'modal_cancel_button_caption':
            self._modal_cancel_button_caption,
        })

        return htmler.Div(css='widget-component')
Esempio n. 7
0
    def render(self) -> str:
        """Render the form
        """
        from ._api import store
        store(self)

        return str(
            htmler.Div(
                css=f'pytsite-form2-container {self._css}'.strip(),
                data_action_url=self._action,
                data_get_widgets_path=self._get_widgets_path,
                data_steps=self._steps,
                data_submit_path=self._submit_path,
                data_name=self._name,
                data_uid=self._uid,
            ))
Esempio n. 8
0
    def _get_embed_rutube(url,
                          width: int = 640,
                          height: int = 360) -> htmler.Element:
        """Get RuTube player embed code.
        """
        match = re.search('rutube\\.ru/video/(\\w{32})', url)
        if match:
            src = '//rutube.ru/video/embed/{}'.format(match.group(1))
            return htmler.Iframe(src=src,
                                 frameborder='0',
                                 width=width,
                                 height=height,
                                 allowfullscreen=True,
                                 css='iframe-responsive')

        raise ValueError(htmler.Div('Invalid video link: ' + url))
Esempio n. 9
0
    def _get_embed_vimeo(url,
                         width: int = 640,
                         height: int = 360) -> htmler.Element:
        """Get Vimeo player embed code.
        """
        match = re.search('vimeo\\.com/(\\d+)', url)
        if match:
            src = '//player.vimeo.com/video/{}'.format(match.group(1))
            return htmler.Iframe(src=src,
                                 frameborder='0',
                                 width=width,
                                 height=height,
                                 allowfullscreen=True,
                                 css='iframe-responsive')

        raise ValueError(htmler.Div('Invalid video link: ' + url))
Esempio n. 10
0
    def _get_embed_facebook(url,
                            width: int = 640,
                            height: int = 360) -> htmler.Element:
        """Get RuTube player embed code.
        """
        match = re.search('facebook\\.com/[^/]+/videos/\\d+', url)
        if match:
            src = 'https://www.facebook.com/plugins/video.php?href={}'.format(
                util.url_quote(url))
            return htmler.Iframe(src=src,
                                 frameborder='0',
                                 width=width,
                                 height=height,
                                 allowfullscreen=True,
                                 css='iframe-responsive')

        raise ValueError(htmler.Div('Invalid video link: ' + url))
Esempio n. 11
0
    def _get_embed_youtube(url,
                           width: int = 640,
                           height: int = 360) -> htmler.Element:
        """Get YouTube player embed code.
        """
        match = re.search(
            '(youtube\\.com/watch.+v=|youtu.be/)([a-zA-Z0-9\\-_]{11})', url)
        if match:
            src = '//www.youtube.com/embed/{}?html5=1'.format(match.group(2))
            return htmler.Iframe(src=src,
                                 frameborder='0',
                                 width=width,
                                 height=height,
                                 allowfullscreen=True,
                                 css='iframe-responsive')

        raise ValueError(htmler.Div('Invalid video link: ' + url))
Esempio n. 12
0
    def _get_element(self, **kwargs) -> htmler.Element:
        self.data.update({
            'enabled': self._enabled,
            'empty_slot_title': self._empty_slot_title,
            'entity_thumb_field': self._entity_thumb_field,
            'entity_title_field': self._entity_title_field,
            'entity_url_field': self._entity_url_field,
            'exclude': json_dumps(self._exclude),
            'modal_ok_button_caption': self._modal_ok_button_caption,
            'modal_title': self._modal_title,
            'model': self._model,
            'search_by': self._search_by,
            'search_delay': self._search_delay,
            'search_minimum_input_length': self._search_minimum_input_length,
            'sort_by': self._sort_by,
            'sort_order': self._sort_order,
            'value': json_dumps(self.get_val()),
        })

        return htmler.Div(css='widget-component')
Esempio n. 13
0
    def __init__(self, uid: str, **kwargs):
        super().__init__(uid, **kwargs)

        self._rows_url = kwargs.get('rows_url')
        if not self._rows_url:
            raise ValueError("'rows_url' argument is not provided")

        self._has_messages = False

        self._data_fields = [
        ]  # type: List[Tuple[str, str, bool]]  # name, title, sortable
        self._default_sort_field = kwargs.get('default_sort_field')
        self._default_sort_order = kwargs.get('default_sort_order', 'asc')
        self._toolbar = htmler.Div(id='{}-toolbar'.format(uid),
                                   css='data-table-toolbar')

        # Pass data fields through setter
        self.data_fields = kwargs.get('data_fields', [])

        self._css += ' widget-data-table'
Esempio n. 14
0
    def _render_dropdown(self, entity: _model.Menu) -> Optional[htmler.Li]:
        if not entity.enabled:
            return

        # Dropdown's root
        root = htmler.Li(css='nav-item dropdown')

        # Toggler
        root.append_child(htmler.A(entity.title, id=entity.ref, href='#', css='nav-link dropdown-toggle', role='button',
                                   data_toggle='dropdown', aria_haspopup='true', aria_expanded='false'))

        # Dropdown
        dropdown = root.append_child(htmler.Div(css='dropdown-menu', aria_labelledby=entity.ref))
        for e in entity.children:  # type: _model.Menu
            if e.enabled:
                a_css = 'dropdown-item {}'.format('active' if self._is_item_active(e) else '')
                a = dropdown.append_child(htmler.A(e.title, href=self._item_url(e), css=a_css))

                if e.new_window:
                    a.set_attr('target', '_blank')

        return root
Esempio n. 15
0
    def renderable(self, **kwargs) -> htmler.Element:
        """Get an HTML element representation of the widget
        """
        cid = []
        cur_cls = self.__class__
        while cur_cls is not Abstract:
            cid.append(cur_cls.cid())
            cur_cls = cur_cls.__bases__[0]
            if not self._inherit_cid:  # Breaks after first iteration
                break

        # Wrapper div
        self._wrap_em.set_attr('data_cid', ' '.join(reversed(cid)))
        self._wrap_em.set_attr('data_uid', self._uid)
        self._wrap_em.set_attr('data_weight', self._weight)
        self._wrap_em.set_attr('data_form_area', self._form_area)
        self._wrap_em.set_attr('data_hidden', self._hidden)
        self._wrap_em.set_attr('data_enabled', self._enabled)
        self._wrap_em.set_attr('data_parent_uid',
                               self._parent.uid if self._parent else None)

        # Replaces
        if self._replaces:
            self._wrap_em.set_attr('data_replaces', self._replaces)

        # Get widget's HTML element
        em = self._get_element(**kwargs)
        if not em:
            return htmler.TagLessElement()

        # Validate element's type
        if not isinstance(em, htmler.Element):
            raise TypeError('{} expected, got {}'.format(
                htmler.Element, type(em)))

        # Wrapper CSS
        cls_css = self.__class__.__name__.lower()
        cid_css = self.cid().lower().replace('_', '-').replace('.', '-')
        wrap_css = 'pytsite-widget widget-{} widget-{} widget-uid-{} {}'.format(
            cls_css, cid_css, self._uid, self._css)
        if self._form_group:
            wrap_css += ' form-group'
        if self._hidden:
            wrap_css += ' hidden sr-only'
        if self._has_messages:
            if self._has_success:
                wrap_css += ' has-success'
            if self._has_warning:
                wrap_css += ' has-warning'
            if self._has_error:
                wrap_css += ' has-error'
        self._wrap_em.set_attr('css', wrap_css)

        # Set widget's data attributes
        if isinstance(self._data, dict):
            for k, v in self._data.items():
                self._wrap_em.set_attr('data_' + k, v)

        # Wrap into size container
        h_sizer = None
        if self._h_size:
            h_sizer = htmler.Div(css='h-sizer ' + self._h_size)
            em = em.wrap(h_sizer)
            em = em.wrap(htmler.Div(css='row ' + self._h_size_row_css))

        # Append label element
        if self._label and not self._label_disabled:
            label = htmler.Label(self._label, label_for=self.uid)
            if self._h_size and self._h_size_label:
                label = label.wrap(htmler.Div(css='h-sizer ' + self._h_size))
                label = label.wrap(
                    htmler.Div(css='row ' + self._h_size_row_css))
            if self._label_hidden:
                label.set_attr('css', 'sr-only')
            self._wrap_em.append_child(label)

        # Append widget's element
        self._wrap_em.append_child(em)

        # Append help block
        if self._help:
            self._wrap_em.append_child(
                htmler.Small(self._help,
                             css='help-block form-text text-muted'))

        # Append messages placeholder
        if self._has_messages:
            messages = htmler.Div(css='widget-messages')
            if h_sizer:
                h_sizer.append_child(messages)
            else:
                self._wrap_em.append_child(messages)

        return self._wrap_em
Esempio n. 16
0
    def __init__(self, uid: str, **kwargs):
        """Init
        """
        self._uid = uid
        self._inherit_cid = kwargs.get('inherit_cid', True)
        self._wrap_em = kwargs.get('wrap_em',
                                   htmler.Div())  # type: htmler.Element
        self._name = kwargs.get('name', uid)
        self._language = kwargs.get('language', lang.get_current())
        self._weight = kwargs.get('weight', 0)
        self._default = kwargs.get('default')
        self._value = None  # Wil be set later
        self._label = kwargs.get('label')
        self._title = kwargs.get('title')
        self._label_hidden = kwargs.get('label_hidden', False)
        self._label_disabled = kwargs.get('label_disabled', False)
        self._placeholder = kwargs.get('placeholder')
        self._css = kwargs.get('css', '')
        self._data = kwargs.get('data', {})
        self._has_messages = kwargs.get('has_messages', True)
        self._has_success = kwargs.get('has_success', False)
        self._has_warning = kwargs.get('has_warning', False)
        self._has_error = kwargs.get('has_error', False)
        self._help = kwargs.get('help')
        self._h_size = kwargs.get('h_size')
        self._h_size_label = kwargs.get('h_size_label', False)
        self._h_size_row_css = kwargs.get('h_size_row_css', '')
        self._hidden = kwargs.get('hidden', False)
        self._rules = kwargs.get('rules',
                                 [])  # type: List[validation.rule.Rule]
        self._form_area = kwargs.get('form_area', 'body')
        self._replaces = kwargs.get('replaces')
        self._required = kwargs.get('required', False)
        self._enabled = kwargs.get('enabled', True)
        self._parent = kwargs.get('parent')
        self._children = []  # type: List[Abstract]
        self._children_uids = []  # type: List[str]
        self._children_sep = kwargs.get('children_sep', '')
        self._last_children_weight = 0
        self._form_group = kwargs.get('form_group', True)

        # Check validation rules
        if not isinstance(self._rules, (list, tuple)):
            self._rules = [self._rules]
        if isinstance(self._rules, tuple):
            self._rules = list(self._rules)
        for rule in self._rules:
            if not isinstance(rule, validation.rule.Rule):
                raise TypeError(
                    'Instance of pytsite.validation.rule.Base expected.')

        # Required
        if self.required:
            self.add_rule(validation.rule.NonEmpty())

        # It is important to filter value through the setter-method
        if 'value' in kwargs:
            self.set_val(kwargs.get('value'))
        else:
            self.set_val(deepcopy(self._default))

        # Process data-attributes
        for k, v in kwargs.items():
            if k.startswith('data_'):
                self._data[k.replace('data_', '')] = v
Esempio n. 17
0
 def _get_element(self, **kwargs) -> htmler.Element:
     return htmler.Div(id=self.uid, css='button-container')
Esempio n. 18
0
 def _get_element(self, **kwargs) -> htmler.Element:
     """Render the widget.
     :param **kwargs:
     """
     return htmler.Div(tpl.render('disqus@widget', {'widget': self}),
                       uid=self._uid)
Esempio n. 19
0
 def _get_element(self, **kwargs) -> htmler.Element:
     """Hook
     """
     return htmler.Div(css='children ' + self._body_css)