Skip to content

Commit

Permalink
Replace extra networks toggle with frontend CSS toggle after first load
Browse files Browse the repository at this point in the history
  • Loading branch information
space-nuko committed Mar 24, 2023
1 parent b675a1c commit ceb0fa8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
25 changes: 25 additions & 0 deletions javascript/extraNetworks.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,28 @@ function extraNetworksShowMetadata(text){

popup(elem);
}

var hookedExtraNetworksButtons = {};
function extraNetworksHookPageToggleIfBuilt(tab_name) {
if (hookedExtraNetworksButtons[tab_name]) {
return;
}

let button = gradioApp().querySelector("#" + tab_name + "_extra_networks.gr-button");
let extra_networks_section = gradioApp().querySelector("div#" + tab_name + "_extra_networks");
let extra_networks_html = extra_networks_section.getElementsByClassName("output-html");
let loaded = new Array(extra_networks_html).some(html => html.innerHTML != "");
if (loaded && button) {
console.log("Replacing Gradio native callback with CSS toggle for extra networks button: " + tab_name)

// Remove event handlers by recreating button node
hookedExtraNetworksButtons[tab_name] = button;
var new_button = button.cloneNode(true);
button.parentNode.replaceChild(new_button, button);

// Add our own event to toggle extra networks section with CSS instead of Gradio
new_button.addEventListener("click", function() {
extra_networks_section.classList.toggle("hidden");
}, false);
}
}
11 changes: 11 additions & 0 deletions modules/ui_extra_networks.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ def create_ui(container, button, tabname):
ui.tabname = tabname

with gr.Tabs(elem_id=tabname+"_extra_tabs") as tabs:
tab_name_state = gr.Textbox(tabname, visible=False)
for page in ui.stored_extra_pages:
with gr.Tab(page.title):
page_elem = gr.HTML("")
Expand Down Expand Up @@ -266,6 +267,16 @@ def toggle_visibility(is_visible, *pages):
state_visible = gr.State(value=False)
button.click(fn=toggle_visibility, inputs=[state_visible] + ui.pages, outputs=[state_visible, container] + ui.pages)

# Gradio has to send the rendered HTML for the extra networks UI to the
# frontend every time the toggle_visibility event handler is called, even if
# all it does is change a single flag on and off. This causes a serious
# performance drop if the pages are huge strings.
# This callback removes Gradio's "click" event listener on the button in the
# frontend once it receives the pages HTML, by replacing the button and
# adding a new click listener to it that toggles the ".hidden" CSS class
# instead, thus bypassing Gradio entirely.
button.click(fn=None, _js="extraNetworksHookPageToggleIfBuilt", inputs=[tab_name_state], outputs=[])

return ui


Expand Down

0 comments on commit ceb0fa8

Please sign in to comment.