Py.Cafe

BSd3v./

dash-app-editable-text-toggle

Dash App with Editable Text and Toggle Button

DocsPricing
  • app.py
  • requirements.txt
app.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
from dash import callback, Input, Output, callback, MATCH, ctx, Patch, Dash, _dash_renderer, no_update, State, html, MATCH
import dash_mantine_components as dmc
import uuid

_dash_renderer._set_react_version("18.2.0")


class EditableText(html.Div):
    class ids:
        ## Designer
        component_id = lambda aio_id: {"index": aio_id, "type": "editable-text-holder"}
        text_id = lambda aio_id: {"index": aio_id, "type": "editable-text"}
        toggle_id = lambda aio_id: {"index": aio_id, "type": "editable-text-toggle"}

    def __init__(self, aio_id=None, value=None):
        self.aio_id = aio_id or str(uuid.uuid4())
        super().__init__([
            dmc.TextInput(id=self.ids.text_id(self.aio_id), value=value),
            dmc.Button("Toggle mode", id=self.ids.toggle_id(self.aio_id), n_clicks=0),
        ], id=self.ids.component_id(self.aio_id))

    @callback(
        Output(ids.component_id(MATCH), 'children'),
        Input(ids.toggle_id(MATCH), 'n_clicks'),
        State(ids.text_id(MATCH), 'value'),
        prevent_initial_call=True
    )
    def swap(n, v):
        if n:
            child = Patch()
            text_id = EditableText.ids.text_id(ctx.triggered_id.index)
            if n % 2 == 0:
                child[0] = dmc.TextInput(id=text_id, value=v)
            else:
                child[0] =  dmc.Textarea(id=text_id, value=v)
            return child
        return no_update


app = Dash(__name__, external_stylesheets=dmc.styles.ALL)
app.layout = dmc.MantineProvider(
    children=[
        EditableText(value="test", aio_id="new"),
        html.Div(id='output')
    ],
)

@app.callback(
    Output('output', 'children'),
    Input(EditableText.ids.text_id('new'), 'value')
)
def display_out(v):
    return v

app.run(debug=True)