Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| from streamlit.components.v1 import html | |
| import time | |
| def main(): | |
| st.title("HTML to Streamlit Sync Demo") | |
| # Create a session state variable for the text | |
| if 'text_value' not in st.session_state: | |
| st.session_state.text_value = "Initial text..." | |
| # HTML component with a textarea | |
| html_code = """ | |
| <textarea id="html-textarea" style="width: 100%; height: 150px; padding: 10px; margin: 10px 0;"> | |
| This is text in the HTML textarea. | |
| Try editing this text! | |
| </textarea> | |
| <script> | |
| // Function to get textarea content | |
| function getTextareaContent() { | |
| let content = document.getElementById('html-textarea').value; | |
| // Send content to Streamlit | |
| window.parent.postMessage({ | |
| type: 'streamlit:setComponentValue', | |
| value: content | |
| }, '*'); | |
| } | |
| // Set up timer to check for changes | |
| setInterval(getTextareaContent, 1000); // Check every second | |
| </script> | |
| """ | |
| # Column layout for side-by-side comparison | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.subheader("HTML Textarea") | |
| # Render the HTML component | |
| html(html_code, height=200) | |
| with col2: | |
| st.subheader("Streamlit Textarea") | |
| # Streamlit textarea that shows the synced content | |
| synced_text = st.text_area( | |
| "Synced content (updates every second):", | |
| value=st.session_state.text_value, | |
| height=150, | |
| key="synced_textarea" | |
| ) | |
| # Show the current value for debugging | |
| st.subheader("Current Value in Session State:") | |
| st.code(st.session_state.text_value) | |
| # Add a note about the sync behavior | |
| st.info("The content from the HTML textarea will sync to the Streamlit textarea every second. Try typing in the HTML textarea and watch the Streamlit textarea update!") | |
| if __name__ == "__main__": | |
| main() |