import gradio as gr def update_ui(code): try: # For the preview, we'll return the code as-is to be rendered in an iframe-like manner # Gradio's HTML component can render HTML/CSS directly, but JS needs special handling return f"""
{code}
""", 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", language="html") with gr.Column(): ui_preview = gr.HTML(label="UI Preview") error_output = gr.Textbox(label="Error", interactive=False) # JavaScript execution needs to be handled client-side, so we use _js to inject it code_input.change( fn=update_ui, inputs=code_input, outputs=[ui_preview, error_output], js=""" function(code) { // Create a temporary div to parse the HTML/CSS/JS const tempDiv = document.createElement('div'); tempDiv.innerHTML = code; // Handle JavaScript by creating new script elements const scripts = tempDiv.querySelectorAll('script'); scripts.forEach(script => { const newScript = document.createElement('script'); newScript.textContent = script.textContent; document.body.appendChild(newScript); script.remove(); // Remove original script to avoid double execution }); // Wrap the content in a styled div for better presentation return `
${tempDiv.innerHTML}
`; } """ ) # Add example section with gr.Accordion("HTML/CSS/JS Code Examples", open=False): with gr.Column(): example_buttons = [] example_codes = [ ('

Hello World

', "Basic Heading"), ('

This is a paragraph.

', "Styled Paragraph"), ('', "Interactive Button"), ("""
""", "CSS Box"), ("""
""", "Flexbox Layout"), (""" Snake Game """, "Snake Game"), ] for code, label in example_codes: button = gr.Button(label) example_buttons.append(button) button.click(fn=lambda x=code: x, outputs=code_input) return demo if __name__ == "__main__": demo = interface() demo.launch()