File size: 2,139 Bytes
7f93673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from streamlit.components.v1 import html

def main():
    st.title("Copy Text Demo")
    st.write("This demo shows how to copy text from an HTML textarea into Streamlit.")
    
    # HTML component with textarea and copy button
    html_code = """
    <textarea id="myTextarea" rows="5" style="width: 100%; padding: 10px; margin: 10px 0;">Here is some sample text that you can copy.
Try modifying this text and clicking the Copy button below!</textarea>
    
    <button onclick="copyToStreamlit()" style="padding: 8px 16px; background-color: #ff4b4b; color: white; border: none; border-radius: 4px; cursor: pointer;">
        Copy to Streamlit
    </button>

    <script>
    function copyToStreamlit() {
        const text = document.getElementById('myTextarea').value;
        window.parent.postMessage({
            type: 'streamlit:message',
            data: {
                type: 'copyText',
                text: text
            }
        }, '*');
    }

    // Listen for messages from Streamlit
    window.addEventListener('message', function(event) {
        if (event.data.type === 'streamlit:render') {
            // Component has been re-rendered
            console.log('Component rendered');
        }
    });
    </script>
    """

    # Create a placeholder for the copied text
    if 'copied_text' not in st.session_state:
        st.session_state.copied_text = None

    # Render HTML component
    html(html_code, height=200)

    # JavaScript message handler
    st.markdown("""
    <script>
    window.addEventListener('message', function(event) {
        if (event.data.type === 'copyText') {
            const text = event.data.text;
            window.streamlitMessageListener.handleMessage({
                type: 'streamlit:setComponentValue',
                value: text
            });
        }
    });
    </script>
    """, unsafe_allow_html=True)

    # Display copied text in a code block if available
    if st.session_state.copied_text:
        st.subheader("Copied Text:")
        st.code(st.session_state.copied_text, language='text')

if __name__ == "__main__":
    main()