-
Notifications
You must be signed in to change notification settings - Fork 4
/
usage2.py
81 lines (69 loc) · 2.07 KB
/
usage2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import json
from dash_socketio import DashSocketIO
import dash_mantine_components as dmc
from dash import Dash, Input, Output, State, callback, clientside_callback, html, no_update
from flask_socketio import SocketIO, emit
from plotly.io.json import to_json_plotly
app = Dash(__name__)
app.server.secret_key = "Test!"
socketio = SocketIO(app.server)
app.layout = dmc.NotificationsProvider(
[
dmc.Title("Hello Socket.IO!", mb="xl"),
dmc.Stack(
[
dmc.Textarea(id="msg", minRows=5, placeholder="Write something in the chat"),
html.Div(dmc.Button("Send", id="send", mb="md", disabled=True)),
],
spacing="xs",
),
dmc.Stack([], id="chat-messages", style={"maxWidth": "60ch"}),
DashSocketIO(id="socketio", eventNames=["chatMsg"]),
],
position="bottom-right",
)
def jsonify_data(data):
return json.loads(to_json_plotly(data))
@callback(
Output("msg", "value"),
Input("send", "n_clicks"),
State("msg", "value"),
State("socketio", "socketId"),
running=[[Output("send", "loading"), True, False]],
prevent_initial_call=True,
)
def display_status(send, msg, socket_id):
if not send or not msg:
return no_update
emit(
"chatMsg",
jsonify_data(dmc.Paper(
[
dmc.Text(f"{socket_id} says", size="xs", color="dimmed", mb=4),
dmc.Text(msg),
],
p="0.5rem 1rem",
withBorder=True,
)),
namespace="/",
broadcast=True,
skip_sid=socket_id,
)
return ""
clientside_callback(
"""connected => !connected""",
Output("send", "disabled"),
Input("socketio", "connected"),
)
clientside_callback(
"""(msg, children) => {
if (!msg) return dash_clientside.no_update
return [...children, msg]
}""",
Output("chat-messages", "children"),
Input("socketio", "data-chatMsg"),
State("chat-messages", "children"),
prevent_initial_call=True,
)
if __name__ == '__main__':
app.run_server(debug=True)