Skip to content

css_tools.py

CSS This module is a set of tools to analyze CSS syntax as well as properties and values.

Declaration

A property and value pair.

A declaration is a pairing of a property with a specific value. Examples include: font-family: Helvetica; which changes the font to Helvetica. Another example could be min-height: 100px which sets the height of the element to be at the very least 100 pixels.

Attributes:

Name Type Description
text str

the text of the declaration in the form of property: value;

property str

the thing you want to change (like color or border-width.

value str

what you want to change it to (like aquamarine or 5px

Source code in webcode_tk/css_tools.py
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
class Declaration:
    """A property and value pair.

    A declaration is a pairing of a property with a specific value.
    Examples include: `font-family: Helvetica;` which changes the
    font to Helvetica. Another example could be `min-height: 100px`
    which sets the height of the element to be at the very least
    100 pixels.

    Attributes:
        text (str): the text of the declaration in the form of
            `property: value;`
        property (str): the thing you want to change (like `color`
            or `border-width`.
        value (str): what you want to change it to (like `aquamarine`
            or `5px`"""

    def __init__(self, text):
        """Inits a Declaration object."""
        self.__text = text
        self.property = ""
        self.value = ""
        self.invalid_message = ""
        self.is_color = False
        # validate before trying to set the declaration.
        try:
            self.validate_declaration()
            self.is_valid = True
            self.set_declaration()
            self.is_color_property()
        except ValueError as e:
            self.is_valid = False
            self.invalid_message = str(e)

    def set_declaration(self):
        """Sets the property and value based on the text (CSS code).

        Note: this only gets run if the declaration was valid, and
        we already ran the validation. Had the code not been valid,
        it would have already thrown an exception, and we wouldn't
        be in this method."""
        elements = self.__text.split(":")
        self.property = elements[0].strip()
        self.value = elements[1].strip()

    def validate_declaration(self):
        """Raises a ValueError if any part of the Declaration is
        invalid."""

        # split text at colon (should have 2 items only: the property
        # on the left of the colon and the value on the right of the
        # colon)
        try:
            property, value = self.__text.split(":")
        except ValueError as err:
            if "not enough values" in str(err):
                # There was no colon - there must be one
                msg = "The code is missing a colon. All declarations "
                msg += "must have a colon between the property and "
                msg += "the value."
                raise ValueError(msg)
            elif "too many values" in str(err):
                # There were two or more colons - can only be one
                msg = "You have too many colons. There should only be "
                msg += "one colon between the property and the value."
                raise ValueError(msg)

        self.validate_property(property)
        self.validate_value(value)

    def validate_property(self, property) -> bool:
        """checks property to make sure it is a valid CSS property.

        A CSS property is valid if there are no spaces in between the
        text. In future versions, we could check against a list of
        valid properties, but that might take us down a rabbit hole
        of ever changing properties.

        Args:
            property (str): the property of the Declaration which might
                or might not be valid.

        Raises:
            ValueError: if the property is an invalid property
        """

        # Make sure there are no spaces in between property
        prop_list = property.strip().split()
        if len(prop_list) > 1:
            msg = "You cannot have a space in the middle of a property."
            msg += "Did you forget the dash `-`?"
            raise ValueError(msg)

    def validate_value(self, value, property=None):
        """Raises a ValueError if the value is invalid.

        Caveat: this is by no means a comprehensive validation, and
        so there is much room for improvement. For now, we're focusing
        on the basics, such as there can be no text after the semi-
        colon and there should be no units if the value is 0.

        In future versions, we could extend the validation to make
        sure the units match the property, which is why we added a
        default value for property.

        Args:
            value (str): the code after the colon (what specifically
                do you want the property set to)
            property (str): the property which defaults to None.

        Raises:
            ValueError: if the value is invalid.
        """
        if property is None:
            property = ""

        value = value.strip()
        # Make sure there's nothing after the semi-colon
        # but account for the empty string element after the split
        # as well as spaces (just in case)
        val_list = value.split(";")
        if len(val_list) > 1 and val_list[1].strip():
            msg = "There should be no text after the semi-colon."
            raise ValueError(msg)
        if value == ";" or not value:
            msg = "You are missing a value. You must include a "
            msg += "value in between the colon : and the semi-"
            msg += "colon ;"
            raise ValueError(msg)
        # Check for a value of 0 and make sure there are no units
        zero_pattern = r"^\b0\w"
        match = re.search(zero_pattern, value)
        if match:
            msg = "Values of 0 do not need a unit. Example: 0px should "
            msg += "be just 0."
            raise ValueError(msg)

        # TODO: add some validation based on property type

    def get_declaration(self) -> str:
        """Returns the declaration in the form of `property: value`

        Returns:
            declaration (str): a property and its value separated by
            a colon. Example: `"color: rebeccapurple"`"""

        declaration = self.property + ": " + self.value
        return declaration

    def is_color_property(self):
        value = self.value
        if value[-1] == ";":
            value = value[:-1]
        self.is_color = color_tools.is_color_value(value)

__init__(text)

Inits a Declaration object.

Source code in webcode_tk/css_tools.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
def __init__(self, text):
    """Inits a Declaration object."""
    self.__text = text
    self.property = ""
    self.value = ""
    self.invalid_message = ""
    self.is_color = False
    # validate before trying to set the declaration.
    try:
        self.validate_declaration()
        self.is_valid = True
        self.set_declaration()
        self.is_color_property()
    except ValueError as e:
        self.is_valid = False
        self.invalid_message = str(e)

get_declaration()

Returns the declaration in the form of property: value

Returns:

Name Type Description
declaration str

a property and its value separated by

str

a colon. Example: "color: rebeccapurple"

Source code in webcode_tk/css_tools.py
707
708
709
710
711
712
713
714
715
def get_declaration(self) -> str:
    """Returns the declaration in the form of `property: value`

    Returns:
        declaration (str): a property and its value separated by
        a colon. Example: `"color: rebeccapurple"`"""

    declaration = self.property + ": " + self.value
    return declaration

set_declaration()

Sets the property and value based on the text (CSS code).

Note: this only gets run if the declaration was valid, and we already ran the validation. Had the code not been valid, it would have already thrown an exception, and we wouldn't be in this method.

Source code in webcode_tk/css_tools.py
602
603
604
605
606
607
608
609
610
611
def set_declaration(self):
    """Sets the property and value based on the text (CSS code).

    Note: this only gets run if the declaration was valid, and
    we already ran the validation. Had the code not been valid,
    it would have already thrown an exception, and we wouldn't
    be in this method."""
    elements = self.__text.split(":")
    self.property = elements[0].strip()
    self.value = elements[1].strip()

validate_declaration()

Raises a ValueError if any part of the Declaration is invalid.

Source code in webcode_tk/css_tools.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
def validate_declaration(self):
    """Raises a ValueError if any part of the Declaration is
    invalid."""

    # split text at colon (should have 2 items only: the property
    # on the left of the colon and the value on the right of the
    # colon)
    try:
        property, value = self.__text.split(":")
    except ValueError as err:
        if "not enough values" in str(err):
            # There was no colon - there must be one
            msg = "The code is missing a colon. All declarations "
            msg += "must have a colon between the property and "
            msg += "the value."
            raise ValueError(msg)
        elif "too many values" in str(err):
            # There were two or more colons - can only be one
            msg = "You have too many colons. There should only be "
            msg += "one colon between the property and the value."
            raise ValueError(msg)

    self.validate_property(property)
    self.validate_value(value)

validate_property(property)

checks property to make sure it is a valid CSS property.

A CSS property is valid if there are no spaces in between the text. In future versions, we could check against a list of valid properties, but that might take us down a rabbit hole of ever changing properties.

Parameters:

Name Type Description Default
property str

the property of the Declaration which might or might not be valid.

required

Raises:

Type Description
ValueError

if the property is an invalid property

Source code in webcode_tk/css_tools.py
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def validate_property(self, property) -> bool:
    """checks property to make sure it is a valid CSS property.

    A CSS property is valid if there are no spaces in between the
    text. In future versions, we could check against a list of
    valid properties, but that might take us down a rabbit hole
    of ever changing properties.

    Args:
        property (str): the property of the Declaration which might
            or might not be valid.

    Raises:
        ValueError: if the property is an invalid property
    """

    # Make sure there are no spaces in between property
    prop_list = property.strip().split()
    if len(prop_list) > 1:
        msg = "You cannot have a space in the middle of a property."
        msg += "Did you forget the dash `-`?"
        raise ValueError(msg)

validate_value(value, property=None)

Raises a ValueError if the value is invalid.

Caveat: this is by no means a comprehensive validation, and so there is much room for improvement. For now, we're focusing on the basics, such as there can be no text after the semi- colon and there should be no units if the value is 0.

In future versions, we could extend the validation to make sure the units match the property, which is why we added a default value for property.

Parameters:

Name Type Description Default
value str

the code after the colon (what specifically do you want the property set to)

required
property str

the property which defaults to None.

None

Raises:

Type Description
ValueError

if the value is invalid.

Source code in webcode_tk/css_tools.py
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
def validate_value(self, value, property=None):
    """Raises a ValueError if the value is invalid.

    Caveat: this is by no means a comprehensive validation, and
    so there is much room for improvement. For now, we're focusing
    on the basics, such as there can be no text after the semi-
    colon and there should be no units if the value is 0.

    In future versions, we could extend the validation to make
    sure the units match the property, which is why we added a
    default value for property.

    Args:
        value (str): the code after the colon (what specifically
            do you want the property set to)
        property (str): the property which defaults to None.

    Raises:
        ValueError: if the value is invalid.
    """
    if property is None:
        property = ""

    value = value.strip()
    # Make sure there's nothing after the semi-colon
    # but account for the empty string element after the split
    # as well as spaces (just in case)
    val_list = value.split(";")
    if len(val_list) > 1 and val_list[1].strip():
        msg = "There should be no text after the semi-colon."
        raise ValueError(msg)
    if value == ";" or not value:
        msg = "You are missing a value. You must include a "
        msg += "value in between the colon : and the semi-"
        msg += "colon ;"
        raise ValueError(msg)
    # Check for a value of 0 and make sure there are no units
    zero_pattern = r"^\b0\w"
    match = re.search(zero_pattern, value)
    if match:
        msg = "Values of 0 do not need a unit. Example: 0px should "
        msg += "be just 0."
        raise ValueError(msg)

DeclarationBlock

A set of properties and values that go with a selector

In CSS a declaration block is a block of code set off by curly brackets {}. They come after a selector and contain one or more declarations (pairs of properties and values such as width: 200px).

Attributes:

Name Type Description
text str

full text of the declaration block including curly brackets.

declarations

a list of Declaration objects (see the Declaration class below).

Source code in webcode_tk/css_tools.py
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
class DeclarationBlock:
    """A set of properties and values that go with a selector

    In CSS a declaration block is a block of code set off by curly
    brackets `{}`. They come after a selector and contain one or more
    declarations (pairs of properties and values such as
    `width: 200px`).

    Attributes:
        text (str): full text of the declaration block including
            curly brackets.
        declarations: a list of Declaration objects (see the
            Declaration class below)."""

    def __init__(self, text):
        """Inits a declaration block"""
        self.text = text
        self.declarations = []
        self.__set_declarations()

    def __set_declarations(self):
        """converts text into a list of declarations."""
        declarations = self.text

        # remove selectors and braces if present
        if "{" in self.text:
            declarations = declarations.split("{")
            declarations = declarations[1]
        if "}" in declarations:
            declarations = declarations.split("}")
            declarations = declarations[0]

        declarations = declarations.split(";")

        # remove all spaces and line returns
        # capture positions of content we want to keep
        keep = []
        for i in range(len(declarations)):
            declarations[i] = declarations[i].replace("\n", "")
            declarations[i] = declarations[i].strip()
            if declarations[i]:
                keep.append(i)

        # get only declarations with content
        to_keep = []
        for pos in keep:
            to_keep.append(declarations[pos])
        declarations = to_keep

        # set all Declaration objects
        for i in range(len(declarations)):
            declarations[i] = Declaration(declarations[i])
        self.declarations = declarations

__init__(text)

Inits a declaration block

Source code in webcode_tk/css_tools.py
527
528
529
530
531
def __init__(self, text):
    """Inits a declaration block"""
    self.text = text
    self.declarations = []
    self.__set_declarations()

__set_declarations()

converts text into a list of declarations.

Source code in webcode_tk/css_tools.py
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
def __set_declarations(self):
    """converts text into a list of declarations."""
    declarations = self.text

    # remove selectors and braces if present
    if "{" in self.text:
        declarations = declarations.split("{")
        declarations = declarations[1]
    if "}" in declarations:
        declarations = declarations.split("}")
        declarations = declarations[0]

    declarations = declarations.split(";")

    # remove all spaces and line returns
    # capture positions of content we want to keep
    keep = []
    for i in range(len(declarations)):
        declarations[i] = declarations[i].replace("\n", "")
        declarations[i] = declarations[i].strip()
        if declarations[i]:
            keep.append(i)

    # get only declarations with content
    to_keep = []
    for pos in keep:
        to_keep.append(declarations[pos])
    declarations = to_keep

    # set all Declaration objects
    for i in range(len(declarations)):
        declarations[i] = Declaration(declarations[i])
    self.declarations = declarations

NestedAtRule

An at-rule rule that is nested, such as @media or @keyframes.

Nested at-rules include animation keyframes, styles for print (@media print), and breakpoints (@media screen). Each nested at-rule has an at-rule, which works like a selector, and a ruleset for that at-rule. The ruleset may contain any number of selectors and their declaration blocks.

You can almost think of them as stylesheets within a stylesheet "A dweam within a dweam" -The Impressive Clergyman. "We have to go deeper" -Dom Cobb.

Nested at-rules are defined in the global variable: nested_at_rules. For more information on nested at-rules, you want to refer to MDN's [nested] (https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule#nested)

Parameters:

Name Type Description Default
at_rule str

the full at-rule such as '@media only and (min-width: 520px)'.

required
text str

the text of the code (without the at_rule). Provide the text if you do not provide a list of rulesets.

''
rules list

a list of Ruleset objects. This is optional and defaults to None. Just be sure to add text if you don't provide a list.

None

Attributes: at_rule (str): the full at-rule such as '@media only and (min-width: 520px)'. rulesets (list): a list of Ruleset objects. selectors (list): a list of all selectors from the rulesets has_repeat_selectors (bool): whether there are any repeated selectors in the NestedAtRule. repeated_selectors (list): a list of any selectors that are repeated.

Source code in webcode_tk/css_tools.py
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
class NestedAtRule:
    """An at-rule rule that is nested, such as @media or @keyframes.

    Nested at-rules include animation keyframes, styles for print
    (@media print), and breakpoints (@media screen). Each nested
    at-rule has an at-rule, which works like a selector, and a
    ruleset for that at-rule. The ruleset may contain any number
    of selectors and their declaration blocks.

    You can almost think of them as stylesheets within a stylesheet
    *"A dweam within a dweam"* -The Impressive Clergyman.
    *"We have to go deeper"* -Dom Cobb.

    Nested at-rules are defined in the global variable: nested_at_rules.
    For more information on nested at-rules, you want to refer to MDN's
    [nested]
    (https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule#nested)

    Args:
        at_rule (str): the full at-rule such as '@media only and
            (min-width: 520px)'.
        text (str): the text of the code (without the at_rule).
            Provide the text if you do not provide a list of rulesets.
        rules (list): a list of Ruleset objects. This is optional and
            defaults to None. Just be sure to add text if you don't
            provide a list.
    Attributes:
        at_rule (str): the full at-rule such as '@media only and
            (min-width: 520px)'.
        rulesets (list): a list of Ruleset objects.
        selectors (list): a list of all selectors from the rulesets
        has_repeat_selectors (bool): whether there are any repeated
            selectors in the NestedAtRule.
        repeated_selectors (list): a list of any selectors that are
            repeated.
    """

    def __init__(self, at_rule, text="", rules=None):
        """Inits a Nested @rule object.

        Raises:
            ValueError: an error is raised if neither at_rule nor text is
                provided for the constructor or both are provided but they
                do not match.
        """
        self.at_rule = at_rule.strip()
        if rules is None:
            self.rulesets = []
        else:
            self.rulesets = rules[:]
        self.selectors = []
        self.has_repeat_selectors = False
        self.repeated_selectors = []

        # If rulesets were NOT passed in, we need to get them from the text
        if not rules:
            self.set_rulesets(text)
        else:
            # if both rules and text were passed in make sure they
            # match and raise a ValueError if not
            if rules and text:
                code_split = text.split("}")
                if len(code_split) != len(rules):
                    msg = "You passed both a ruleset and text, but "
                    msg += "The text does not match the rules"
                    raise ValueError(msg)
            # let's get our selectors
            for rule in self.rulesets:
                selector = rule.selector
                self.selectors.append(selector)
        self.check_repeat_selectors()

    def check_repeat_selectors(self):
        """Checks to see if there are any repeated selectors"""
        for selector in self.selectors:
            count = self.selectors.count(selector)
            if count > 1:
                self.has_repeat_selectors = True
                self.repeated_selectors.append(selector)

    def set_rulesets(self, text):
        """Converts string of text into a list of ruleset objects"""
        # first, make sure text was not an empty string
        if text.strip():
            self.__text = minify_code(text)
        else:
            msg = "A NestedAtRule must be provided either rulesets"
            msg += " or text, but you provided no useable code."
            raise ValueError(msg)
        if self.__text.count("}") == 1:
            ruleset = Ruleset(self.__text)
            self.selectors.append(ruleset.selector)
            self.rulesets.append(ruleset)
        else:
            code_split = self.__text.split("}")
            rulesets = []
            for part in code_split:
                if part.strip():
                    ruleset = Ruleset(part + "}")
                    if ruleset:
                        selector = ruleset.selector
                        self.selectors.append(selector)
                    rulesets.append(ruleset)
            if rulesets:
                self.rulesets = rulesets

__init__(at_rule, text='', rules=None)

Inits a Nested @rule object.

Raises:

Type Description
ValueError

an error is raised if neither at_rule nor text is provided for the constructor or both are provided but they do not match.

Source code in webcode_tk/css_tools.py
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
def __init__(self, at_rule, text="", rules=None):
    """Inits a Nested @rule object.

    Raises:
        ValueError: an error is raised if neither at_rule nor text is
            provided for the constructor or both are provided but they
            do not match.
    """
    self.at_rule = at_rule.strip()
    if rules is None:
        self.rulesets = []
    else:
        self.rulesets = rules[:]
    self.selectors = []
    self.has_repeat_selectors = False
    self.repeated_selectors = []

    # If rulesets were NOT passed in, we need to get them from the text
    if not rules:
        self.set_rulesets(text)
    else:
        # if both rules and text were passed in make sure they
        # match and raise a ValueError if not
        if rules and text:
            code_split = text.split("}")
            if len(code_split) != len(rules):
                msg = "You passed both a ruleset and text, but "
                msg += "The text does not match the rules"
                raise ValueError(msg)
        # let's get our selectors
        for rule in self.rulesets:
            selector = rule.selector
            self.selectors.append(selector)
    self.check_repeat_selectors()

check_repeat_selectors()

Checks to see if there are any repeated selectors

Source code in webcode_tk/css_tools.py
428
429
430
431
432
433
434
def check_repeat_selectors(self):
    """Checks to see if there are any repeated selectors"""
    for selector in self.selectors:
        count = self.selectors.count(selector)
        if count > 1:
            self.has_repeat_selectors = True
            self.repeated_selectors.append(selector)

set_rulesets(text)

Converts string of text into a list of ruleset objects

Source code in webcode_tk/css_tools.py
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
def set_rulesets(self, text):
    """Converts string of text into a list of ruleset objects"""
    # first, make sure text was not an empty string
    if text.strip():
        self.__text = minify_code(text)
    else:
        msg = "A NestedAtRule must be provided either rulesets"
        msg += " or text, but you provided no useable code."
        raise ValueError(msg)
    if self.__text.count("}") == 1:
        ruleset = Ruleset(self.__text)
        self.selectors.append(ruleset.selector)
        self.rulesets.append(ruleset)
    else:
        code_split = self.__text.split("}")
        rulesets = []
        for part in code_split:
            if part.strip():
                ruleset = Ruleset(part + "}")
                if ruleset:
                    selector = ruleset.selector
                    self.selectors.append(selector)
                rulesets.append(ruleset)
        if rulesets:
            self.rulesets = rulesets

Ruleset

Creates a ruleset: a selector with a declaration block.

For more information about Rulesets, please read MDN's article on [Rulesets] (https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_rulesets)

Parameters:

Name Type Description Default
text str

the CSS code in text form.

required

Attributes:

Name Type Description
__text str

the CSS code.

selector str

the selector of the Ruleset

declaration_block DeclarationBlock

a DeclarationBlock object.

is_valid bool

whether the Ruleset is valid or not.

Source code in webcode_tk/css_tools.py
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
class Ruleset:
    """Creates a ruleset: a selector with a declaration block.

    For more information about Rulesets, please read MDN's article on
    [Rulesets]
    (https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_rulesets)

    Args:
        text (str): the CSS code in text form.

    Attributes:
        __text (str): the CSS code.
        selector (str): the selector of the Ruleset
        declaration_block (DeclarationBlock): a DeclarationBlock
            object.
        is_valid (bool): whether the Ruleset is valid or not.
    """

    def __init__(self, text):
        """Inits a DeclarationBlock object using CSS code"""
        self.__text = text
        self.selector = ""
        self.declaration_block = None
        self.is_valid = True
        self.validate()
        self.initialize()

    def initialize(self):
        """converts the text into a DeclarationBlock."""
        if self.is_valid:
            contents = self.__text.split("{")
            self.selector = contents[0].replace("\n", "").strip()
            block = contents[1].replace("\n", "")
            self.declaration_block = DeclarationBlock(block)

    def validate(self):
        """Determines whether the code is valid or not"""
        try:
            open_brace_pos = self.__text.index("{")
            close_brace_pos = self.__text.index("}")
            if open_brace_pos > close_brace_pos:
                # { needs to come before }
                self.is_valid = False
        except Exception:
            self.is_valid = False

        if "{" not in self.__text or "}" not in self.__text:
            self.is_valid = False

__init__(text)

Inits a DeclarationBlock object using CSS code

Source code in webcode_tk/css_tools.py
481
482
483
484
485
486
487
488
def __init__(self, text):
    """Inits a DeclarationBlock object using CSS code"""
    self.__text = text
    self.selector = ""
    self.declaration_block = None
    self.is_valid = True
    self.validate()
    self.initialize()

initialize()

converts the text into a DeclarationBlock.

Source code in webcode_tk/css_tools.py
490
491
492
493
494
495
496
def initialize(self):
    """converts the text into a DeclarationBlock."""
    if self.is_valid:
        contents = self.__text.split("{")
        self.selector = contents[0].replace("\n", "").strip()
        block = contents[1].replace("\n", "")
        self.declaration_block = DeclarationBlock(block)

validate()

Determines whether the code is valid or not

Source code in webcode_tk/css_tools.py
498
499
500
501
502
503
504
505
506
507
508
509
510
def validate(self):
    """Determines whether the code is valid or not"""
    try:
        open_brace_pos = self.__text.index("{")
        close_brace_pos = self.__text.index("}")
        if open_brace_pos > close_brace_pos:
            # { needs to come before }
            self.is_valid = False
    except Exception:
        self.is_valid = False

    if "{" not in self.__text or "}" not in self.__text:
        self.is_valid = False

Stylesheet

A Stylesheet object with details about the sheet and its components.

The stylesheet object has the full code, a list of comments from the stylesheet, a list of nested @rules, rulesets pertaining to colors, a list of all selectors, and information about repeated selectors.

About repeated selectors, front-end developers should always employ the DRY principle: Don't Repeat Yourself. In other words, if you use a selector once in your stylesheet, the only other place you would logically put the same selector would be in a nested at-rule (in particular, an @media or @print breakpoint)

For this reason, both the Stylesheet object and the NesteAtRule objects have attributes that show whether there are repeated selectors or not as well as which selectors get repeated.

Attributes:

Name Type Description
href

the filename (not path), which may end with .css or .html (if stylesheet object comes from a style tag).

text

the actual code itself of the entire file or style tag.

type

whether it's a file or local if it's from an style tag.

nested_at_rules

a list of all nested at-rules.

rulesets

a list of all rulesets.

comments

a list of all comments in string format.

color_rulesets

a list of all rulesets that target color or background colors.

selectors

a list of all selectors.

has_repeat_selectors bool

whether there are any repeated selectors anywhere in the stylesheet (including in the NestedAtRule.

repeated_selectors list

a list of any selectors that are repeated. They might be repeated in the main stylesheet or they might be repeated in one of the nested @rules.

Source code in webcode_tk/css_tools.py
 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
class Stylesheet:
    """A Stylesheet object with details about the sheet and its
    components.

    The stylesheet object has the full code, a list of comments from the
    stylesheet, a list of nested @rules, rulesets pertaining to colors,
    a list of all selectors, and information about repeated selectors.

    About repeated selectors, front-end developers should always employ
    the DRY principle: Don't Repeat Yourself. In other words, if you
    use a selector once in your stylesheet, the only other place you
    would logically put the same selector would be in a nested at-rule
    (in particular, an @media or @print breakpoint)

    For this reason, both the Stylesheet object and the NesteAtRule
    objects have attributes that show whether there are repeated
    selectors or not as well as which selectors get repeated.

    Attributes:
        href: the filename (not path), which may end with .css or .html
            (if stylesheet object comes from a style tag).
        text: the actual code itself of the entire file or style tag.
        type: whether it's a file or local if it's from an style tag.
        nested_at_rules: a list of all nested at-rules.
        rulesets: a list of all rulesets.
        comments: a list of all comments in string format.
        color_rulesets: a list of all rulesets that target color or
            background colors.
        selectors: a list of all selectors.
        has_repeat_selectors (bool): whether there are any repeated
            selectors anywhere in the stylesheet (including in the
            NestedAtRule.
        repeated_selectors (list): a list of any selectors that are
            repeated. They might be repeated in the main stylesheet
            or they might be repeated in one of the nested @rules.
    """

    def __init__(
        self, href: str, text: str, stylesheet_type: str = "file"
    ) -> None:
        """Inits Stylesheet with href, text (CSS code), and type."""
        self.type = stylesheet_type
        self.href = href
        self.text = text
        self.__clean_text()
        self.nested_at_rules = []
        self.rulesets = []
        self.comments = []
        self.color_rulesets = []
        self.selectors = []
        self.has_repeat_selectors = False
        self.repeated_selectors = []
        self.__minify()
        self.__replace_variables()
        self.__remove_external_imports()
        self.__extract_comments()
        self.__extract_nested_at_rules()
        self.__extract_rulesets()
        self.__set_selectors()

    def __clean_text(self):
        """cleans up CSS like removing extra line returns

        This is here because if a student has more than 2 blank lines, it
        could trigger an attribute error (at least it did in the past)
        """
        text_to_clean = self.text
        split_text = text_to_clean.split("\n")
        cleaned_text = ""
        consecutive_blanks = 0
        for line in split_text:
            if not line:
                consecutive_blanks += 1
            if consecutive_blanks > 1:
                consecutive_blanks = 1
                continue
            else:
                if not line and cleaned_text:
                    cleaned_text += "\n"
                cleaned_text += line + "\n"
        if cleaned_text[-1:] == "\n":
            cleaned_text = cleaned_text[:-1].strip()
        self.text = cleaned_text

    def __minify(self):
        """Removes all whitespace, line returns, and tabs from text."""
        self.text = minify_code(self.text)

    def __replace_variables(self):
        """Looks for and replaces any variables set in stylesheet with
        the variable's values."""
        # get a list of all variables and their values
        variable_list = get_variables(self.text)

        # Loop through the variable list and do a find
        # and replace on all occurrances of the variable
        new_text = self.text
        for variable in variable_list:
            var = variable.get("variable")
            value = variable.get("value")
            var = r"var\(" + var + r"\)"
            new_text = re.sub(var, value, new_text)
        self.text = new_text

    def __extract_comments(self):
        """Gets all comments from the code and stores in a list."""
        # split all CSS text at opening comment
        text_comment_split = self.text.split("/*")
        comments = []
        code_without_comments = ""

        # loop through the list of code
        # in each iteration extract the comment
        for i in text_comment_split:
            if "*/" in i:
                comment = i.split("*/")
                comments.append("/*" + comment[0] + "*/")
                code_without_comments += comment[1]
            else:
                # no comments, just get code
                code_without_comments += i
        self.comments = comments
        self.text = code_without_comments

    def __extract_nested_at_rules(self):
        """Pulls out any nested at-rule and stores them in a list.

        Algorithm: get # of @ signs"""
        at_rules = []
        non_at_rules_css = []

        css_code = self.text

        # no @ sign, no at_rules - we're done
        num_at_rules = css_code.count("@")
        if num_at_rules == 0:
            return

        # add a marker symbols !! to indicate @ sign after split
        css_code = css_code.replace("@", "@!!")

        # everything between @ sign and }} is a nested at rule
        css_split_at_at = css_code.split("@")

        # Loop through code, each string beginning with ! is an at-rule
        for code in css_split_at_at:
            if code[:2] == "!!":
                code = code.replace("!!", "@")

                # get a slice up to }} (end of @rule)
                code_split = code.split("}}")

                # first element is the @rule
                at_rule = code_split[0] + "}}"

                # create a nested at-rule object
                pos = at_rule.find("{")
                rule = at_rule[:pos]
                ruleset_string = at_rule[pos + 1 : -1]
                nested = NestedAtRule(rule, ruleset_string)
                if nested.has_repeat_selectors:
                    self.has_repeat_selectors = True
                at_rules.append(nested)

                # second element is any other CSS code
                non_at_rule = code_split[1]
                if non_at_rule:
                    non_at_rules_css.append(non_at_rule)
            else:
                non_at_rules_css.append(code)

        self.text = "".join(non_at_rules_css)
        self.nested_at_rules = at_rules

    def __extract_rulesets(self):
        """Separates all code into individual rulesets."""
        # split rulesets by closing of rulesets: }
        ruleset_list = self.text.split("}")
        for ruleset in ruleset_list:
            if ruleset:
                ruleset = Ruleset(ruleset + "}")
                self.rulesets.append(ruleset)
                self.get_color_ruleset(ruleset)

    def __remove_external_imports(self):
        text = self.text
        # look for external link by protocol (http or https)
        external_import_re = r"@import url\(['\"]https://|"
        external_import_re += r"@import url\(['\"]http://"

        # remove external imports if there's a protocol
        # text = text.lower()
        match = re.search(external_import_re, text)
        if match:
            # but only if it's in an @import url function
            split_text = re.split(external_import_re, text)

            # we now have 1 or more code segments without the
            # beginnings of an @import url( segment
            for i in range(1, len(split_text)):
                segment = split_text[i]
                # get everything after the first );
                paren_pos = segment.index(")") + 1
                segment = segment[paren_pos:]
                if ";" in segment[:2]:
                    pos = segment[:2].index(";")
                    segment = segment[pos + 1 :]
                split_text[i] = segment
            # put text back in string form
            text = "".join(split_text)
        self.text = text

    def get_color_ruleset(self, ruleset: "Ruleset") -> list:
        """Returns a list of all rules targetting color or background color.

        Args:
            ruleset(Ruleset): a Ruleset object complete with selector
                and declaration block.

        Returns:
            color_rulesets: a list of all selectors that target color
                in some way, but just with the color-based declarations.
        """
        color_rulesets = []
        if ruleset.declaration_block and (
            "color:" in ruleset.declaration_block.text
            or "background" in ruleset.declaration_block.text
        ):
            selector = ruleset.selector
            for declaration in ruleset.declaration_block.declarations:
                color_counts = (
                    "color" in declaration.property
                    or "background" in declaration.property
                    and declaration.property
                    not in [
                        "border-color",
                        "outline-color",
                        "text-declaration-color",
                        "text-emphasis-color",
                        "text-shadow",
                        "caret-color",
                        "column-rule-color",
                        "print-color-adjust",
                    ]
                )
                if color_counts:
                    property = declaration.property
                    value = declaration.value

                    # Check for a gradient bg color
                    is_bg_gradient = color_tools.is_gradient(value)
                    if is_bg_gradient:
                        print()
                    # skip if has vendor prefix
                    if has_vendor_prefix(value):
                        continue
                    # skip if not valid color value
                    is_valid_color = color_tools.is_color_value(value)
                    if not is_valid_color and not is_bg_gradient:
                        continue
                    # make sure the value is a color (not other)
                    rule = {selector: {property: value}}
                    color_rulesets.append(rule)
        if color_rulesets:
            self.color_rulesets += color_rulesets

    def __set_selectors(self):
        """Adds all selectors from stylesheet to selectors attribute."""
        for rule in self.rulesets:
            if rule.selector in self.selectors:
                self.has_repeat_selectors = True
                self.repeated_selectors.append(rule.selector)
            self.selectors.append(rule.selector)

    def sort_selectors(self):
        """Puts all selectors in alphabetical order."""
        self.selectors.sort()

__clean_text()

cleans up CSS like removing extra line returns

This is here because if a student has more than 2 blank lines, it could trigger an attribute error (at least it did in the past)

Source code in webcode_tk/css_tools.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def __clean_text(self):
    """cleans up CSS like removing extra line returns

    This is here because if a student has more than 2 blank lines, it
    could trigger an attribute error (at least it did in the past)
    """
    text_to_clean = self.text
    split_text = text_to_clean.split("\n")
    cleaned_text = ""
    consecutive_blanks = 0
    for line in split_text:
        if not line:
            consecutive_blanks += 1
        if consecutive_blanks > 1:
            consecutive_blanks = 1
            continue
        else:
            if not line and cleaned_text:
                cleaned_text += "\n"
            cleaned_text += line + "\n"
    if cleaned_text[-1:] == "\n":
        cleaned_text = cleaned_text[:-1].strip()
    self.text = cleaned_text

__extract_comments()

Gets all comments from the code and stores in a list.

Source code in webcode_tk/css_tools.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def __extract_comments(self):
    """Gets all comments from the code and stores in a list."""
    # split all CSS text at opening comment
    text_comment_split = self.text.split("/*")
    comments = []
    code_without_comments = ""

    # loop through the list of code
    # in each iteration extract the comment
    for i in text_comment_split:
        if "*/" in i:
            comment = i.split("*/")
            comments.append("/*" + comment[0] + "*/")
            code_without_comments += comment[1]
        else:
            # no comments, just get code
            code_without_comments += i
    self.comments = comments
    self.text = code_without_comments

__extract_nested_at_rules()

Pulls out any nested at-rule and stores them in a list.

Algorithm: get # of @ signs

Source code in webcode_tk/css_tools.py
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
def __extract_nested_at_rules(self):
    """Pulls out any nested at-rule and stores them in a list.

    Algorithm: get # of @ signs"""
    at_rules = []
    non_at_rules_css = []

    css_code = self.text

    # no @ sign, no at_rules - we're done
    num_at_rules = css_code.count("@")
    if num_at_rules == 0:
        return

    # add a marker symbols !! to indicate @ sign after split
    css_code = css_code.replace("@", "@!!")

    # everything between @ sign and }} is a nested at rule
    css_split_at_at = css_code.split("@")

    # Loop through code, each string beginning with ! is an at-rule
    for code in css_split_at_at:
        if code[:2] == "!!":
            code = code.replace("!!", "@")

            # get a slice up to }} (end of @rule)
            code_split = code.split("}}")

            # first element is the @rule
            at_rule = code_split[0] + "}}"

            # create a nested at-rule object
            pos = at_rule.find("{")
            rule = at_rule[:pos]
            ruleset_string = at_rule[pos + 1 : -1]
            nested = NestedAtRule(rule, ruleset_string)
            if nested.has_repeat_selectors:
                self.has_repeat_selectors = True
            at_rules.append(nested)

            # second element is any other CSS code
            non_at_rule = code_split[1]
            if non_at_rule:
                non_at_rules_css.append(non_at_rule)
        else:
            non_at_rules_css.append(code)

    self.text = "".join(non_at_rules_css)
    self.nested_at_rules = at_rules

__extract_rulesets()

Separates all code into individual rulesets.

Source code in webcode_tk/css_tools.py
251
252
253
254
255
256
257
258
259
def __extract_rulesets(self):
    """Separates all code into individual rulesets."""
    # split rulesets by closing of rulesets: }
    ruleset_list = self.text.split("}")
    for ruleset in ruleset_list:
        if ruleset:
            ruleset = Ruleset(ruleset + "}")
            self.rulesets.append(ruleset)
            self.get_color_ruleset(ruleset)

__init__(href, text, stylesheet_type='file')

Inits Stylesheet with href, text (CSS code), and type.

Source code in webcode_tk/css_tools.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def __init__(
    self, href: str, text: str, stylesheet_type: str = "file"
) -> None:
    """Inits Stylesheet with href, text (CSS code), and type."""
    self.type = stylesheet_type
    self.href = href
    self.text = text
    self.__clean_text()
    self.nested_at_rules = []
    self.rulesets = []
    self.comments = []
    self.color_rulesets = []
    self.selectors = []
    self.has_repeat_selectors = False
    self.repeated_selectors = []
    self.__minify()
    self.__replace_variables()
    self.__remove_external_imports()
    self.__extract_comments()
    self.__extract_nested_at_rules()
    self.__extract_rulesets()
    self.__set_selectors()

__minify()

Removes all whitespace, line returns, and tabs from text.

Source code in webcode_tk/css_tools.py
161
162
163
def __minify(self):
    """Removes all whitespace, line returns, and tabs from text."""
    self.text = minify_code(self.text)

__replace_variables()

Looks for and replaces any variables set in stylesheet with the variable's values.

Source code in webcode_tk/css_tools.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def __replace_variables(self):
    """Looks for and replaces any variables set in stylesheet with
    the variable's values."""
    # get a list of all variables and their values
    variable_list = get_variables(self.text)

    # Loop through the variable list and do a find
    # and replace on all occurrances of the variable
    new_text = self.text
    for variable in variable_list:
        var = variable.get("variable")
        value = variable.get("value")
        var = r"var\(" + var + r"\)"
        new_text = re.sub(var, value, new_text)
    self.text = new_text

__set_selectors()

Adds all selectors from stylesheet to selectors attribute.

Source code in webcode_tk/css_tools.py
343
344
345
346
347
348
349
def __set_selectors(self):
    """Adds all selectors from stylesheet to selectors attribute."""
    for rule in self.rulesets:
        if rule.selector in self.selectors:
            self.has_repeat_selectors = True
            self.repeated_selectors.append(rule.selector)
        self.selectors.append(rule.selector)

get_color_ruleset(ruleset)

Returns a list of all rules targetting color or background color.

Parameters:

Name Type Description Default
ruleset(Ruleset)

a Ruleset object complete with selector and declaration block.

required

Returns:

Name Type Description
color_rulesets list

a list of all selectors that target color in some way, but just with the color-based declarations.

Source code in webcode_tk/css_tools.py
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
def get_color_ruleset(self, ruleset: "Ruleset") -> list:
    """Returns a list of all rules targetting color or background color.

    Args:
        ruleset(Ruleset): a Ruleset object complete with selector
            and declaration block.

    Returns:
        color_rulesets: a list of all selectors that target color
            in some way, but just with the color-based declarations.
    """
    color_rulesets = []
    if ruleset.declaration_block and (
        "color:" in ruleset.declaration_block.text
        or "background" in ruleset.declaration_block.text
    ):
        selector = ruleset.selector
        for declaration in ruleset.declaration_block.declarations:
            color_counts = (
                "color" in declaration.property
                or "background" in declaration.property
                and declaration.property
                not in [
                    "border-color",
                    "outline-color",
                    "text-declaration-color",
                    "text-emphasis-color",
                    "text-shadow",
                    "caret-color",
                    "column-rule-color",
                    "print-color-adjust",
                ]
            )
            if color_counts:
                property = declaration.property
                value = declaration.value

                # Check for a gradient bg color
                is_bg_gradient = color_tools.is_gradient(value)
                if is_bg_gradient:
                    print()
                # skip if has vendor prefix
                if has_vendor_prefix(value):
                    continue
                # skip if not valid color value
                is_valid_color = color_tools.is_color_value(value)
                if not is_valid_color and not is_bg_gradient:
                    continue
                # make sure the value is a color (not other)
                rule = {selector: {property: value}}
                color_rulesets.append(rule)
    if color_rulesets:
        self.color_rulesets += color_rulesets

sort_selectors()

Puts all selectors in alphabetical order.

Source code in webcode_tk/css_tools.py
351
352
353
def sort_selectors(self):
    """Puts all selectors in alphabetical order."""
    self.selectors.sort()

adjust_overrides(file_path, rules)

Returns a dictionary with a single global ruleset.

Gets the final computed value of all rulesets in a file. It loops through the rulesets, and whenever there is an override (due to a repeat selector), it replaces whichever value is in the repeated selector.

Parameters:

Name Type Description Default
file_path str

path to the file in question, to be used as a key in the adjusted rule

required
rules dict

a dictionary where the key is the filename and the value is a list of rules.

required

Returns:

Name Type Description
adjusted_rule dict

a dictionary where the key is the same, but there is only one ruleset (the computed ruleset).

Source code in webcode_tk/css_tools.py
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
def adjust_overrides(file_path: str, rules: dict) -> dict:
    """Returns a dictionary with a single global ruleset.

    Gets the final computed value of all rulesets in a file. It loops
    through the rulesets, and whenever there is an override (due to a
    repeat selector), it replaces whichever value is in the repeated
    selector.

    Args:
        file_path: path to the file in question, to be used as a
            key in the adjusted rule
        rules: a dictionary where the key is the filename and the value
            is a list of rules.

    Returns:
        adjusted_rule: a dictionary where the key is the same, but
            there is only one ruleset (the computed ruleset).
    """
    adjusted_rule = {}
    old_rules = list(rules.get(file_path))
    pre_selector, pre_bg_color, pre_color = ("", "", "")
    for rule in old_rules:
        selector = rule.get("selector")
        bg_color = rule.get("background-color")
        color = rule.get("color")
        if pre_selector:
            # we have looped at least once.
            # check to see if we have the same selector or not
            if selector == pre_selector:
                # same selector, it's time to check our stats
                # for an override
                if bg_color and bg_color != pre_bg_color:
                    adjusted_rule[file_path]["background-color"] = bg_color
                if color and color != pre_color:
                    adjusted_rule[file_path]["color"] = color
        else:
            # this is the first time we are looping
            adjusted_rule[file_path] = rule
            pre_selector = selector
            pre_bg_color = bg_color
            pre_color = color
    return adjusted_rule

border_checks_out(declaration)

returns whether the border would display or not.

In order for the border shorthand to display, the border style must be a valid border style.

Parameters:

Name Type Description Default
declaration Declaration

the declaration with a border shorthand property.

required

Returns:

Name Type Description
checks_out bool

whether the border would be visible or not

Source code in webcode_tk/css_tools.py
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
def border_checks_out(declaration: Declaration) -> bool:
    """returns whether the border would display or not.

    In order for the border shorthand to display, the border style must be
    a valid border style.

    Args:
        declaration: the declaration with a border shorthand property.

    Returns:
        checks_out: whether the border would be visible or not"""
    checks_out = False
    values = declaration.value.split()
    for val in values:
        if val in visible_border_styles:
            checks_out = True
    return checks_out

check_for_inherited_colors(rules, condensed, source_file)

Double-check and fix any necessary overrides.

This is a tough one. The goal is to look for advanced selectors (descendant, class, id, pseudo, attribute), and if they did NOT specify color or bg color, then replace it with the nearest ancestor

Parameters:

Name Type Description Default
rules list

a list of all color rules.

required
condensed dict

the already condensed set of color rules

required
source_file str

the file we are looking at.

required
Source code in webcode_tk/css_tools.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
def check_for_inherited_colors(
    rules: list, condensed: dict, source_file: str
) -> None:
    """Double-check and fix any necessary overrides.

    This is a tough one. The goal is to look for advanced selectors
    (descendant, class, id, pseudo, attribute), and if they did NOT
    specify color or bg color, then replace it with the nearest
    ancestor

    Args:
        rules: a list of all color rules.
        condensed: the already condensed set of color rules
        source_file: the file we are looking at."""
    for rule in rules:
        file, sel, prop, val = rule
        if file != source_file:
            continue
        if "." in sel or ":" in sel or "#" in sel or "[" in sel:
            # if either color or bg color is missing, look behind
            if not condensed[sel].get("color") or not condensed[sel].get(
                "background-color"
            ):
                for char in ".:#[":
                    if char in sel:
                        split_selector = sel.split(char)
                        behind = split_selector[0]
                        if condensed.get(behind):
                            for data in rules:
                                filename = data[0]
                                if filename != source_file:
                                    continue
                                rule_selector = data[1]
                                if behind == rule_selector:
                                    # we found an ancestor
                                    ancestor_data = condensed.get(behind)
                                    current_condensed = condensed.get(sel)
                                    if not current_condensed.get("color"):
                                        color = ancestor_data.get("color")
                                        current_condensed["color"] = color
                                    if not current_condensed.get(
                                        "background-color"
                                    ):
                                        bg = ancestor_data.get(
                                            "background-color"
                                        )
                                        cur_bg = current_condensed
                                        cur_bg["background-color"] = bg
                                    break

condense_the_rules(rules, source_file)

takes a list of color rules and returns only the unique color rulesets

Brings together both background and foreground color for each selector (when present)

Parameters:

Name Type Description Default
rules list

list of tuples that contain filename, selector, property, and value

required
source_file str

the HTML document the contains the rules

required

Returns: condensed: a dictionary with file and all selectors that target colors with what was set for background-color and color

Source code in webcode_tk/css_tools.py
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
def condense_the_rules(rules: list, source_file: str) -> dict:
    """takes a list of color rules and returns only the unique color rulesets

    Brings together both background and foreground color for each selector
    (when present)

    Args:
        rules: list of tuples that contain filename, selector, property,
            and value
        source_file: the HTML document the contains the rules
    Returns:
        condensed: a dictionary with file and all selectors that target
            colors with what was set for background-color and color
    """
    condensed = {"file": source_file}
    for rule in rules:
        file, sel, prop, val = rule
        if file != source_file:
            continue
        if not condensed.get("file"):
            condensed["file"] = file
        if not condensed.get(sel):
            # we don't yet have the selector in place
            condensed[sel] = {}
        # set the color or background color here
        if prop == "color":
            condensed[sel]["color"] = val
        if prop == "background-color":
            condensed[sel]["background-color"] = val
    check_for_inherited_colors(rules, condensed, source_file)
    return condensed

file_applies_property_by_selector(file_path, selector, property)

determines whether a specific property is applied to selector or not.

Parameters:

Name Type Description Default
file_path str

path to html doc in question.

required
selector str

CSS selector (or element) that the property is applied.

required
property str

the CSS property we are looking for.

required

Returns:

Name Type Description
applies_property bool

whether that selector applies the property or not.

Source code in webcode_tk/css_tools.py
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
def file_applies_property_by_selector(
    file_path: str, selector: str, property: str
) -> bool:
    """determines whether a specific property is applied to selector or not.

    Args:
        file_path: path to html doc in question.
        selector: CSS selector (or element) that the property is applied.
        property: the CSS property we are looking for.

    Returns:
        applies_property: whether that selector applies the property or not.
    """
    applies_property = False
    style_sheets = get_all_stylesheets_by_file(file_path)

    # look for the selector get all declaration block
    declarations = []
    for sheet in style_sheets:
        declaration_block = get_declaration_block_from_selector(
            selector, sheet
        )
        if declaration_block:
            declarations.append(declaration_block)
    combined_declaration_block = "\n".join(declarations)
    if combined_declaration_block:
        # check for property in declaration_block
        declarations = combined_declaration_block.split(";")
        for declaration in declarations:
            try:
                prop, value = declaration.split(":")
                if property in prop:
                    applies_property = True
                    break
            except ValueError:
                print("Declaration is missing a colon!")
    return applies_property

fonts_applied_report(project_dir, min=1, max=2)

returns a report of all files in a project folder that apply font families.

You can set the minimum and maximum number of fonts applied per page.

Parameters:

Name Type Description Default
project_dir str

the relative path to the project folder we want to check.

required
min

the minimum number of fonts applied per file.

1
max

the maximum number of fonts applied per file.

2

Returns: report: a list of font data results.

Source code in webcode_tk/css_tools.py
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
def fonts_applied_report(project_dir: str, min=1, max=2) -> list:
    """returns a report of all files in a project folder that apply font
    families.

    You can set the minimum and maximum number of fonts applied per page.

    Args:
        project_dir: the relative path to the project folder we want to check.
        min: the minimum number of fonts applied per file.
        max: the maximum number of fonts applied per file.
    Returns:
        report: a list of font data results.
    """
    report = []
    all_file_data = get_styles_by_html_files(project_dir)
    for file in all_file_data:
        font_families_applied = []
        number_of_fonts = 0
        filename = clerk.get_file_name(file.get("file"))
        stylesheets = file.get("stylesheets")
        for sheet in stylesheets:
            font_details = get_font_families(sheet)
            number_of_fonts += len(font_details)
            for item in font_details:
                results = None
                selector = item.get("selector")
                family = item.get("family")
                if "," in family:
                    first_font = family.split(",")[0].strip()
                else:
                    first_font = family
                first_font = first_font.replace("'", "")
                first_font = first_font.replace('"', "")
                if first_font not in font_families_applied:
                    font_families_applied.append(first_font)
                if first_font.lower() == "times new roman":
                    results = f"fail: {filename}: {selector} element was set "
                    results += "to the default font"
        num_fonts = len(font_families_applied)
        if num_fonts >= min and num_fonts <= max:
            results = f"pass: {filename} applied {num_fonts} "
            if num_fonts == 1:
                current_font = font_families_applied[0]
                results += f"font: {current_font}"
            else:
                results += "fonts:"
                for i in range(num_fonts):
                    current_font = font_families_applied[i]
                    if current_font == font_families_applied[-1]:
                        results += f"and {current_font}"
                    elif num_fonts > 2:
                        results += f" {current_font}, "
                    else:
                        results += f" {current_font} "
            results += "."
        elif num_fonts < min:
            results = f"fail: {filename} did not apply {min} fonts, "
            results += f"instead, it applied {num_fonts} fonts."
        elif num_fonts > max:
            results = f"fail: {filename} applied too many fonts; "
            results += f" it applied {num_fonts} fonts."
        if results and results not in report:
            report.append(results)
    if not report:
        report.append("fail: no html files to apply font styling to")
    return report

get_all_color_rules(file)

gets all color rulesets from html file

Gets all color rulesets applied to an HTML file, whether that be through a style tag or linked stylesheet and condensing them.

Creates a list of tuples that include filename, selector, color, and background color, and adjusts for overrides. In other words, it should be each selector and the final color applied.

Caveats: It does not yet account for inheritance. That would require traversing the DOM. It also does not yet account for @media rules. As of now, it's ignoring any @media breakpoint rule.

Parameters:

Name Type Description Default
file str

an html file

required

Returns:

Name Type Description
all_color_rules list

a dictionary of all color rulesets applied to an

list

html document.

Source code in webcode_tk/css_tools.py
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
def get_all_color_rules(file: str) -> list:
    """gets all color rulesets from html file

    Gets all color rulesets applied to an HTML file, whether that be
    through a style tag or linked stylesheet and condensing them.

    Creates a list of tuples that include filename, selector, color,
    and background color, and adjusts for overrides. In other words,
    it should be each selector and the final color applied.

    Caveats: It does not yet account for inheritance. That would require
    traversing the DOM. It also does not yet account for @media rules. As
    of now, it's ignoring any @media breakpoint rule.

    Args:
        file: an html file

    Returns:
        all_color_rules: a dictionary of all color rulesets applied to an
        html document."""
    all_color_rules = []
    styles_by_file = get_all_stylesheets_by_file(file)
    for style in styles_by_file:
        rules = get_color_rules_from_stylesheet(style)
        if rules:
            for rule in rules:
                all_color_rules.append((file,) + rule)
    condensed_rules = condense_the_rules(all_color_rules, file)
    return condensed_rules

get_all_font_rules(sheet)

returns a list of all rules targetting font properties.

Parameters:

Name Type Description Default
sheet Stylesheet

a stylesheet object.

required

Returns:

Name Type Description
font_rules list

a list of all font rules.

Source code in webcode_tk/css_tools.py
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
def get_all_font_rules(sheet: Stylesheet) -> list:
    """returns a list of all rules targetting font properties.

    Args:
        sheet: a stylesheet object.

    Returns:
        font_rules: a list of all font rules.
    """
    rules = {}
    for rule in sheet.rulesets:
        if "font" in rule._Ruleset__text:
            for declaration in rule.declaration_block.declarations:
                if "font" in declaration.property:
                    selector = rule.selector
                    property = declaration.property
                    value = declaration.value
                    if not rules.get(selector):
                        rules[selector] = {}
                    rules[selector]["at_rule"] = None
                    rules[selector]["property"] = property
                    rules[selector]["value"] = value
    font_rules = list(rules.items())
    at_rules = get_all_at_rules(sheet)
    font_rules = font_rules + at_rules
    return font_rules

returns all rules that target a hyperlink

returns all rules that target a link

Parameters:

Name Type Description Default
sheet Stylesheet

the stylesheet object.

required

Returns:

Name Type Description
rules list

a list of all rules that target a link

Source code in webcode_tk/css_tools.py
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
def get_all_link_rules(sheet: Stylesheet) -> list:
    """returns all rules that target a hyperlink

    returns all rules that target a link

    Args:
        sheet: the stylesheet object.

    Returns:
        rules: a list of all rules that target a link"""
    rules = []
    link_selectors = get_all_link_selectors(sheet)
    all_rulesets = sheet.rulesets
    for rule in all_rulesets:
        current_selector = rule.selector
        if current_selector in link_selectors:
            rules.append(rule)
    return rules

returns all selectors that target a link

Parameters:

Name Type Description Default
sheet Stylesheet

the stylesheet object.

required

Returns:

Name Type Description
selectors list

a list of all selectors that target a link

Source code in webcode_tk/css_tools.py
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
def get_all_link_selectors(sheet: Stylesheet) -> list:
    """returns all selectors that target a link

    Args:
        sheet: the stylesheet object.

    Returns:
        selectors: a list of all selectors that target a link"""
    selectors = []
    all_selectors = sheet.selectors
    for selector in all_selectors:
        selector_match = is_link_selector(selector)
        if selector_match:
            selectors.append(selector.strip())
    return selectors

get_all_project_stylesheets(project_dir)

returns a list of all styles and stylesheets from a project folder.

This includes styles from style tags as well as linked stylesheets.

Parameters:

Name Type Description Default
project_dir str

the relative link to the folder with the web docs.

required

Returns:

Name Type Description
all_files_styles list

a list of all stylesheets and style tag contents.

Source code in webcode_tk/css_tools.py
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
def get_all_project_stylesheets(project_dir: str) -> list:
    """returns a list of all styles and stylesheets from a project folder.

    This includes styles from style tags as well as linked stylesheets.

    Args:
        project_dir: the relative link to the folder with the web docs.

    Returns:
        all_files_styles: a list of all stylesheets and style tag contents.
    """
    directory = project_dir
    html_files = clerk.get_all_files_of_type(directory, "html")
    all_files_styles = []
    for file in html_files:
        filename = clerk.get_file_name(file)
        stylesheets = get_all_stylesheets_by_file(file)
        all_files_styles.append((filename, stylesheets))
    return all_files_styles

get_all_styles_in_order(project_path)

returns a list of all files' stylesheets in order of appearance.

The goal is to allows user to identify the cascade order of selectors and their values. This will allow one to determine if one ruleset overrides another (same specificity)

Iterates through each html file in a project folder and extracts any style tags and local stylesheets. Each styletag or stylesheet is converted into a Stylesheet object and appended to a dictionary of file names.

Parameters:

Name Type Description Default
project_path str

the path to the main project folder.

required

Returns:

Name Type Description
styles_by_html_files list

a list of dictionary objects. Each dictionary has two keys: file and stylesheets.

Source code in webcode_tk/css_tools.py
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
def get_all_styles_in_order(project_path: str) -> list:
    """returns a list of all files' stylesheets in order of appearance.

    The goal is to allows user to identify the cascade order of selectors
    and their values. This will allow one to determine if one ruleset
    overrides another (same specificity)

    Iterates through each html file in a project folder and extracts
    any style tags and local stylesheets. Each styletag or stylesheet
    is converted into a Stylesheet object and appended to a dictionary
    of file names.

    Args:
        project_path: the path to the main project folder.

    Returns:
        styles_by_html_files: a list of dictionary objects. Each dictionary
            has two keys: file and stylesheets.
    """
    styles_by_html_files = []
    html_files = html_tools.get_all_html_files(project_path)
    for file in html_files:
        file_data = get_all_stylesheets_by_file(file)
        styles_by_html_files.append({"file": file, "stylesheets": file_data})
    return styles_by_html_files

get_all_stylesheets_by_file(file_path)

returns a list of all Stylesheet objects from an HTML file in order of appearance.

This will check an HTML file for any links to stylesheets or style tags, and get each stylesheet in the order in which they were called (in case there is a CSS override).

It will only accept links to local stylesheets and ignore any external stylesheets called with an http or https.

Parameters:

Name Type Description Default
file_path str

the path to an HTML file.

required

Returns:

Name Type Description
all_styles list

a list of stylesheet objects in the order in which they are called (as a link or style tag).

Source code in webcode_tk/css_tools.py
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
def get_all_stylesheets_by_file(file_path: str) -> list:
    """returns a list of all Stylesheet objects from an HTML file in order of
    appearance.

    This will check an HTML file for any links to stylesheets or style tags,
    and get each stylesheet in the order in which they were called (in case
    there is a CSS override).

    It will only accept links to local stylesheets and ignore any external
    stylesheets called with an http or https.

    Args:
        file_path: the path to an HTML file.

    Returns:
        all_styles: a list of stylesheet objects in the order in which they
            are called (as a link or style tag).
    """
    all_styles = []
    head_tags = html_tools.get_elements("head", file_path)
    for item in head_tags:
        for tag in item.contents:
            if tag == "\n":
                continue
            if tag.name == "link":
                href = tag.attrs.get("href")
                if ".css" in href:
                    if "http" not in href[:5]:
                        # remove html filename with sheet href
                        path_list = clerk.get_path_list(file_path)
                        path_list.pop()
                        path_list.append(href)
                        sheet_path = "/".join(path_list)
                        code = clerk.file_to_string(sheet_path)
                        css_sheet = Stylesheet(sheet_path, code)
                        all_styles.append(css_sheet)
            if tag.name == "style":
                # first check for @import url
                contents = tag.text
                if "@import url(" in contents:
                    filename = contents.split("url(")[1]
                    filename = filename.split(")")[0]
                    filename = filename.replace('"', "")
                    filename = filename.replace("'", "")
                    path_list = clerk.get_path_list(file_path)
                    path_list.pop()
                    path_list.append(filename)
                    sheet_path = "/".join(path_list)
                    code = clerk.file_to_string(sheet_path)
                    css_sheet = Stylesheet(sheet_path, code)
                    all_styles.append(css_sheet)
                else:
                    css_sheet = Stylesheet(file_path, tag.text, "styletag")
                    all_styles.append(css_sheet)
    return all_styles

get_background_color(declaration)

Returns a color value from a declaration with a property of background

Parameters:

Name Type Description Default
declaration Declaration

the declaration we want to test.

required

Returns:

Name Type Description
color_value Union[str, None]

either a valid color value, None, or gradient - if it's a gradient

Source code in webcode_tk/css_tools.py
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
def get_background_color(declaration: Declaration) -> Union[str, None]:
    """Returns a color value from a declaration with a property of background

    Args:
        declaration: the declaration we want to test.

    Returns:
        color_value: either a valid color value, None, or gradient - if it's a
            gradient"""
    color_value = None
    is_rgb = color_tools.is_rgb(declaration.value)
    if is_rgb:
        return declaration.value
    values = declaration.value.split()
    for val in values:
        color = color_tools.is_color_value(val)
        if color:
            color_value = val
            break
        is_keyword = val in color_tools.color_keywords.get_all_keywords()
        if is_keyword:
            color_value = val
            break
        gradient = is_gradient(val)
        if gradient:
            color_value = "gradient"
            break
    return color_value

get_class_score(selector)

receives a selector and returns the class score

The class score represents the combined number of class, pseudo-class, and attribute selectors.

Parameters:

Name Type Description Default
selector str

the complete CSS selector

required

Returns:

Name Type Description
score int

the number of class selectors, which includes attribute

int

and pseudoclass selectors (but NOT pseudo-elements).

Source code in webcode_tk/css_tools.py
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
def get_class_score(selector: str) -> int:
    """receives a selector and returns the class score

    The class score represents the combined number of class,
    pseudo-class, and attribute selectors.

    Args:
        selector (str): the complete CSS selector

    Returns:
        score: the number of class selectors, which includes attribute
        and pseudoclass selectors (but NOT pseudo-elements).
    """
    class_re = regex_patterns["class_selector"]
    selectors = re.findall(class_re, selector)
    pseudo_re = regex_patterns["pseudoclass_selector"]
    pseudo_selectors = re.findall(pseudo_re, selector)
    selectors += pseudo_selectors
    attribute_re = regex_patterns["attribute_selectors"]
    attribute_selectorss = re.findall(attribute_re, selector)
    selectors += attribute_selectorss
    score = len(selectors)
    return score

get_color_codes_of_type(color_type, gradient)

returns all color codes of a particular type from a gradient

Parameters:

Name Type Description Default
color_type str

the type of color code it might be (hex, rgb, hsl, or keyword)

required
gradient str

the gradient code.

required

Returns:

Name Type Description
colors list

any color values that were found.

Source code in webcode_tk/css_tools.py
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
def get_color_codes_of_type(color_type: str, gradient: str) -> list:
    """returns all color codes of a particular type from a gradient

    Args:
        color_type: the type of color code it might be (hex, rgb, hsl,
            or keyword)
        gradient: the gradient code.

    Returns:
        colors: any color values that were found.
    """
    colors = []
    if color_type == "hsl":
        colors = re.findall(color_tools.hsl_all_forms_re, gradient)
    elif color_type == "rgb":
        colors = re.findall(color_tools.rgb_all_forms_re, gradient)
    elif color_type == "hex":
        colors = re.findall(color_tools.hex_re, gradient)
    elif color_type == "keywords":
        words = re.findall(r"[+a-z+A-Z]*", gradient)
        for i in words:
            # regex captures non-strings, so we don't process if empty
            if i:
                i = i.strip().lower()
                is_keyword = keyword.is_a_keyword(i.strip(" "))
                if is_keyword:
                    colors.append(i)
    if colors:
        # strip each color code (if hex regex)
        colors = [i.strip(" ") for i in colors]
    return colors

get_color_data(file, color_details, level='aaa')

returns the color contrast data on a color.

pulls out the selector, background color, text color, contrast ratio, and whether it passes color contrast.

Parameters:

Name Type Description Default
file str

just the name of the file (not path).

required
color_details dict

tuple of full color & bg color details.

required
level

the level of normal text (AAA or AA).

'aaa'

Returns:

Name Type Description
color_data tuple

a tuple with filename and results as a string

Source code in webcode_tk/css_tools.py
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
def get_color_data(file: str, color_details: dict, level="aaa") -> tuple:
    """returns the color contrast data on a color.

    pulls out the selector, background color, text color, contrast
    ratio, and whether it passes color contrast.

    Args:
        file: just the name of the file (not path).
        color_details: tuple of full color & bg color details.
        level: the level of normal text (AAA or AA).

    Returns:
        color_data: a tuple with filename and results as a string"""
    selector = color_details.get("selector")
    bg_color = color_details.get("background-color")
    color = color_details.get("color")
    contrast_ratio = color_details.get("contrast_ratio")
    if level == "aaa":
        passes = color_details.get("passes_normal_aaa")
    else:
        passes = color_details.get("passes_normal_aa")
    if passes:
        results = "passes global colors"
    else:
        results = f"{selector} {bg_color} and {color} fail with a contrast"
        results += f" ratio of {contrast_ratio}."
    color_data = (file, results)
    return color_data

get_color_rules_from_stylesheet(stylesheet)

Gets all color-based rules from a stylesheet.

Parameters:

Name Type Description Default
stylesheet Stylesheet

Stylesheet object.

required

Returns:

Name Type Description
rules list

a list of color-based rules

Source code in webcode_tk/css_tools.py
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
def get_color_rules_from_stylesheet(stylesheet: Stylesheet) -> list:
    """Gets all color-based rules from a stylesheet.

    Args:
        stylesheet: Stylesheet object.

    Returns:
        rules: a list of color-based rules"""
    rules = []
    for ruleset in stylesheet.rulesets:
        declaration_block = ruleset.declaration_block
        declarations = declaration_block.declarations
        for declaration in declarations:
            property = declaration.property
            if property == "color" or "background" in property:
                selector = ruleset.selector
                value = declaration.value
                if "background" in property:
                    background_color = get_background_color(declaration)
                    if not background_color:
                        continue
                    else:
                        value = background_color
                rules.append((selector, property, value))
    return rules

get_colors_from_gradient(gradient)

extract all color codes from gradient

Parameters:

Name Type Description Default
gradient str

the CSS color gradient value.

required

Returns:

Name Type Description
colors list

a list of all colors found in the gradient.

Source code in webcode_tk/css_tools.py
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
def get_colors_from_gradient(gradient: str) -> list:
    """extract all color codes from gradient

    Args:
        gradient: the CSS color gradient value.

    Returns:
        colors: a list of all colors found in the gradient.
    """
    colors = []
    # use regex to pull all possible color codes first
    color_types = ("hsl", "rgb", "hex", "keywords")
    for color_type in color_types:
        items = get_color_codes_of_type(color_type, gradient)
        if items:
            colors += items
    return colors

get_comment_positions(code)

looks for index positions of first opening and closing comment.

From this function, you can create a slice of a comment from the code. You would do this if you want to extract the comments from the code, or if you wanted to inspect what was in the comments, or even identify if there are comments.

Note: this only works for the first comment in code. You would want to loop through the code extracting each comment one at a time using this function until it returns None.

Parameters:

Name Type Description Default
code str

the CSS code you want to extract comments from.

required

Returns:

Name Type Description
list Union[list, None]

a list of the index positions for the beginning and end of the first occuring comment in the code.

Source code in webcode_tk/css_tools.py
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
def get_comment_positions(code: (str)) -> Union[list, None]:
    """looks for index positions of first opening and closing comment.

    From this function, you can create a slice of a comment from the
    code. You would do this if you want to extract the comments from
    the code, or if you wanted to inspect what was in the comments, or
    even identify if there are comments.

    Note: this only works for the first comment in code. You would
    want to loop through the code extracting each comment one at a
    time using this function until it returns None.

    Args:
        code (str): the CSS code you want to extract comments from.

    Returns:
        list: a list of the index positions for the beginning and end
            of the first occuring comment in the code.
    """
    positions = []
    try:
        positions.append(code.index("/*"))
        positions.append(code.index("*/"))
        return positions
    except Exception as ex:
        print(ex)
        return

get_declaration_value_by_property(block, property)

returns the value of a property from a declaration block

Parameters:

Name Type Description Default
block Union[str, DeclarationBlock]

the declaration block in question (could be as a string or as a DeclarationBlock)

required
property str

the property we are looking for

required

Returns:

Name Type Description
value str

the value of the property

Source code in webcode_tk/css_tools.py
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
def get_declaration_value_by_property(
    block: Union[str, DeclarationBlock], property: str
) -> str:
    """returns the value of a property from a declaration block

    Args:
        block: the declaration block in question (could be as a string
            or as a DeclarationBlock)
        property: the property we are looking for

    Returns:
        value: the value of the property"""
    value = ""
    try:
        block = block.text
    except AttributeError:
        declarations = block.strip()
    declarations = block.split(";")
    for item in declarations:
        item = item.strip()
        try:
            # check for @media rules
            if "{" in item:
                item_split = item.split("{")
                item = item_split[1].strip()
            prop, val = item.split(":")
            if prop.lower().strip() == property.lower():
                value = val.strip()
                continue
        except ValueError:
            print("Doh! no colon")
    return value

get_families(declaration_block)

returns a list of all font families in a declaration block

Source code in webcode_tk/css_tools.py
1329
1330
1331
1332
1333
1334
1335
1336
def get_families(declaration_block: DeclarationBlock) -> list:
    """returns a list of all font families in a declaration block"""
    families = []
    if declaration_block:
        for ruleset in declaration_block.declarations:
            if ruleset.property in ("font", "font-family"):
                families.append(ruleset.value)
    return families

get_font_families(sheet)

returns a list of all font families targeted in a stylesheet

Parameters:

Name Type Description Default
sheet Stylesheet

a stylesheet object, which could be a style tag or entire stylesheet (*.css file)

required

Returns:

Name Type Description
font_families list

a list of dictionary objects that contain all selectors and their values (but only if the value is a font family)

Source code in webcode_tk/css_tools.py
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
def get_font_families(sheet: Stylesheet) -> list:
    """returns a list of all font families targeted in a stylesheet

    Args:
        sheet: a stylesheet object, which could be a style tag or entire
            stylesheet (*.css file)

    Returns:
        font_families: a list of dictionary objects that contain all selectors
            and their values (but only if the value is a font family)
    """
    font_families = []
    for ruleset in sheet.rulesets:
        try:
            block = ruleset.declaration_block
        except AttributeError:
            continue
        families = get_families(block)
        if families:
            # create dict of selector and family
            selector = ruleset.selector

            # always take the last family as it would be an override in CSS
            family = families[-1]
            font_families.append({"selector": selector, "family": family})
    return font_families

get_global_color_details(rulesets)

receives rulesets and returns data on global colors

Note: a global selector is any selector that targets all elements in the DOM. Examples include html, body, :root, and the universal selector: *.

Parameters:

Name Type Description Default
rulesets Union[list, tuple]

a list or tuple of Ruleset objects

required

Returns:

Name Type Description
global_rulesets list

a list of dictionary objects that each contain a selector, a background color, a text color, contrast ratio, whether it passes at various levels.

Source code in webcode_tk/css_tools.py
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
def get_global_color_details(rulesets: Union[list, tuple]) -> list:
    """receives rulesets and returns data on global colors

    Note: a global selector is any selector that targets all elements
    in the DOM. Examples include `html`, `body`, `:root`, and
    the universal selector: `*`.

    Args:
        rulesets: a list or tuple of Ruleset objects

    Returns:
        global_rulesets: a list of dictionary objects that each contain
            a selector, a background color, a text color, contrast ratio,
            whether it passes at various levels.
    """
    # Are color and background color set on global selectors?
    global_selectors = ("html", "body", ":root", "*")
    global_rulesets = []
    for ruleset in rulesets:
        if ruleset.selector in global_selectors:
            selector = ruleset.selector
            background_color = ""
            color = ""
            for declaration in ruleset.declaration_block.declarations:
                if declaration.property == "background-color":
                    background_color = declaration.value
                elif declaration.property == "color":
                    color = declaration.value
                    if is_gradient(color):
                        colors = process_gradient(color)
                        todo = input("We have colors: " + colors)
                        print(todo)
                elif declaration.property == "background":
                    background_color = declaration.value
                    if is_gradient(background_color):
                        bg_colors = process_gradient(background_color)
                        print("We have bg colors: " + str(bg_colors))

            if background_color or color:
                contrast_ratio = "NA"
                passes_normal_aaa = False
                passes_normal_aa = False
                passes_large_aaa = False
                if background_color and color:
                    bg_hex = color_tools.get_hex(background_color)
                    color_hex = color_tools.get_hex(color)
                    contrast_ratio = color_tools.contrast_ratio(
                        bg_hex, color_hex
                    )
                    passes_normal_aaa = color_tools.passes_color_contrast(
                        "Normal AAA", bg_hex, color_hex
                    )
                    passes_normal_aa = color_tools.passes_color_contrast(
                        "Normal AA", bg_hex, color_hex
                    )
                    passes_large_aaa = color_tools.passes_color_contrast(
                        "Large AAA", bg_hex, color_hex
                    )
                global_rulesets.append(
                    {
                        "selector": selector,
                        "background-color": background_color,
                        "color": color,
                        "contrast_ratio": contrast_ratio,
                        "passes_normal_aaa": passes_normal_aaa,
                        "passes_normal_aa": passes_normal_aa,
                        "passes_large_aaa": passes_large_aaa,
                    }
                )
    return global_rulesets

get_global_color_report(project_dir, level='aaa')

Returns a report on which files in a project apply global colors

Parameters:

Name Type Description Default
project_dir str

the project folder path.

required
level

whether we are testing for Normal AAA or Normal AA

'aaa'

Returns:

Name Type Description
report list

a list of files and a pass or fail message for each.

Source code in webcode_tk/css_tools.py
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
def get_global_color_report(project_dir: str, level="aaa") -> list:
    """Returns a report on which files in a project apply global colors

    Args:
        project_dir: the project folder path.
        level: whether we are testing for Normal AAA or Normal AA

    Returns:
        report: a list of files and a pass or fail message for each."""
    report = []
    all_file_data = get_all_project_stylesheets(project_dir)
    for data in all_file_data:
        filename = data[0]
        passes = []
        for sheet in data[1]:
            rules = sheet.rulesets
            global_color_data = get_global_color_details(rules)
            if global_color_data:
                for item in global_color_data:
                    file, result = get_color_data(filename, item, level)
                    passes.append(f"pass: {file} {result}")
        if passes:
            details = ""
            for detail in passes:
                details += detail
        else:
            details = f"fail: {filename} does NOT apply global colors"
        report.append(details)
    if not report:
        report.append("fail: no html files to apply color styles to")
    return report

get_global_colors(file_path)

Returns a dictionary of color rules applied the entire document.

Global colors (in this context) are colors that apply to an entire document. Selectors that target the entire document are *, html, and body.

Since it's possible that an author could accidentally override a color or background color, this function will remove any previous rules that are overridden in a file.

NOTE: This should not consider an override if the would-be selector is in an @media ruleset, we won't treat it as an override.

Parameters:

Name Type Description Default
file_path str

the path to the file.

required

Returns:

Name Type Description
global_color_rules dict

a dictionary of filenames and their global rulesets.

Source code in webcode_tk/css_tools.py
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
def get_global_colors(file_path: str) -> dict:
    """Returns a dictionary of color rules applied the entire document.

    Global colors (in this context) are colors that apply to an entire
    document. Selectors that target the entire document are *, html,
    and body.

    Since it's possible that an author could accidentally override
    a color or background color, this function will remove any
    previous rules that are overridden in a file.

    NOTE: This should not consider an override if the would-be
    selector is in an @media ruleset, we won't treat it as an
    override.

    Args:
        file_path: the path to the file.

    Returns:
        global_color_rules: a dictionary of filenames and their global
            rulesets.
    """
    global_color_rules = {}
    sheets = get_all_stylesheets_by_file(file_path)
    if sheets:
        for sheet in sheets:
            rules = sheet.rulesets
            global_colors = get_global_color_details(rules)
            if global_colors:
                # Have we added the file to the global rules?
                if not global_color_rules.get(file_path):
                    global_color_rules[file_path] = []
                for gc in global_colors:
                    global_color_rules[file_path].append(gc)
        if sheets and len(global_color_rules.get(file_path)) > 1:
            # figure out the override
            global_colors = adjust_overrides(file_path, global_color_rules)
            adjusted_rule = global_colors.get(file_path)
            global_color_rules[file_path] = adjusted_rule
    return global_color_rules

get_header_color_details(rulesets)

receives rulesets and returns data on colors set by headers

This function will look through all rules in a ruleset and extracts the rules that target color or background color for a heading (h1 -h6).

Parameters:

Name Type Description Default
rulesets Union[list, tuple]

a list or tuple of Ruleset objects.

required

Returns:

Name Type Description
header_rulesets list

a list of dictionary objects that each contain a selector, a background color, and a text color.

Source code in webcode_tk/css_tools.py
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
def get_header_color_details(rulesets: Union[list, tuple]) -> list:
    """receives rulesets and returns data on colors set by headers

    This function will look through all rules in a ruleset and extracts
    the rules that target color or background color for a heading (h1
    -h6).

    Args:
        rulesets: a list or tuple of Ruleset objects.

    Returns:
        header_rulesets: a list of dictionary objects that each contain
            a selector, a background color, and a text color.
    """
    header_rulesets = []
    for ruleset in rulesets:
        selector = ruleset.selector
        # check selector for having a header
        heading_selectors = get_header_selectors(selector)
        if heading_selectors:
            # get color data
            background_color = ""
            color = ""
            for declaration in ruleset.declaration_block.declarations:
                if declaration.property == "background-color":
                    background_color = declaration.value
                elif declaration.property == "color":
                    color = declaration.value
                elif declaration.property == "background":
                    # check to see if the color value is present
                    print("it's time to figure out the background shorthand")
                if background_color and color:
                    break

            # then apply color data to all others
            if background_color or color:
                for h_selector in heading_selectors:
                    header_rulesets.append(
                        {
                            "selector": h_selector,
                            "background-color": background_color,
                            "color": color,
                        }
                    )

    return header_rulesets

get_header_selectors(selector)

takes selector and returns any selector that selects an h1-h6

Parameters:

Name Type Description Default
selector str

A CSS selector

required

Returns:

Name Type Description
header_selectors list

a list of selectors that target a heading.

Source code in webcode_tk/css_tools.py
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
def get_header_selectors(selector: str) -> list:
    """takes selector and returns any selector that selects an h1-h6

    Args:
        selector: A CSS selector

    Returns:
        header_selectors: a list of selectors that target a heading.
    """
    # NOTE the following:
    # a selector is only selecting a header if it's the last item
    # example: header h1 {} does but h1 a {} does not
    header_selectors = []
    selectors = [sel.strip() for sel in selector.split(",")]
    if selectors[0]:
        for selector in selectors:
            items = selector.split()
            pattern = regex_patterns["header_selector"]
            h_match = re.search(pattern, items[-1])
            if h_match:
                header_selectors.append(selector)
    return header_selectors

get_heading_color_report(project_dir)

Returns a report on which files in a project apply heading colors

For now, we just want to have at least a color or background color applied.

Parameters:

Name Type Description Default
project_dir str

the project folder path.

required

Returns:

Name Type Description
report list

a list of files and a pass or fail message for each.

Source code in webcode_tk/css_tools.py
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
def get_heading_color_report(project_dir: str) -> list:
    """Returns a report on which files in a project apply heading colors

    For now, we just want to have at least a color or background color
    applied.

    Args:
        project_dir: the project folder path.

    Returns:
        report: a list of files and a pass or fail message for each."""
    report = []
    header_re = regex_patterns.get("header_selector")

    # make sure we have a trailing slash separator
    if project_dir[-1] != "/":
        project_dir += "/"
    all_file_data = get_all_project_stylesheets(project_dir)
    for file in all_file_data:
        filename = file[0]
        filepath = project_dir + filename
        all_color_rules = get_all_color_rules(filepath)
        header_selectors = []

        # Look through all selectors and their values
        # if selector is a header selector, then check color
        for sel, val in all_color_rules.items():
            is_header_selector = re.findall(header_re, sel)
            if is_header_selector:
                color_data = val
                color_value = color_data.get("color")
                bg_value = color_data.get("background-color")
                if color_value:
                    if bg_value:
                        header_selectors.append(
                            (filename, color_value, bg_value)
                        )
                    else:
                        header_selectors.append((filename, color_value, None))
                if bg_value:
                    header_selectors.append((filename, None, bg_value))
        if header_selectors:
            report.append(f"pass: {filename} applies colors to headers")
        else:
            report.append(f"fail: {filename} does NOT apply colors to headers")
    if not report:
        report.append("fail: no html files to apply header colors to")
    return report

get_id_score(selector)

receives a selector and returns # of ID selectors

Parameters:

Name Type Description Default
selector str

the complete CSS selector

required

Returns:

Name Type Description
score int

the number of ID selectors.

Source code in webcode_tk/css_tools.py
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
def get_id_score(selector: str) -> int:
    """receives a selector and returns # of ID selectors

    Args:
        selector (str): the complete CSS selector

    Returns:
        score: the number of ID selectors.
    """
    pattern = regex_patterns["id_selector"]
    id_selectors = re.findall(pattern, selector)
    score = len(id_selectors)
    return score

returns all colors applied to links.

Identifies all selectors that target a link, and gets a list of dictionaries that identify colors.

Parameters:

Name Type Description Default
project_path str

path to project folder

required

Returns:

Name Type Description
link_styles list

a list of link color data applied to each file that includes a link color data

Source code in webcode_tk/css_tools.py
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
def get_link_color_data(project_path: str) -> list:
    """returns all colors applied to links.

    Identifies all selectors that target a link, and gets a
    list of dictionaries that identify colors.

    Args:
        project_path: path to project folder

    Returns:
        link_styles: a list of link color data applied to each
            file that includes a link color data"""
    link_styles = []
    color_contrast_data = get_project_color_contrast(project_path)
    for item in color_contrast_data:
        selector = item[1]
        if not is_link_selector(selector):
            continue
        # it must be a link selector, let's get our data
        link_styles.append(item)
    return link_styles

get_number_required_selectors(selector_type, sheet)

returns # of a specific selector type in a stylesheet

Parameters:

Name Type Description Default
selector_type str

what kind of selector we're looking for.

required
sheet Stylesheet

the Stylesheet object we're inspecting.

required

Returns:

Name Type Description
count int

the number of occurrences of the selector.

Source code in webcode_tk/css_tools.py
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
def get_number_required_selectors(
    selector_type: str, sheet: Stylesheet
) -> int:
    """returns # of a specific selector type in a stylesheet

    Args:
        selector_type: what kind of selector we're looking for.
        sheet: the Stylesheet object we're inspecting.

    Returns:
        count: the number of occurrences of the selector.
    """
    count = 0
    pattern = regex_patterns[selector_type]
    for selector in sheet.selectors:
        matches = re.findall(pattern, selector)
        count += len(matches)
    # Loop through all nested @rules and count selectors
    for rules in sheet.nested_at_rules:
        for selector in rules.selectors:
            matches = re.findall(pattern, selector)
            count += len(matches)
    return count

get_project_color_contrast(project_path, normal_goal='Normal AAA', large_goal='Large AAA')

checks all color rules for each file in a project folder for contrast

Parameters:

Name Type Description Default
project_path str

path to project folder.

required
normal_goal

color contrast goal for most text in document (all except headers) - could be 'Normal AAA' or 'Normal AA' (default set to 'Normal AAA')

'Normal AAA'
large_goal

color contrast goal for large (headings) text. May be 'Large AAA' or 'Large AA' (default is set to 'Large AAA')

'Large AAA'

Returns:

Name Type Description
results list

a list of tuples. Each tuple contains a filename, selector, goal, color, bg_color, computed contrast ratio, passes_color

Source code in webcode_tk/css_tools.py
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
def get_project_color_contrast(
    project_path: str, normal_goal="Normal AAA", large_goal="Large AAA"
) -> list:
    """checks all color rules for each file in a project folder for contrast

    Args:
        project_path: path to project folder.
        normal_goal: color contrast goal for most text in document (all except
            headers) - could be 'Normal AAA' or 'Normal AA' (default set to
            'Normal AAA')
        large_goal: color contrast goal for large (headings) text. May be
            'Large AAA' or 'Large AA' (default is set to 'Large AAA')

    Returns:
        results: a list of tuples. Each tuple contains a filename, selector,
            goal, color, bg_color, computed contrast ratio, passes_color"""

    results = []
    global_color_rules = get_project_global_colors(project_path)
    for file in global_color_rules.keys():
        global_details = global_color_rules.get(file)
        all_color_rules = get_all_color_rules(file)
        if global_details:
            if isinstance(global_details, list):
                if len(global_details) == 1:
                    global_details = global_details[0]
            global_color = global_details.get("color")
            global_bg = global_details.get("background-color")
        items = list(all_color_rules.keys())
        heading_tag_re = r"h[1-6]"

        for key in items:
            # skip first key and any key that is a global selector
            if key == "file":
                continue
            goal = normal_goal
            if re.search(heading_tag_re, key):
                goal = large_goal
            else:
                goal = normal_goal
            selector = key
            details = all_color_rules.get(selector)
            color = details.get("color")
            if not color:
                if not global_color:
                    color = "#000000"
                else:
                    color = global_color
            color_hex = color_tools.get_hex(color)
            bg_color = details.get("background-color")
            if not bg_color:
                if not global_bg:
                    bg_color = "#ffffff"
                else:
                    bg_color = global_bg
            bg_hex = color_tools.get_hex(bg_color)
            passes_color = color_tools.passes_color_contrast(
                goal, bg_hex, color_hex
            )
            contrast_ratio = color_tools.contrast_ratio(color_hex, bg_hex)
            results.append(
                (
                    file,
                    selector,
                    goal,
                    color,
                    bg_color,
                    contrast_ratio,
                    passes_color,
                )
            )
    return results

get_project_color_contrast_report(project_dir, level='AAA')

returns a report of pass or fail for each element targetting color.

NOTE: We are replacing this report with the one in the cascade_tools for two reasons: one, it more accurately targest a large or regular sized font; and two, it only targets any element with direct text because it's the text that is visible in the browser that we are concerned with.

See issue #28: Color Contrast issue with cascade https://github.com/HundredVisionsGuy/webcode-tk/issues/28

Parameters:

Name Type Description Default
project_dir str

the project folder where the html and css files are found.

required
level

the level for the report (AAA or AA)

'AAA'

Returns: report: a report of every targetted color and whether it passes or fails.

Source code in webcode_tk/css_tools.py
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
def get_project_color_contrast_report(project_dir: str, level="AAA") -> list:
    """returns a report of pass or fail for each element targetting color.

    NOTE: We are replacing this report with the one in the cascade_tools for
    two reasons: one, it more accurately targest a large or regular sized
    font; and two, it only targets any element with direct text because it's
    the text that is visible in the browser that we are concerned with.

    See issue #28: Color Contrast issue with cascade
    https://github.com/HundredVisionsGuy/webcode-tk/issues/28

    Args:
        project_dir: the project folder where the html and css files are found.
        level: the level for the report (AAA or AA)
    Returns:
        report: a report of every targetted color and whether it passes or
            fails.
    """
    report = cascade_tools.get_color_contrast_report(project_dir, level)
    return report

get_project_global_colors(project_path)

Returns a dictionary of color rules applied to all html files in a project folder.

Global colors (in this context) are colors that apply to an entire document. Selectors that target the entire document are *, html, and body.

Since it's possible that an author could accidentally override a color or background color, this function will remove any previous rules that are overridden in a file.

NOTE: This should not consider an override if the would-be selector is in an @media ruleset, we won't treat it as an override.

Parameters:

Name Type Description Default
project_path str

the project folder path.

required

Returns:

Name Type Description
global_color_rules dict

a dictionary of filenames and their global rulesets.

Source code in webcode_tk/css_tools.py
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
def get_project_global_colors(project_path: str) -> dict:
    """Returns a dictionary of color rules applied to all html files
    in a project folder.

    Global colors (in this context) are colors that apply to an entire
    document. Selectors that target the entire document are *, html,
    and body.

    Since it's possible that an author could accidentally override
    a color or background color, this function will remove any
    previous rules that are overridden in a file.

    NOTE: This should not consider an override if the would-be
    selector is in an @media ruleset, we won't treat it as an
    override.

    Args:
        project_path: the project folder path.

    Returns:
        global_color_rules: a dictionary of filenames and their global
            rulesets.
    """
    global_color_rules = {}
    styles_by_files = get_styles_by_html_files(project_path)
    for file in styles_by_files:
        filename = file.get("file")
        sheets = file.get("stylesheets")
        if sheets:
            for sheet in sheets:
                rules = sheet.rulesets
                global_colors = get_global_color_details(rules)
                if global_colors:
                    # Have we added the file to the global rules?
                    if not global_color_rules.get(filename):
                        global_color_rules[filename] = []
                    for gc in global_colors:
                        global_color_rules[filename].append(gc)
        if sheets and len(global_color_rules.get(filename)) > 1:
            # figure out the override
            global_colors = adjust_overrides(filename, global_color_rules)
            adjusted_rule = global_colors.get(filename)
            global_color_rules[filename] = adjusted_rule
    return global_color_rules

get_properties_applied_report(project_dir, goals)

returns a report on any elements that fail to have a property applied

goals should be a dictionary with a key for each element we are checking. Each key has as it's value a dictionary with 1 to 3 possible keys... 1. (required) properties (the properties that should be applied) 2. (optional) min_required: If min_required is specified, then to pass it only requires the minimum number of properties to be present.

Sample goals might look like the following: goals_simple = { "figure": { "properties": ("box-shadow", "border-radius", "animation"), } } goals_complex = { "figure": { "properties": ("box-shadow", "border-radius", "animation"), "min_required": 2, } }

Parameters:

Name Type Description Default
project_dir str

the path to the project folder

required
goals dict

a dictionary of elements and the properties expected to be present

required

Returns:

Name Type Description
report list

a list of pass or fail messages that indicates the file, the element, and the missing property.

Source code in webcode_tk/css_tools.py
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
def get_properties_applied_report(project_dir: str, goals: dict) -> list:
    """returns a report on any elements that fail to have a property applied

    goals should be a dictionary with a key for each element we are checking.
    Each key has as it's value a dictionary with 1 to 3 possible keys...
      1. (required) properties (the properties that should be applied)
      2. (optional) min_required: If min_required is specified, then to pass
         it only requires the minimum number of properties to be present.

    Sample goals might look like the following:
    goals_simple = {
        "figure": {
            "properties": ("box-shadow", "border-radius", "animation"),
        }
    }
    goals_complex = {
        "figure": {
            "properties": ("box-shadow", "border-radius", "animation"),
            "min_required": 2,
        }
    }

    Args:
        project_dir: the path to the project folder
        goals: a dictionary of elements and the properties expected to be
            present

    Returns:
        report: a list of pass or fail messages that indicates the file, the
            element, and the missing property.
    """
    report = []
    elements = list(goals.keys())
    for element in elements:
        details = goals.get(element)
        min_required = 0
        # details might be a tuple or a dictionary
        if isinstance(details, tuple):
            properties = details
            min_required = len(properties)
        else:
            properties = details.get("properties")
            min_required = details.get("min_required")

        html_files = get_styles_by_html_files(project_dir)
        for file in html_files:
            properties_found = []
            found_properties_remaining = list(properties)
            file_path = file.get("file")
            targetted_elements_in_file = html_tools.get_elements(
                element, file_path
            )
            # check all selectors in all stylesheet objects
            for sheet in file.get("stylesheets"):
                for rule in sheet.rulesets:
                    selector = rule.selector
                    selector_type = get_selector_type(selector)
                    if selector_type == "type_selector":
                        if selector == element:
                            # loop through all properties and take what we can
                            take_targetted_properties(
                                properties_found,
                                properties,
                                found_properties_remaining,
                                rule,
                            )
                    if selector_type == "descendant_selector":
                        sel_split = selector.split()
                        target = sel_split[-1]
                        if element == target:
                            take_targetted_properties(
                                properties_found,
                                properties,
                                found_properties_remaining,
                                rule,
                            )
                    if selector_type == "grouped_selector":
                        sel_split = selector.split(",")
                        if element in sel_split:
                            take_targetted_properties(
                                properties_found,
                                properties,
                                found_properties_remaining,
                                rule,
                            )
                    if selector_type == "pseudo_selector":
                        sel_split = selector.split(":")
                        target = sel_split[0]
                        if target == element:
                            take_targetted_properties(
                                properties_found,
                                properties,
                                found_properties_remaining,
                                rule,
                            )
                    if selector_type == "id_selector":
                        # could be starting with # or have tag, then hash
                        # tag, then ID
                        the_tag, its_id = selector.split("#")
                        for target in targetted_elements_in_file:
                            # our target must have an id attribute or no match
                            if target.attrs:
                                target_id = target.attrs.get("id")
                                if target_id:
                                    a_match = ""
                                    if the_tag:
                                        a_match = element + "#" + target_id
                                    else:
                                        a_match = "#" + target_id
                                    if selector == a_match:
                                        take_targetted_properties(
                                            properties_found,
                                            properties,
                                            found_properties_remaining,
                                            rule,
                                        )
                    if selector_type == "class_selector":
                        # is the first part the tag?

                        selector_split = selector.split(".")
                        selector_tag = ""
                        if selector[0] != ".":
                            selector_tag = selector_split[0]
                        its_classes = selector_split[1:]
                        for target in targetted_elements_in_file:
                            # our target must have attributes
                            if target.attrs:
                                target_classes = target.attrs.get("class")
                                if target_classes:
                                    # We need to sort both and compare
                                    its_classes.sort()
                                    target_classes.sort()
                                    if its_classes == target_classes:
                                        # could be a match
                                        if selector_tag:
                                            # but not if the selector
                                            # doesn't match
                                            if selector_tag != element:
                                                continue
                                        # It's a match
                                        take_targetted_properties(
                                            properties_found,
                                            properties,
                                            found_properties_remaining,
                                            rule,
                                        )

            # If there are any properties left, it's a fail
            filename = clerk.get_file_name(file.get("file"))
            if found_properties_remaining:
                count = len(found_properties_remaining)
                if min_required:
                    applied = len(properties) - count
                    if applied >= min_required:
                        msg = f"pass: in {filename} the {element} tag applies"
                        msg += " minimum required properties ("
                        msg += f"{min_required})."
                    else:
                        msg = f"fail: in {filename}, the {element} tag only "
                        msg += f" applied {applied} properties out of "
                        msg += f" {min_required} required properties."
                else:
                    msg = f"fail: in {filename}, the {element} tag does not "
                    msg += "apply "
                    if count == 1:
                        msg += f"1 property: {found_properties_remaining[0]}."
                    else:
                        msg += f"{count} properties: "
                        msg += f"{found_properties_remaining}."

            # all properties were accounted for (none remaining)
            else:
                msg = f"pass: in {filename}, the {element} tag applies all "
                msg += "required properties."
            report.append(msg)
    if not report:
        msg = f"fail: no file directly targetted the {element} tag's "
        msg += f"properties: {properties}."
        report.append(msg)
    return report

get_selector_type(selector)

returns the type of selector it is.

Cycles through selector regexes to see which one it is. When it has a match, it returns the key.

Parameters:

Name Type Description Default
selector str

the selector in question.

required

Returns:

Name Type Description
str str

the key of the selector regex dictionary if there's a match.

Source code in webcode_tk/css_tools.py
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
def get_selector_type(selector: str) -> str:
    """returns the type of selector it is.

    Cycles through selector regexes to see which one it is. When it has a
    match, it returns the key.

    Args:
        selector: the selector in question.

    Returns:
        str: the key of the selector regex dictionary if there's a match."""
    for type, regex in regex_patterns.items():
        match = re.match(regex, selector)
        if "#" in selector and selector.index("#") != len(selector) - 1:
            return "id_selector"
        if match:
            if type == "single_type_selector":
                return "type_selector"
            return type

get_shorthand(sel)

returns a shorthand version of a property if it could be a portion of a shorthand property

It's more efficient if you check for a dash before passing it as an argument.

Parameters:

Name Type Description Default
sel str

a CSS selector (should be one with a dash)

required

Returns:

Name Type Description
shorthand str

the shorthand version of a property if it is or an empty string if not.

Source code in webcode_tk/css_tools.py
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
def get_shorthand(sel: str) -> str:
    """returns a shorthand version of a property if it could be a portion
    of a shorthand property

    It's more efficient if you check for a dash before passing it as an
    argument.

    Arguments:
        sel: a CSS selector (should be one with a dash)

    Returns:
        shorthand: the shorthand version of a property if it is or an empty
            string if not.
    """
    shorthand = ""

    # if so, check if the part before the first dash is a shorthand
    prefix = sel.split("-")[0]
    if prefix in shorthand_properties:
        shorthand = prefix

    # if so, return the shorthand variant

    return shorthand

get_specificity(selector)

Gets the specificity score on the selector.

According to MDN's article on Specificity, Specificity is the algorithm used by browsers to determine the CSS declaration that is the most relevant to an element, which in turn, determines the property value to apply to the element.

The specificity algorithm calculates the weight of a CSS selector to determine which rule from competing CSS declarations gets applied to an element.

The specificity score is basically a number, and if two selectors target the same element, the selector with the highest specificity score wins. The number is like a 3-digit number, where the "ones" place is the number of type selectors, the "tens" place is the number of class selectors, and the "hundreds" place is the number of id selectors.

For example, the selector: h1, h2, h3 has a specificity of 003 because there are neither id nor class selectors, but there are 3 type selectors.

The selector: nav#main ul has a specificity of 102 because there is one id selector (#main) and two type selectors (nav and ul).

Parameters:

Name Type Description Default
selector str

the CSS selector in question.

required

Returns:

Name Type Description
specificity str

the specificity score.

Source code in webcode_tk/css_tools.py
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
def get_specificity(selector: str) -> str:
    """Gets the specificity score on the selector.

    According to MDN's article on Specificity, Specificity is the
    algorithm used by browsers to determine the CSS declaration that
    is the most relevant to an element, which in turn, determines
    the property value to apply to the element.

    The specificity algorithm calculates the weight of a CSS selector
    to determine which rule from competing CSS declarations gets
    applied to an element.

    The specificity score is basically a number, and if two selectors
    target the same element, the selector with the highest specificity
    score wins. The number is like a 3-digit number, where the "ones"
    place is the number of type selectors, the "tens" place is the
    number of class selectors, and the "hundreds" place is the number
    of id selectors.

    For example, the selector: `h1, h2, h3` has a specificity of `003`
    because there are neither id nor class selectors, but there are 3
    type selectors.

    The selector: `nav#main ul` has a specificity of `102` because
    there is one id selector (`#main`) and two type selectors (`nav`
    and `ul`).

    Args:
        selector (str): the CSS selector in question.

    Returns:
        specificity: the specificity score.
    """
    id_selector = get_id_score(selector)
    class_selector = get_class_score(selector)
    pseudo_element_selector = get_psuedo_element_score(selector)
    type_selector = get_type_score(selector)
    type_count = type_selector + pseudo_element_selector
    specificity = "{}{}{}".format(id_selector, class_selector, type_count)
    return specificity

get_styles_by_html_files(project_path)

Returns a list of filenames with their stylesheets in order of appearance.

This will identify all HTML documents in the project folder. For each HTML document, it will create a dictionary with two keys: filename for the HTML document and stylesheets for a list of the css styles created through link tags or style tags.

As it uses get_all_stylesheets_by_files, you can be sure that no external stylesheets (https://...) will be included in the list.

Parameters:

Name Type Description Default
project_path str

a string of the path to the project folder you want to test.

required

Returns:

Name Type Description
styles_by_html_files list

a list of dictionary objects indicating each html document and its styles in order of appearance.

Source code in webcode_tk/css_tools.py
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
def get_styles_by_html_files(project_path: str) -> list:
    """Returns a list of filenames with their stylesheets in order of
    appearance.

    This will identify all HTML documents in the project folder. For
    each HTML document, it will create a dictionary with two keys:
    filename for the HTML document and stylesheets for a list of the
    css styles created through link tags or style tags.

    As it uses get_all_stylesheets_by_files, you can be sure that no
    external stylesheets (https://...) will be included in the list.

    Args:
        project_path: a string of the path to the project folder you
            want to test.

    Returns:
        styles_by_html_files: a list of dictionary objects indicating
            each html document and its styles in order of appearance.
    """
    styles_by_html_files = []
    html_files = html_tools.get_all_html_files(project_path)
    for file in html_files:
        file_data = get_all_stylesheets_by_file(file)
        styles_by_html_files.append({"file": file, "stylesheets": file_data})
    return styles_by_html_files

get_type_score(selector)

receives a selector and returns the number of type selectors

Parameters:

Name Type Description Default
selector str

the complete CSS selector

required

Returns:

Name Type Description
score int

the number of type selectors.

Source code in webcode_tk/css_tools.py
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
def get_type_score(selector: str) -> int:
    """receives a selector and returns the number of type selectors

    Args:
        selector: the complete CSS selector

    Returns:
        score: the number of type selectors.
    """
    pattern = regex_patterns["type_selector"]
    selectors = re.findall(pattern, selector)
    score = len(selectors)
    return score

get_unique_font_rules(project_folder)

Returns list of files with only unique font rules applied.

Parameters:

Name Type Description Default
project_folder str

a string path to the project folder we are testing.

required

Returns:

Name Type Description
project_font_data list

a list of dictionary objects that each store the file where styles are applied and their unique font-related rules.

Source code in webcode_tk/css_tools.py
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
def get_unique_font_rules(project_folder: str) -> list:
    """Returns list of files with only unique font rules applied.

    Args:
        project_folder: a string path to the project folder we are testing.

    Returns:
        project_font_data: a list of dictionary objects that each store
            the file where styles are applied and their unique font-related
            rules.
    """
    styles_by_html_files = get_styles_by_html_files(project_folder)
    font_families_tests = []
    for file in styles_by_html_files:
        style_sheets = file.get("stylesheets")
        unique_rules = []
        unique_font_values = []
        unique_font_selectors = []
        font_rules = []
        for sheet in style_sheets:
            font_families = get_font_families(sheet)
            if font_families:
                for family in font_families:
                    font_rules.append(family)
        # Let's build results for this page
        for rule in font_rules:
            if rule:
                if rule not in unique_rules:
                    unique_rules.append(rule)
                    selector = rule.get("selector")
                    value = rule.get("family")
                    if selector not in unique_font_selectors:
                        unique_font_selectors.append(selector)
                    if value not in unique_font_values:
                        unique_font_values.append(value)
                else:
                    print()
        # apply the file, unique rules, unique selectors, and unique values
        filename = file.get("file")
        file_data = {"file": filename, "rules": unique_rules}
        font_families_tests.append(file_data)
    return font_families_tests

get_variables(text)

returns a list of css variables and their values.

This will extract any variables if they exist, copy the variable name and its value and create a dictionary object and append to list.

Parameters:

Name Type Description Default
text str

full text of css stylesheet

required

Returns:

Name Type Description
variables list

a list of variable dictionaries each with a key for the variable and a value for its value.

Source code in webcode_tk/css_tools.py
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
def get_variables(text: str) -> list:
    """returns a list of css variables and their values.

    This will extract any variables if they exist, copy the
    variable name and its value and create a dictionary object
    and append to list.

    Args:
        text: full text of css stylesheet

    Returns:
        variables: a list of variable dictionaries each with a
            key for the variable and a value for its value.
    """
    variables = []
    variable_split = text.split(":root {")
    if len(variable_split) == 1:
        return []
    variable_text = variable_split[1].strip()
    variables_list = variable_text.strip().split(";")
    for var in variables_list:
        var = var.strip()
        if "}" in var:
            break
        variable, value = var.split(":")
        var_dict = {"variable": variable, "value": value}
        variables.append(var_dict)
    return variables

returns whether any style in a stylesheet targets a hyperlink

There could be one or more link selectors. This will check each possible link selector (or psuedoselector). It only has to target a link and not a descendant of a link.

Parameters:

Name Type Description Default
sheet Stylesheet

the stylesheet object.

required

Returns:

Name Type Description
has_selector bool

whether there is a selector that targets a link

Source code in webcode_tk/css_tools.py
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
def has_link_selector(sheet: Stylesheet) -> bool:
    """returns whether any style in a stylesheet targets a hyperlink

    There could be one or more link selectors. This will check each possible
    link selector (or psuedoselector). It only has to target a link and not
    a descendant of a link.

    Args:
        sheet: the stylesheet object.

    Returns:
        has_selector: whether there is a selector that targets a link"""
    has_selector = False
    all_selectors = sheet.selectors
    for selector in all_selectors:
        selector_copy = selector
        if " " in selector:
            # we need to add a space at the end for the split to work
            selector = selector.strip() + " "
            selector_split = selector.split()
            selector_copy = selector_split[-1]
        if selector_copy == "a":
            has_selector = True
            break
        # Check selector_copy to see if it's an anchor
        regex_pattern = regex_patterns.get("advanced_link_selector")
        selector_match = re.search(regex_pattern, selector_copy)
        if selector_match:
            has_selector = True
            break
    return has_selector

has_required_property(property, sheet)

checks stylesheet for a particular property

Parameters:

Name Type Description Default
property str

the property we're looking for

required
sheet Stylesheet

the Stylesheet object we're inspecting

required

Returns:

Name Type Description
has_property bool

whether the Stylesheet has the property or not.

Source code in webcode_tk/css_tools.py
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
def has_required_property(property: str, sheet: Stylesheet) -> bool:
    """checks stylesheet for a particular property

    Args:
        property: the property we're looking for
        sheet (Stylesheet): the Stylesheet object we're inspecting

    Returns:
        has_property: whether the Stylesheet has the property or not.
    """
    has_property = False
    for rule in sheet.rulesets:
        for declaration in rule.declaration_block.declarations:
            if declaration.property == property:
                return True
    return has_property

has_vendor_prefix(property)

Checks a property to see if it uses a vendor prefix or not.

Parameters:

Name Type Description Default
property str

A CSS property in string format.

required

Returns:

Name Type Description
has_prefix bool

whether the property uses a vendor prefix or not.

Source code in webcode_tk/css_tools.py
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
def has_vendor_prefix(property: str) -> bool:
    """Checks a property to see if it uses a vendor prefix or not.

    Args:
        property: A CSS property in string format.

    Returns:
        has_prefix: whether the property uses a vendor prefix or not.
    """
    vendor_prefixes = ("-webkit-", "-moz-", "-o-", "-ms-")
    has_prefix = False
    for prefix in vendor_prefixes:
        if prefix in property:
            has_prefix = True
            break
    return has_prefix

is_gradient(value)

checks a CSS value to see if it's using a gradient or not.

Parameters:

Name Type Description Default
value str

a CSS value.

required

Returns:

Name Type Description
uses_gradient bool

whether it uses a gradient or not.

Source code in webcode_tk/css_tools.py
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
def is_gradient(value: str) -> bool:
    """checks a CSS value to see if it's using a gradient or not.

    Args:
        value (str): a CSS value.

    Returns:
        uses_gradient: whether it uses a gradient or not.
    """
    uses_gradient = "gradient" in value
    return uses_gradient

returns a true if selector targets a link

Parameters:

Name Type Description Default
selector str

the selector in question

required
Source code in webcode_tk/css_tools.py
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
def is_link_selector(selector: str) -> bool:
    """returns a true if selector targets a link

    Args:
        selector: the selector in question"""
    selector_copy = selector
    if " " in selector:
        # we need to add a space at the end for the split to work
        selector = selector.strip() + " "
        selector_split = selector.split()
        selector_copy = selector_split[-1]
    if selector_copy == "a":
        return True
        # Check selector_copy to see if it's an anchor
    regex_pattern = regex_patterns.get("advanced_link_selector")
    selector_match = re.search(regex_pattern, selector_copy)
    return bool(selector_match)

is_required_selector(selector_type, selector)

checks selector to see if it's required type or not.

Example: you may wish to loop through selectors and see which ones are class selectors, or id selectors, etc..

It makes use of the list of regex_patterns for selector type.

Parameters:

Name Type Description Default
selector_type str

the type of selector in question, such as an id, class, type, etc.

required
selector str

the selector we are checking.

required

Returns:

Name Type Description
match bool

whether the selector matches the type.

Source code in webcode_tk/css_tools.py
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
def is_required_selector(selector_type: str, selector: str) -> bool:
    """checks selector to see if it's required type or not.

    Example: you may wish to loop through selectors and see which
    ones are class selectors, or id selectors, etc..

    It makes use of the list of regex_patterns for selector type.

    Args:
        selector_type: the type of selector in question, such as
            an id, class, type, etc.
        selector: the selector we are checking.

    Returns:
        match: whether the selector matches the type.
    """
    pattern = regex_patterns[selector_type]
    match = bool(re.search(pattern, selector))
    return match

is_selector_at_end_of_descendant(selector, cur_selector)

returns whether a selector is at the end of a descendant selector

Source code in webcode_tk/css_tools.py
2236
2237
2238
2239
2240
2241
2242
2243
2244
def is_selector_at_end_of_descendant(selector: str, cur_selector: str) -> bool:
    """returns whether a selector is at the end of a descendant selector"""
    selector_at_end_of_descendant = False
    selectors = cur_selector.split()
    if selector in selectors[-1]:
        # selector must be at the end of descendant selector
        # or it doesn't count
        selector_at_end_of_descendant = True
    return selector_at_end_of_descendant

minify_code(text)

remove all new lines, tabs, and double spaces from text

This is a classic function for web developers to minify their code by removing new lines, tabs, and any double spaces from text.

Parameters:

Name Type Description Default
text str

the code you want to minify.

required

Returns:

Name Type Description
text str

the code without all the additional whitespace.

Source code in webcode_tk/css_tools.py
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
def minify_code(text: str) -> str:
    """remove all new lines, tabs, and double spaces from text

    This is a classic function for web developers to minify their code
    by removing new lines, tabs, and any double spaces from text.

    Args:
        text: the code you want to minify.

    Returns:
        text: the code without all the additional whitespace."""
    text = text.replace("\n", "")
    text = text.replace("  ", "")
    text = text.replace("\t", "")
    return text

no_style_attributes_allowed_report(project_dir)

returns a report on whether HTML docs use style attributes or not.

Only call this report if you do not allow a style attribute in an HTML doc

Parameters:

Name Type Description Default
project_dir str

the relative link to the folder with the web docs.

required

Returns:

Name Type Description
report list

a list of all HTML docs and a pass or fail message.

Source code in webcode_tk/css_tools.py
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
def no_style_attributes_allowed_report(project_dir: str) -> list:
    """returns a report on whether HTML docs use style attributes or not.

    Only call this report if you do not allow a style attribute in an
    HTML doc

    Args:
        project_dir: the relative link to the folder with the web docs.

    Returns:
        report: a list of all HTML docs and a pass or fail message.
    """
    report = []

    html_files = clerk.get_all_files_of_type(project_dir, "html")
    for file in html_files:
        try:
            has_style_attr = html_tools.has_style_attribute_data(file)
        except AttributeError:
            continue
        if has_style_attr:
            result = f"fail: {file} uses style attributes"
        else:
            result = f"pass: {file} does not use style attributes"
        report.append(result)
    return report

passes_global_color_contrast(file, goal='Normal AAA')

determines whether a file passes global color contrast

Parameters:

Name Type Description Default
file str

path to file in question.

required
goal

what's the color contrast goal - set to Normal AAA by default.

'Normal AAA'

Returns:

Name Type Description
meets bool

whether it passes contrast goals or not

Source code in webcode_tk/css_tools.py
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
def passes_global_color_contrast(file: str, goal="Normal AAA") -> bool:
    """determines whether a file passes global color contrast

    Args:
        file: path to file in question.

        goal: what's the color contrast goal - set to Normal AAA by
            default.

    Returns:
        meets: whether it passes contrast goals or not
    """
    global_colors = get_global_colors(file)
    details = global_colors.get(file)
    goal_key = "passes_" + goal.replace(" ", "_").lower()
    meets = details.get(goal_key)
    return meets

process_gradient(code)

returns list of all colors from gradient sorted light to dark

This function is a work in progress. The goal is to eventually use it to determine whether a gradient meets color contrast accessibility ratings when compared against another color or color gradient.

In order to do this, the plan is to find the lightest color and the darkest color, so we can check both sides of the range. If the lightest or darkest color fails color contrast, then it's a fail. If both pass, then all colors in between will pass.

Note: we may be adding more to this and refactoring functionality.

Parameters:

Name Type Description Default
code str

the color gradient value

required

Returns:

Name Type Description
only_colors list

a list of just color codes sorted by luminance

Source code in webcode_tk/css_tools.py
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
def process_gradient(code: str) -> list:
    """returns list of all colors from gradient sorted light to dark

    This function is a work in progress. The goal is to eventually use
    it to determine whether a gradient meets color contrast
    accessibility ratings when compared against another color or
    color gradient.

    In order to do this, the plan is to find
    the lightest color and the darkest color, so we can check both
    sides of the range. If the lightest or darkest color fails color
    contrast, then it's a fail. If both pass, then all colors in
    between will pass.

    Note: we may be adding more to this and refactoring functionality.

    Args:
        code: the color gradient value

    Returns:
        only_colors: a list of just color codes sorted by luminance
    """
    colors = []
    data = code.split("),")

    # split the last datum in data into two
    last_item = data[-1].strip()
    last_split = last_item.split("\n")
    if len(last_split) == 2:
        data.append(last_split[1])

    # remove all vendor prefixes
    pattern = regex_patterns["vendor_prefix"]
    for datum in data:
        datum = datum.strip()
        if not re.match(pattern, datum):
            colors.append(datum)

    # capture only color codes and append to colors
    only_colors = []
    if colors:
        # grab only color codes (Nothing else)
        for gradient in colors:
            color_codes = get_colors_from_gradient(gradient)
            if color_codes:
                only_colors += color_codes
    only_colors = sort_color_codes(only_colors)
    return only_colors

remove_alpha(color_code)

removes the alpha channel from rgba or hsla

Honestly, I'm not sure if this is even needed. I am looking to eventually move over to the APCA algorithm for testing color contrast accessibility, but at this point, I cannot find the algorithm. If and when I do, I will work to replace the current algorithm (WCAG AA/AAA rating).

Parameters:

Name Type Description Default
color_code str

the color code (hex, rgb, or hsl) with an alpha channel.

required

Returns:

Name Type Description
color_code str

the color code without the alpha channel.

Source code in webcode_tk/css_tools.py
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
def remove_alpha(color_code: str) -> str:
    """removes the alpha channel from rgba or hsla

    Honestly, I'm not sure if this is even needed. I am looking to
    eventually move over to the APCA algorithm for testing color
    contrast accessibility, but at this point, I cannot find the
    algorithm. If and when I do, I will work to replace the current
    algorithm (WCAG AA/AAA rating).

    Args:
        color_code: the color code (hex, rgb, or hsl) with an alpha
            channel.

    Returns:
        color_code: the color code without the alpha channel.
    """
    color_code = color_code.split(",")
    a = color_code[0].index("a")
    color_code[0] = color_code[0][:a] + color_code[0][a + 1 :]
    color_code.pop(-1)
    color_code = ",".join(color_code)
    color_code += ")"
    return color_code

restore_braces(split)

restore the missing braces removed by the .split() method

This is more of a helper function to make sure that after splitting at-rule code by two curly braces, we restore it back.

In CSS, to find the end of a nested @rule, you can use the following code: css_code.split("}}") This is because a nested @rule ends with two closing curly braces: one for the last declaration, and the other for the end of the nested @rule.

Parameters:

Name Type Description Default
split list

a list created by the split method on CSS code

required

Returns:

Name Type Description
list list

the list but with the double closing braces restored from the split.

Source code in webcode_tk/css_tools.py
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
def restore_braces(split: list) -> list:
    """restore the missing braces removed by the .split() method

    This is more of a helper function to make sure that after splitting
    at-rule code by two curly braces, we restore it back.

    In CSS, to find the end of a nested @rule, you can use the
    following code: `css_code.split("}}")` This is because a nested
    @rule ends with two closing curly braces: one for the last
    declaration, and the other for the end of the nested @rule.

    Args:
        split (list): a list created by the split method on CSS code

    Returns:
        list: the list but with the double closing braces restored from
            the split.
    """
    result = []
    split = tuple(split)
    if len(split) <= 1:
        return split
    for item in split:
        # only restore braces if there is an at-rule
        # this is more of a precaution in case there we
        # two closing brackets on accident.
        if len(item) > 0 and "@" in item:
            item = item + "}}"
            result.append(item)
    return result

separate_code(code)

splits code into two lists: code & comments

Parameters:

Name Type Description Default
code str

the stylesheet or style tag code

required

Returns:

Name Type Description
splitzky dict

a dictionary with two lists: a list of code snippets without comments, and a list of comments.

Raises:

Type Description
ValueError

if there is only one comment symbol: either / or / but not both (a syntax error)

Source code in webcode_tk/css_tools.py
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
def separate_code(code: str) -> dict:
    """splits code into two lists: code & comments

    Args:
        code (str): the stylesheet or style tag code

    Returns:
        splitzky: a dictionary with two lists: a list of code snippets
            without comments, and a list of comments.

    Raises:
        ValueError: if there is only one comment symbol: either /* or
            */ but not both (a syntax error)
    """
    code = code.strip()
    splitzky = {"code": [], "comments": []}

    new_code = []
    comments = []
    # Get positions of comments and place all code up to the comments
    # in code and comments in comments
    # do this till all code has been separated
    while code:
        positions = get_comment_positions(code)
        if positions and len(positions) == 2:
            start = positions[0]
            stop = positions[1]
            if code[:start]:
                new_code.append(code[:start])
            if code[start : stop + 2]:
                comments.append(code[start : stop + 2])
            code = code[stop + 2 :]
            code = code.strip()
        else:
            if "/*" not in code and "*/" not in code:
                new_code.append(code)
                code = ""
            else:
                # we're here because we have only one valid comment
                # symbol
                if "/*" in code:
                    has, has_not = (
                        "opening comment symbol: /*",
                        "closing comment symbol: */",
                    )
                else:
                    has, has_not = (
                        "closing comment symbol: */",
                        "opening comment symbol: /*",
                    )
                msg = "There's a syntax issue with your code comments."
                msg += " You have a {0} but no {1}.".format(has, has_not)
                raise ValueError(msg)
    splitzky["code"] = new_code
    splitzky["comments"] = comments
    return splitzky

sort_color_codes(codes)

sorts color codes from light to dark (luminance)

Parameters:

Name Type Description Default
codes Union[list, tuple]

a list or tuple of color values.

required

Returns:

Name Type Description
sorted list

a list of initial color values but in order from lightest to darkest (using luminance).

Source code in webcode_tk/css_tools.py
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
def sort_color_codes(codes: Union[list, tuple]) -> list:
    """sorts color codes from light to dark (luminance)

    Args:
        codes: a list or tuple of color values.

    Returns:
        sorted: a list of initial color values but in order from
            lightest to darkest (using luminance).
    """
    # convert code to rgb then calculate luminance
    colors = []
    for c in codes:
        # get the color type and convert to hsl
        temp_c = c
        color_type = color_tools.get_color_type(c)
        has_alpha = color_tools.has_alpha_channel(c)
        is_hex = color_tools.is_hex(temp_c)
        if has_alpha and not is_hex:
            temp_c = remove_alpha(c)
        if "hsl" not in color_type:
            if is_hex:
                rgb = color_tools.hex_to_rgb(temp_c)
            else:
                rgb = temp_c
        else:
            rgb = color_tools.hsl_to_rgb(c)
        if "<class 'str'>" == str(type(rgb)):
            r, g, b = color_tools.extract_rgb_from_string(rgb)
            light = color_tools.luminance((int(r), int(g), int(b)))
        else:
            light = color_tools.luminance(rgb)
        colors.append([light, c])
    colors.sort()
    colors.reverse()
    sorted = []
    for i in colors:
        sorted.append(i[1])
    return sorted

styles_applied_report(project_dir)

returns a report of all files in a project folder that apply styles

This lets us know for each HTML doc if they apply styles (pass) or if they do not apply styles (fail)

Parameters:

Name Type Description Default
project_dir str

a relative path to the project folder.

required

Returns:

Name Type Description
report list

a list of HTML docs and whether they pass or fail (pass) means they did apply styles and fail is the opposite.

Source code in webcode_tk/css_tools.py
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
def styles_applied_report(project_dir: str) -> list:
    """returns a report of all files in a project folder that apply styles

    This lets us know for each HTML doc if they apply styles (pass) or
    if they do not apply styles (fail)

    Args:
        project_dir: a relative path to the project folder.

    Returns:
        report: a list of HTML docs and whether they pass or fail (pass) means
            they did apply styles and fail is the opposite.
    """
    report = []
    html_files = clerk.get_all_files_of_type(project_dir, "html")
    for file in html_files:
        styles = get_all_stylesheets_by_file(file)
        if not styles:
            results = f"fail: {file} does NOT apply CSS."
        else:
            results = f"pass: {file} applies CSS."
        report.append(results)
    return report