Spaces:
Running
Running
File size: 4,412 Bytes
c83e641 |
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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
---
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
```
|