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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
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
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
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_css_inheritance(computed_styles)

Apply traditional CSS inheritance for inheritable properties. Only inherit from the closest ancestor with an explicit rule.

Source code in webcode_tk/contrast_tools.py
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
def apply_css_inheritance(computed_styles: dict) -> None:
    """
    Apply traditional CSS inheritance for inheritable properties.
    Only inherit from the closest ancestor with an explicit rule.
    """
    inheritable_props = {"color", "font-size", "font-weight"}

    for child_element in computed_styles:
        child_styles = computed_styles[child_element]

        # find closest ancestor with explicit value
        for prop in inheritable_props:
            child_prop = child_styles.get(prop)

            # Skip if child has explicit CSS rule (not default)
            if child_prop and child_prop.get("source") not in [
                "default",
                None,
            ]:
                continue

            # Walk up tree to find first ancestor with explicit value
            current = child_element.parent
            inherited_value = None

            while current and not inherited_value:
                if current in computed_styles:
                    parent_styles = computed_styles[current]
                    parent_prop = parent_styles.get(prop)

                    # Found a parent with this property
                    if parent_prop:
                        # Only inherit if parent has explicit rule
                        if parent_prop.get("source") == "rule":
                            inherited_value = parent_prop
                            inherited_from = current
                            break  # ← Stop at first explicit ancestor

                current = current.parent

            # Apply inherited value if found
            if inherited_value:
                child_styles[prop] = {
                    "value": inherited_value["value"],
                    "specificity": inherited_value["specificity"],
                    "source": "inheritance",
                    "selector": inherited_value.get("selector", "inherited"),
                    "css_file": inherited_value.get("css_file"),
                    "css_source_type": inherited_value.get("css_source_type"),
                    "inherited_from": inherited_from,
                }

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
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
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
 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
 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
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

apply_visual_background_inheritance(computed_styles)

Apply visual background colors to elements without explicit backgrounds.

Parameters:

Name Type Description Default
computed_styles dict

a dictionary of elements with computed styles.

required

Returns: None

Source code in webcode_tk/contrast_tools.py
1183
1184
1185
1186
1187
1188
1189
1190
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
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
def apply_visual_background_inheritance(computed_styles: dict) -> None:
    """
    Apply visual background colors to elements without explicit backgrounds.

    Args:
        computed_styles: a dictionary of elements with computed styles.
    Returns:
        None
    """

    for element in computed_styles:
        element_styles = computed_styles[element]

        # Check for BOTH background-color AND background
        current_bg = element_styles.get("background-color")
        has_background_shorthand = "background" in element_styles

        # If element has background shorthand, process it for images
        if has_background_shorthand:
            bg_value = element_styles["background"]["value"]

            # Check if background contains a raster image
            if contains_raster_image(bg_value):
                # Mark as contrast-indeterminate - cannot analyze
                element_styles["background-color"] = {
                    "value": None,
                    "specificity": "000",
                    "contrast_analysis": "indeterminate",
                    "reason": "background_image_blocks_color_analysis",
                    "original_background": bg_value,
                    "visual_inheritance": False,
                }
                continue
            else:
                # Has usable background shorthand - skip inheritance
                continue
        if not current_bg:
            continue

        bg_source = current_bg.get("source")
        bg_value = current_bg.get("value")

        # Skip elements with explicit CSS rules
        if bg_source == "rule":
            continue

        # Only update elements that still have the default white background
        # This prevents overwriting elements with existing proper backgrounds
        if bg_source != "default":
            continue

        # Element needs background inheritance (lines 1120-1141)
        ancestor_bg = find_ancestor_background(element, computed_styles)

        if not ancestor_bg or ancestor_bg.get("source") == "default":
            # No explicit background to inherit - keep browser default
            continue

        if ancestor_bg.get("contrast_analysis") == "indeterminate":
            # Ancestor is indeterminate - propagate that status
            element_styles["background-color"] = {
                "value": None,
                "specificity": "000",
                "contrast_analysis": "indeterminate",
                "reason": ancestor_bg["reason"],
                "inherited_from": ancestor_bg["source_element"],
                "source": "visual_inheritance",
                "original_background": ancestor_bg.get("original_background"),
            }

        else:
            # Normal inheritance - extract usable color
            contrast_color = extract_contrast_color(ancestor_bg["value"])
            effective_color = (
                contrast_color if contrast_color else ancestor_bg["value"]
            )
            element_styles["background-color"] = {
                "value": effective_color,
                "specificity": "000",
                "source": "visual_inheritance",
                "inherited_from": ancestor_bg["source_element"],
                "contrast_analysis": "determinable",
                "original_background": (
                    ancestor_bg["value"]
                    if ancestor_bg["value"] != DEFAULT_GLOBAL_BACKGROUND
                    else None
                ),
            }

