bricks/bricks/websocket.js

54 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-04-25 18:08:32 +08:00
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);