Gradio 中如何让 Chatbot 自动滚动

在 Gradio 中, Chatbot 是对话组件,接受 history 参数,在目前版本中 (gradio==4.44.0),不支持自动滚动,用起来很不方便,该功能在社区中已经提出了,目前该功能还没有发布。本文将通过自定义 JS 来实现滚动事件。

在这里插入图片描述
Gradio 中支持自定义 JS,通过 JS 添加滚动事件,启动时间传入 JS 代码,JS代码如下

js = """
function createScrollListener() {
    const target = document.querySelector('.chatbot .bubble-wrap');
    // Function to scroll to the bottom
    function scrollToBottom() {
        if (target) {
            target.scrollTop = target.scrollHeight;
        }
    }

    // Function to scroll if needed
    function scrollToBottomIfNeeded() {
        if (target) {
            target.scrollTop = target.scrollHeight;
        }
    }

    // Mutation Observer with Debounce
    let timeout;
    function debounce(func, delay) {
        clearTimeout(timeout);
        timeout = setTimeout(func, delay);
    }

    if (target) {
        const observer = new MutationObserver((mutations) => {
            debounce(scrollToBottomIfNeeded, 100);
        });

        observer.observe(target, { childList: true, subtree: true });

        // Initial scroll to bottom
        scrollToBottom();

        // Scroll on window resize
        window.addEventListener('resize', scrollToBottom);
    }

    console.log(target)
}
"""
with gr.Blocks(js=js) as demo:
    chatbot = gr.Chatbot(elem_classes="chatbot")
    msg = gr.Textbox()
    clear = gr.Button("Clear")

总结

Gradio 中使用自定义 JS 是通过原生的 JS 进行元素选择,并在元素绑定事件来进行事件控制的。写起来还是比较费劲,如果是比较复杂的效果还是通过自定义组件来实现,希望社区提供这个功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值