How to use the cssutils.css.CSSStyleDeclaration function in cssutils

To help you get started, we’ve selected a few cssutils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github hsoft / pdfmasher / ebooks / oeb / stylizer.py View on Github external
def _apply_style_attr(self):
        attrib = self._element.attrib
        if 'style' not in attrib:
            return
        css = attrib['style'].split(';')
        css = [_f for _f in (x.strip() for x in css) if _f]
        css = [x.strip() for x in css]
        css = [x for x in css if self.MS_PAT.match(x) is None]
        try:
            style = CSSStyleDeclaration('; '.join(css))
        except CSSSyntaxError:
            return
        self._style.update(self._stylizer.flatten_style(style))
github myfreeweb / cssprefixer / cssprefixer / engine.py View on Github external
# BUG: doesn't work when minified
            s = '' if minify else '\n'
            return '@-webkit-keyframes {' + s + \
            ''.join([magic(rs, debug, minify, ['webkit'], parser) for rs in inner]) \
            + '}' + s + '@-moz-keyframes {' + s + \
            ''.join([magic(rs, debug, minify, ['moz'], parser) for rs in inner]) \
            + '}' + s + ruleset.cssText
        elif ruleset.cssText.startswith('from') or ruleset.cssText.startswith('to'):
            return "".join([magic(rs, debug, minify, filt, parser) for rs in parser.parseString(re.sub(r'\w+\s?\{(.*)\}', r'\1', ruleset.cssText.replace('\n', ''))[1])])
        else:
            return
    elif hasattr(ruleset, 'style'):  # Comments don't
        ruleSet = set()
        rules = list()
        children = list(ruleset.style.children())
        ruleset.style = cssutils.css.CSSStyleDeclaration()  # clear out the styles that were there
        for rule in children:
            if not hasattr(rule, 'name'):  # comments don't have name
                rules.append(rule)
                continue
            name = prefixRegex.sub('', rule.name)
            if name in tr_rules:
                rule.name = name
            if rule.cssText in ruleSet:
                continue
            ruleSet.add(rule.cssText)
            rules.append(rule)

        ruleset.style.seq._readonly = False
        for rule in rules:
            if not hasattr(rule, 'name'):
                ruleset.style.seq.append(rule, 'Comment')
github disqus / toronado / toronado / __init__.py View on Github external
def from_string(cls, value):
        values = {}
        for property in CSSStyleDeclaration(value).getProperties():
            values.update(expand_property(property))
        return cls(values)
github palexu / send2kindle / cssutils / parse.py View on Github external
:param encoding:
            It will be used to decode `cssText` if given as a (byte)
            string.
        :param validate:
            If given defines if validation is used. Uses CSSParser settings as
            fallback
        :returns:
            :class:`~cssutils.css.CSSStyleDeclaration`
        """
        self.__parseSetting(True)
        if isinstance(cssText, bytes):
            # TODO: use codecs.getdecoder('css') here?
            cssText = cssText.decode(encoding)
        if validate is None:
            validate = self._validate
        style = css.CSSStyleDeclaration(cssText, validating=validate)
        self.__parseSetting(False)
        return style
github pib / PyBrowser / domhtml.py View on Github external
def getComputedStyle(self, elt, psuedoElt):
        """ Return a CSSStyleDeclaration with the computed style of the element
        (or psuedo element if psuedoElt is not None)

        This is just a dummy version for now which returns the very minimum
        basic styles.
        """
        return css.CSSStyleDeclaration(cssText =
                                       """
                                       position: static;
                                       display: inline;
                                       visibility: visible;
                                       z-index: auto;
                                       overflow: visible;
                                       white-space: normal;
                                       clip: auto;
                                       float: none;
                                       clear: none;

                                       width: auto;
                                       height: auto;
                                       top: auto;
                                       right: auto;
                                       bottom: auto;
github rennat / pynliner / pynliner / __init__.py View on Github external
for rule in rules:
            for selector in rule.selectorList:
                for element in select(self.soup, selector.selectorText):
                    element_tuple = (element, id(element))
                    if element_tuple not in elem_prop_map:
                        elem_prop_map[element_tuple] = []
                    elem_prop_map[element_tuple].append({
                        'specificity': selector.specificity,
                        'props': rule.style.getProperties(),
                    })

        # build up another property list using selector specificity
        for elem_tuple, props in elem_prop_map.items():
            elem, elem_id = elem_tuple
            if elem_tuple not in elem_style_map:
                elem_style_map[elem_tuple] = cssutils.css.CSSStyleDeclaration()
            # ascending sort of prop_lists based on specificity
            props = sorted(props, key=lambda p: p['specificity'])
            # for each prop_list, apply to CSSStyleDeclaration
            for prop_list in map(lambda obj: obj['props'], props):
                for prop in prop_list:
                    elem_style_map[elem_tuple].removeProperty(prop.name)
                    elem_style_map[elem_tuple].setProperty(prop.name, prop.value)

        # apply rules to elements
        for elem_tuple, style_declaration in elem_style_map.items():
            elem, elem_id = elem_tuple
            if elem.has_attr('style'):
                elem['style'] = u'%s; %s' % (style_declaration.cssText.replace('\n', ' '), elem['style'])
            else:
                elem['style'] = style_declaration.cssText.replace('\n', ' ')
github lavr / python-emails / emails / loader / cssinliner.py View on Github external
style=rule.style))
                    continue

                matching = cssselector.evaluate(document)

                for element in matching:

                        if element.tag in self.NONVISUAL_TAGS:
                            continue

                        # add styles for all matching DOM elements
                        self.log(1, 'ELEMENT', id(element), element.text)

                        if element not in view:
                            # add initial empty style declatation
                            view[element] = CSSStyleDeclaration()
                            specificities[element] = {}

                            # and add inline @style if present
                            inlinestyle = styleCallback(element)
                            if inlinestyle:
                                for p in inlinestyle:
                                    # set inline style specificity
                                    view[element].setProperty(p)
                                    specificities[element][p.name] = (1, 0, 0, 0)

                        for p in rule.style:
                            # update style declaration
                            if p not in view[element]:
                                # setProperty needs a new Property object and
                                # MUST NOT reuse the existing Property
                                # which would be the same for all elements!
github dlanger / inlinestyler / inlinestyler / converter.py View on Github external
def styleattribute(self, element):
        """
          returns css.CSSStyleDeclaration of inline styles, for html: @style
          """
        css_text = element.get('style')
        if css_text:
            return cssutils.css.CSSStyleDeclaration(cssText=css_text)
        else:
            return None