import gradio as gr import re def update_ui(code): try: # Extract HTML, CSS, and JavaScript using regex html_content = re.search(r']*>[\s\S]*?<\/html>', code, re.IGNORECASE) if html_content: html_content = html_content.group(0) else: html_content = code # If no tag, assume all is HTML content # Extract CSS if present in a {html_content} """ return ui_output, js_only, None except Exception as e: return "", "", str(e) def interface(): with gr.Blocks() as demo: gr.Markdown("# Learn Frontend UI") with gr.Row(): code_input = gr.Code(label="Write your HTML/CSS/JS here", lines=500, language="html") with gr.Column(): ui_preview = gr.HTML(label="UI Preview") error_output = gr.Textbox(label="Error", interactive=False) # Hidden output to store JavaScript for _js execution js_output = gr.Textbox(visible=False) # Use _js to execute JavaScript in the browser context code_input.change( fn=update_ui, inputs=code_input, outputs=[ui_preview, js_output, error_output], js=""" function(code, ui_output, js_code) { // Create a temporary div to parse the HTML const tempDiv = document.createElement('div'); tempDiv.innerHTML = ui_output; // If there's JavaScript code, execute it if (js_code) { const script = document.createElement('script'); script.textContent = js_code; document.body.appendChild(script); // Clean up script tag after execution to prevent duplicates setTimeout(() => script.remove(), 0); } // Return the HTML content for Gradio to display return tempDiv.innerHTML; } """ ) return demo if __name__ == "__main__": demo = interface() demo.launch()