Skip to content

Commit

Permalink
Add onAfterUiUpdate callback
Browse files Browse the repository at this point in the history
  • Loading branch information
akx committed May 25, 2023
1 parent 54696dc commit bc53ecf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
7 changes: 4 additions & 3 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,14 @@ module.exports = {
globals: {
//script.js
gradioApp: "readonly",
executeCallbacks: "readonly",
onAfterUiUpdate: "readonly",
onOptionsChanged: "readonly",
onUiLoaded: "readonly",
onUiUpdate: "readonly",
onOptionsChanged: "readonly",
uiCurrentTab: "writable",
uiElementIsVisible: "readonly",
uiElementInSight: "readonly",
executeCallbacks: "readonly",
uiElementIsVisible: "readonly",
//ui.js
opts: "writable",
all_gallery_buttons: "readonly",
Expand Down
27 changes: 27 additions & 0 deletions script.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ function get_uiCurrentTabContent() {
}

var uiUpdateCallbacks = [];
var uiAfterUpdateCallbacks = [];
var uiLoadedCallbacks = [];
var uiTabChangeCallbacks = [];
var optionsChangedCallbacks = [];
var uiAfterUpdateTimeout = null;
var uiCurrentTab = null;

/**
Expand All @@ -32,6 +34,18 @@ function onUiUpdate(callback) {
uiUpdateCallbacks.push(callback);
}

/**
* Register callback to be called soon after UI updates.
* The callback receives no arguments.
*
* This is preferred over `onUiUpdate` if you don't need
* access to the MutationRecords, as your function will
* not be called quite as often.
*/
function onAfterUiUpdate(callback) {
uiAfterUpdateCallbacks.push(callback);
}

/**
* Register callback to be called when the UI is loaded.
* The callback receives no arguments.
Expand Down Expand Up @@ -66,6 +80,18 @@ function executeCallbacks(queue, arg) {
}
}
}

/**
* Schedule the execution of the callbacks registered with onAfterUiUpdate.
* The callbacks are executed after a short while, unless another call to this function
* is made before that time. IOW, the callbacks are executed only once, even
* when there are multiple mutations observed.
*/
function scheduleAfterUiUpdateCallbacks() {
clearTimeout(uiAfterUpdateTimeout);
uiAfterUpdateTimeout = setTimeout(function() {
executeCallbacks(uiAfterUpdateCallbacks);
}, 200);
}

var executedOnLoaded = false;
Expand All @@ -78,6 +104,7 @@ document.addEventListener("DOMContentLoaded", function() {
}

executeCallbacks(uiUpdateCallbacks, m);
scheduleAfterUiUpdateCallbacks();
const newTab = get_uiCurrentTab();
if (newTab && (newTab !== uiCurrentTab)) {
uiCurrentTab = newTab;
Expand Down

0 comments on commit bc53ecf

Please sign in to comment.