-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathusage3.py
More file actions
84 lines (71 loc) · 2.59 KB
/
usage3.py
File metadata and controls
84 lines (71 loc) · 2.59 KB
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
82
83
84
import uuid
from dash_socketio import DashSocketIO
import dash_mantine_components as dmc
from dash import ALL, Dash, Input, Output, State, _dash_renderer, callback, clientside_callback, ctx, html, no_update
from flask import session
from flask_socketio import SocketIO, emit, join_room
_dash_renderer._set_react_version("18.3.1")
app = Dash(__name__, external_stylesheets=dmc.styles.ALL)
app.server.secret_key = "Test!"
socketio = SocketIO(app.server)
app.layout = dmc.MantineProvider(
dmc.Container(
[
dmc.NotificationProvider(position="top-right"),
dmc.Title("Hello Socket.IO!", mb="xl"),
dmc.Group(
[
dmc.TextInput(id={"type": "control", "id": "name"}, debounce=500, label="Name"),
dmc.Select(data=["Montreal", "NYC", "Paris"], id={"type": "control", "id": "city"}, label="City"),
dmc.SegmentedControl(data=["Male", "Female"], id={"type": "control", "id": "gender"}),
],
align="end",
p="1rem 2rem",
),
html.Div(id="dummy"),
DashSocketIO(id='socketio', eventNames=["syncControl"]),
],
p="1rem 2rem",
),
)
@app.server.before_request
def add_session_id():
if "session_id" not in session:
session["session_id"] = uuid.uuid4().hex
@socketio.on("connect")
def join_session_id_room():
session_id = session["session_id"]
join_room(session_id)
@callback(
Output("dummy", "data-noOutput"),
Input({"type": "control", "id": ALL}, "value"),
State("socketio", "socketId")
)
def sync_controls(controls, socket_id):
if not ctx.triggered_id or not any(controls):
return no_update
emit(
"syncControl",
{
"control_id": ctx.triggered_id["id"],
"value": ctx.triggered[0]["value"],
},
to=session["session_id"],
skip_sid=socket_id,
namespace="/",
)
return no_update
clientside_callback(
"""(data, ids, current) => {
if (!data) return Array(ids.length).fill(dash_clientside.no_update)
const idxToChange = ids.map((x, i) => [x.id, i]).filter(y => y[0] === data.control_id)[0][1]
return current.slice(0, idxToChange).concat([data.value]).concat(current.slice(idxToChange + 1))
}""",
Output({"type": "control", "id": ALL}, "value"),
Input("socketio", "data-syncControl"),
State({"type": "control", "id": ALL}, "id"),
State({"type": "control", "id": ALL}, "value"),
prevent_initial_call=True,
)
if __name__ == '__main__':
app.run_server(debug=True)