classify_font_unit(font_size_value)

Classify font-size unit type for analysis.

Source code in webcode_tk/contrast_tools.py
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
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
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
722
723
724
725
726
727
728
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

contains_raster_image(background_value)

Check if background contains a raster image that blocks color analysis.

Parameters:

Name Type Description Default
background_value str

the css value applied to the background property.

required

Returns:

Name Type Description
bool bool

whether the background value includes a raster image or not.

Source code in webcode_tk/contrast_tools.py
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
def contains_raster_image(background_value: str) -> bool:
    """Check if background contains a raster image that blocks color analysis.

    Args:
        background_value: the css value applied to the background property.

    Returns:
        bool: whether the background value includes a raster image or not.
    """
    # Add None check
    if background_value is None:
        return False

    return bool(
        re.search(
            r"url\([^)]*\.(jpg|jpeg|png|gif|webp|bmp)", background_value, re.I
        )
    )

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
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
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
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
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
1680
1681
1682
1683
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_contrast_color(background_value)

Extract usable color for contrast analysis, or None.

Parameters:

Name Type Description Default
background_value str

CSS background property value.

required

Returns:

Name Type Description
str str

Color value suitable for contrast analysis, or None if no usable color found.

Source code in webcode_tk/contrast_tools.py
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
def extract_contrast_color(background_value: str) -> str:
    """
    Extract usable color for contrast analysis, or None.

    Args:
        background_value (str): CSS background property value.

    Returns:
        str: Color value suitable for contrast analysis, or None if no
            usable color found.
    """
    # Add None check at the beginning
    if background_value is None:
        return None

    # Remove raster images - they block color visibility
    if re.search(
        r"url\([^)]*\.(jpg|jpeg|png|gif|webp|bmp)", background_value, re.I
    ):
        return None

    # Handle gradients - extract representative color
    if "gradient" in background_value.lower():
        return extract_gradient_contrast_color(background_value)

    # Handle solid colors
    re_pattern = r"(#[a-f0-9]{3,6}|rgb\([^)]+\)|rgba\([^)]+\)|hsl\([^)]+\)|"
    re_pattern += r"hsla\([^)]+\)|[a-z]+)"
    color_match = re.search(
        re_pattern,
        background_value,
        re.I,
    )
    return color_match.group(1) if color_match else None

extract_gradient_contrast_color(background_value)

Extract representative color from gradient for contrast analysis.

Parameters:

Name Type Description Default
background_value str

CSS gradient value (e.g., 'linear-gradient(red, blue)').

required

Returns:

Name Type Description
str str

Representative color for contrast analysis, or None if no color found.

