aboutsummaryrefslogtreecommitdiff
path: root/javascript
diff options
context:
space:
mode:
Diffstat (limited to 'javascript')
-rw-r--r--javascript/aspectRatioOverlay.js82
-rw-r--r--javascript/contextMenus.js25
-rw-r--r--javascript/edit-attention.js48
-rw-r--r--javascript/extensions.js34
-rw-r--r--javascript/extraNetworks.js106
-rw-r--r--javascript/generationParams.js8
-rw-r--r--javascript/hints.js87
-rw-r--r--javascript/hires_fix.js16
-rw-r--r--javascript/imageMaskFix.js13
-rw-r--r--javascript/imageParams.js1
-rw-r--r--javascript/imageviewer.js105
-rw-r--r--javascript/imageviewerGamepad.js57
-rw-r--r--javascript/localization.js76
-rw-r--r--javascript/notification.js8
-rw-r--r--javascript/progressbar.js76
-rw-r--r--javascript/ui.js171
-rw-r--r--javascript/ui_settings_hints.js62
17 files changed, 627 insertions, 348 deletions
diff --git a/javascript/aspectRatioOverlay.js b/javascript/aspectRatioOverlay.js
index 0f164b82..5160081d 100644
--- a/javascript/aspectRatioOverlay.js
+++ b/javascript/aspectRatioOverlay.js
@@ -12,7 +12,7 @@ function dimensionChange(e, is_width, is_height){
currentHeight = e.target.value*1.0
}
- var inImg2img = Boolean(gradioApp().querySelector("button.rounded-t-lg.border-gray-200"))
+ var inImg2img = gradioApp().querySelector("#tab_img2img").style.display == "block";
if(!inImg2img){
return;
@@ -22,7 +22,7 @@ function dimensionChange(e, is_width, is_height){
var tabIndex = get_tab_index('mode_img2img')
if(tabIndex == 0){ // img2img
- targetElement = gradioApp().querySelector('div[data-testid=image] img');
+ targetElement = gradioApp().querySelector('#img2img_image div[data-testid=image] img');
} else if(tabIndex == 1){ //Sketch
targetElement = gradioApp().querySelector('#img2img_sketch div[data-testid=image] img');
} else if(tabIndex == 2){ // Inpaint
@@ -30,7 +30,7 @@ function dimensionChange(e, is_width, is_height){
} else if(tabIndex == 3){ // Inpaint sketch
targetElement = gradioApp().querySelector('#inpaint_sketch div[data-testid=image] img');
}
-
+
if(targetElement){
@@ -38,36 +38,31 @@ function dimensionChange(e, is_width, is_height){
if(!arPreviewRect){
arPreviewRect = document.createElement('div')
arPreviewRect.id = "imageARPreview";
- gradioApp().getRootNode().appendChild(arPreviewRect)
+ gradioApp().appendChild(arPreviewRect)
}
var viewportOffset = targetElement.getBoundingClientRect();
- viewportscale = Math.min( targetElement.clientWidth/targetElement.naturalWidth, targetElement.clientHeight/targetElement.naturalHeight )
-
- scaledx = targetElement.naturalWidth*viewportscale
- scaledy = targetElement.naturalHeight*viewportscale
+ var viewportscale = Math.min( targetElement.clientWidth/targetElement.naturalWidth, targetElement.clientHeight/targetElement.naturalHeight )
- cleintRectTop = (viewportOffset.top+window.scrollY)
- cleintRectLeft = (viewportOffset.left+window.scrollX)
- cleintRectCentreY = cleintRectTop + (targetElement.clientHeight/2)
- cleintRectCentreX = cleintRectLeft + (targetElement.clientWidth/2)
+ var scaledx = targetElement.naturalWidth*viewportscale
+ var scaledy = targetElement.naturalHeight*viewportscale
- viewRectTop = cleintRectCentreY-(scaledy/2)
- viewRectLeft = cleintRectCentreX-(scaledx/2)
- arRectWidth = scaledx
- arRectHeight = scaledy
+ var cleintRectTop = (viewportOffset.top+window.scrollY)
+ var cleintRectLeft = (viewportOffset.left+window.scrollX)
+ var cleintRectCentreY = cleintRectTop + (targetElement.clientHeight/2)
+ var cleintRectCentreX = cleintRectLeft + (targetElement.clientWidth/2)
- arscale = Math.min( arRectWidth/currentWidth, arRectHeight/currentHeight )
- arscaledx = currentWidth*arscale
- arscaledy = currentHeight*arscale
+ var arscale = Math.min( scaledx/currentWidth, scaledy/currentHeight )
+ var arscaledx = currentWidth*arscale
+ var arscaledy = currentHeight*arscale
- arRectTop = cleintRectCentreY-(arscaledy/2)
- arRectLeft = cleintRectCentreX-(arscaledx/2)
- arRectWidth = arscaledx
- arRectHeight = arscaledy
+ var arRectTop = cleintRectCentreY-(arscaledy/2)
+ var arRectLeft = cleintRectCentreX-(arscaledx/2)
+ var arRectWidth = arscaledx
+ var arRectHeight = arscaledy
arPreviewRect.style.top = arRectTop+'px';
arPreviewRect.style.left = arRectLeft+'px';
@@ -91,23 +86,26 @@ onUiUpdate(function(){
if(arPreviewRect){
arPreviewRect.style.display = 'none';
}
- var inImg2img = Boolean(gradioApp().querySelector("button.rounded-t-lg.border-gray-200"))
- if(inImg2img){
- let inputs = gradioApp().querySelectorAll('input');
- inputs.forEach(function(e){
- var is_width = e.parentElement.id == "img2img_width"
- var is_height = e.parentElement.id == "img2img_height"
-
- if((is_width || is_height) && !e.classList.contains('scrollwatch')){
- e.addEventListener('input', function(e){dimensionChange(e, is_width, is_height)} )
- e.classList.add('scrollwatch')
- }
- if(is_width){
- currentWidth = e.value*1.0
- }
- if(is_height){
- currentHeight = e.value*1.0
- }
- })
- }
+ var tabImg2img = gradioApp().querySelector("#tab_img2img");
+ if (tabImg2img) {
+ var inImg2img = tabImg2img.style.display == "block";
+ if(inImg2img){
+ let inputs = gradioApp().querySelectorAll('input');
+ inputs.forEach(function(e){
+ var is_width = e.parentElement.id == "img2img_width"
+ var is_height = e.parentElement.id == "img2img_height"
+
+ if((is_width || is_height) && !e.classList.contains('scrollwatch')){
+ e.addEventListener('input', function(e){dimensionChange(e, is_width, is_height)} )
+ e.classList.add('scrollwatch')
+ }
+ if(is_width){
+ currentWidth = e.value*1.0
+ }
+ if(is_height){
+ currentHeight = e.value*1.0
+ }
+ })
+ }
+ }
});
diff --git a/javascript/contextMenus.js b/javascript/contextMenus.js
index 11bcce1b..b2bdf053 100644
--- a/javascript/contextMenus.js
+++ b/javascript/contextMenus.js
@@ -4,7 +4,7 @@ contextMenuInit = function(){
let menuSpecs = new Map();
const uid = function(){
- return Date.now().toString(36) + Math.random().toString(36).substr(2);
+ return Date.now().toString(36) + Math.random().toString(36).substring(2);
}
function showContextMenu(event,element,menuEntries){
@@ -16,8 +16,7 @@ contextMenuInit = function(){
oldMenu.remove()
}
- let tabButton = uiCurrentTab
- let baseStyle = window.getComputedStyle(tabButton)
+ let baseStyle = window.getComputedStyle(uiCurrentTab)
const contextMenu = document.createElement('nav')
contextMenu.id = "context-menu"
@@ -36,14 +35,14 @@ contextMenuInit = function(){
menuEntries.forEach(function(entry){
let contextMenuEntry = document.createElement('a')
contextMenuEntry.innerHTML = entry['name']
- contextMenuEntry.addEventListener("click", function(e) {
+ contextMenuEntry.addEventListener("click", function() {
entry['func']();
})
contextMenuList.append(contextMenuEntry);
})
- gradioApp().getRootNode().appendChild(contextMenu)
+ gradioApp().appendChild(contextMenu)
let menuWidth = contextMenu.offsetWidth + 4;
let menuHeight = contextMenu.offsetHeight + 4;
@@ -63,7 +62,7 @@ contextMenuInit = function(){
function appendContextMenuOption(targetElementSelector,entryName,entryFunction){
- currentItems = menuSpecs.get(targetElementSelector)
+ var currentItems = menuSpecs.get(targetElementSelector)
if(!currentItems){
currentItems = []
@@ -79,7 +78,7 @@ contextMenuInit = function(){
}
function removeContextMenuOption(uid){
- menuSpecs.forEach(function(v,k) {
+ menuSpecs.forEach(function(v) {
let index = -1
v.forEach(function(e,ei){if(e['id']==uid){index=ei}})
if(index>=0){
@@ -93,8 +92,7 @@ contextMenuInit = function(){
return;
}
gradioApp().addEventListener("click", function(e) {
- let source = e.composedPath()[0]
- if(source.id && source.id.indexOf('check_progress')>-1){
+ if(! e.isTrusted){
return
}
@@ -112,7 +110,6 @@ contextMenuInit = function(){
if(e.composedPath()[0].matches(k)){
showContextMenu(e,e.composedPath()[0],v)
e.preventDefault()
- return
}
})
});
@@ -161,14 +158,6 @@ addContextMenuEventListener = initResponse[2];
appendContextMenuOption('#img2img_interrupt','Cancel generate forever',cancelGenerateForever)
appendContextMenuOption('#img2img_generate', 'Cancel generate forever',cancelGenerateForever)
- appendContextMenuOption('#roll','Roll three',
- function(){
- let rollbutton = get_uiCurrentTabContent().querySelector('#roll');
- setTimeout(function(){rollbutton.click()},100)
- setTimeout(function(){rollbutton.click()},200)
- setTimeout(function(){rollbutton.click()},300)
- }
- )
})();
//End example Context Menu Items
diff --git a/javascript/edit-attention.js b/javascript/edit-attention.js
index 619bb1fa..d2c2f190 100644
--- a/javascript/edit-attention.js
+++ b/javascript/edit-attention.js
@@ -1,6 +1,6 @@
function keyupEditAttention(event){
let target = event.originalTarget || event.composedPath()[0];
- if (!target.matches("[id*='_toprow'] textarea.gr-text-input[placeholder]")) return;
+ if (! target.matches("[id*='_toprow'] [id*='_prompt'] textarea")) return;
if (! (event.metaKey || event.ctrlKey)) return;
let isPlus = event.key == "ArrowUp"
@@ -17,7 +17,7 @@ function keyupEditAttention(event){
// Find opening parenthesis around current cursor
const before = text.substring(0, selectionStart);
let beforeParen = before.lastIndexOf(OPEN);
- if (beforeParen == -1) return false;
+ if (beforeParen == -1) return false;
let beforeParenClose = before.lastIndexOf(CLOSE);
while (beforeParenClose !== -1 && beforeParenClose > beforeParen) {
beforeParen = before.lastIndexOf(OPEN, beforeParen - 1);
@@ -27,7 +27,7 @@ function keyupEditAttention(event){
// Find closing parenthesis around current cursor
const after = text.substring(selectionStart);
let afterParen = after.indexOf(CLOSE);
- if (afterParen == -1) return false;
+ if (afterParen == -1) return false;
let afterParenOpen = after.indexOf(OPEN);
while (afterParenOpen !== -1 && afterParen > afterParenOpen) {
afterParen = after.indexOf(CLOSE, afterParen + 1);
@@ -43,16 +43,34 @@ function keyupEditAttention(event){
target.setSelectionRange(selectionStart, selectionEnd);
return true;
}
+
+ function selectCurrentWord(){
+ if (selectionStart !== selectionEnd) return false;
+ const delimiters = opts.keyedit_delimiters + " \r\n\t";
+
+ // seek backward until to find beggining
+ while (!delimiters.includes(text[selectionStart - 1]) && selectionStart > 0) {
+ selectionStart--;
+ }
+
+ // seek forward to find end
+ while (!delimiters.includes(text[selectionEnd]) && selectionEnd < text.length) {
+ selectionEnd++;
+ }
- // If the user hasn't selected anything, let's select their current parenthesis block
- if(! selectCurrentParenthesisBlock('<', '>')){
- selectCurrentParenthesisBlock('(', ')')
+ target.setSelectionRange(selectionStart, selectionEnd);
+ return true;
+ }
+
+ // If the user hasn't selected anything, let's select their current parenthesis block or word
+ if (!selectCurrentParenthesisBlock('<', '>') && !selectCurrentParenthesisBlock('(', ')')) {
+ selectCurrentWord();
}
event.preventDefault();
- closeCharacter = ')'
- delta = opts.keyedit_precision_attention
+ var closeCharacter = ')'
+ var delta = opts.keyedit_precision_attention
if (selectionStart > 0 && text[selectionStart - 1] == '<'){
closeCharacter = '>'
@@ -73,15 +91,21 @@ function keyupEditAttention(event){
selectionEnd += 1;
}
- end = text.slice(selectionEnd + 1).indexOf(closeCharacter) + 1;
- weight = parseFloat(text.slice(selectionEnd + 1, selectionEnd + 1 + end));
+ var end = text.slice(selectionEnd + 1).indexOf(closeCharacter) + 1;
+ var weight = parseFloat(text.slice(selectionEnd + 1, selectionEnd + 1 + end));
if (isNaN(weight)) return;
weight += isPlus ? delta : -delta;
weight = parseFloat(weight.toPrecision(12));
if(String(weight).length == 1) weight += ".0"
- text = text.slice(0, selectionEnd + 1) + weight + text.slice(selectionEnd + 1 + end - 1);
+ if (closeCharacter == ')' && weight == 1) {
+ text = text.slice(0, selectionStart - 1) + text.slice(selectionStart, selectionEnd) + text.slice(selectionEnd + 5);
+ selectionStart--;
+ selectionEnd--;
+ } else {
+ text = text.slice(0, selectionEnd + 1) + weight + text.slice(selectionEnd + 1 + end - 1);
+ }
target.focus();
target.value = text;
@@ -93,4 +117,4 @@ function keyupEditAttention(event){
addEventListener('keydown', (event) => {
keyupEditAttention(event);
-}); \ No newline at end of file
+});
diff --git a/javascript/extensions.js b/javascript/extensions.js
index c593cd2e..2a2d2f8e 100644
--- a/javascript/extensions.js
+++ b/javascript/extensions.js
@@ -1,19 +1,19 @@
-function extensions_apply(_, _){
+function extensions_apply(_disabled_list, _update_list, disable_all){
var disable = []
var update = []
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x){
if(x.name.startsWith("enable_") && ! x.checked)
- disable.push(x.name.substr(7))
+ disable.push(x.name.substring(7))
if(x.name.startsWith("update_") && x.checked)
- update.push(x.name.substr(7))
+ update.push(x.name.substring(7))
})
restart_reload()
- return [JSON.stringify(disable), JSON.stringify(update)]
+ return [JSON.stringify(disable), JSON.stringify(update), disable_all]
}
function extensions_check(){
@@ -21,7 +21,7 @@ function extensions_check(){
gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x){
if(x.name.startsWith("enable_") && ! x.checked)
- disable.push(x.name.substr(7))
+ disable.push(x.name.substring(7))
})
gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x){
@@ -41,9 +41,31 @@ function install_extension_from_index(button, url){
button.disabled = "disabled"
button.value = "Installing..."
- textarea = gradioApp().querySelector('#extension_to_install textarea')
+ var textarea = gradioApp().querySelector('#extension_to_install textarea')
textarea.value = url
updateInput(textarea)
gradioApp().querySelector('#install_extension_button').click()
}
+
+function config_state_confirm_restore(_, config_state_name, config_restore_type) {
+ if (config_state_name == "Current") {
+ return [false, config_state_name, config_restore_type];
+ }
+ let restored = "";
+ if (config_restore_type == "extensions") {
+ restored = "all saved extension versions";
+ } else if (config_restore_type == "webui") {
+ restored = "the webui version";
+ } else {
+ restored = "the webui version and all saved extension versions";
+ }
+ let confirmed = confirm("Are you sure you want to restore from this state?\nThis will reset " + restored + ".");
+ if (confirmed) {
+ restart_reload();
+ gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x){
+ x.innerHTML = "Loading..."
+ })
+ }
+ return [confirmed, config_state_name, config_restore_type];
+}
diff --git a/javascript/extraNetworks.js b/javascript/extraNetworks.js
index 2fb87cd5..4d9a522c 100644
--- a/javascript/extraNetworks.js
+++ b/javascript/extraNetworks.js
@@ -1,4 +1,3 @@
-
function setupExtraNetworksForTab(tabname){
gradioApp().querySelector('#'+tabname+'_extra_tabs').classList.add('extra-networks')
@@ -10,16 +9,34 @@ function setupExtraNetworksForTab(tabname){
tabs.appendChild(search)
tabs.appendChild(refresh)
- search.addEventListener("input", function(evt){
- searchTerm = search.value.toLowerCase()
+ var applyFilter = function(){
+ var searchTerm = search.value.toLowerCase()
gradioApp().querySelectorAll('#'+tabname+'_extra_tabs div.card').forEach(function(elem){
- text = elem.querySelector('.name').textContent.toLowerCase() + " " + elem.querySelector('.search_term').textContent.toLowerCase()
- elem.style.display = text.indexOf(searchTerm) == -1 ? "none" : ""
+ 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
+ }
+
+ elem.style.display = visible ? "" : "none"
})
- });
+ }
+
+ search.addEventListener("input", applyFilter);
+ applyFilter();
+
+ extraNetworksApplyFilter[tabname] = applyFilter;
+}
+
+function applyExtraNetworkFilter(tabname){
+ setTimeout(extraNetworksApplyFilter[tabname], 1);
}
+var extraNetworksApplyFilter = {}
var activePromptTextarea = {};
function setupExtraNetworks(){
@@ -51,18 +68,27 @@ var re_extranet_g = /\s+<([^:]+:[^:]+):[\d\.]+>/g;
function tryToRemoveExtraNetworkFromPrompt(textarea, text){
var m = text.match(re_extranet)
- if(! m) return false
-
- var partToSearch = m[1]
var replaced = false
- var newTextareaText = textarea.value.replaceAll(re_extranet_g, function(found, index){
- m = found.match(re_extranet);
- if(m[1] == partToSearch){
- replaced = true;
- return ""
- }
- return found;
- })
+ var newTextareaText
+ if(m) {
+ var partToSearch = m[1]
+ newTextareaText = textarea.value.replaceAll(re_extranet_g, function(found){
+ m = found.match(re_extranet);
+ if(m[1] == partToSearch){
+ replaced = true;
+ return ""
+ }
+ return found;
+ })
+ } else {
+ newTextareaText = textarea.value.replaceAll(new RegExp(text, "g"), function(found){
+ if(found == text) {
+ replaced = true;
+ return ""
+ }
+ return found;
+ })
+ }
if(replaced){
textarea.value = newTextareaText
@@ -96,9 +122,9 @@ function saveCardPreview(event, tabname, filename){
}
function extraNetworksSearchButton(tabs_id, event){
- searchTextarea = gradioApp().querySelector("#" + tabs_id + ' > div > textarea')
- button = event.target
- text = button.classList.contains("search-all") ? "" : button.textContent.trim()
+ var searchTextarea = gradioApp().querySelector("#" + tabs_id + ' > div > textarea')
+ var button = event.target
+ var text = button.classList.contains("search-all") ? "" : button.textContent.trim()
searchTextarea.value = text
updateInput(searchTextarea)
@@ -133,9 +159,47 @@ function popup(contents){
}
function extraNetworksShowMetadata(text){
- elem = document.createElement('pre')
+ var elem = document.createElement('pre')
elem.classList.add('popup-metadata');
elem.textContent = text;
popup(elem);
}
+
+function requestGet(url, data, handler, errorHandler){
+ var xhr = new XMLHttpRequest();
+ var args = Object.keys(data).map(function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }).join('&')
+ xhr.open("GET", url + "?" + args, true);
+
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ if (xhr.status === 200) {
+ try {
+ var js = JSON.parse(xhr.responseText);
+ handler(js)
+ } catch (error) {
+ console.error(error);
+ errorHandler()
+ }
+ } else{
+ errorHandler()
+ }
+ }
+ };
+ var js = JSON.stringify(data);
+ xhr.send(js);
+}
+
+function extraNetworksRequestMetadata(event, extraPage, cardName){
+ var showError = function(){ extraNetworksShowMetadata("there was an error getting metadata"); }
+
+ requestGet("./sd_extra_networks/metadata", {"page": extraPage, "item": cardName}, function(data){
+ if(data && data.metadata){
+ extraNetworksShowMetadata(data.metadata)
+ } else{
+ showError()
+ }
+ }, showError)
+
+ event.stopPropagation()
+}
diff --git a/javascript/generationParams.js b/javascript/generationParams.js
index 95f05093..ef64ee2e 100644
--- a/javascript/generationParams.js
+++ b/javascript/generationParams.js
@@ -16,14 +16,14 @@ onUiUpdate(function(){
let modalObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
- let selectedTab = gradioApp().querySelector('#tabs div button.bg-white')?.innerText
- if (mutationRecord.target.style.display === 'none' && selectedTab === 'txt2img' || selectedTab === 'img2img')
- gradioApp().getElementById(selectedTab+"_generation_info_button").click()
+ let selectedTab = gradioApp().querySelector('#tabs div button.selected')?.innerText
+ if (mutationRecord.target.style.display === 'none' && (selectedTab === 'txt2img' || selectedTab === 'img2img'))
+ gradioApp().getElementById(selectedTab+"_generation_info_button")?.click()
});
});
function attachGalleryListeners(tab_name) {
- gallery = gradioApp().querySelector('#'+tab_name+'_gallery')
+ var gallery = gradioApp().querySelector('#'+tab_name+'_gallery')
gallery?.addEventListener('click', () => gradioApp().getElementById(tab_name+"_generation_info_button").click());
gallery?.addEventListener('keydown', (e) => {
if (e.keyCode == 37 || e.keyCode == 39) // left or right arrow
diff --git a/javascript/hints.js b/javascript/hints.js
index 7f4101b2..d2efd35e 100644
--- a/javascript/hints.js
+++ b/javascript/hints.js
@@ -9,6 +9,7 @@ titles = {
"UniPC": "Unified Predictor-Corrector Framework for Fast Sampling of Diffusion Models",
"DPM adaptive": "Ignores step count - uses a number of steps determined by the CFG and resolution",
+ "\u{1F4D0}": "Auto detect size from img2img",
"Batch count": "How many batches of images to create (has no impact on generation performance or VRAM usage)",
"Batch size": "How many image to create in a single batch (increases generation performance at cost of higher VRAM usage)",
"CFG Scale": "Classifier Free Guidance Scale - how strongly the image should conform to prompt - lower values produce more creative results",
@@ -18,11 +19,11 @@ titles = {
"\u2199\ufe0f": "Read generation parameters from prompt or last generation if prompt is empty into user interface.",
"\u{1f4c2}": "Open images output directory",
"\u{1f4be}": "Save style",
- "\u{1f5d1}": "Clear prompt",
+ "\u{1f5d1}\ufe0f": "Clear prompt",
"\u{1f4cb}": "Apply selected styles to current prompt",
"\u{1f4d2}": "Paste available values into the field",
- "\u{1f3b4}": "Show extra networks",
-
+ "\u{1f3b4}": "Show/hide extra networks",
+ "\u{1f300}": "Restore progress",
"Inpaint a part of image": "Draw a mask over an image, and the script will regenerate the masked area with content according to prompt",
"SD upscale": "Upscale image normally, split result into tiles, improve each tile using img2img, merge whole image back",
@@ -40,8 +41,7 @@ titles = {
"Inpaint at full resolution": "Upscale masked region to target resolution, do inpainting, downscale back and paste into original image",
"Denoising strength": "Determines how little respect the algorithm should have for image's content. At 0, nothing will change, and at 1 you'll get an unrelated image. With values below 1.0, processing will take less steps than the Sampling Steps slider specifies.",
- "Denoising strength change factor": "In loopback mode, on each loop the denoising strength is multiplied by this value. <1 means decreasing variety so your sequence will converge on a fixed picture. >1 means increasing variety so your sequence will become more and more chaotic.",
-
+
"Skip": "Stop processing current image and continue processing.",
"Interrupt": "Stop processing images and return any results accumulated so far.",
"Save": "Write image to a directory (default - log/images) and generation parameters into csv file.",
@@ -67,12 +67,14 @@ titles = {
"Interrogate": "Reconstruct prompt from existing image and put it into the prompt field.",
- "Images filename pattern": "Use following tags to define how filenames for images are chosen: [steps], [cfg], [prompt_hash], [prompt], [prompt_no_styles], [prompt_spaces], [width], [height], [styles], [sampler], [seed], [model_hash], [model_name], [prompt_words], [date], [datetime], [datetime<Format>], [datetime<Format><Time Zone>], [job_timestamp]; leave empty for default.",
- "Directory name pattern": "Use following tags to define how subdirectories for images and grids are chosen: [steps], [cfg],[prompt_hash], [prompt], [prompt_no_styles], [prompt_spaces], [width], [height], [styles], [sampler], [seed], [model_hash], [model_name], [prompt_words], [date], [datetime], [datetime<Format>], [datetime<Format><Time Zone>], [job_timestamp]; leave empty for default.",
+ "Images filename pattern": "Use tags like [seed] and [date] to define how filenames for images are chosen. Leave empty for default.",
+ "Directory name pattern": "Use tags like [seed] and [date] to define how subdirectories for images and grids are chosen. Leave empty for default.",
"Max prompt words": "Set the maximum number of words to be used in the [prompt_words] option; ATTENTION: If the words are too long, they may exceed the maximum length of the file path that the system can handle",
- "Loopback": "Process an image, use it as an input, repeat.",
- "Loops": "How many times to repeat processing an image and using it as input for the next iteration",
+ "Loopback": "Performs img2img processing multiple times. Output images are used as input for the next loop.",
+ "Loops": "How many times to process an image. Each output is used as the input of the next loop. If set to 1, behavior will be as if this script were not used.",
+ "Final denoising strength": "The denoising strength for the final loop of each image in the batch.",
+ "Denoising strength curve": "The denoising curve controls the rate of denoising strength change each loop. Aggressive: Most of the change will happen towards the start of the loops. Linear: Change will be constant through all loops. Lazy: Most of the change will happen towards the end of the loops.",
"Style 1": "Style to apply; styles have components for both positive and negative prompts and apply to both",
"Style 2": "Style to apply; styles have components for both positive and negative prompts and apply to both",
@@ -85,7 +87,6 @@ titles = {
"vram": "Torch active: Peak amount of VRAM used by Torch during generation, excluding cached data.\nTorch reserved: Peak amount of VRAM allocated by Torch, including all active and cached data.\nSys VRAM: Peak amount of VRAM allocation across all applications / total GPU VRAM (peak utilization%).",
"Eta noise seed delta": "If this values is non-zero, it will be added to seed and used to initialize RNG for noises when using samplers with Eta. You can use this to produce even more variation of images, or you can use this to match images of other software if you know what you are doing.",
- "Do not add watermark to images": "If this option is enabled, watermark will not be added to created images. Warning: if you do not add watermark, you may be behaving in an unethical manner.",
"Filename word regex": "This regular expression will be used extract words from filename, and they will be joined using the option below into label text used for training. Leave empty to keep filename text as it is.",
"Filename join string": "This string will be used to join split words into a single line if the option above is enabled.",
@@ -111,37 +112,57 @@ titles = {
"Resize height to": "Resizes image to this height. If 0, height is inferred from either of two nearby sliders.",
"Multiplier for extra networks": "When adding extra network such as Hypernetwork or Lora to prompt, use this multiplier for it.",
"Discard weights with matching name": "Regular expression; if weights's name matches it, the weights is not written to the resulting checkpoint. Use ^model_ema to discard EMA weights.",
- "Extra networks tab order": "Comma-separated list of tab names; tabs listed here will appear in the extra networks UI first and in order lsited."
+ "Extra networks tab order": "Comma-separated list of tab names; tabs listed here will appear in the extra networks UI first and in order lsited.",
+ "Negative Guidance minimum sigma": "Skip negative prompt for steps where image is already mostly denoised; the higher this value, the more skips there will be; provides increased performance in exchange for minor quality reduction."
}
+function updateTooltipForSpan(span){
+ if (span.title) return; // already has a title
-onUiUpdate(function(){
- gradioApp().querySelectorAll('span, button, select, p').forEach(function(span){
- tooltip = titles[span.textContent];
+ let tooltip = localization[titles[span.textContent]] || titles[span.textContent];
- if(!tooltip){
- tooltip = titles[span.value];
- }
+ if(!tooltip){
+ tooltip = localization[titles[span.value]] || titles[span.value];
+ }
- if(!tooltip){
- for (const c of span.classList) {
- if (c in titles) {
- tooltip = titles[c];
- break;
- }
+ if(!tooltip){
+ for (const c of span.classList) {
+ if (c in titles) {
+ tooltip = localization[titles[c]] || titles[c];
+ break;
}
}
+ }
- if(tooltip){
- span.title = tooltip;
- }
- })
+ if(tooltip){
+ span.title = tooltip;
+ }
+}
+
+function updateTooltipForSelect(select){
+ if (select.onchange != null) return;
- gradioApp().querySelectorAll('select').forEach(function(select){
- if (select.onchange != null) return;
+ select.onchange = function(){
+ select.title = localization[titles[select.value]] || titles[select.value] || "";
+ }
+}
- select.onchange = function(){
- select.title = titles[select.value] || "";
- }
- })
+observedTooltipElements = {"SPAN": 1, "BUTTON": 1, "SELECT": 1, "P": 1}
+
+onUiUpdate(function(m){
+ m.forEach(function(record){
+ record.addedNodes.forEach(function(node){
+ if(observedTooltipElements[node.tagName]){
+ updateTooltipForSpan(node)
+ }
+ if(node.tagName == "SELECT"){
+ updateTooltipForSelect(node)
+ }
+
+ if(node.querySelectorAll){
+ node.querySelectorAll('span, button, select, p').forEach(updateTooltipForSpan)
+ node.querySelectorAll('select').forEach(updateTooltipForSelect)
+ }
+ })
+ })
})
diff --git a/javascript/hires_fix.js b/javascript/hires_fix.js
index 0629475f..48196be4 100644
--- a/javascript/hires_fix.js
+++ b/javascript/hires_fix.js
@@ -1,16 +1,12 @@
-function setInactive(elem, inactive){
- if(inactive){
- elem.classList.add('inactive')
- } else{
- elem.classList.remove('inactive')
+function onCalcResolutionHires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y){
+ function setInactive(elem, inactive){
+ elem.classList.toggle('inactive', !!inactive)
}
-}
-function onCalcResolutionHires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y){
- hrUpscaleBy = gradioApp().getElementById('txt2img_hr_scale')
- hrResizeX = gradioApp().getElementById('txt2img_hr_resize_x')
- hrResizeY = gradioApp().getElementById('txt2img_hr_resize_y')
+ var hrUpscaleBy = gradioApp().getElementById('txt2img_hr_scale')
+ var hrResizeX = gradioApp().getElementById('txt2img_hr_resize_x')
+ var hrResizeY = gradioApp().getElementById('txt2img_hr_resize_y')
gradioApp().getElementById('txt2img_hires_fix_row2').style.display = opts.use_old_hires_fix_width_height ? "none" : ""
diff --git a/javascript/imageMaskFix.js b/javascript/imageMaskFix.js
index 9fe7a603..a612705d 100644
--- a/javascript/imageMaskFix.js
+++ b/javascript/imageMaskFix.js
@@ -2,11 +2,10 @@
* temporary fix for https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/668
* @see https://github.com/gradio-app/gradio/issues/1721
*/
-window.addEventListener( 'resize', () => imageMaskResize());
function imageMaskResize() {
const canvases = gradioApp().querySelectorAll('#img2maskimg .touch-none canvas');
if ( ! canvases.length ) {
- canvases_fixed = false;
+ canvases_fixed = false; // TODO: this is unused..?
window.removeEventListener( 'resize', imageMaskResize );
return;
}
@@ -15,7 +14,7 @@ function imageMaskResize() {
const previewImage = wrapper.previousElementSibling;
if ( ! previewImage.complete ) {
- previewImage.addEventListener( 'load', () => imageMaskResize());
+ previewImage.addEventListener( 'load', imageMaskResize);
return;
}
@@ -24,7 +23,6 @@ function imageMaskResize() {
const nw = previewImage.naturalWidth;
const nh = previewImage.naturalHeight;
const portrait = nh > nw;
- const factor = portrait;
const wW = Math.min(w, portrait ? h/nh*nw : w/nw*nw);
const wH = Math.min(h, portrait ? h/nh*nh : w/nw*nh);
@@ -40,6 +38,7 @@ function imageMaskResize() {
c.style.maxHeight = '100%';
c.style.objectFit = 'contain';
});
- }
-
- onUiUpdate(() => imageMaskResize());
+}
+
+onUiUpdate(imageMaskResize);
+window.addEventListener( 'resize', imageMaskResize);
diff --git a/javascript/imageParams.js b/javascript/imageParams.js
index 67404a89..64aee93b 100644
--- a/javascript/imageParams.js
+++ b/javascript/imageParams.js
@@ -1,7 +1,6 @@
window.onload = (function(){
window.addEventListener('drop', e => {
const target = e.composedPath()[0];
- const idx = selected_gallery_index();
if (target.placeholder.indexOf("Prompt") == -1) return;
let prompt_target = get_tab_index('tabs') == 1 ? "img2img_prompt_image" : "txt2img_prompt_image";
diff --git a/javascript/imageviewer.js b/javascript/imageviewer.js
index 28e748b7..32066ab8 100644
--- a/javascript/imageviewer.js
+++ b/javascript/imageviewer.js
@@ -32,13 +32,7 @@ function negmod(n, m) {
function updateOnBackgroundChange() {
const modalImage = gradioApp().getElementById("modalImage")
if (modalImage && modalImage.offsetParent) {
- let allcurrentButtons = gradioApp().querySelectorAll(".gallery-item.transition-all.\\!ring-2")
- let currentButton = null
- allcurrentButtons.forEach(function(elem) {
- if (elem.parentElement.offsetParent) {
- currentButton = elem;
- }
- })
+ let currentButton = selected_gallery_button();
if (currentButton?.children?.length > 0 && modalImage.src != currentButton.children[0].src) {
modalImage.src = currentButton.children[0].src;
@@ -50,22 +44,10 @@ function updateOnBackgroundChange() {
}
function modalImageSwitch(offset) {
- var allgalleryButtons = gradioApp().querySelectorAll(".gallery-item.transition-all")
- var galleryButtons = []
- allgalleryButtons.forEach(function(elem) {
- if (elem.parentElement.offsetParent) {
- galleryButtons.push(elem);
- }
- })
+ var galleryButtons = all_gallery_buttons();
if (galleryButtons.length > 1) {
- var allcurrentButtons = gradioApp().querySelectorAll(".gallery-item.transition-all.\\!ring-2")
- var currentButton = null
- allcurrentButtons.forEach(function(elem) {
- if (elem.parentElement.offsetParent) {
- currentButton = elem;
- }
- })
+ var currentButton = selected_gallery_button();
var result = -1
galleryButtons.forEach(function(v, i) {
@@ -75,7 +57,7 @@ function modalImageSwitch(offset) {
})
if (result != -1) {
- nextButton = galleryButtons[negmod((result + offset), galleryButtons.length)]
+ var nextButton = galleryButtons[negmod((result + offset), galleryButtons.length)]
nextButton.click()
const modalImage = gradioApp().getElementById("modalImage");
const modal = gradioApp().getElementById("lightboxModal");
@@ -136,49 +118,37 @@ function modalKeyHandler(event) {
}
}
-function showGalleryImage() {
- setTimeout(function() {
- fullImg_preview = gradioApp().querySelectorAll('img.w-full.object-contain')
-
- if (fullImg_preview != null) {
- fullImg_preview.forEach(function function_name(e) {
- if (e.dataset.modded)
- return;
- e.dataset.modded = true;
- if(e && e.parentElement.tagName == 'DIV'){
- e.style.cursor='pointer'
- e.style.userSelect='none'
-
- var isFirefox = isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1
-
- // For Firefox, listening on click first switched to next image then shows the lightbox.
- // If you know how to fix this without switching to mousedown event, please.
- // For other browsers the event is click to make it possiblr to drag picture.
- var event = isFirefox ? 'mousedown' : 'click'
-
- e.addEventListener(event, function (evt) {
- if(!opts.js_modal_lightbox || evt.button != 0) return;
- modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initially_zoomed)
- evt.preventDefault()
- showModal(evt)
- }, true);
- }
- });
- }
+function setupImageForLightbox(e) {
+ if (e.dataset.modded)
+ return;
+
+ e.dataset.modded = true;
+ e.style.cursor='pointer'
+ e.style.userSelect='none'
+
+ var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1
+
+ // For Firefox, listening on click first switched to next image then shows the lightbox.
+ // If you know how to fix this without switching to mousedown event, please.
+ // For other browsers the event is click to make it possiblr to drag picture.
+ var event = isFirefox ? 'mousedown' : 'click'
+
+ e.addEventListener(event, function (evt) {
+ if(!opts.js_modal_lightbox || evt.button != 0) return;
+
+ modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initially_zoomed)
+ evt.preventDefault()
+ showModal(evt)
+ }, true);
- }, 100);
}
function modalZoomSet(modalImage, enable) {
- if (enable) {
- modalImage.classList.add('modalImageFullscreen');
- } else {
- modalImage.classList.remove('modalImageFullscreen');
- }
+ if(modalImage) modalImage.classList.toggle('modalImageFullscreen', !!enable);
}
function modalZoomToggle(event) {
- modalImage = gradioApp().getElementById("modalImage");
+ var modalImage = gradioApp().getElementById("modalImage");
modalZoomSet(modalImage, !modalImage.classList.contains('modalImageFullscreen'))
event.stopPropagation()
}
@@ -199,21 +169,21 @@ function modalTileImageToggle(event) {
}
function galleryImageHandler(e) {
- if (e && e.parentElement.tagName == 'BUTTON') {
+ //if (e && e.parentElement.tagName == 'BUTTON') {
e.onclick = showGalleryImage;
- }
+ //}
}
onUiUpdate(function() {
- fullImg_preview = gradioApp().querySelectorAll('img.w-full')
+ var fullImg_preview = gradioApp().querySelectorAll('.gradio-gallery > div > img')
if (fullImg_preview != null) {
- fullImg_preview.forEach(galleryImageHandler);
+ fullImg_preview.forEach(setupImageForLightbox);
}
updateOnBackgroundChange();
})
document.addEventListener("DOMContentLoaded", function() {
- const modalFragment = document.createDocumentFragment();
+ //const modalFragment = document.createDocumentFragment();
const modal = document.createElement('div')
modal.onclick = closeModal;
modal.id = "lightboxModal";
@@ -277,9 +247,12 @@ document.addEventListener("DOMContentLoaded", function() {
modal.appendChild(modalNext)
+ try {
+ gradioApp().appendChild(modal);
+ } catch (e) {
+ gradioApp().body.appendChild(modal);
+ }
- gradioApp().getRootNode().appendChild(modal)
-
- document.body.appendChild(modalFragment);
+ document.body.appendChild(modal);
});
diff --git a/javascript/imageviewerGamepad.js b/javascript/imageviewerGamepad.js
new file mode 100644
index 00000000..6297a12b
--- /dev/null
+++ b/javascript/imageviewerGamepad.js
@@ -0,0 +1,57 @@
+window.addEventListener('gamepadconnected', (e) => {
+ const index = e.gamepad.index;
+ let isWaiting = false;
+ setInterval(async () => {
+ if (!opts.js_modal_lightbox_gamepad || isWaiting) return;
+ const gamepad = navigator.getGamepads()[index];
+ const xValue = gamepad.axes[0];
+ if (xValue <= -0.3) {
+ modalPrevImage(e);
+ isWaiting = true;
+ } else if (xValue >= 0.3) {
+ modalNextImage(e);
+ isWaiting = true;
+ }
+ if (isWaiting) {
+ await sleepUntil(() => {
+ const xValue = navigator.getGamepads()[index].axes[0]
+ if (xValue < 0.3 && xValue > -0.3) {
+ return true;
+ }
+ }, opts.js_modal_lightbox_gamepad_repeat);
+ isWaiting = false;
+ }
+ }, 10);
+});
+
+/*
+Primarily for vr controller type pointer devices.
+I use the wheel event because there's currently no way to do it properly with web xr.
+ */
+let isScrolling = false;
+window.addEventListener('wheel', (e) => {
+ if (!opts.js_modal_lightbox_gamepad || isScrolling) return;
+ isScrolling = true;
+
+ if (e.deltaX <= -0.6) {
+ modalPrevImage(e);
+ } else if (e.deltaX >= 0.6) {
+ modalNextImage(e);
+ }
+
+ setTimeout(() => {
+ isScrolling = false;
+ }, opts.js_modal_lightbox_gamepad_repeat);
+});
+
+function sleepUntil(f, timeout) {
+ return new Promise((resolve) => {
+ const timeStart = new Date();
+ const wait = setInterval(function() {
+ if (f() || new Date() - timeStart > timeout) {
+ clearInterval(wait);
+ resolve();
+ }
+ }, 20);
+ });
+}
diff --git a/javascript/localization.js b/javascript/localization.js
index 1a5a1dbb..86e5ca67 100644
--- a/javascript/localization.js
+++ b/javascript/localization.js
@@ -25,6 +25,10 @@ re_emoji = /[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]/u
original_lines = {}
translated_lines = {}
+function hasLocalization() {
+ return window.localization && Object.keys(window.localization).length > 0;
+}
+
function textNodesUnder(el){
var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
while(n=walk.nextNode()) a.push(n);
@@ -35,11 +39,11 @@ function canBeTranslated(node, text){
if(! text) return false;
if(! node.parentElement) return false;
- parentType = node.parentElement.nodeName
+ var parentType = node.parentElement.nodeName
if(parentType=='SCRIPT' || parentType=='STYLE' || parentType=='TEXTAREA') return false;
if (parentType=='OPTION' || parentType=='SPAN'){
- pnode = node
+ var pnode = node
for(var level=0; level<4; level++){
pnode = pnode.parentElement
if(! pnode) break;
@@ -69,7 +73,7 @@ function getTranslation(text){
}
function processTextNode(node){
- text = node.textContent.trim()
+ var text = node.textContent.trim()
if(! canBeTranslated(node, text)) return
@@ -105,30 +109,52 @@ function processNode(node){
}
function dumpTranslations(){
- dumped = {}
+ if(!hasLocalization()) {
+ // If we don't have any localization,
+ // we will not have traversed the app to find
+ // original_lines, so do that now.
+ processNode(gradioApp());
+ }
+ var dumped = {}
if (localization.rtl) {
- dumped.rtl = true
+ dumped.rtl = true;
}
- Object.keys(original_lines).forEach(function(text){
- if(dumped[text] !== undefined) return
+ for (const text in original_lines) {
+ if(dumped[text] !== undefined) continue;
+ dumped[text] = localization[text] || text;
+ }
- dumped[text] = localization[text] || text
- })
+ return dumped;
+}
+
+function download_localization() {
+ var text = JSON.stringify(dumpTranslations(), null, 4)
- return dumped
+ var element = document.createElement('a');
+ element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
+ element.setAttribute('download', "localization.json");
+ element.style.display = 'none';
+ document.body.appendChild(element);
+
+ element.click();
+
+ document.body.removeChild(element);
}
-onUiUpdate(function(m){
- m.forEach(function(mutation){
- mutation.addedNodes.forEach(function(node){
- processNode(node)
- })
- });
-})
+document.addEventListener("DOMContentLoaded", function () {
+ if (!hasLocalization()) {
+ return;
+ }
+ onUiUpdate(function (m) {
+ m.forEach(function (mutation) {
+ mutation.addedNodes.forEach(function (node) {
+ processNode(node)
+ })
+ });
+ })
-document.addEventListener("DOMContentLoaded", function() {
processNode(gradioApp())
if (localization.rtl) { // if the language is from right to left,
@@ -149,17 +175,3 @@ document.addEventListener("DOMContentLoaded", function() {
})).observe(gradioApp(), { childList: true });
}
})
-
-function download_localization() {
- text = JSON.stringify(dumpTranslations(), null, 4)
-
- var element = document.createElement('a');
- element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
- element.setAttribute('download', "localization.json");
- element.style.display = 'none';
- document.body.appendChild(element);
-
- element.click();
-
- document.body.removeChild(element);
-}
diff --git a/javascript/notification.js b/javascript/notification.js
index 5ae6df24..83fce1f8 100644
--- a/javascript/notification.js
+++ b/javascript/notification.js
@@ -2,20 +2,20 @@
let lastHeadImg = null;
-notificationButton = null
+let notificationButton = null;
onUiUpdate(function(){
if(notificationButton == null){
notificationButton = gradioApp().getElementById('request_notifications')
if(notificationButton != null){
- notificationButton.addEventListener('click', function (evt) {
- Notification.requestPermission();
+ notificationButton.addEventListener('click', () => {
+ void Notification.requestPermission();
},true);
}
}
- const galleryPreviews = gradioApp().querySelectorAll('div[id^="tab_"][style*="display: block"] div[id$="_results"] img.h-full.w-full.overflow-hidden');
+ const galleryPreviews = gradioApp().querySelectorAll('div[id^="tab_"][style*="display: block"] div[id$="_results"] .thumbnail-item > img');
if (galleryPreviews == null) return;
diff --git a/javascript/progressbar.js b/javascript/progressbar.js
index 9ccc9da4..8d2c3492 100644
--- a/javascript/progressbar.js
+++ b/javascript/progressbar.js
@@ -1,81 +1,15 @@
// code related to showing and updating progressbar shown as the image is being made
+function rememberGallerySelection(){
-galleries = {}
-storedGallerySelections = {}
-galleryObservers = {}
-
-function rememberGallerySelection(id_gallery){
- storedGallerySelections[id_gallery] = getGallerySelectedIndex(id_gallery)
}
-function getGallerySelectedIndex(id_gallery){
- let galleryButtons = gradioApp().querySelectorAll('#'+id_gallery+' .gallery-item')
- let galleryBtnSelected = gradioApp().querySelector('#'+id_gallery+' .gallery-item.\\!ring-2')
-
- let currentlySelectedIndex = -1
- galleryButtons.forEach(function(v, i){ if(v==galleryBtnSelected) { currentlySelectedIndex = i } })
+function getGallerySelectedIndex(){
- return currentlySelectedIndex
}
-// this is a workaround for https://github.com/gradio-app/gradio/issues/2984
-function check_gallery(id_gallery){
- let gallery = gradioApp().getElementById(id_gallery)
- // if gallery has no change, no need to setting up observer again.
- if (gallery && galleries[id_gallery] !== gallery){
- galleries[id_gallery] = gallery;
- if(galleryObservers[id_gallery]){
- galleryObservers[id_gallery].disconnect();
- }
-
- storedGallerySelections[id_gallery] = -1
-
- galleryObservers[id_gallery] = new MutationObserver(function (){
- let galleryButtons = gradioApp().querySelectorAll('#'+id_gallery+' .gallery-item')
- let galleryBtnSelected = gradioApp().querySelector('#'+id_gallery+' .gallery-item.\\!ring-2')
- let currentlySelectedIndex = getGallerySelectedIndex(id_gallery)
- prevSelectedIndex = storedGallerySelections[id_gallery]
- storedGallerySelections[id_gallery] = -1
-
- if (prevSelectedIndex !== -1 && galleryButtons.length>prevSelectedIndex && !galleryBtnSelected) {
- // automatically re-open previously selected index (if exists)
- activeElement = gradioApp().activeElement;
- let scrollX = window.scrollX;
- let scrollY = window.scrollY;
-
- galleryButtons[prevSelectedIndex].click();
- showGalleryImage();
-
- // When the gallery button is clicked, it gains focus and scrolls itself into view
- // We need to scroll back to the previous position
- setTimeout(function (){
- window.scrollTo(scrollX, scrollY);
- }, 50);
-
- if(activeElement){
- // i fought this for about an hour; i don't know why the focus is lost or why this helps recover it
- // if someone has a better solution please by all means
- setTimeout(function (){
- activeElement.focus({
- preventScroll: true // Refocus the element that was focused before the gallery was opened without scrolling to it
- })
- }, 1);
- }
- }
- })
- galleryObservers[id_gallery].observe( gallery, { childList:true, subtree:false })
- }
-}
-
-onUiUpdate(function(){
- check_gallery('txt2img_gallery')
- check_gallery('img2img_gallery')
-})
-
function request(url, data, handler, errorHandler){
var xhr = new XMLHttpRequest();
- var url = url;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
@@ -131,7 +65,7 @@ function randomId(){
// starts sending progress requests to "/internal/progress" uri, creating progressbar above progressbarContainer element and
// preview inside gallery element. Cleans up all created stuff when the task is over and calls atEnd.
// calls onProgress every time there is a progress update
-function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgress){
+function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgress, inactivityTimeout=40){
var dateStart = new Date()
var wasEverActive = false
var parentProgressbar = progressbarContainer.parentNode
@@ -172,7 +106,7 @@ function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgre
divProgress.style.width = rect.width + "px";
}
- progressText = ""
+ let progressText = ""
divInner.style.width = ((res.progress || 0) * 100.0) + '%'
divInner.style.background = res.progress ? "" : "transparent"
@@ -203,7 +137,7 @@ function requestProgress(id_task, progressbarContainer, gallery, atEnd, onProgre
return
}
- if(elapsedFromStart > 5 && !res.queued && !res.active){
+ if(elapsedFromStart > inactivityTimeout && !res.queued && !res.active){
removeProgressBar()
return
}
diff --git a/javascript/ui.js b/javascript/ui.js
index b7a8268a..6d4119d7 100644
--- a/javascript/ui.js
+++ b/javascript/ui.js
@@ -1,15 +1,37 @@
// various functions for interaction with ui.py not large enough to warrant putting them in separate files
function set_theme(theme){
- gradioURL = window.location.href
+ var gradioURL = window.location.href
if (!gradioURL.includes('?__theme=')) {
window.location.replace(gradioURL + '?__theme=' + theme);
}
}
+function all_gallery_buttons() {
+ var allGalleryButtons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery].gradio-gallery .thumbnails > .thumbnail-item.thumbnail-small');
+ var visibleGalleryButtons = [];
+ allGalleryButtons.forEach(function(elem) {
+ if (elem.parentElement.offsetParent) {
+ visibleGalleryButtons.push(elem);
+ }
+ })
+ return visibleGalleryButtons;
+}
+
+function selected_gallery_button() {
+ var allCurrentButtons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery].gradio-gallery .thumbnail-item.thumbnail-small.selected');
+ var visibleCurrentButton = null;
+ allCurrentButtons.forEach(function(elem) {
+ if (elem.parentElement.offsetParent) {
+ visibleCurrentButton = elem;
+ }
+ })
+ return visibleCurrentButton;
+}
+
function selected_gallery_index(){
- var buttons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery] .gallery-item')
- var button = gradioApp().querySelector('[style="display: block;"].tabitem div[id$=_gallery] .gallery-item.\\!ring-2')
+ var buttons = all_gallery_buttons();
+ var button = selected_gallery_button();
var result = -1
buttons.forEach(function(v, i){ if(v==button) { result = i } })
@@ -18,21 +40,25 @@ function selected_gallery_index(){
}
function extract_image_from_gallery(gallery){
- if(gallery.length == 1){
- return [gallery[0]]
+ if (gallery.length == 0){
+ return [null];
+ }
+ if (gallery.length == 1){
+ return [gallery[0]];
}
- index = selected_gallery_index()
+ var index = selected_gallery_index()
if (index < 0 || index >= gallery.length){
- return [null]
+ // Use the first image in the gallery as the default
+ index = 0;
}
return [gallery[index]];
}
function args_to_array(args){
- res = []
+ var res = []
for(var i=0;i<args.length;i++){
res.push(args[i])
}
@@ -86,7 +112,7 @@ function get_tab_index(tabId){
var res = 0
gradioApp().getElementById(tabId).querySelector('div').querySelectorAll('button').forEach(function(button, i){
- if(button.className.indexOf('bg-white') != -1)
+ if(button.className.indexOf('selected') != -1)
res = i
})
@@ -112,7 +138,7 @@ function get_img2img_tab_index() {
}
function create_submit_args(args){
- res = []
+ var res = []
for(var i=0;i<args.length;i++){
res.push(args[i])
}
@@ -133,14 +159,24 @@ function showSubmitButtons(tabname, show){
gradioApp().getElementById(tabname+'_skip').style.display = show ? "none" : "block"
}
+function showRestoreProgressButton(tabname, show){
+ var button = gradioApp().getElementById(tabname + "_restore_progress")
+ if(! button) return
+
+ button.style.display = show ? "flex" : "none"
+}
+
function submit(){
rememberGallerySelection('txt2img_gallery')
showSubmitButtons('txt2img', false)
var id = randomId()
+ localStorage.setItem("txt2img_task_id", id);
+
requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function(){
showSubmitButtons('txt2img', true)
-
+ localStorage.removeItem("txt2img_task_id")
+ showRestoreProgressButton('txt2img', false)
})
var res = create_submit_args(arguments)
@@ -155,8 +191,12 @@ function submit_img2img(){
showSubmitButtons('img2img', false)
var id = randomId()
+ localStorage.setItem("img2img_task_id", id);
+
requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function(){
showSubmitButtons('img2img', true)
+ localStorage.removeItem("img2img_task_id")
+ showRestoreProgressButton('img2img', false)
})
var res = create_submit_args(arguments)
@@ -167,6 +207,42 @@ function submit_img2img(){
return res
}
+function restoreProgressTxt2img(){
+ showRestoreProgressButton("txt2img", false)
+ var id = localStorage.getItem("txt2img_task_id")
+
+ id = localStorage.getItem("txt2img_task_id")
+
+ if(id) {
+ requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function(){
+ showSubmitButtons('txt2img', true)
+ }, null, 0)
+ }
+
+ return id
+}
+
+function restoreProgressImg2img(){
+ showRestoreProgressButton("img2img", false)
+
+ var id = localStorage.getItem("img2img_task_id")
+
+ if(id) {
+ requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function(){
+ showSubmitButtons('img2img', true)
+ }, null, 0)
+ }
+
+ return id
+}
+
+
+onUiLoaded(function () {
+ showRestoreProgressButton('txt2img', localStorage.getItem("txt2img_task_id"))
+ showRestoreProgressButton('img2img', localStorage.getItem("img2img_task_id"))
+});
+
+
function modelmerger(){
var id = randomId()
requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function(){})
@@ -178,7 +254,7 @@ function modelmerger(){
function ask_for_style_name(_, prompt_text, negative_prompt_text) {
- name_ = prompt('Style name:')
+ var name_ = prompt('Style name:')
return [name_, prompt_text, negative_prompt_text]
}
@@ -213,11 +289,11 @@ function recalculate_prompts_img2img(){
}
-opts = {}
+var opts = {}
onUiUpdate(function(){
if(Object.keys(opts).length != 0) return;
- json_elem = gradioApp().getElementById('settings_json')
+ var json_elem = gradioApp().getElementById('settings_json')
if(json_elem == null) return;
var textarea = json_elem.querySelector('textarea')
@@ -255,7 +331,6 @@ onUiUpdate(function(){
}
prompt.parentElement.insertBefore(counter, prompt)
- counter.classList.add("token-counter")
prompt.parentElement.style.position = "relative"
promptTokecountUpdateFuncs[id] = function(){ update_token_counter(id_button); }
@@ -267,12 +342,15 @@ onUiUpdate(function(){
registerTextarea('img2img_prompt', 'img2img_token_counter', 'img2img_token_button')
registerTextarea('img2img_neg_prompt', 'img2img_negative_token_counter', 'img2img_negative_token_button')
- show_all_pages = gradioApp().getElementById('settings_show_all_pages')
- settings_tabs = gradioApp().querySelector('#settings div')
+ var show_all_pages = gradioApp().getElementById('settings_show_all_pages')
+ var settings_tabs = gradioApp().querySelector('#settings div')
if(show_all_pages && settings_tabs){
settings_tabs.appendChild(show_all_pages)
show_all_pages.onclick = function(){
gradioApp().querySelectorAll('#settings > div').forEach(function(elem){
+ if(elem.id == "settings_tab_licenses")
+ return;
+
elem.style.display = "block";
})
}
@@ -280,9 +358,9 @@ onUiUpdate(function(){
})
onOptionsChanged(function(){
- elem = gradioApp().getElementById('sd_checkpoint_hash')
- sd_checkpoint_hash = opts.sd_checkpoint_hash || ""
- shorthash = sd_checkpoint_hash.substr(0,10)
+ var elem = gradioApp().getElementById('sd_checkpoint_hash')
+ var sd_checkpoint_hash = opts.sd_checkpoint_hash || ""
+ var shorthash = sd_checkpoint_hash.substring(0,10)
if(elem && elem.textContent != shorthash){
elem.textContent = shorthash
@@ -317,7 +395,16 @@ function update_token_counter(button_id) {
function restart_reload(){
document.body.innerHTML='<h1 style="font-family:monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>';
- setTimeout(function(){location.reload()},2000)
+
+ var requestPing = function(){
+ requestGet("./internal/ping", {}, function(data){
+ location.reload();
+ }, function(){
+ setTimeout(requestPing, 500);
+ })
+ }
+
+ setTimeout(requestPing, 2000);
return []
}
@@ -336,3 +423,45 @@ function selectCheckpoint(name){
desiredCheckpointName = name;
gradioApp().getElementById('change_checkpoint').click()
}
+
+function currentImg2imgSourceResolution(_, _, scaleBy){
+ var img = gradioApp().querySelector('#mode_img2img > div[style="display: block;"] img')
+ return img ? [img.naturalWidth, img.naturalHeight, scaleBy] : [0, 0, scaleBy]
+}
+
+function updateImg2imgResizeToTextAfterChangingImage(){
+ // At the time this is called from gradio, the image has no yet been replaced.
+ // There may be a better solution, but this is simple and straightforward so I'm going with it.
+
+ setTimeout(function() {
+ gradioApp().getElementById('img2img_update_resize_to').click()
+ }, 500);
+
+ return []
+
+}
+
+
+
+function setRandomSeed(elem_id) {
+ var input = gradioApp().querySelector("#" + elem_id + " input");
+ if (!input) return [];
+
+ input.value = "-1";
+ updateInput(input);
+ return [];
+}
+
+function switchWidthHeight(tabname) {
+ var width = gradioApp().querySelector("#" + tabname + "_width input[type=number]");
+ var height = gradioApp().querySelector("#" + tabname + "_height input[type=number]");
+ if (!width || !height) return [];
+
+ var tmp = width.value;
+ width.value = height.value;
+ height.value = tmp;
+
+ updateInput(width);
+ updateInput(height);
+ return [];
+}
diff --git a/javascript/ui_settings_hints.js b/javascript/ui_settings_hints.js
new file mode 100644
index 00000000..6d1933dc
--- /dev/null
+++ b/javascript/ui_settings_hints.js
@@ -0,0 +1,62 @@
+// various hints and extra info for the settings tab
+
+settingsHintsSetup = false
+
+onOptionsChanged(function(){
+ if(settingsHintsSetup) return
+ settingsHintsSetup = true
+
+ gradioApp().querySelectorAll('#settings [id^=setting_]').forEach(function(div){
+ var name = div.id.substr(8)
+ var commentBefore = opts._comments_before[name]
+ var commentAfter = opts._comments_after[name]
+
+ if(! commentBefore && !commentAfter) return
+
+ var span = null
+ if(div.classList.contains('gradio-checkbox')) span = div.querySelector('label span')
+ else if(div.classList.contains('gradio-checkboxgroup')) span = div.querySelector('span').firstChild
+ else if(div.classList.contains('gradio-radio')) span = div.querySelector('span').firstChild
+ else span = div.querySelector('label span').firstChild
+
+ if(!span) return
+
+ if(commentBefore){
+ var comment = document.createElement('DIV')
+ comment.className = 'settings-comment'
+ comment.innerHTML = commentBefore
+ span.parentElement.insertBefore(document.createTextNode('\xa0'), span)
+ span.parentElement.insertBefore(comment, span)
+ span.parentElement.insertBefore(document.createTextNode('\xa0'), span)
+ }
+ if(commentAfter){
+ var comment = document.createElement('DIV')
+ comment.className = 'settings-comment'
+ comment.innerHTML = commentAfter
+ span.parentElement.insertBefore(comment, span.nextSibling)
+ span.parentElement.insertBefore(document.createTextNode('\xa0'), span.nextSibling)
+ }
+ })
+})
+
+function settingsHintsShowQuicksettings(){
+ requestGet("./internal/quicksettings-hint", {}, function(data){
+ var table = document.createElement('table')
+ table.className = 'settings-value-table'
+
+ data.forEach(function(obj){
+ var tr = document.createElement('tr')
+ var td = document.createElement('td')
+ td.textContent = obj.name
+ tr.appendChild(td)
+
+ var td = document.createElement('td')
+ td.textContent = obj.label
+ tr.appendChild(td)
+
+ table.appendChild(tr)
+ })
+
+ popup(table);
+ })
+}