File size: 4,330 Bytes
daac93a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import re
import streamlit as st
from bs4 import BeautifulSoup
from copy import deepcopy

def parse_variable_file(variable_content):
    """Parses the SCSS variable content and returns a mapping of color names to their values."""
    variables = {}
    
    # Print the variables content for debugging
    st.write("Parsing variables file...")
    
    # Process each line
    for line in variable_content.splitlines():
        # Skip comments and empty lines
        if not line.strip() or line.strip().startswith('//'):
            continue
            
        # Basic variable pattern (including !default)
        var_match = re.match(r'^\s*\$([\w-]+):\s*([^;]+)\s*(!default)?\s*;', line)
        
        if var_match:
            var_name = var_match.group(1)
            var_value = var_match.group(2).strip()
            
            # Store both the variable and its value
            if re.match(r'^(#[a-fA-F0-9]{3,6}|rgba?\([^)]+\))$', var_value):
                variables[var_value] = f"${var_name}"
                # Debug output
                st.write(f"Found color variable: ${var_name} = {var_value}")
    
    st.write(f"Total variables found: {len(variables)}")
    return variables

def convert_css_to_scss(css_content, variable_mapping):
    """Converts CSS content to SCSS by replacing color values with variable names."""
    # Debug output
    st.write("Starting CSS to SCSS conversion...")
    st.write("Available variable mappings:", variable_mapping)
    
    result_lines = []
    for line in css_content.splitlines():
        original_line = line
        processed_line = line
        
        # Handle comments separately
        if '/*' in line and '*/' in line:
            # Split the line into parts (before comment, comment, after comment)
            parts = re.split(r'(/\*.*?\*/)', line)
            processed_parts = []
            
            for part in parts:
                if part.startswith('/*'):
                    processed_parts.append(part)
                else:
                    # Process the non-comment part
                    processed_part = part
                    for color, variable in variable_mapping.items():
                        if color in processed_part:
                            processed_part = processed_part.replace(color, variable)
                            st.write(f"Replaced {color} with {variable}")
                    processed_parts.append(processed_part)
            
            processed_line = ''.join(processed_parts)
        else:
            # Process lines without comments
            for color, variable in variable_mapping.items():
                if color in processed_line:
                    processed_line = processed_line.replace(color, variable)
                    st.write(f"Replaced {color} with {variable}")
        
        # Debug output if line was changed
        if original_line != processed_line:
            st.write(f"Changed line:\nFrom: {original_line}\nTo:   {processed_line}")
        
        result_lines.append(processed_line)
    
    return '\n'.join(result_lines)

# Streamlit app
st.title("SCSS Variable Converter with Debug Output")

# File uploaders
css_file = st.file_uploader("Upload CSS File", type=["css"])
variables_file = st.file_uploader("Upload SCSS Variables File", type=["scss"])

if css_file and variables_file:
    try:
        css_content = css_file.read().decode("utf-8")
        variables_content = variables_file.read().decode("utf-8")
        
        st.write("Processing files...")
        st.write("---")
        
        variable_mapping = parse_variable_file(variables_content)
        if variable_mapping:
            scss_content = convert_css_to_scss(css_content, variable_mapping)
            
            if scss_content:
                st.subheader("SCSS Output")
                st.code(scss_content, language="scss")
                st.download_button(
                    "Download SCSS File",
                    data=scss_content,
                    file_name="converted.scss",
                    mime="text/plain"
                )
        else:
            st.error("No valid color variables found in the variables file.")
            
    except Exception as e:
        st.error(f"An error occurred: {str(e)}")
        st.write("Error details:", str(e))