diff --git a/html/extra-networks-copy-path-button.html b/html/extra-networks-copy-path-button.html
new file mode 100644
index 00000000000..8083bb03357
--- /dev/null
+++ b/html/extra-networks-copy-path-button.html
@@ -0,0 +1,5 @@
+
+
\ No newline at end of file
diff --git a/html/extra-networks-edit-item-button.html b/html/extra-networks-edit-item-button.html
new file mode 100644
index 00000000000..0fe43082ad1
--- /dev/null
+++ b/html/extra-networks-edit-item-button.html
@@ -0,0 +1,4 @@
+
+
\ No newline at end of file
diff --git a/html/extra-networks-metadata-button.html b/html/extra-networks-metadata-button.html
new file mode 100644
index 00000000000..285b5b3b658
--- /dev/null
+++ b/html/extra-networks-metadata-button.html
@@ -0,0 +1,4 @@
+
+
\ No newline at end of file
diff --git a/html/extra-networks-pane.html b/html/extra-networks-pane.html
new file mode 100644
index 00000000000..9f5b3ecee62
--- /dev/null
+++ b/html/extra-networks-pane.html
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {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
new file mode 100644
index 00000000000..9dc2e2a40c8
--- /dev/null
+++ b/html/extra-networks-tree-button.html
@@ -0,0 +1,23 @@
+{search_terms}
+
\ No newline at end of file
diff --git a/javascript/extraNetworks.js b/javascript/extraNetworks.js
index f1ad19a66b7..ce788328ce5 100644
--- a/javascript/extraNetworks.js
+++ b/javascript/extraNetworks.js
@@ -16,99 +16,100 @@ function toggleCss(key, css, enable) {
}
function setupExtraNetworksForTab(tabname) {
- gradioApp().querySelector('#' + tabname + '_extra_tabs').classList.add('extra-networks');
-
- var tabs = gradioApp().querySelector('#' + tabname + '_extra_tabs > div');
- var searchDiv = gradioApp().getElementById(tabname + '_extra_search');
- var search = searchDiv.querySelector('textarea');
- var sort = gradioApp().getElementById(tabname + '_extra_sort');
- var sortOrder = gradioApp().getElementById(tabname + '_extra_sortorder');
- var refresh = gradioApp().getElementById(tabname + '_extra_refresh');
- var showDirsDiv = gradioApp().getElementById(tabname + '_extra_show_dirs');
- var showDirs = gradioApp().querySelector('#' + tabname + '_extra_show_dirs input');
- var promptContainer = gradioApp().querySelector('.prompt-container-compact#' + tabname + '_prompt_container');
- var negativePrompt = gradioApp().querySelector('#' + tabname + '_neg_prompt');
-
- tabs.appendChild(searchDiv);
- tabs.appendChild(sort);
- tabs.appendChild(sortOrder);
- tabs.appendChild(refresh);
- tabs.appendChild(showDirsDiv);
-
- var applyFilter = function() {
- var searchTerm = search.value.toLowerCase();
-
- gradioApp().querySelectorAll('#' + tabname + '_extra_tabs div.card').forEach(function(elem) {
- var searchOnly = elem.querySelector('.search_only');
- var text = elem.querySelector('.name').textContent.toLowerCase() + " " + elem.querySelector('.search_term').textContent.toLowerCase();
-
- var visible = text.indexOf(searchTerm) != -1;
-
- if (searchOnly && searchTerm.length < 4) {
- visible = false;
- }
+ function registerPrompt(tabname, id) {
+ var textarea = gradioApp().querySelector("#" + id + " > label > textarea");
+
+ if (!activePromptTextarea[tabname]) {
+ activePromptTextarea[tabname] = textarea;
+ }
- elem.style.display = visible ? "" : "none";
+ textarea.addEventListener("focus", function() {
+ activePromptTextarea[tabname] = textarea;
});
+ }
- applySort();
- };
+ var this_tab = gradioApp().querySelector('#' + tabname + '_extra_tabs');
+ this_tab.classList.add('extra-networks');
+ this_tab.querySelectorAll(":scope > [id^='" + tabname + "_']").forEach(function(elem) {
+ // tabname_full = {tabname}_{extra_networks_tabname}
+ var tabname_full = elem.id;
+ var search = gradioApp().querySelector("#" + tabname_full + "_extra_search");
+ var sort_mode = gradioApp().querySelector("#" + tabname_full + "_extra_sort");
+ var sort_dir = gradioApp().querySelector("#" + tabname_full + "_extra_sort_dir");
+ var refresh = gradioApp().querySelector("#" + tabname_full + "_extra_refresh");
+
+ // 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 applySort = function() {
- var cards = gradioApp().querySelectorAll('#' + tabname + '_extra_tabs div.card');
+ var applyFilter = function() {
+ var searchTerm = search.value.toLowerCase();
+ gradioApp().querySelectorAll('#' + tabname + '_extra_tabs div.card').forEach(function(elem) {
+ var searchOnly = elem.querySelector('.search_only');
+ var text = Array.prototype.map.call(elem.querySelectorAll('.search_terms'), function(t) {
+ return t.textContent.toLowerCase();
+ }).join(" ");
+
+ var visible = text.indexOf(searchTerm) != -1;
+ if (searchOnly && searchTerm.length < 4) {
+ visible = false;
+ }
+ if (visible) {
+ elem.classList.remove("hidden");
+ } else {
+ elem.classList.add("hidden");
+ }
+ });
- var reverse = sortOrder.classList.contains("sortReverse");
- var sortKey = sort.querySelector("input").value.toLowerCase().replace("sort", "").replaceAll(" ", "_").replace(/_+$/, "").trim() || "name";
- sortKey = "sort" + sortKey.charAt(0).toUpperCase() + sortKey.slice(1);
- var sortKeyStore = sortKey + "-" + (reverse ? "Descending" : "Ascending") + "-" + cards.length;
+ applySort();
+ };
- if (sortKeyStore == sort.dataset.sortkey) {
- return;
- }
- sort.dataset.sortkey = sortKeyStore;
+ var applySort = function() {
+ var cards = gradioApp().querySelectorAll('#' + tabname + '_extra_tabs div.card');
+ var reverse = sort_dir.dataset.sortdir == "Descending";
+ 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;
- cards.forEach(function(card) {
- card.originalParentElement = card.parentElement;
- });
- var sortedCards = Array.from(cards);
- sortedCards.sort(function(cardA, cardB) {
- var a = cardA.dataset[sortKey];
- var b = cardB.dataset[sortKey];
- if (!isNaN(a) && !isNaN(b)) {
- return parseInt(a) - parseInt(b);
+ if (sortKeyStore == sort_mode.dataset.sortkey) {
+ return;
}
+ sort_mode.dataset.sortkey = sortKeyStore;
+
+ cards.forEach(function(card) {
+ card.originalParentElement = card.parentElement;
+ });
+ var sortedCards = Array.from(cards);
+ sortedCards.sort(function(cardA, cardB) {
+ var a = cardA.dataset[sortKey];
+ var b = cardB.dataset[sortKey];
+ if (!isNaN(a) && !isNaN(b)) {
+ return parseInt(a) - parseInt(b);
+ }
- return (a < b ? -1 : (a > b ? 1 : 0));
- });
- if (reverse) {
- sortedCards.reverse();
- }
- cards.forEach(function(card) {
- card.remove();
- });
- sortedCards.forEach(function(card) {
- card.originalParentElement.appendChild(card);
- });
- };
-
- search.addEventListener("input", applyFilter);
- sortOrder.addEventListener("click", function() {
- sortOrder.classList.toggle("sortReverse");
+ return (a < b ? -1 : (a > b ? 1 : 0));
+ });
+ if (reverse) {
+ sortedCards.reverse();
+ }
+ cards.forEach(function(card) {
+ card.remove();
+ });
+ sortedCards.forEach(function(card) {
+ card.originalParentElement.appendChild(card);
+ });
+ };
+
+ search.addEventListener("input", applyFilter);
applySort();
+ applyFilter();
+ extraNetworksApplySort[tabname_full] = applySort;
+ extraNetworksApplyFilter[tabname_full] = applyFilter;
});
- applyFilter();
-
- extraNetworksApplySort[tabname] = applySort;
- extraNetworksApplyFilter[tabname] = applyFilter;
- var showDirsUpdate = function() {
- var css = '#' + tabname + '_extra_tabs .extra-network-subdirs { display: none; }';
- toggleCss(tabname + '_extra_show_dirs_style', css, !showDirs.checked);
- localSet('extra-networks-show-dirs', showDirs.checked ? 1 : 0);
- };
- showDirs.checked = localGet('extra-networks-show-dirs', 1) == 1;
- showDirs.addEventListener("change", showDirsUpdate);
- showDirsUpdate();
+ registerPrompt(tabname, tabname + "_prompt");
+ registerPrompt(tabname, tabname + "_neg_prompt");
}
function extraNetworksMovePromptToTab(tabname, id, showPrompt, showNegativePrompt) {
@@ -137,21 +138,20 @@ function extraNetworksMovePromptToTab(tabname, id, showPrompt, showNegativePromp
}
-function extraNetworksUrelatedTabSelected(tabname) { // called from python when user selects an unrelated tab (generate)
+function extraNetworksUnrelatedTabSelected(tabname) { // called from python when user selects an unrelated tab (generate)
extraNetworksMovePromptToTab(tabname, '', false, false);
}
function extraNetworksTabSelected(tabname, id, showPrompt, showNegativePrompt) { // called from python when user selects an extra networks tab
extraNetworksMovePromptToTab(tabname, id, showPrompt, showNegativePrompt);
-
}
-function applyExtraNetworkFilter(tabname) {
- setTimeout(extraNetworksApplyFilter[tabname], 1);
+function applyExtraNetworkFilter(tabname_full) {
+ setTimeout(extraNetworksApplyFilter[tabname_full], 1);
}
-function applyExtraNetworkSort(tabname) {
- setTimeout(extraNetworksApplySort[tabname], 1);
+function applyExtraNetworkSort(tabname_full) {
+ setTimeout(extraNetworksApplySort[tabname_full], 1);
}
var extraNetworksApplyFilter = {};
@@ -161,27 +161,8 @@ var activePromptTextarea = {};
function setupExtraNetworks() {
setupExtraNetworksForTab('txt2img');
setupExtraNetworksForTab('img2img');
-
- function registerPrompt(tabname, id) {
- var textarea = gradioApp().querySelector("#" + id + " > label > textarea");
-
- if (!activePromptTextarea[tabname]) {
- activePromptTextarea[tabname] = textarea;
- }
-
- textarea.addEventListener("focus", function() {
- activePromptTextarea[tabname] = textarea;
- });
- }
-
- registerPrompt('txt2img', 'txt2img_prompt');
- registerPrompt('txt2img', 'txt2img_neg_prompt');
- registerPrompt('img2img', 'img2img_prompt');
- registerPrompt('img2img', 'img2img_neg_prompt');
}
-onUiLoaded(setupExtraNetworks);
-
var re_extranet = /<([^:^>]+:[^:]+):[\d.]+>(.*)/;
var re_extranet_g = /<([^:^>]+:[^:]+):[\d.]+>/g;
@@ -191,8 +172,8 @@ function tryToRemoveExtraNetworkFromPrompt(textarea, text, isNeg) {
var m = text.match(isNeg ? re_extranet_neg : re_extranet);
var replaced = false;
var newTextareaText;
+ var extraTextBeforeNet = opts.extra_networks_add_text_separator;
if (m) {
- var extraTextBeforeNet = opts.extra_networks_add_text_separator;
var extraTextAfterNet = m[2];
var partToSearch = m[1];
var foundAtPosition = -1;
@@ -205,7 +186,6 @@ function tryToRemoveExtraNetworkFromPrompt(textarea, text, isNeg) {
}
return found;
});
-
if (foundAtPosition >= 0) {
if (extraTextAfterNet && newTextareaText.substr(foundAtPosition, extraTextAfterNet.length) == extraTextAfterNet) {
newTextareaText = newTextareaText.substr(0, foundAtPosition) + newTextareaText.substr(foundAtPosition + extraTextAfterNet.length);
@@ -215,13 +195,8 @@ function tryToRemoveExtraNetworkFromPrompt(textarea, text, isNeg) {
}
}
} else {
- newTextareaText = textarea.value.replaceAll(new RegExp(text, "g"), function(found) {
- if (found == text) {
- replaced = true;
- return "";
- }
- return found;
- });
+ newTextareaText = textarea.value.replaceAll(new RegExp(`((?:${extraTextBeforeNet})?${text})`, "g"), "");
+ replaced = (newTextareaText != textarea.value);
}
if (replaced) {
@@ -233,7 +208,6 @@ function tryToRemoveExtraNetworkFromPrompt(textarea, text, isNeg) {
}
function updatePromptArea(text, textArea, isNeg) {
-
if (!tryToRemoveExtraNetworkFromPrompt(textArea, text, isNeg)) {
textArea.value = textArea.value + opts.extra_networks_add_text_separator + text;
}
@@ -264,13 +238,200 @@ function saveCardPreview(event, tabname, filename) {
event.preventDefault();
}
-function extraNetworksSearchButton(tabs_id, event) {
- var searchTextarea = gradioApp().querySelector("#" + tabs_id + ' > label > textarea');
- var button = event.target;
- var text = button.classList.contains("search-all") ? "" : button.textContent.trim();
+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 extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
+ */
+ // NOTE: Currently unused.
+ return;
+}
+
+function extraNetworksTreeProcessDirectoryClick(event, btn, tabname, extra_networks_tabname) {
+ /**
+ * Processes `onclick` events when user clicks on directories in tree.
+ *
+ * Here is how the tree reacts to clicks for various states:
+ * unselected unopened directory: Diretory is selected and expanded.
+ * unselected opened directory: Directory is selected.
+ * 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 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.
+ // We use this to detect if the chevron was clicked.
+ var true_targ = event.target;
+
+ function _expand_or_collapse(_ul, _btn) {
+ // Expands
if it is collapsed, collapses otherwise. Updates button attributes.
+ if (_ul.hasAttribute("hidden")) {
+ _ul.removeAttribute("hidden");
+ _btn.dataset.expanded = "";
+ } else {
+ _ul.setAttribute("hidden", "");
+ delete _btn.dataset.expanded;
+ }
+ }
+
+ function _remove_selected_from_all() {
+ // Removes the `selected` attribute from all buttons.
+ var sels = document.querySelectorAll("div.tree-list-content");
+ [...sels].forEach(el => {
+ delete el.dataset.selected;
+ });
+ }
+
+ function _select_button(_btn) {
+ // Removes `data-selected` attribute from all buttons then adds to passed button.
+ _remove_selected_from_all();
+ _btn.dataset.selected = "";
+ }
+
+ function _update_search(_tabname, _extra_networks_tabname, _search_text) {
+ // Update search input with select button's path.
+ var search_input_elem = gradioApp().querySelector("#" + tabname + "_" + extra_networks_tabname + "_extra_search");
+ search_input_elem.value = _search_text;
+ updateInput(search_input_elem);
+ }
+
+
+ // If user clicks on the chevron, then we do not select the folder.
+ if (true_targ.matches(".tree-list-item-action--leading, .tree-list-item-action-chevron")) {
+ _expand_or_collapse(ul, btn);
+ } else {
+ // User clicked anywhere else on the button.
+ if ("selected" in btn.dataset && !(ul.hasAttribute("hidden"))) {
+ // If folder is select and open, collapse and deselect button.
+ _expand_or_collapse(ul, btn);
+ 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, extra_networks_tabname);
+ _update_search(tabname, extra_networks_tabname, btn.dataset.path);
+ } else {
+ // All other cases, just select the button.
+ _select_button(btn, tabname, extra_networks_tabname);
+ _update_search(tabname, extra_networks_tabname, btn.dataset.path);
+ }
+ }
+}
+
+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 extra_networks_tabname The id of the active extraNetworks tab. Ex: lora, checkpoints, etc.
+ */
+ var btn = event.currentTarget;
+ var par = btn.parentElement;
+ if (par.dataset.treeEntryType === "file") {
+ extraNetworksTreeProcessFileClick(event, btn, tabname, extra_networks_tabname);
+ } else {
+ extraNetworksTreeProcessDirectoryClick(event, btn, tabname, extra_networks_tabname);
+ }
+}
+
+function extraNetworksControlSortOnClick(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 + "_" + extra_networks_tabname + "_extra_sort_dir");
+ var sort_dir = el_sort_dir.dataset.sortdir;
+ if (curr_mode == "path") {
+ event.currentTarget.dataset.sortmode = "name";
+ event.currentTarget.dataset.sortkey = "sortName-" + sort_dir + "-640";
+ event.currentTarget.setAttribute("title", "Sort by filename");
+ } else if (curr_mode == "name") {
+ event.currentTarget.dataset.sortmode = "date_created";
+ event.currentTarget.dataset.sortkey = "sortDate_created-" + sort_dir + "-640";
+ event.currentTarget.setAttribute("title", "Sort by date created");
+ } else if (curr_mode == "date_created") {
+ event.currentTarget.dataset.sortmode = "date_modified";
+ event.currentTarget.dataset.sortkey = "sortDate_modified-" + sort_dir + "-640";
+ event.currentTarget.setAttribute("title", "Sort by date modified");
+ } else {
+ event.currentTarget.dataset.sortmode = "path";
+ event.currentTarget.dataset.sortkey = "sortPath-" + sort_dir + "-640";
+ event.currentTarget.setAttribute("title", "Sort by path");
+ }
+ applyExtraNetworkSort(tabname + "_" + extra_networks_tabname);
+}
+
+function extraNetworksControlSortDirOnClick(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 + "_" + extra_networks_tabname);
+}
- searchTextarea.value = text;
- updateInput(searchTextarea);
+function extraNetworksControlTreeViewOnClick(event, tabname, extra_networks_tabname) {
+ /**
+ * Handles `onclick` events for the Tree View button.
+ *
+ * Toggles the tree view in the extra networks pane.
+ *
+ * @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.
+ */
+ gradioApp().getElementById(tabname + "_" + extra_networks_tabname + "_tree").classList.toggle("hidden");
+ event.currentTarget.classList.toggle("extra-network-control--enabled");
+}
+
+function extraNetworksControlRefreshOnClick(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"));
}
var globalPopup = null;
@@ -348,6 +509,11 @@ function requestGet(url, data, handler, errorHandler) {
xhr.send(js);
}
+function extraNetworksCopyCardPath(event, path) {
+ navigator.clipboard.writeText(path);
+ event.stopPropagation();
+}
+
function extraNetworksRequestMetadata(event, extraPage, cardName) {
var showError = function() {
extraNetworksShowMetadata("there was an error getting metadata");
@@ -409,3 +575,36 @@ window.addEventListener("keydown", function(event) {
closePopup();
}
});
+
+/**
+ * Setup custom loading for this script.
+ * We need to wait for all of our HTML to be generated in the extra networks tabs
+ * before we can actually run the `setupExtraNetworks` function.
+ * The `onUiLoaded` function actually runs before all of our extra network tabs are
+ * finished generating. Thus we needed this new method.
+ *
+ */
+
+var uiAfterScriptsCallbacks = [];
+var uiAfterScriptsTimeout = null;
+var executedAfterScripts = false;
+
+function scheduleAfterScriptsCallbacks() {
+ clearTimeout(uiAfterScriptsTimeout);
+ uiAfterScriptsTimeout = setTimeout(function() {
+ executeCallbacks(uiAfterScriptsCallbacks);
+ }, 200);
+}
+
+document.addEventListener("DOMContentLoaded", function() {
+ var mutationObserver = new MutationObserver(function(m) {
+ if (!executedAfterScripts &&
+ gradioApp().querySelectorAll("[id$='_extra_search']").length == 8) {
+ executedAfterScripts = true;
+ scheduleAfterScriptsCallbacks();
+ }
+ });
+ mutationObserver.observe(gradioApp(), {childList: true, subtree: true});
+});
+
+uiAfterScriptsCallbacks.push(setupExtraNetworks);
diff --git a/modules/shared_options.py b/modules/shared_options.py
index 74a2a67f933..ec5cb0264da 100644
--- a/modules/shared_options.py
+++ b/modules/shared_options.py
@@ -254,6 +254,7 @@
"extra_networks_card_show_desc": OptionInfo(True, "Show description on card"),
"extra_networks_card_order_field": OptionInfo("Path", "Default order field for Extra Networks cards", gr.Dropdown, {"choices": ['Path', 'Name', 'Date Created', 'Date Modified']}).needs_reload_ui(),
"extra_networks_card_order": OptionInfo("Ascending", "Default order for Extra Networks cards", gr.Dropdown, {"choices": ['Ascending', 'Descending']}).needs_reload_ui(),
+ "extra_networks_tree_view_default_enabled": OptionInfo(False, "Enables the Extra Networks directory tree view by default").needs_reload_ui(),
"extra_networks_add_text_separator": OptionInfo(" ", "Extra networks separator").info("extra text to add before <...> when adding extra network to prompt"),
"ui_extra_networks_tab_reorder": OptionInfo("", "Extra networks tab order").needs_reload_ui(),
"textual_inversion_print_at_load": OptionInfo(False, "Print a list of Textual Inversion embeddings when loading model"),
diff --git a/modules/ui_extra_networks.py b/modules/ui_extra_networks.py
index 62db36f53cc..157b3a6d4a9 100644
--- a/modules/ui_extra_networks.py
+++ b/modules/ui_extra_networks.py
@@ -2,6 +2,8 @@
import os.path
import urllib.parse
from pathlib import Path
+from typing import Optional, Union
+from dataclasses import dataclass
from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks, util
from modules.images import read_info_from_image, save_image_with_geninfo
@@ -11,14 +13,11 @@
from fastapi.exceptions import HTTPException
from modules.infotext_utils import image_from_url_text
-from modules.ui_components import ToolButton
extra_pages = []
allowed_dirs = set()
-
default_allowed_preview_extensions = ["png", "jpg", "jpeg", "webp", "gif"]
-
@functools.cache
def allowed_preview_extensions_with_extra(extra_extensions=None):
return set(default_allowed_preview_extensions) | set(extra_extensions or [])
@@ -28,6 +27,62 @@ def allowed_preview_extensions():
return allowed_preview_extensions_with_extra((shared.opts.samples_format, ))
+@dataclass
+class ExtraNetworksItem:
+ """Wrapper for dictionaries representing ExtraNetworks items."""
+ item: dict
+
+
+def get_tree(paths: Union[str, list[str]], items: dict[str, ExtraNetworksItem]) -> dict:
+ """Recursively builds a directory tree.
+
+ Args:
+ paths: Path or list of paths to directories. These paths are treated as roots from which
+ the tree will be built.
+ items: A dictionary associating filepaths to an ExtraNetworksItem instance.
+
+ Returns:
+ The result directory tree.
+ """
+ if isinstance(paths, (str,)):
+ paths = [paths]
+
+ def _get_tree(_paths: list[str], _root: str):
+ _res = {}
+ for path in _paths:
+ relpath = os.path.relpath(path, _root)
+ if os.path.isdir(path):
+ dir_items = os.listdir(path)
+ # Ignore empty directories.
+ if not dir_items:
+ continue
+ dir_tree = _get_tree([os.path.join(path, x) for x in dir_items], _root)
+ # We only want to store non-empty folders in the tree.
+ if dir_tree:
+ _res[relpath] = dir_tree
+ else:
+ if path not in items:
+ continue
+ # Add the ExtraNetworksItem to the result.
+ _res[relpath] = items[path]
+ return _res
+
+ res = {}
+ # Handle each root directory separately.
+ # Each root WILL have a key/value at the root of the result dict though
+ # the value can be an empty dict if the directory is empty. We want these
+ # placeholders for empty dirs so we can inform the user later.
+ for path in paths:
+ root = os.path.dirname(path)
+ relpath = os.path.relpath(path, root)
+ # Wrap the path in a list since that is what the `_get_tree` expects.
+ res[relpath] = _get_tree([path], root)
+ if res[relpath]:
+ # We need to pull the inner path out one for these root dirs.
+ res[relpath] = res[relpath][relpath]
+
+ return res
+
def register_page(page):
"""registers extra networks page for the UI; recommend doing it in on_before_ui() callback for extensions"""
@@ -80,7 +135,7 @@ def get_single_card(page: str = "", tabname: str = "", name: str = ""):
item = page.items.get(name)
page.read_user_metadata(item)
- item_html = page.create_html_for_item(item, tabname)
+ item_html = page.create_item_html(tabname, item)
return JSONResponse({"html": item_html})
@@ -96,18 +151,24 @@ def quote_js(s):
s = s.replace('"', '\\"')
return f'"{s}"'
-
class ExtraNetworksPage:
def __init__(self, title):
self.title = title
self.name = title.lower()
- self.id_page = self.name.replace(" ", "_")
- self.card_page = shared.html("extra-networks-card.html")
+ # 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.card_tpl = shared.html("extra-networks-card.html")
+ self.btn_tree_tpl = shared.html("extra-networks-tree-button.html")
+ 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")
def refresh(self):
pass
@@ -129,117 +190,69 @@ def link_preview(self, filename):
def search_terms_from_path(self, filename, possible_directories=None):
abspath = os.path.abspath(filename)
-
for parentdir in (possible_directories if possible_directories is not None else self.allowed_directories_for_previews()):
- parentdir = os.path.abspath(parentdir)
+ parentdir = os.path.dirname(os.path.abspath(parentdir))
if abspath.startswith(parentdir):
- return abspath[len(parentdir):].replace('\\', '/')
+ return os.path.relpath(abspath, parentdir)
return ""
- def create_html(self, tabname):
- self.lister.reset()
-
- items_html = ''
-
- self.metadata = {}
-
- subdirs = {}
- for parentdir in [os.path.abspath(x) for x in self.allowed_directories_for_previews()]:
- for root, dirs, _ in sorted(os.walk(parentdir, followlinks=True), key=lambda x: shared.natural_sort_key(x[0])):
- for dirname in sorted(dirs, key=shared.natural_sort_key):
- x = os.path.join(root, dirname)
-
- if not os.path.isdir(x):
- continue
-
- subdir = os.path.abspath(x)[len(parentdir):].replace("\\", "/")
-
- if shared.opts.extra_networks_dir_button_function:
- if not subdir.startswith("/"):
- subdir = "/" + subdir
- else:
- while subdir.startswith("/"):
- subdir = subdir[1:]
-
- is_empty = len(os.listdir(x)) == 0
- if not is_empty and not subdir.endswith("/"):
- subdir = subdir + "/"
-
- if ("/." in subdir or subdir.startswith(".")) and not shared.opts.extra_networks_show_hidden_directories:
- continue
-
- subdirs[subdir] = 1
-
- if subdirs:
- subdirs = {"": 1, **subdirs}
-
- subdirs_html = "".join([f"""
-
-""" for subdir in subdirs])
-
- self.items = {x["name"]: x for x in self.list_items()}
- for item in self.items.values():
- metadata = item.get("metadata")
- if metadata:
- self.metadata[item["name"]] = metadata
-
- if "user_metadata" not in item:
- self.read_user_metadata(item)
-
- items_html += self.create_html_for_item(item, tabname)
-
- if items_html == '':
- dirs = "".join([f"
{x}
" for x in self.allowed_directories_for_previews()])
- items_html = shared.html("extra-networks-no-cards.html").format(dirs=dirs)
-
- self_name_id = self.name.replace(" ", "_")
-
- res = f"""
-
-{subdirs_html}
-
-
-{items_html}
-
-"""
-
- return res
-
- def create_item(self, name, index=None):
- raise NotImplementedError()
-
- def list_items(self):
- raise NotImplementedError()
-
- def allowed_directories_for_previews(self):
- return []
-
- def create_html_for_item(self, item, tabname):
+ def create_item_html(
+ self,
+ tabname: str,
+ item: dict,
+ template: Optional[str] = None,
+ ) -> Union[str, dict]:
+ """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:
+ 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.
"""
- Create HTML for card item in tab tabname; can return empty string if the item is not meant to be shown.
- """
-
preview = item.get("preview", None)
+ style_height = f"height: {shared.opts.extra_networks_card_height}px;" if shared.opts.extra_networks_card_height else ''
+ style_width = f"width: {shared.opts.extra_networks_card_width}px;" if shared.opts.extra_networks_card_width else ''
+ style_font_size = f"font-size: {shared.opts.extra_networks_card_text_scale*100}%;"
+ card_style = style_height + style_width + style_font_size
+ background_image = f'' if preview else ''
onclick = item.get("onclick", None)
if onclick is None:
- if "negative_prompt" in item:
- onclick = '"' + html.escape(f"""return cardClicked({quote_js(tabname)}, {item["prompt"]}, {item["negative_prompt"]}, {"true" if self.allow_negative_prompt else "false"})""") + '"'
- else:
- onclick = '"' + html.escape(f"""return cardClicked({quote_js(tabname)}, {item["prompt"]}, {'""'}, {"true" if self.allow_negative_prompt else "false"})""") + '"'
-
- height = f"height: {shared.opts.extra_networks_card_height}px;" if shared.opts.extra_networks_card_height else ''
- width = f"width: {shared.opts.extra_networks_card_width}px;" if shared.opts.extra_networks_card_width else ''
- background_image = f'' if preview else ''
- metadata_button = ""
+ # Don't quote prompt/neg_prompt since they are stored as js strings already.
+ onclick_js_tpl = "cardClicked('{tabname}', {prompt}, {neg_prompt}, {allow_neg});"
+ onclick = onclick_js_tpl.format(
+ **{
+ "tabname": tabname,
+ "prompt": item["prompt"],
+ "neg_prompt": item.get("negative_prompt", "''"),
+ "allow_neg": str(self.allow_negative_prompt).lower(),
+ }
+ )
+ onclick = html.escape(onclick)
+
+ btn_copy_path = self.btn_copy_path_tpl.format(**{"filename": item["filename"]})
+ btn_metadata = ""
metadata = item.get("metadata")
if metadata:
- metadata_button = f""
-
- edit_button = f""
+ btn_metadata = self.btn_metadata_tpl.format(
+ **{
+ "extra_networks_tabname": self.extra_networks_tabname,
+ "name": html.escape(item["name"]),
+ }
+ )
+ btn_edit_item = self.btn_edit_item_tpl.format(
+ **{
+ "tabname": tabname,
+ "extra_networks_tabname": self.extra_networks_tabname,
+ "name": html.escape(item["name"]),
+ }
+ )
local_path = ""
filename = item.get("filename", "")
@@ -259,26 +272,282 @@ def create_html_for_item(self, item, tabname):
if search_only and shared.opts.extra_networks_hidden_models == "Never":
return ""
- sort_keys = " ".join([f'data-sort-{k}="{html.escape(str(v))}"' for k, v in item.get("sort_keys", {}).items()]).strip()
-
+ sort_keys = " ".join(
+ [
+ f'data-sort-{k}="{html.escape(str(v))}"'
+ for k, v in item.get("sort_keys", {}).items()
+ ]
+ ).strip()
+
+ search_terms_html = ""
+ search_term_template = "{search_term}"
+ for search_term in item.get("search_terms", []):
+ search_terms_html += search_term_template.format(
+ **{
+ "class": f"search_terms{' search_only' if search_only else ''}",
+ "search_term": search_term,
+ }
+ )
+
+ # Some items here might not be used depending on HTML template used.
args = {
"background_image": background_image,
- "style": f"'display: none; {height}{width}; font-size: {shared.opts.extra_networks_card_text_scale*100}%'",
- "prompt": item.get("prompt", None),
- "tabname": quote_js(tabname),
+ "card_clicked": onclick,
+ "copy_path_button": btn_copy_path,
+ "description": (item.get("description", "") or "" if shared.opts.extra_networks_card_show_desc else ""),
+ "edit_button": btn_edit_item,
"local_preview": quote_js(item["local_preview"]),
+ "metadata_button": btn_metadata,
"name": html.escape(item["name"]),
- "description": (item.get("description") or "" if shared.opts.extra_networks_card_show_desc else ""),
- "card_clicked": onclick,
- "save_card_preview": '"' + html.escape(f"""return saveCardPreview(event, {quote_js(tabname)}, {quote_js(item["local_preview"])})""") + '"',
- "search_term": item.get("search_term", ""),
- "metadata_button": metadata_button,
- "edit_button": edit_button,
+ "prompt": item.get("prompt", None),
+ "save_card_preview": html.escape(f"return saveCardPreview(event, '{tabname}', '{item['local_preview']}');"),
"search_only": " search_only" if search_only else "",
+ "search_terms": search_terms_html,
"sort_keys": sort_keys,
+ "style": card_style,
+ "tabname": tabname,
+ "extra_networks_tabname": self.extra_networks_tabname,
}
- return self.card_page.format(**args)
+ if template:
+ return template.format(**args)
+ else:
+ return args
+
+ 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
"
+ )
+
+ 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(
+ [
+ item_html_args["copy_path_button"],
+ item_html_args["metadata_button"],
+ item_html_args["edit_button"],
+ ]
+ )
+ action_buttons = f"
"
+ )
+
+ def create_tree_view_html(self, tabname: str) -> str:
+ """Generates HTML for displaying folders in a tree view.
+
+ Args:
+ tabname: The name of the active tab.
+
+ Returns:
+ HTML string generated for this tree view.
+ """
+ res = ""
+
+ # 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)
+
+ if not tree:
+ return res
+
+ def _build_tree(data: Optional[dict[str, ExtraNetworksItem]] = None) -> Optional[str]:
+ """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
+
+ # Lists for storing
items html for directories and files separately.
+ _dir_li = []
+ _file_li = []
+
+ for k, v in sorted(data.items(), key=lambda x: shared.natural_sort_key(x[0])):
+ if isinstance(v, (ExtraNetworksItem,)):
+ _file_li.append(self.create_tree_file_item_html(tabname, k, v.item))
+ else:
+ _dir_li.append(self.create_tree_dir_item_html(tabname, k, _build_tree(v)))
+
+ # 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])):
+ item_html = self.create_tree_dir_item_html(tabname, k, _build_tree(v))
+ # Only add non-empty entries to the tree.
+ if item_html is not None:
+ res += item_html
+
+ return f"
{res}
"
+
+ 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`
with
+ `id='{tabname}_{extra_networks_tabname}_cards`.
+
+ Args:
+ tabname: The name of the active tab.
+
+ Returns:
+ HTML formatted string.
+ """
+ res = ""
+ for item in self.items.values():
+ res += self.create_item_html(tabname, item, self.card_tpl)
+
+ if res == "":
+ dirs = "".join([f"