UI: move the new morphdom code to a .js file

This commit is contained in:
oobabooga 2025-01-13 06:20:42 -08:00
parent facb4155d4
commit c85e5e58d0
2 changed files with 25 additions and 26 deletions

View File

@ -21,3 +21,27 @@ function copyToClipboard(element) {
function regenerateClick() {
document.getElementById("Regenerate").click();
}
function handleMorphdomUpdate(text) {
console.log("Morphing!");
morphdom(
document.getElementById("chat").parentNode,
"<div class=\"prose svelte-1ybaih5\">" + text + "</div>",
{
onBeforeElUpdated: function(fromEl, toEl) {
if (fromEl.tagName === "PRE" && fromEl.querySelector("code[data-highlighted]")) {
const fromCode = fromEl.querySelector("code");
const toCode = toEl.querySelector("code");
if (fromCode && toCode && fromCode.textContent === toCode.textContent) {
// If the <code> content is the same, preserve the entire <pre> element
toEl.className = fromEl.className;
toEl.innerHTML = fromEl.innerHTML;
return false; // Skip updating the <pre> element
}
}
return !fromEl.isEqualNode(toEl); // Update only if nodes differ
}
}
);
}

View File

@ -181,32 +181,7 @@ def create_event_handlers():
shared.reload_inputs = gradio(reload_arr)
# Morph HTML updates instead of updating everything
shared.gradio['display'].change(None, gradio('display'), None,
js="""
(text) => {
morphdom(
document.getElementById('chat').parentNode,
'<div class="prose svelte-1ybaih5">' + text + '</div>',
{
onBeforeElUpdated: function(fromEl, toEl) {
if (fromEl.tagName === 'PRE' && fromEl.querySelector('code[data-highlighted]')) {
const fromCode = fromEl.querySelector('code');
const toCode = toEl.querySelector('code');
if (fromCode && toCode && fromCode.textContent === toCode.textContent) {
// If the <code> content is the same, preserve the entire <pre> element
toEl.className = fromEl.className;
toEl.innerHTML = fromEl.innerHTML;
return false; // Skip updating the <pre> element
}
}
return !fromEl.isEqualNode(toEl); // Update only if nodes differ
}
}
);
}
"""
);
shared.gradio['display'].change(None, gradio('display'), None, js="(text) => handleMorphdomUpdate(text)")
shared.gradio['Generate'].click(
ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(