gradio_htmlinjector / README.md
elismasilva's picture
Upload folder using huggingface_hub
c83e641 verified
---
tags: [gradio-custom-component, ]
title: gradio_htmlinjector
short_description: A HTML injector for css and js
colorFrom: blue
colorTo: yellow
sdk: gradio
pinned: false
app_file: space.py
---
# `gradio_htmlinjector`
<img alt="Static Badge" src="https://img.shields.io/badge/version%20-%200.0.1%20-%20blue"> <a href="https://huggingface.co/spaces/elismasilva/gradio_htmlinjector"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Demo-blue"></a><p><span>💻 <a href='https://github.com/DEVAIEXP/gradio_component_htmlinjector'>Component GitHub Code</a></span></p>
An HTML, JS, and CSS element injector
## Installation
```bash
pip install gradio_htmlinjector
```
## Usage
```python
import gradio as gr
from gradio_htmlinjector import HTMLInjector
def inject_all_assets():
"""
This function prepares the payload of CSS, JS, and HTML content.
It's called by the demo.load() event listener.
"""
css_code = ""
js_code = ""
# Define the HTML for a floating popup, initially hidden.
popup_html = """
<div id="my-floating-popup" style="display: none; position: fixed; top: 20%; left: 50%; transform: translateX(-50%); z-index: 9999; background: var(--panel-background-fill, white); border: 1px solid var(--border-color-primary); padding: 25px; border-radius: var(--radius-lg); box-shadow: var(--shadow-drop-lg);">
<h2>Injected HTML Popup</h2>
<p>This content exists outside the main Gradio layout.</p>
<br>
<button class="lg primary svelte-1ixn6qd" onclick="hideElementById('my-floating-popup')">
Close Me
</button>
</div>
"""
# Load JavaScript helper functions from an external file.
try:
with open("custom_script.js", "r", encoding="utf-8") as f:
js_code += f.read() + "\n"
except FileNotFoundError as e:
print(f"Info: 'custom_script.js' file not found: {e}")
# Load custom styles from an external file.
try:
with open("custom_styles.css", "r", encoding="utf-8") as f:
css_code += f.read() + "\n"
except FileNotFoundError as e:
print(f"Info: 'custom_styles.css' file not found: {e}")
return {"css": css_code, "js": js_code, "body_html": popup_html}
with gr.Blocks() as demo:
gr.Markdown("# HTMLInjector Component Demo")
gr.Markdown("This demo uses a custom component to inject a floating HTML popup and its controlling JavaScript.")
html_injector = HTMLInjector()
show_popup_button = gr.Button("Show Injected Popup", variant="primary")
# This intelligent JS snippet solves the race condition.
# It defines the action to perform, checks if the helper function is ready,
# and if not, it waits for the custom 'assets-injected' event before proceeding.
show_popup_js = """
() => {
const action = () => showElementById('my-floating-popup');
if (typeof showElementById === 'function') {
action();
} else {
console.log("[Button Click] Helpers not ready, waiting for 'assets-injected' event...");
document.addEventListener('assets-injected', action, { once: true });
}
}
"""
show_popup_button.click(fn=None, inputs=None, outputs=None, js=show_popup_js)
demo.load(fn=inject_all_assets, inputs=None, outputs=[html_injector])
if __name__ == '__main__':
demo.launch()
```
## `HTMLInjector`
### Initialization
<table>
<thead>
<tr>
<th align="left">name</th>
<th align="left" style="width: 25%;">type</th>
<th align="left">default</th>
<th align="left">description</th>
</tr>
</thead>
<tbody></tbody></table>
### User function
The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).
- When used as an Input, the component only impacts the input signature of the user function.
- When used as an output, the component only impacts the return signature of the user function.
The code snippet below is accurate in cases where the component is used as both an input and an output.
```python
def predict(
value: Any
) -> typing.Optional[typing.Dict[str, str]][
typing.Dict[str, str][str, str], None
]:
return value
```