Skip to main content

An HTML, JS, and CSS element injector

Project description


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

Static Badge

An HTML, JS, and CSS element injector

Installation

pip install gradio_htmlinjector

Usage

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

name type default description

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.

def predict(
    value: Any
) -> typing.Optional[typing.Dict[str, str]][
   typing.Dict[str, str][str, str], None
]:
    return value

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gradio_htmlinjector-0.0.1.tar.gz (119.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gradio_htmlinjector-0.0.1-py3-none-any.whl (57.5 kB view details)

Uploaded Python 3

File details

Details for the file gradio_htmlinjector-0.0.1.tar.gz.

File metadata

  • Download URL: gradio_htmlinjector-0.0.1.tar.gz
  • Upload date:
  • Size: 119.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.11

File hashes

Hashes for gradio_htmlinjector-0.0.1.tar.gz
Algorithm Hash digest
SHA256 65029a987cc14e29f4433c785ff9159641cdf0453163e3a96bc77442f210e109
MD5 0b7179b2872be2bafc3c5e28c30c8b1f
BLAKE2b-256 cfcde5e39419b81defa3d94998619804a1dc09b7194fbf8fb119a7f16e3e9635

See more details on using hashes here.

File details

Details for the file gradio_htmlinjector-0.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for gradio_htmlinjector-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 934a20a4f3b6283cabbb5a8ed6e81489f7840563334212935bef0c5e823d5557
MD5 58fa83ed238de700efaec64babc9d6f3
BLAKE2b-256 d4bbe069ec1ab0f8595607478cc46de3f813f3e715bd4b14ef674dd2dfe4bbd0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page