bricks/bricks/websocket.js
2024-04-25 18:08:32 +08:00

54 lines
1.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var bricks = window.bricks || {}
bricks.WebSocket = class extends bricks.VBox {
constructor(opts){
super(opts);
this.dialog = new bricks.VScrollPanel({})
this.dialog.set_css('filler')
this.input = new bricks.UiStr({
name:'prompt',
label:'Say something'
});
this.add_widget(this.dialog);
this.add_widget(this.input);
this.input.bind('keypress', this.check_keypress.bind(this));
this.ws = new WebSocket(this.ws_url);
this.ws.onopen = function(){
console.log("open");
}
this.ws.onclose = function(e){
//当客户端收到服务端发送的关闭连接请求时触发onclose事件
console.log("close");
}
this.ws.onerror = function(e){
//如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
console.log(error);
}
this.ws.onmessage = this.show_response.bind(this);
}
check_keypress(e){
if (e.key == 'Enter'){
var v = this.input.getValue();
var s = v.prompt;
console.log('check_keypress()', v, s);
if (s != ''){
this.show_input(s);
}
}
}
show_input(s){
var w = new bricks.MdWidget({mdtext:s});
w.set_css('user_msg');
this.dialog.add_widget(w);
this.ws.send(s);
}
show_response(e){
var d = JSON.parse(e.data);
console.log(e.data, d.type, d.data, d);
var w = new bricks.MdWidget({mdtext:d.data});
w.set_css('llm_msg');
this.dialog.add_widget(w);
}
}
bricks.Factory.register('WebSocket', bricks.WebSocket);