UI_learn_js / app.py
broadfield-dev's picture
Update app.py
e6d5c9e verified
raw
history blame
1.81 kB
import gradio as gr
def update_ui(code):
try:
# Here, we're not parsing JavaScript out but passing the whole code through
return code, ""
except Exception as e:
return "", str(e)
def interface():
with gr.Blocks() as demo:
gr.Markdown("# Learn Frontend UI with Snake Game")
with gr.Row():
code_input = gr.Code(label="Write your HTML/CSS/JS here", language="html")
with gr.Column():
# For JavaScript to work, you need to use the _js argument in the HTML component
ui_preview = gr.HTML(label="UI Preview")
error_output = gr.Textbox(label="Error", interactive=False)
# We'll use the _js argument to inject JavaScript directly into the HTML component
code_input.change(
fn=update_ui,
inputs=code_input,
outputs=[ui_preview, error_output],
_js="""
function(code) {
// This function runs in the browser context, not Python
const tempDiv = document.createElement('div');
tempDiv.innerHTML = code;
// Extract scripts from the code
const scripts = tempDiv.querySelectorAll('script');
for (let script of scripts) {
const newScript = document.createElement('script');
newScript.textContent = script.textContent;
script.parentNode.replaceChild(newScript, script);
}
// Return the HTML content without the script tags for Gradio to display
return tempDiv.innerHTML;
}
"""
)
return demo
if __name__ == "__main__":
demo = interface()
demo.launch()