Skip to content

contrast_tools.py

Contrast Tools Tools for determining CSS as applied through inheritance and the cascade.

This module analyzes the DOM, inheritance, and the cascade to determine all styles applied to every element on a page. It scans each stylesheet and applies each style, one at a time, to all applicable elements and their children.

Constants

DEFAULT_GLOBAL_COLOR (str): Default text color for all elements (#000000). DEFAULT_GLOBAL_BACKGROUND (str): Default background color (#ffffff). DEFAULT_LINK_COLOR (str): Default color for unvisited links (#0000EE). DEFAULT_LINK_VISITED (str): Default color for visited links (#551A8B). ROOT_FONT_SIZE (int): Base font size in pixels for root element (16). IS_BOLD (list[str]): HTML elements that are bold by default. HEADING_FONT_SIZES (dict[str, int]): Default font sizes for heading elements in pixels (h1-h6). WCAG_AA_NORMAL (float): WCAG AA contrast ratio threshold for normal text (4.5). WCAG_AA_LARGE (float): WCAG AA contrast ratio threshold for large text (3.0). WCAG_AAA_NORMAL (float): WCAG AAA contrast ratio threshold for normal text (7.0). WCAG_AAA_LARGE (float): WCAG AAA contrast ratio threshold for large text (4.5). LARGE_TEXT_SIZE_PX (float): Minimum font size in pixels for large text (24.0). LARGE_TEXT_BOLD_SIZE_PX (float): Minimum font size in pixels for large bold text (18.66). CONTRAST_RELEVANT_PROPERTIES (tuple): properties that directly impact the mathematical contrast ratios and size thresholds that determine WCAG compliance.

analyze_contrast(project_folder)

Analyzes color contrast for all HTML documents in the given project folder.

Parameters:

Name Type Description Default
project_folder str

Path to the root folder of the website project.

required

Returns:

Type Description
list[dict]

list[dict]: List of dictionaries with contrast analysis results for

list[dict]

each element.

Source code in webcode_tk/contrast_tools.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def analyze_contrast(project_folder: str) -> list[dict]:
    """
    Analyzes color contrast for all HTML documents in the given project
    folder.

    Args:
        project_folder (str): Path to the root folder of the website project.

    Returns:
        list[dict]: List of dictionaries with contrast analysis results for
        each element.
    """

    project_contrast_results = []
    parsed_html_docs = get_parsed_documents(project_folder)
    css_files = load_css_files(parsed_html_docs, project_folder)

    # Analyze CSS Files
    for html_doc in parsed_html_docs:
        doc_results = analyze_css(html_doc, css_files, project_folder)
        project_contrast_results.extend(doc_results)
    return project_contrast_results

analyze_css(html_doc, css_files, project_path='')

Analyzes CSS application and color contrast for a single HTML document.

Parameters:

Name Type Description Default
html_doc dict

Dictionary containing 'filename' and 'soup' for an HTML document.

required
css_files list[dict]

List of dictionaries containing parsed CSS sources for all HTML files, with each dict mapping filename to CSS sources in cascade order.

required

Returns:

Type Description
list[dict]

list[dict]: List of dictionaries with contrast analysis results for each element in this HTML document. Each result contains element info, computed styles, colors, contrast ratio, and WCAG compliance.

Source code in webcode_tk/contrast_tools.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
def analyze_css(
    html_doc: dict, css_files: list[dict], project_path=""
) -> list[dict]:
    """
    Analyzes CSS application and color contrast for a single HTML document.

    Args:
        html_doc (dict): Dictionary containing 'filename' and 'soup' for an
            HTML document.
        css_files (list[dict]): List of dictionaries containing parsed CSS
            sources for all HTML files, with each dict mapping filename to
            CSS sources in cascade order.

    Returns:
        list[dict]: List of dictionaries with contrast analysis results for
            each element in this HTML document. Each result contains element
            info, computed styles, colors, contrast ratio, and WCAG
            compliance.
    """
    doc_results = []
    filename = html_doc["filename"]
    soup = html_doc["soup"]

    # Check to see if background color was set globally
    global_bg = detect_document_background(project_path, filename)

    # Check for CSS sources and create warnings if needed
    warnings = []

    if not has_any_css_sources(soup):
        message = f"{filename} has no CSS sources "
        message += "(no <link> or <style> tags)"
        warnings.append(
            {
                "type": "no_css_sources",
                "message": message,
                "impact": "Only browser defaults will be applied",
            }
        )

    # Step 1: Apply default styles to all elements
    default_styles = apply_browser_defaults(soup, default_bg=global_bg)

    # Find CSS rules specific to this HTML document
    doc_css_rules = get_css_rules_for_document(filename, css_files)

    # Additional warning if no CSS rules found
    if not doc_css_rules or all(len(rules) <= 1 for rules in doc_css_rules):
        warnings.append(
            {
                "type": "no_css_rules",
                "message": f"{filename} has no CSS rules to process",
                "impact": "Results will only show browser default styling",
            }
        )

    # Apply CSS rules to elements and compute styles
    computed_styles = compute_element_styles(
        soup, doc_css_rules, default_styles
    )

    # Traverse DOM and analyze contrast for elements with text
    doc_results = analyze_elements_for_contrast(computed_styles, filename)

    # Add warnings to results if any exist
    if warnings:
        for warning in warnings:
            warning_result = {
                "filename": filename,
                "element_tag": None,
                "element_id": None,
                "element_class": None,
                "text_content": None,
                "text_color": None,
                "text_color_source": None,
                "background_color": None,
                "background_color_source": None,
                "font_size_px": None,
                "font_weight": None,
                "is_large_text": None,
                "contrast_ratio": None,
                "wcag_aa_pass": None,
                "wcag_aaa_pass": None,
                "contrast_analysis": "warning",
                "warning_type": warning["type"],
                "warning_message": warning["message"],
                "warning_impact": warning["impact"],
            }
            doc_results.append(warning_result)
    return doc_results

analyze_elements_for_contrast(computed_styles, filename)

Returns a list of elements with text with contrast results

Parameters:

Name Type Description Default
computed_styles dict

a dictionary of elements with font size, background color, color, and any other pertinent metadata

required
filename str

the name of the HTML document.

required

Returns:

Name Type Description
contrast_results list

a list of all elements that contain content

Source code in webcode_tk/contrast_tools.py
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
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
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
def analyze_elements_for_contrast(
    computed_styles: dict, filename: str
) -> list:
    """Returns a list of elements with text with contrast results

    Args:
        computed_styles: a dictionary of elements with font size, background
            color, color, and any other pertinent metadata
        filename: the name of the HTML document.

    Returns:
        contrast_results: a list of all elements that contain content
    """
    contrast_results = []

    for element in computed_styles:
        # filter out any element that doesn't directly render text
        direct_text = get_direct_text(element)
        if not direct_text:
            continue

        # get element contrast data
        element_data = computed_styles.get(element)
        font_size = element_data["font-size"].get("value")
        size, unit = font_tools.split_value_unit(font_size)
        font_size = font_tools.compute_font_size(size, unit)
        font_weight = element_data.get("font-weight").get("value")
        is_large = is_large_text(font_size, font_weight)
        text_color = element_data["color"].get("value")
        color_hex = color_tools.get_hex(text_color)
        text_bg = element_data["background-color"].get("value")
        bg_hex = color_tools.get_hex(text_bg)
        contrast_ratio = color_tools.contrast_ratio(color_hex, bg_hex)

        # Round to 1 decimal place before running the report
        contrast_ratio = round(contrast_ratio, 1)
        contrast_report = color_tools.get_color_contrast_report(
            color_hex, bg_hex
        )
        contrast_analysis = element_data["background-color"].get(
            "contrast_analysis"
        )

        if is_large:
            aaa_results = contrast_report.get("Large AAA")
            aa_results = contrast_report.get("Large AA")
        else:
            aaa_results = contrast_report.get("Normal AAA")
            aa_results = contrast_report.get("Normal AA")

        # apply results
        element_result = {
            "filename": filename,
            "element_tag": element.name,
            "element_id": element.get("id"),
            "element_class": element.get("class"),
            "text_content": direct_text,
            # Color values and their sources
            "text_color": text_color,
            "text_color_source": extract_property_source(
                element_data["color"]
            ),
            "background_color": text_bg,
            "background_color_source": extract_property_source(
                element_data["background-color"]
            ),
            # Font and contrast results
            "font_size_px": font_size,
            "font_weight": font_weight,
            "is_large_text": is_large,
            "contrast_ratio": contrast_ratio,
            "wcag_aa_pass": aa_results,
            "wcag_aaa_pass": aaa_results,
            "contrast_analysis": contrast_analysis,
        }

        # add to results
        contrast_results.append(element_result)
    return contrast_results

append_style_data(html_file, sheet, href, parsed, css_source)

Append CSS style data to css_source dictionary.

Parameters:

Name Type Description Default
html_file str

HTML filename.

required
sheet dict

Sheet metadata dictionary.

required
href str

CSS file href or identifier.

required
parsed list

Parsed CSS rules from tinycss2.

required
css_source dict

Dictionary to append data to (modified in place).

required

Returns:

Name Type Description
None None

Modifies css_source dictionary in place.

Source code in webcode_tk/contrast_tools.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def append_style_data(
    html_file: str, sheet: dict, href: str, parsed: list, css_source: dict
) -> None:
    """
    Append CSS style data to css_source dictionary.

    Args:
        html_file (str): HTML filename.
        sheet (dict): Sheet metadata dictionary.
        href (str): CSS file href or identifier.
        parsed (list): Parsed CSS rules from tinycss2.
        css_source (dict): Dictionary to append data to (modified in place).

    Returns:
        None: Modifies css_source dictionary in place.
    """
    data = {}
    data["source_type"] = sheet.get("type")
    data["css_name"] = href
    data["stylesheet"] = parsed
    css_source[html_file].append(data)

apply_browser_defaults(soup, default_bg=DEFAULT_GLOBAL_BACKGROUND)

Apply browser default styles to all elements with text content.

Returns:

Name Type Description
dict dict

Mapping of elements to their default computed styles

Source code in webcode_tk/contrast_tools.py
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
def apply_browser_defaults(
    soup: BeautifulSoup, default_bg: str = DEFAULT_GLOBAL_BACKGROUND
) -> dict:
    """
    Apply browser default styles to all elements with text content.

    Returns:
        dict: Mapping of elements to their default computed styles
    """
    element_styles = {}
    default_specificity = css_tools.get_specificity("")

    for element in soup.descendants:
        # Skip non-tag elements
        if not isinstance(element, Tag):
            continue

        # Always include html and body elements for inheritance chain
        is_structural = element.name in ["html", "body"]
        has_text = not element.is_empty_element and element.get_text(
            strip=True
        )

        if is_structural or has_text:
            # The element object itself becomes the key
            element_styles[element] = {
                "color": {
                    "value": DEFAULT_GLOBAL_COLOR,
                    "specificity": default_specificity,
                    "source": "default",
                    "is_default": True,
                },
                "background-color": {
                    "value": default_bg,
                    "specificity": default_specificity,
                    "source": "default",
                    "is_default": True,
                },
                "font-size": {
                    "value": f"{ROOT_FONT_SIZE}px",
                    "specificity": default_specificity,
                    "source": "default",
                    "is_default": True,
                },
                "font-weight": {
                    "value": "bold" if element.name in IS_BOLD else "normal",
                    "specificity": default_specificity,
                    "source": "default",
                    "is_default": True,
                },
            }

            if element.name in ["html", "body"]:
                print(f"  ✓ Added <{element.name}> to element_styles")
            # Apply element-specific defaults
            # Apply link colors
            if element.name == "a":
                element_styles[element]["color"] = {
                    "value": DEFAULT_LINK_COLOR,
                    "specificity": default_specificity,
                }
                element_styles[element]["visited-color"] = {
                    "value": DEFAULT_LINK_VISITED,
                    "specificity": default_specificity,
                }
            if element.name in HEADING_FONT_SIZES:
                element_styles[element]["font-size"] = {
                    "value": f"{HEADING_FONT_SIZES[element.name]}px",
                    "specificity": default_specificity,
                    "source": "default",
                    "is_default": True,
                }
    return element_styles

apply_inheritance(soup, computed_styles)

Applies CSS inheritance rules, copying inheritable property values from parent elements to child elements.

Parameters:

Name Type Description Default
soup BeautifulSoup

Parsed HTML document for DOM traversal.

required
computed_styles dict

Dictionary mapping elements to their computed styles (modified in place).

required

Returns:

Name Type Description
None None

Modifies computed_styles dictionary in place.

Source code in webcode_tk/contrast_tools.py
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
def apply_inheritance(soup: BeautifulSoup, computed_styles: dict) -> None:
    """
    Applies CSS inheritance rules, copying inheritable property values from
    parent elements to child elements.

    Args:
        soup (BeautifulSoup): Parsed HTML document for DOM traversal.
        computed_styles (dict): Dictionary mapping elements to their computed
            styles (modified in place).

    Returns:
        None: Modifies computed_styles dictionary in place.
    """
    # Step 1: Apply true CSS inheritance (color, font properties)
    apply_css_inheritance(computed_styles)

    # Step 2: Apply visual background inheritance
    apply_visual_background_inheritance(computed_styles)

apply_rule_to_element(element, rule, computed_styles, css_source_info=None)

Applies CSS declarations from a rule to a specific element, handling specificity conflicts.

Parameters:

Name Type Description Default
element Tag

BeautifulSoup Tag object representing the target element.

required
rule dict

CSS rule dictionary containing 'selector' and 'declarations'.

required
computed_styles dict

Dictionary mapping elements to their current computed styles (modified in place).

required
css_source_info dict

Information about the CSS source.

None

Returns:

Name Type Description
None None

Modifies computed_styles dictionary in place.

Source code in webcode_tk/contrast_tools.py
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 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
 889
 890
 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
 920
 921
 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
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
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
1033
1034
1035
1036
def apply_rule_to_element(
    element: Tag,
    rule: dict,
    computed_styles: dict,
    css_source_info: dict = None,
) -> None:
    """
    Applies CSS declarations from a rule to a specific element, handling
    specificity conflicts.

    Args:
        element: BeautifulSoup Tag object representing the target element.
        rule (dict): CSS rule dictionary containing 'selector' and
            'declarations'.
        computed_styles (dict): Dictionary mapping elements to their current
            computed styles (modified in place).
        css_source_info (dict): Information about the CSS source.

    Returns:
        None: Modifies computed_styles dictionary in place.
    """
    # Check if element of key exists
    element_styles = computed_styles.get(element)
    if element_styles:
        selector = rule.get("selector")
        rule_specificity = css_tools.get_specificity(selector)
        declarations = rule.get("declarations", {})

        for property_name, property_value in declarations.items():
            if property_name not in CONTRAST_RELEVANT_PROPERTIES:
                continue

            # Special handling for font-size - convert to pixels
            # and store enhanced data
            if property_name == "font-size":
                original_value = property_value
                computed_pixels = convert_font_size_to_pixels(
                    property_value, element, computed_styles
                )

                # Classify unit type for debugging/analysis
                unit_type = classify_font_unit(original_value)

                font_size_data = {
                    "value": computed_pixels,
                    "original_value": original_value,
                    "unit_type": unit_type,
                    "specificity": rule_specificity,
                    "source": "rule",
                    "selector": selector,
                    "css_file": (
                        css_source_info.get("filename")
                        if css_source_info
                        else None
                    ),
                    "css_source_type": (
                        css_source_info.get("source_type")
                        if css_source_info
                        else None
                    ),
                }

                # Check if we should apply this font-size rule
                current_prop = computed_styles[element].get(property_name)
                should_apply = False

                if current_prop is None:
                    should_apply = True
                elif (
                    isinstance(current_prop, dict)
                    and "specificity" in current_prop
                ):
                    current_specificity = current_prop["specificity"]
                    if isinstance(current_specificity, tuple):
                        current_specificity = "".join(
                            map(str, current_specificity)
                        )
                    if rule_specificity >= current_specificity:
                        should_apply = True
                else:
                    should_apply = True

                if should_apply:
                    computed_styles[element][property_name] = font_size_data

            # Special handling for background-color and background
            elif property_name in ["background-color", "background"]:
                # Check if this background contains a raster image
                if contains_raster_image(property_value):
                    background_data = {
                        "value": None,
                        "specificity": rule_specificity,
                        "source": "rule",
                        "selector": selector,
                        "css_file": (
                            css_source_info.get("filename")
                            if css_source_info
                            else None
                        ),
                        "css_source_type": (
                            css_source_info.get("source_type")
                            if css_source_info
                            else None
                        ),
                        "contrast_analysis": "indeterminate",
                        "reason": "background_image_blocks_color_analysis",
                        "original_background": property_value,
                    }
                else:
                    # Extract usable color for contrast analysis
                    contrast_color = extract_contrast_color(property_value)
                    effective_color = (
                        contrast_color if contrast_color else property_value
                    )

                    background_data = {
                        "value": effective_color,
                        "specificity": rule_specificity,
                        "source": "rule",
                        "selector": selector,
                        "css_file": (
                            css_source_info.get("filename")
                            if css_source_info
                            else None
                        ),
                        "css_source_type": (
                            css_source_info.get("source_type")
                            if css_source_info
                            else None
                        ),
                        "contrast_analysis": "determinable",
                        "original_background": (
                            property_value
                            if property_value != effective_color
                            else None
                        ),
                    }

                # Apply specificity logic and set the property
                current_prop = computed_styles[element].get(property_name)
                should_apply = False

                if current_prop is None:
                    should_apply = True
                elif (
                    isinstance(current_prop, dict)
                    and "specificity" in current_prop
                ):
                    current_specificity = current_prop["specificity"]
                    if isinstance(current_specificity, tuple):
                        current_specificity = "".join(
                            map(str, current_specificity)
                        )
                    if rule_specificity >= current_specificity:
                        should_apply = True
                else:
                    should_apply = True

                if should_apply:
                    computed_styles[element][property_name] = background_data

            else:
                # Regular property handling for non-font-size, non-background
                # properties
                # ... rest of your existing else block code ...
                # Regular property handling for non-font-size properties
                current_prop = computed_styles[element].get(property_name)
                should_apply = False

                if current_prop is None:
                    # property doesn't exist, apply it
                    should_apply = True
                elif (
                    isinstance(current_prop, dict)
                    and "specificity" in current_prop
                ):
                    # property exists with specificity info
                    current_specificity = current_prop["specificity"]
                    if isinstance(current_specificity, tuple):
                        current_specificity = "".join(
                            map(str, current_specificity)
                        )
                    if rule_specificity >= current_specificity:
                        should_apply = True
                else:
                    # property exists but no specificity (default)
                    should_apply = True
                if should_apply:
                    computed_styles[element][property_name] = {
                        "value": property_value,
                        "specificity": rule_specificity,
                        "source": "rule",
                        "selector": selector,
                        "css_file": (
                            css_source_info.get("filename")
                            if css_source_info
                            else None
                        ),
                        "css_source_type": (
                            css_source_info.get("source_type")
                            if css_source_info
                            else None
                        ),
                    }

    return

classify_font_unit(font_size_value)

Classify font-size unit type for analysis.

Source code in webcode_tk/contrast_tools.py
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
def classify_font_unit(font_size_value: str) -> str:
    """Classify font-size unit type for analysis."""
    if re.match(r"^\d*\.?\d+(px|pt|pc|in|cm|mm)$", font_size_value, re.I):
        return "absolute"
    # Match number + unit pattern for relative units
    elif re.match(r"^\d*\.?\d+(em|rem|%)$", font_size_value, re.I):
        return "relative"
    elif font_size_value.lower() in ["larger", "smaller"]:
        return "relative_keyword"
    elif font_size_value.lower() in [
        "xx-small",
        "x-small",
        "small",
        "medium",
        "large",
        "x-large",
        "xx-large",
    ]:
        return "absolute_keyword"
    else:
        return "unknown"

compute_element_styles(soup, css_rules, default_styles)

Computes final styles for all elements by applying CSS rules and inheritance.

Parameters:

Name Type Description Default
soup BeautifulSoup

Parsed HTML document.

required
css_rules list[dict]

List of CSS rule dictionaries with selectors and declarations.

required
default_styles dict

Dictionary mapping elements to their default browser styles.

required

Returns:

Name Type Description
dict dict

Dictionary mapping elements to their final computed styles after applying CSS cascade and inheritance.

Source code in webcode_tk/contrast_tools.py
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
def compute_element_styles(
    soup: BeautifulSoup, css_rules: list[dict], default_styles: dict
) -> dict:
    """
    Computes final styles for all elements by applying CSS rules and
    inheritance.

    Args:
        soup (BeautifulSoup): Parsed HTML document.
        css_rules (list[dict]): List of CSS rule dictionaries with selectors
            and declarations.
        default_styles (dict): Dictionary mapping elements to their default
            browser styles.

    Returns:
        dict: Dictionary mapping elements to their final computed styles
            after applying CSS cascade and inheritance.
    """
    # ✅ NEW: Shallow copy of dict, deep copy only the style values
    computed_styles = {}
    for element, styles in default_styles.items():
        # Keep the SAME element object (preserves parent relationship)
        # but deep copy its styles dictionary
        computed_styles[element] = copy.deepcopy(styles)

    # Step 2: Apply all CSS rules (cascade resolution)
    for rules_list in css_rules:
        # Extract source data (first item in the list)
        source_data = rules_list[0]
        actual_rules = rules_list[1:]

        # Create CSS source info object
        css_source_info = {
            "filename": source_data.get("css_name"),
            "source_type": source_data.get("source_type"),
        }
        # Now iterate over the actual CSS rules
        for rule in actual_rules:
            # Find elements that match this rule's selector
            matching_elements = find_matching_elements(soup, rule["selector"])

            # Apply the rule to each matching element
            for element in matching_elements:
                apply_rule_to_element(
                    element, rule, computed_styles, css_source_info
                )

    # Step 3: Apply inheritance (after all rules processed)
    apply_inheritance(soup, computed_styles)

    return computed_styles

convert_font_size_to_pixels(font_size_value, element, computed_styles)

Converts font-size values to pixels for WCAG analysis using font_tools.

Parameters:

Name Type Description Default
font_size_value str

CSS font-size value (e.g., "2em", "120%", "16px")

required
element Tag

BeautifulSoup element for context

required
computed_styles dict

Current computed styles for inheritance context

required

Returns:

Name Type Description
str str

Font size converted to pixels (e.g., "32.0px")

Source code in webcode_tk/contrast_tools.py
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
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
def convert_font_size_to_pixels(
    font_size_value: str, element: Tag, computed_styles: dict
) -> str:
    """
    Converts font-size values to pixels for WCAG analysis using font_tools.

    Args:
        font_size_value (str): CSS font-size value (e.g., "2em", "120%",
            "16px")
        element: BeautifulSoup element for context
        computed_styles (dict): Current computed styles for inheritance
            context

    Returns:
        str: Font size converted to pixels (e.g., "32.0px")
    """
    font_size_value = font_size_value.strip()

    # Use font_tools to split value and unit
    try:
        value, unit = split_value_unit(font_size_value)

        # Get parent font size for relative calculations
        parent_font_size_px = get_parent_font_size(element, computed_styles)

        # Get element name for heading-specific calculations
        element_name = element.name if element else ""

        # Use your comprehensive compute_font_size function
        computed_px = compute_font_size(
            value=value,
            unit=unit,
            parent_size=parent_font_size_px,
            element_name=element_name,
        )

        return f"{computed_px:.1f}px"

    except Exception as e:
        # Fallback for parsing errors
        print(f"DEBUG: Exception caught: '{e}'")
        return f"{font_size_value}px"  # Assume it's already in pixels

detect_document_background(project_path, filename)

Detect global background color from CSS rules for this document.

Parameters:

Name Type Description Default
project_path str

Path to project root

required
filename str

Name of current HTML file

required

Returns:

Name Type Description
str str

Background color hex value, or DEFAULT_GLOBAL_BACKGROUND if none found

Source code in webcode_tk/contrast_tools.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
def detect_document_background(project_path: str, filename: str) -> str:
    """
    Detect global background color from CSS rules for this document.

    Args:
        project_path: Path to project root
        filename: Name of current HTML file

    Returns:
        str: Background color hex value, or DEFAULT_GLOBAL_BACKGROUND if
            none found
    """
    # Get global colors for entire project
    global_colors = css_tools.get_project_global_colors(project_path)

    # Find entry for this specific HTML file
    for file_path, color_data_list in global_colors.items():
        # Match filename (handle both full path and just filename)
        if filename in file_path:
            # color_data_list is a list of dicts with global selector info
            if isinstance(color_data_list, dict):
                color_data_list = [
                    color_data_list,
                ]
            for color_data in color_data_list:
                # Look for body selector specifically
                if color_data.get("selector") == "body":
                    bg_color = color_data.get("background-color")
                    if bg_color:
                        return bg_color

                # Also check for html or * selectors
                if color_data.get("selector") in ["html", "*"]:
                    bg_color = color_data.get("background-color")
                    if bg_color:
                        return bg_color

    # No global background found, use default white
    return DEFAULT_GLOBAL_BACKGROUND

element_name_or_default(property_data)

Get element name for default styling or fallback.

Source code in webcode_tk/contrast_tools.py
1377
1378
1379
1380
def element_name_or_default(property_data: dict) -> str:
    """Get element name for default styling or fallback."""
    # You might need to pass element context here
    return "default"

extract_property_source(property_data)

Extract source information from a computed property.

Parameters:

Name Type Description Default
property_data dict

Property dictionary with metadata

required

Returns:

Name Type Description
dict dict

Source information for reporting

Source code in webcode_tk/contrast_tools.py
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
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
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
def extract_property_source(property_data: dict) -> dict:
    """
    Extract source information from a computed property.

    Args:
        property_data (dict): Property dictionary with metadata

    Returns:
        dict: Source information for reporting
    """
    if not property_data:
        return {
            "source_type": "missing",
            "css_file": None,
            "selector": None,
            "inherited_from": None,
        }

    source_type = property_data.get("source", "unknown")

    if source_type == "inheritance":
        return {
            "source_type": "inherited",
            "css_file": property_data.get("css_file"),
            "selector": property_data.get("selector"),
            "inherited_from": getattr(
                property_data.get("inherited_from"), "name", None
            ),
        }
    elif source_type == "visual_inheritance":
        inherited_element = property_data.get("inherited_from")
        return {
            "source_type": "visual_inheritance",
            "css_file": "visual_cascade",
            "selector": "ancestor_background",
            "inherited_from": (
                getattr(inherited_element, "name", None)
                if inherited_element
                else None
            ),
        }
    elif source_type == "rule":
        return {
            "source_type": "css_rule",
            "css_file": property_data.get("css_file"),
            "selector": property_data.get("selector"),
            "inherited_from": None,
        }
    elif source_type == "default":
        return {
            "source_type": "browser_default",
            "css_file": "user_agent_stylesheet",
            "selector": element_name_or_default(property_data),
            "inherited_from": None,
        }
    else:
        return {
            "source_type": source_type,
            "css_file": property_data.get("css_file"),
            "selector": property_data.get("selector"),
            "inherited_from": None,
        }

find_matching_elements(soup, selector)

Finds all elements in the DOM that match a given CSS selector.

Parameters:

Name Type Description Default
soup BeautifulSoup

Parsed HTML document.

required
selector str

CSS selector string (e.g., "p", ".class", "#id").

required

Returns:

Type Description
list

list[Tag]: List of BeautifulSoup Tag objects that match the selector.

Source code in webcode_tk/contrast_tools.py
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
766
767
768
769
def find_matching_elements(soup: BeautifulSoup, selector: str) -> list:
    """
    Finds all elements in the DOM that match a given CSS selector.

    Args:
        soup (BeautifulSoup): Parsed HTML document.
        selector (str): CSS selector string (e.g., "p", ".class", "#id").

    Returns:
        list[Tag]: List of BeautifulSoup Tag objects that match the selector.
    """

    # Clean and validate
    selector = selector.strip()

    # Handle empty selectors
    if not selector:
        return []

    # Check for valid, but not supported by bs4 selectors
    if not is_selector_supported_by_bs4(selector):
        warning = f"Warning: Selector '{selector}' contains features not "
        warning += "supported by BS4"
        print(warning)
        return []

    # Try BeautifulSoup's select method
    try:
        return soup.select(selector)
    except Exception as e:
        print(f"Error parsing selector '{selector}': {e}")
        return []

generate_contrast_report(project_path, wcag_level='AAA')

returns a report on a project's color contrast results.

Gets all contrast results (all elements that contains text), filters out warning entries, identify any failures. If there are no failures in a doc, then append a single pass for the file. Append a fail message for each element that fails to mee contrast requirement.

Example Output: [ "pass: index.html passes color contrast.", "fail: in about.html, the

element failed WCAG AA contrast requirements (ratio: 3.2, required: 4.5).", "fail: in about.html, the

element failed WCAG AA contrast requirements (ratio: 2.1, required: 4.5).", "pass: contact.html passes color contrast.", "fail: in gallery.html, the element failed WCAG AA contrast requirements (indeterminate due to background image)." ]

Parameters:

Name Type Description Default
project_path str

the web project's root folder.

required
wcag_level str

the WCAG level (AAA or AA).

'AAA'

Returns:

Name Type Description
report list[str]

the list of strings to determine whether a page passes or fails.

Source code in webcode_tk/contrast_tools.py
 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
def generate_contrast_report(
    project_path: str, wcag_level: str = "AAA"
) -> list[str]:
    """returns a report on a project's color contrast results.

    Gets all contrast results (all elements that contains text), filters out
    warning entries, identify any failures. If there are no failures in a doc,
    then append a single pass for the file. Append a fail message for each
    element that fails to mee contrast requirement.

    Example Output:
    [
        "pass: index.html passes color contrast.",
        "fail: in about.html, the <h1> element failed WCAG AA contrast
            requirements (ratio: 3.2, required: 4.5).",
        "fail: in about.html, the <p class='intro'> element failed WCAG AA
            contrast requirements (ratio: 2.1, required: 4.5).",
        "pass: contact.html passes color contrast.",
        "fail: in gallery.html, the <a id='nav-home'> element failed WCAG AA
            contrast requirements (indeterminate due to background image)."
    ]

    Args:
        project_path: the web project's root folder.
        wcag_level: the WCAG level (AAA or AA).

    Returns:
        report: the list of strings to determine whether a page passes
            or fails.

    """
    report = []
    project_files = {}
    wcag_level_key = f"wcag_{wcag_level}_pass".lower()

    # Collect data from project folder
    contrast_data = analyze_contrast(project_path)

    # Analayze documents
    for item in contrast_data:
        current_file = item.get("filename")
        if current_file not in project_files:
            project_files[current_file] = []

        # Check if fails WCAG level
        result = item.get(wcag_level_key)

        if result:
            result = result.lower()
        else:
            warning_msg = item.get("warning_message")
            warning_msg = "fail: " + warning_msg
            project_files[current_file].append(warning_msg)
            continue
        if result == "fail":
            # collect data
            element = item.get("element_tag")
            is_large = item.get("is_large_text")
            if is_large:
                if wcag_level == "AAA":
                    target_ratio = WCAG_AAA_LARGE
                else:
                    target_ratio = WCAG_AA_LARGE
            else:
                if wcag_level == "AAA":
                    target_ratio = WCAG_AAA_NORMAL
                else:
                    target_ratio = WCAG_AA_NORMAL
            actual_ratio = item.get("contrast_ratio")
            actual_ratio = round(actual_ratio, 1)

            msg = f"{result}: in {current_file}, the <{element}> element"
            msg += f" WCAG {wcag_level} contrast requirements with a "
            msg += f"ratio of {actual_ratio} (min: {target_ratio})."

            if msg not in project_files[current_file]:
                project_files[current_file].append(msg)

    # Check for html docs with no fails.
    for file in project_files:
        errors = project_files.get(file)

        # Now append to report
        if errors:
            if "has no CSS" in errors[0]:
                report.append(errors[0])
            else:
                report.extend(errors)
        else:
            # File has no element-level failures
            msg = f"pass: {file} passes color contrast."
            report.append(msg)

    return report

get_css_rules_for_document(filename, css_files)

Extracts CSS rules specific to a given HTML document from the CSS files list.

Parameters:

Name Type Description Default
filename str

The HTML filename to find CSS rules for.

required
css_files list[dict]

List of dictionaries containing parsed CSS sources for all HTML files, with each dict mapping filename to CSS sources in cascade order.

required

Returns:

Type Description
list[dict]

list[dict]: List of CSS rule dictionaries for the specified HTML document, maintaining the cascade order.

Source code in webcode_tk/contrast_tools.py
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
def get_css_rules_for_document(
    filename: str, css_files: list[dict]
) -> list[dict]:
    """
    Extracts CSS rules specific to a given HTML document from the CSS files
    list.

    Args:
        filename (str): The HTML filename to find CSS rules for.
        css_files (list[dict]): List of dictionaries containing parsed CSS
            sources for all HTML files, with each dict mapping filename to
            CSS sources in cascade order.

    Returns:
        list[dict]: List of CSS rule dictionaries for the specified HTML
            document, maintaining the cascade order.
    """
    css_rules = []
    for sheet in css_files:
        if sheet.get(filename):
            source = sheet.get(filename)[0]
            if source.get("source_type") == "internal":
                source["css_name"] = f"style_tag--{filename}"
            parsed_styles = source.get("stylesheet")
            rules = parse_css_rules_from_tinycss2(parsed_styles)
            rules = [
                source,
            ] + rules
            css_rules.append(rules)
    return css_rules

get_css_source_order(soup)

Returns the ordered list of CSS sources (external stylesheets and internal style tags) as they appear in the of the HTML document.

Parameters:

Name Type Description Default
soup BeautifulSoup

Parsed BeautifulSoup object of the HTML document.

required

Returns:

Type Description
list[dict]

list[dict]: A list of dictionaries, each representing a CSS source in

list[dict]

order. For external stylesheets: {"type": "external", "href": ""} For internal style tags: {"type": "internal", "content": "