Source code in webcode_tk/contrast_tools.py
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
def extract_gradient_contrast_color(background_value: str) -> str:
    """
    Extract representative color from gradient for contrast analysis.

    Args:
        background_value (str): CSS gradient value (e.g.,
            'linear-gradient(red, blue)').

    Returns:
        str: Representative color for contrast analysis, or None if no
            color found.
    """
    # Add None check
    if background_value is None:
        return None

    # Strategy: Use the final color in gradient (most visible for reading)
    # This handles: linear-gradient(red, blue) -> blue
    #              radial-gradient(center, red, blue) -> blue

    # Find all colors in gradient
    color_pattern = r"(#[a-f0-9]{3,6}|rgb\([^)]+\)|rgba\([^)]+\)|"
    color_pattern += r"hsl\([^)]+\)|hsla\([^)]+\)|[a-z]+)"
    colors = re.findall(color_pattern, background_value, re.I)

    if colors:
        # Use last color (end of gradient)
        return colors[-1]

    return None

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
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
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_ancestor_background(element, computed_styles)

Walk up DOM tree to find first ancestor with background.

Parameters:

Name Type Description Default
element Tag

BeautifulSoup Tag object to start searching from.

required
computed_styles dict

Dictionary mapping elements to their computed styles.

required

Returns:

Name Type Description
dict dict

Dictionary containing 'value' (background color) and 'source_element' (ancestor element or None).

Source code in webcode_tk/contrast_tools.py
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
1437
1438
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
1479
1480
1481
1482
1483
1484
1485
1486
def find_ancestor_background(element: Tag, computed_styles: dict) -> dict:
    """
    Walk up DOM tree to find first ancestor with background.

    Args:
        element (Tag): BeautifulSoup Tag object to start searching from.
        computed_styles (dict): Dictionary mapping elements to their
            computed styles.

    Returns:
        dict: Dictionary containing 'value' (background color) and
            'source_element' (ancestor element or None).
    """
    current = element.parent

    while current:
        if current in computed_styles:
            current_styles = computed_styles[current]

            # Flag to track if we should skip this ancestor
            skip_ancestor = False

            # Check for background-color or background
            for bg_prop in ["background-color", "background"]:
                if bg_prop in current_styles:
                    bg_source = current_styles[bg_prop].get("source")

                    # Skip elements that only have visual inheritance
                    if bg_source == "visual_inheritance":
                        skip_ancestor = True
                        break  # ✅ Break out of property loop

                    # Accept both "rule" and "default" sources
                    if bg_source in ["rule", "default"]:
                        bg_value = current_styles[bg_prop]["value"]
                        if bg_source == "default":
                            # Skip ancestors with only default backgrounds
                            skip_ancestor = True
                            break

                        # Does this ancestor already is indeterminate status
                        if (
                            current_styles[bg_prop].get("contrast_analysis")
                            == "indeterminate"
                        ):
                            return {
                                "value": None,
                                "source_element": current,
                                "contrast_analysis": "indeterminate",
                                "reason": "ancestor_has_background_image",
                                "original_background": current_styles[
                                    bg_prop
                                ].get("original_background", bg_value),
                            }

                        # Skip None values and continue searching
                        if bg_value is None:
                            continue  # Continue to next property

                        # Check if this background contains a raster image
                        if contains_raster_image(bg_value):
                            return {
                                "value": None,
                                "source_element": current,
                                "contrast_analysis": "indeterminate",
                                "reason": "ancestor_has_background_image",
                                "original_background": bg_value,
                            }

                        # Found explicit background
                        bg_items = current_styles[bg_prop].items()
                        return {
                            "value": bg_value,
                            "source_element": current,
                            "contrast_analysis": "determinable",
                            # Copy metadata from ancestor
                            **{
                                metadata_key: metadata_value
                                for metadata_key, metadata_value in bg_items
                                if metadata_key not in ["value"]
                            },
                        }

            # If we flagged this ancestor to skip, move to next ancestor
            if skip_ancestor:
                current = current.parent
                continue  # ✅ Now this continues to next ancestor

        current = current.parent

    # No ancestor background found, use default
    return {
        "value": DEFAULT_GLOBAL_BACKGROUND,
        "source_element": None,
        "contrast_analysis": "determinable",
        "source": "default",
    }

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
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
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
 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
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
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
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": "