\ No newline at end of file
diff --git a/html/extra-networks-metadata-button.html b/html/extra-networks-metadata-button.html
index ad6d6f416..285b5b3b6 100644
--- a/html/extra-networks-metadata-button.html
+++ b/html/extra-networks-metadata-button.html
@@ -1,4 +1,4 @@
\ No newline at end of file
diff --git a/html/extra-networks-pane.html b/html/extra-networks-pane.html
index 20cf66867..bf46ca163 100644
--- a/html/extra-networks-pane.html
+++ b/html/extra-networks-pane.html
@@ -1,8 +1,8 @@
-
-
+
+
{tree_html}
-
+
{items_html}
\ No newline at end of file
diff --git a/html/extra-networks-tree-button.html b/html/extra-networks-tree-button.html
index 20a9b0b86..9dc2e2a40 100644
--- a/html/extra-networks-tree-button.html
+++ b/html/extra-networks-tree-button.html
@@ -1,8 +1,7 @@
{search_terms}
diff --git a/javascript/extraNetworks.js b/javascript/extraNetworks.js
index cf98452a2..a3f003bf4 100644
--- a/javascript/extraNetworks.js
+++ b/javascript/extraNetworks.js
@@ -31,25 +31,15 @@ function setupExtraNetworksForTab(tabname) {
var this_tab = gradioApp().querySelector('#' + tabname + '_extra_tabs');
this_tab.classList.add('extra-networks');
this_tab.querySelectorAll(":scope > [id^='" + tabname + "_']").forEach(function(elem) {
- var tab_id = elem.getAttribute("id");
- var search = gradioApp().querySelector("#" + tab_id + "_extra_search");
- if (!search) {
- return; // `continue` doesn't work in `forEach` loops. This is equivalent.
- }
+ var extra_networks_tabname = elem.id;
+ var search = gradioApp().querySelector("#" + extra_networks_tabname + "_extra_search");
+ var sort_mode = gradioApp().querySelector("#" + extra_networks_tabname + "_extra_sort");
+ var sort_dir = gradioApp().querySelector("#" + extra_networks_tabname + "_extra_sort_dir");
+ var refresh = gradioApp().querySelector("#" + extra_networks_tabname + "_extra_refresh");
- var sort = gradioApp().querySelector("#" + tab_id + "_extra_sort");
- if (!sort) {
- return; // `continue` doesn't work in `forEach` loops. This is equivalent.
- }
-
- var sort_dir = gradioApp().querySelector("#" + tab_id + "_extra_sort_dir");
- if (!sort_dir) {
- return; // `continue` doesn't work in `forEach` loops. This is equivalent.
- }
-
- var refresh = gradioApp().querySelector("#" + tab_id + "_extra_refresh");
- if (!refresh) {
- return; // `continue` doesn't work in `forEach` loops. This is equivalent.
+ // If any of the buttons above don't exist, we want to skip this iteration of the loop.
+ if (!search || !sort_mode || !sort_dir || !refresh) {
+ return; // `return` is equivalent of `continue` but for forEach loops.
}
var applyFilter = function() {
@@ -78,14 +68,14 @@ function setupExtraNetworksForTab(tabname) {
var cards = gradioApp().querySelectorAll('#' + tabname + '_extra_tabs div.card');
var reverse = sort_dir.dataset.sortdir == "Descending";
- var sortKey = sort.dataset.sortmode.toLowerCase().replace("sort", "").replaceAll(" ", "_").replace(/_+$/, "").trim() || "name";
+ var sortKey = sort_mode.dataset.sortmode.toLowerCase().replace("sort", "").replaceAll(" ", "_").replace(/_+$/, "").trim() || "name";
sortKey = "sort" + sortKey.charAt(0).toUpperCase() + sortKey.slice(1);
var sortKeyStore = sortKey + "-" + (reverse ? "Descending" : "Ascending") + "-" + cards.length;
- if (sortKeyStore == sort.dataset.sortkey) {
+ if (sortKeyStore == sort_mode.dataset.sortkey) {
return;
}
- sort.dataset.sortkey = sortKeyStore;
+ sort_mode.dataset.sortkey = sortKeyStore;
cards.forEach(function(card) {
card.originalParentElement = card.parentElement;
@@ -115,8 +105,8 @@ function setupExtraNetworksForTab(tabname) {
applySort();
applyFilter();
- extraNetworksApplySort[tab_id] = applySort;
- extraNetworksApplyFilter[tab_id] = applyFilter;
+ extraNetworksApplySort[extra_networks_tabname] = applySort;
+ extraNetworksApplyFilter[extra_networks_tabname] = applyFilter;
});
registerPrompt(tabname, tabname + "_prompt");
@@ -148,14 +138,6 @@ function extraNetworksMovePromptToTab(tabname, id, showPrompt, showNegativePromp
}
}
-function clearSearch(tabname) {
- // Clear search box.
- var tab_id = tabname + "_extra_search";
- var searchTextarea = gradioApp().querySelector("#" + tab_id + ' > label > textarea');
- searchTextarea.value = "";
- updateInput(searchTextarea);
-}
-
function extraNetworksUnrelatedTabSelected(tabname) { // called from python when user selects an unrelated tab (generate)
extraNetworksMovePromptToTab(tabname, '', false, false);
@@ -264,22 +246,20 @@ function saveCardPreview(event, tabname, filename) {
event.preventDefault();
}
-function extraNetworksTreeProcessFileClick(event, btn, tabname, tab_id) {
+function extraNetworksTreeProcessFileClick(event, btn, tabname, extra_networks_tabname) {
/**
* Processes `onclick` events when user clicks on files in tree.
*
- * @param event The generated event.
- * @param btn The clicked `tree-list-item` button.
- * @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
- * @param tab_id The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
+ * @param event The generated event.
+ * @param btn The clicked `tree-list-item` button.
+ * @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
+ * @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
*/
- var par = btn.parentElement;
- var search_id = tabname + "_" + tab_id + "_extra_search";
- var type = par.getAttribute("data-tree-entry-type");
- var path = btn.getAttribute("data-path");
+ // NOTE: Currently unused.
+ return;
}
-function extraNetworksTreeProcessDirectoryClick(event, btn, tabname, tab_id) {
+function extraNetworksTreeProcessDirectoryClick(event, btn, tabname, extra_networks_tabname) {
/**
* Processes `onclick` events when user clicks on directories in tree.
*
@@ -289,10 +269,10 @@ function extraNetworksTreeProcessDirectoryClick(event, btn, tabname, tab_id) {
* selected opened directory: Directory is collapsed and deselected.
* chevron is clicked: Directory is expanded or collapsed. Selected state unchanged.
*
- * @param event The generated event.
- * @param btn The clicked `tree-list-item` button.
- * @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
- * @param tab_id The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
+ * @param event The generated event.
+ * @param btn The clicked `tree-list-item` button.
+ * @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
+ * @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
*/
var ul = btn.nextElementSibling;
// This is the actual target that the user clicked on within the target button.
@@ -301,12 +281,12 @@ function extraNetworksTreeProcessDirectoryClick(event, btn, tabname, tab_id) {
function _expand_or_collapse(_ul, _btn) {
// Expands
if it is collapsed, collapses otherwise. Updates button attributes.
- if (_ul.hasAttribute("data-hidden")) {
- _ul.removeAttribute("data-hidden");
- _btn.setAttribute("expanded", "true");
+ if (_ul.hasAttribute("hidden")) {
+ _ul.removeAttribute("hidden");
+ _btn.dataset.expanded = "";
} else {
- _ul.setAttribute("data-hidden", "");
- _btn.setAttribute("expanded", "false");
+ _ul.setAttribute("hidden", "");
+ delete _btn.dataset.expanded;
}
}
@@ -314,19 +294,19 @@ function extraNetworksTreeProcessDirectoryClick(event, btn, tabname, tab_id) {
// Removes the `selected` attribute from all buttons.
var sels = document.querySelectorAll("div.tree-list-content");
[...sels].forEach(el => {
- el.removeAttribute("selected");
+ delete el.dataset.selected;
});
}
function _select_button(_btn) {
- // Removes `selected` attribute from all buttons then adds to passed button.
+ // Removes `data-selected` attribute from all buttons then adds to passed button.
_remove_selected_from_all();
- _btn.setAttribute("selected", "");
+ _btn.dataset.selected = "";
}
- function _update_search(_tabname, _tab_id, _search_text) {
+ function _update_search(_tabname, _extra_networks_tabname, _search_text) {
// Update search input with select button's path.
- var search_input_elem = gradioApp().querySelector("#" + tabname + "_" + tab_id + "_extra_search");
+ var search_input_elem = gradioApp().querySelector("#" + tabname + "_" + extra_networks_tabname + "_extra_search");
search_input_elem.value = _search_text;
updateInput(search_input_elem);
}
@@ -337,48 +317,58 @@ function extraNetworksTreeProcessDirectoryClick(event, btn, tabname, tab_id) {
_expand_or_collapse(ul, btn);
} else {
// User clicked anywhere else on the button.
- if (btn.hasAttribute("selected") && !ul.hasAttribute("data-hidden")) {
+ if ("selected" in btn.dataset && !(ul.hasAttribute("hidden"))) {
// If folder is select and open, collapse and deselect button.
_expand_or_collapse(ul, btn);
- btn.removeAttribute("selected");
- _update_search(tabname, tab_id, "");
- } else if (!(!btn.hasAttribute("selected") && !ul.hasAttribute("data-hidden"))) {
+ delete btn.dataset.selected;
+ _update_search(tabname, extra_networks_tabname, "");
+ } else if (!(!("selected" in btn.dataset) && !(ul.hasAttribute("hidden")))) {
// If folder is open and not selected, then we don't collapse; just select.
// NOTE: Double inversion sucks but it is the clearest way to show the branching here.
_expand_or_collapse(ul, btn);
- _select_button(btn, tabname, tab_id);
- _update_search(tabname, tab_id, btn.getAttribute("data-path"));
+ _select_button(btn, tabname, extra_networks_tabname);
+ _update_search(tabname, extra_networks_tabname, btn.dataset.path);
} else {
// All other cases, just select the button.
- _select_button(btn, tabname, tab_id);
- _update_search(tabname, tab_id, btn.getAttribute("data-path"));
+ _select_button(btn, tabname, extra_networks_tabname);
+ _update_search(tabname, extra_networks_tabname, btn.dataset.path);
}
}
}
-function extraNetworksTreeOnClick(event, tabname, tab_id) {
+function extraNetworksTreeOnClick(event, tabname, extra_networks_tabname) {
/**
* Handles `onclick` events for buttons within an `extra-network-tree .tree-list--tree`.
*
* Determines whether the clicked button in the tree is for a file entry or a directory
* then calls the appropriate function.
*
- * @param event The generated event.
- * @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
- * @param tab_id The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
+ * @param event The generated event.
+ * @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
+ * @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
*/
var btn = event.currentTarget;
var par = btn.parentElement;
- if (par.getAttribute("data-tree-entry-type") === "file") {
- extraNetworksTreeProcessFileClick(event, btn, tabname, tab_id);
+ if (par.dataset.treeEntryType === "file") {
+ extraNetworksTreeProcessFileClick(event, btn, tabname, extra_networks_tabname);
} else {
- extraNetworksTreeProcessDirectoryClick(event, btn, tabname, tab_id);
+ extraNetworksTreeProcessDirectoryClick(event, btn, tabname, extra_networks_tabname);
}
}
-function extraNetworksTreeSortOnClick(event, tabname, tab_id) {
+function extraNetworksTreeSortOnClick(event, tabname, extra_networks_tabname) {
+ /**
+ * Handles `onclick` events for the Sort Mode button.
+ *
+ * Modifies the data attributes of the Sort Mode button to cycle between
+ * various sorting modes.
+ *
+ * @param event The generated event.
+ * @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
+ * @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
+ */
var curr_mode = event.currentTarget.dataset.sortmode;
- var el_sort_dir = gradioApp().querySelector("#" + tabname + "_" + tab_id + "_extra_sort_dir");
+ var el_sort_dir = gradioApp().querySelector("#" + tabname + "_" + extra_networks_tabname + "_extra_sort_dir");
var sort_dir = el_sort_dir.dataset.sortdir;
if (curr_mode == "path") {
event.currentTarget.dataset.sortmode = "name";
@@ -397,23 +387,43 @@ function extraNetworksTreeSortOnClick(event, tabname, tab_id) {
event.currentTarget.dataset.sortkey = "sortPath-" + sort_dir + "-640";
event.currentTarget.setAttribute("title", "Sort by path");
}
- applyExtraNetworkSort(tabname + "_" + tab_id);
+ applyExtraNetworkSort(tabname + "_" + extra_networks_tabname);
}
-function extraNetworksTreeSortDirOnClick(event, tabname, tab_id) {
- var curr_dir = event.currentTarget.getAttribute("data-sortdir");
- if (curr_dir == "Ascending") {
+function extraNetworksTreeSortDirOnClick(event, tabname, extra_networks_tabname) {
+ /**
+ * Handles `onclick` events for the Sort Direction button.
+ *
+ * Modifies the data attributes of the Sort Direction button to cycle between
+ * ascending and descending sort directions.
+ *
+ * @param event The generated event.
+ * @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
+ * @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
+ */
+ if (event.currentTarget.dataset.sortdir == "Ascending") {
event.currentTarget.dataset.sortdir = "Descending";
event.currentTarget.setAttribute("title", "Sort descending");
} else {
event.currentTarget.dataset.sortdir = "Ascending";
event.currentTarget.setAttribute("title", "Sort ascending");
}
- applyExtraNetworkSort(tabname + "_" + tab_id);
+ applyExtraNetworkSort(tabname + "_" + extra_networks_tabname);
}
-function extraNetworksTreeRefreshOnClick(event, tabname, tab_id) {
- console.log("refresh clicked");
+function extraNetworksTreeRefreshOnClick(event, tabname, extra_networks_tabname) {
+ /**
+ * Handles `onclick` events for the Refresh Page button.
+ *
+ * In order to actually call the python functions in `ui_extra_networks.py`
+ * to refresh the page, we created an empty gradio button in that file with an
+ * event handler that refreshes the page. So what this function here does
+ * is it manually raises a `click` event on that button.
+ *
+ * @param event The generated event.
+ * @param tabname The name of the active tab in the sd webui. Ex: txt2img, img2img, etc.
+ * @param extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
+ */
var btn_refresh_internal = gradioApp().getElementById(tabname + "_extra_refresh_internal");
btn_refresh_internal.dispatchEvent(new Event("click"));
}
diff --git a/modules/ui_extra_networks.py b/modules/ui_extra_networks.py
index 06fa22afa..a03207b2b 100644
--- a/modules/ui_extra_networks.py
+++ b/modules/ui_extra_networks.py
@@ -155,7 +155,14 @@ class ExtraNetworksPage:
def __init__(self, title):
self.title = title
self.name = title.lower()
- self.id_page = self.name.replace(" ", "_")
+ # This is the actual name of the extra networks tab (not txt2img/img2img).
+ self.extra_networks_tabname = self.name.replace(" ", "_")
+ self.allow_prompt = True
+ self.allow_negative_prompt = False
+ self.metadata = {}
+ self.items = {}
+ self.lister = util.MassFileLister()
+ # HTML Templates
self.pane_tpl = shared.html("extra-networks-pane.html")
self.tree_tpl = shared.html("extra-networks-tree.html")
self.card_tpl = shared.html("extra-networks-card.html")
@@ -163,11 +170,6 @@ class ExtraNetworksPage:
self.btn_copy_path_tpl = shared.html("extra-networks-copy-path-button.html")
self.btn_metadata_tpl = shared.html("extra-networks-metadata-button.html")
self.btn_edit_item_tpl = shared.html("extra-networks-edit-item-button.html")
- self.allow_prompt = True
- self.allow_negative_prompt = False
- self.metadata = {}
- self.items = {}
- self.lister = util.MassFileLister()
def refresh(self):
pass
@@ -202,15 +204,17 @@ class ExtraNetworksPage:
item: dict,
template: Optional[str] = None,
) -> Union[str, dict]:
- """Generates HTML for a single ExtraNetworks Item
+ """Generates HTML for a single ExtraNetworks Item.
Args:
tabname: The name of the active tab.
item: Dictionary containing item information.
+ template: Optional template string to use.
Returns:
- HTML string generated for this item.
- Can be empty if the item is not meant to be shown.
+ If a template is passed: HTML string generated for this item.
+ Can be empty if the item is not meant to be shown.
+ If no template is passed: A dictionary containing the generated item's attributes.
"""
metadata = item.get("metadata")
if metadata:
@@ -244,14 +248,14 @@ class ExtraNetworksPage:
if metadata:
btn_metadata = self.btn_metadata_tpl.format(
**{
- "page_id": self.id_page,
+ "extra_networks_tabname": self.extra_networks_tabname,
"name": html.escape(item["name"]),
}
)
btn_edit_item = self.btn_edit_item_tpl.format(
**{
"tabname": tabname,
- "page_id": self.id_page,
+ "extra_networks_tabname": self.extra_networks_tabname,
"name": html.escape(item["name"]),
}
)
@@ -307,9 +311,9 @@ class ExtraNetworksPage:
"search_only": " search_only" if search_only else "",
"search_terms": search_terms_html,
"sort_keys": sort_keys,
- "style": f"'display: none; {height}{width}; font-size: {shared.opts.extra_networks_card_text_scale*100}%'",
+ "style": f"display: none; {height}{width}; font-size: {shared.opts.extra_networks_card_text_scale*100}%",
"tabname": tabname,
- "tab_id": self.id_page,
+ "extra_networks_tabname": self.extra_networks_tabname,
}
if template:
@@ -317,7 +321,32 @@ class ExtraNetworksPage:
else:
return args
- def create_tree_dir_item_html(self, tabname: str, dir_path: str, content: Optional[str] = None) -> Optional[str]:
+ def create_tree_dir_item_html(
+ self,
+ tabname: str,
+ dir_path: str,
+ content: Optional[str] = None,
+ ) -> Optional[str]:
+ """Generates HTML for a directory item in the tree.
+
+ The generated HTML is of the format:
+ ```html
+
+
+
+ {content}
+
+
+ ```
+
+ Args:
+ tabname: The name of the active tab.
+ dir_path: Path to the directory for this item.
+ content: Optional HTML string that will be wrapped by this
.
+
+ Returns:
+ HTML formatted string.
+ """
if not content:
return None
@@ -326,7 +355,7 @@ class ExtraNetworksPage:
"search_terms": "",
"subclass": "tree-list-content-dir",
"tabname": tabname,
- "tab_id": self.id_page,
+ "extra_networks_tabname": self.extra_networks_tabname,
"onclick_extra": "",
"data_path": dir_path,
"data_hash": "",
@@ -337,10 +366,32 @@ class ExtraNetworksPage:
"action_list_item_action_trailing": "",
}
)
- ul = f"
{content}
"
- return f"
{btn + ul}
"
+ ul = f"
{content}
"
+ return (
+ "
"
+ f"{btn + ul}"
+ "
"
+ )
- def create_tree_file_item_html(self, tabname: str, item_name: str, item: dict) -> str:
+ def create_tree_file_item_html(self, tabname: str, file_path: str, item: dict) -> str:
+ """Generates HTML for a file item in the tree.
+
+ The generated HTML is of the format:
+ ```html
+
+
+
+
+ ```
+
+ Args:
+ tabname: The name of the active tab.
+ file_path: The path to the file for this item.
+ item: Dictionary containing the item information.
+
+ Returns:
+ HTML formatted string.
+ """
item_html_args = self.create_item_html(tabname, item)
action_buttons = "".join(
[
@@ -355,9 +406,9 @@ class ExtraNetworksPage:
"search_terms": "",
"subclass": "tree-list-content-file",
"tabname": tabname,
- "tab_id": self.id_page,
+ "extra_networks_tabname": self.extra_networks_tabname,
"onclick_extra": item_html_args["card_clicked"],
- "data_path": item_name,
+ "data_path": file_path,
"data_hash": item["shorthash"],
"action_list_item_action_leading": "",
"action_list_item_visual_leading": "🗎",
@@ -366,11 +417,17 @@ class ExtraNetworksPage:
"action_list_item_action_trailing": action_buttons,
}
)
- return f"
{btn}
"
+ return (
+ "
"
+ f"{btn}"
+ "
"
+ )
def create_tree_view_html(self, tabname: str) -> str:
"""Generates HTML for displaying folders in a tree view.
+ The generated HTML uses `extra-networks-tree.html` as a template.
+
Args:
tabname: The name of the active tab.
@@ -379,7 +436,7 @@ class ExtraNetworksPage:
"""
res = ""
- # Generate HTML for the tree.
+ # Setup the tree dictionary.
roots = self.allowed_directories_for_previews()
tree_items = {v["filename"]: ExtraNetworksItem(v) for v in self.items.values()}
tree = get_tree([os.path.abspath(x) for x in roots], items=tree_items)
@@ -388,7 +445,17 @@ class ExtraNetworksPage:
return res
def _build_tree(data: Optional[dict[str, ExtraNetworksItem]] = None) -> Optional[str]:
- """Recursively builds HTML for a tree."""
+ """Recursively builds HTML for a tree.
+
+ Args:
+ data: Dictionary representing a directory tree. Can be NoneType.
+ Data keys should be absolute paths from the root and values
+ should be subdirectory trees or an ExtraNetworksItem.
+
+ Returns:
+ If data is not None: HTML string
+ Else: None
+ """
if not data:
return None
@@ -402,25 +469,36 @@ class ExtraNetworksPage:
else:
_dir_li.append(self.create_tree_dir_item_html(tabname, k, _build_tree(v)))
- # Directories should always be displayed before files.
+ # Directories should always be displayed before files so we order them here.
return "".join(_dir_li) + "".join(_file_li)
# Add each root directory to the tree.
for k, v in sorted(tree.items(), key=lambda x: shared.natural_sort_key(x[0])):
- # If root is empty, append the "disabled" attribute to the template details tag.
item_html = self.create_tree_dir_item_html(tabname, k, _build_tree(v))
- if item_html:
+ # Only add non-empty entries to the tree.
+ if item_html is not None:
res += item_html
return self.tree_tpl.format(
**{
"tabname": tabname,
- "tab_id": self.id_page,
+ "extra_networks_tabname": self.extra_networks_tabname,
"tree": f"
{res}
"
}
)
- def create_card_view_html(self, tabname):
+ def create_card_view_html(self, tabname: str) -> str:
+ """Generates HTML for the network Card View section for a tab.
+
+ This HTML goes into the `extra-networks-pane.html`