derek-thomas's picture
derek-thomas HF staff
Fixing issuex
4f2747f verified
raw
history blame
1.93 kB
import gradio as gr
# Define the pre-stored text snippets
snippet1 = "This is the first predefined text snippet."
snippet2 = "This is the second predefined text snippet."
# Function to insert snippet at a given position
def insert_snippet(text, snippet, position):
return text[:position] + snippet + text[position:]
with gr.Blocks() as demo:
gr.Markdown("# Blog Writing Helper")
with gr.Row():
with gr.Column():
text_input = gr.Textbox(lines=10, placeholder="Write your blog here...", label="Text Editor")
button1 = gr.Button("Insert Snippet 1")
button2 = gr.Button("Insert Snippet 2")
with gr.Column():
gr.Markdown("**Live Preview**")
markdown_preview = gr.Markdown(label="Live Preview", elem_id="preview-box")
button1.click(lambda text, position: insert_snippet(text, snippet1, position), inputs=[text_input, gr.State(0)], outputs=text_input)
button2.click(lambda text, position: insert_snippet(text, snippet2, position), inputs=[text_input, gr.State(0)], outputs=text_input)
text_input.change(lambda text: text, inputs=text_input, outputs=markdown_preview)
# Add custom JavaScript to get cursor position
js_code = """
<script>
let textbox = document.querySelector('textarea');
let position = 0;
textbox.addEventListener('click', () => {
position = textbox.selectionStart;
});
textbox.addEventListener('keyup', () => {
position = textbox.selectionStart;
});
gradio.input('state', position);
</script>
"""
gr.HTML(js_code)
# Add custom CSS for the preview box
css = """
#preview-box {
border: 1px solid #ccc;
padding: 10px;
height: auto;
min-height: 200px;
max-height: 400px;
overflow: auto;
background-color: #f9f9f9;
}
"""
demo.launch(css=css)