Skip to content
This repository was archived by the owner on Aug 29, 2025. It is now read-only.

Dash Clientside Transformations - #142

Closed
chriddyp wants to merge 7 commits into
masterfrom
clientside
Closed

Dash Clientside Transformations#142
chriddyp wants to merge 7 commits into
masterfrom
clientside

Conversation

@chriddyp

Copy link
Copy Markdown
Member

This PR enables outputs to be updated clientside with user-defined JavaScript code. It enables users to replace certain Python callbacks with JavaScript callbacks for faster updates, lighter server load, and re-usable components+logic groups.

Unlike the Python callbacks, the JS callback signatures are embedded in the app layout. In this way, it's similar to the approach discussed in https://community.plot.ly/t/could-output-be-moved-inside-the-components-to-improve-readability/17178/2, except done clientside in JavaScript.

Embedding the function signatures in the layout has a couple of main advantages:

  1. It more easily enables re-usable code logic+component blocks.
  2. It enables slightly easier callbacks with dynamic components (e.g. a TODO list), as the IDs or indices of the dynamic components can be embedded directly in the static argument list.
  3. It's relatively easy to read.

This PR introduces two new serializations: the function signatures and the clientside version of Input/State. These objects are serialized within the initial layout. Here's an example of what this looks like:

{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"children": [
{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"id": "my-output",
"children": {
# A simple check for "_dash-type" will indicate to# dash-renderer that this is something "special"# and not user defined."_dash_type": "function",
"function": "my_function",
"namespace": "my_library",
"positional_arguments": [
{
"_dash_type": "input", # or state"id": "my-input",
"property": "value"
},
3# also allow constants
]
}
}
},
{
"type": "Input",
"namespace": "dash_core_components",
"props": {
"id": "my-input",
"value": "my value"
}
}
]
}
}

This implementation differs from previous attempts in a few ways:

  1. We are no longer prescriptive about what clientside libraries or functions are available to you. You are responsible for writing the functions. Of course, you may find yourself very productive with Ramda 😉
  2. We do not allow updating arbitrarily nested properties of components (e.g. figure.layout.title) - only top level properties can be updated. In this way, it mirrors the Python callbacks.
  3. The Python interface is light - it just serializes a lookup to the window[namespace][function] and descriptions the arguments of that function (which can be a combination of constants & deferred-evaluated Input and State objects)

This feels to me like the appropriate level of abstraction: very little "magic", pretty similar to Python callbacks, and still quite fast and powerful. It also requires very little backend integration, so all Dash backends (Python & R) can easily have the same interface and community members will be able to re-use the same clientside snippets.

Here are four examples of apps built with clientside that demonstrate different features.

Serverside initial data + clientside filtering

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
dcc.Store(
id='df',
data=df.to_dict('records')
),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='lines'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideState('df', 'data')]
)
),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following clientside function in assets/my_functions.js:

window.clientside = {
updateFig: function(search, years, mode, rows) {
var filtered_rows = R.filter(
R.allPass([
R.compose(
R.contains(search),
R.prop('country')
),
R.compose(
R.flip(R.contains)(years),
R.prop('year')
),
]), rows);
return {
'data': [{
'x': R.pluck('gdpPercap', filtered_rows),
'y': R.pluck('lifeExp', filtered_rows),
'text': R.map(
R.join(' - '),
R.zip(
R.pluck('year', filtered_rows),
R.pluck('country', filtered_rows)
)
),
'type': 'scatter',
'mode': mode,
'marker': {
'opacity': 0.7
}
}],
'layout': {
'hovermode': 'closest',
'xaxis': {'type': 'log'}
}
}
},
}

clientside-filtering


Example 2 - Serverside "Refresh" button + clientside graphing & filtering

Same as above, but with dynamic data, refreshed via a serverside function

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportnumpyasnpimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Truedf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app.layout=html.Div([
html.Button('Refresh Data', id='refresh', n_clicks=0),
dcc.Store(
id='df',
# data=df.to_dict('records')
),
html.Pre(id='head'),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='markers'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideInput('df', 'data')]
)
),
])
@app.callback(Output('df', 'data'), [Input('refresh', 'n_clicks')])defupdate_data(n_clicks):
df=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
df['lifeExp'] =np.random.randn(len(df))
df['gdpPercap'] =np.random.randn(len(df))
returndf.to_dict('records')
@app.callback(Output('head', 'children'), [Input('df', 'data')])defdisplay_head(data):
returnstr(pd.DataFrame(data).head())
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

clientside-refresh

Example 3 - Chaining clientside + serverside callbacks
Mix and match! The DAG remains alive and well - callbacks, no matter where they are executed, will wait their turn.

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from dash_renderer.clientside import ClientsideFunction, ClientsideInput, ClientsideState
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app = dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
app.layout = html.Div([
html.Label('x'),
dcc.Input(id='x', value=3),
html.Label('y'),
dcc.Input(id='y', value=6),
# clientside
html.Label('x + y (clientside)'),
dcc.Input(
id='x+y',
value=ClientsideFunction(
'R',
'add',
[ClientsideInput('x', 'value'),
ClientsideInput('y', 'value')]
)
),
# server-side
html.Label('x+y / 2 (serverside - takes 5 seconds)'),
dcc.Input(id='x+y / 2'),
# server-side
html.Div([
html.Label('Display x, y, x+y/2 (serverside) - takes 5 seconds'),
html.Pre(id='display-all-of-the-values'),
]),
# clientside
html.Label('Mean(x, y, x+y, x+y/2) (clientside)'),
html.Div(
id='mean-of-all-values',
children=ClientsideFunction(
'clientside',
'mean',
[
ClientsideInput('x', 'value'),
ClientsideInput('y', 'value'),
ClientsideInput('x+y', 'value'),
ClientsideInput('x+y / 2', 'value'),
]
)
),
])
@app.callback(Output('x+y / 2', 'value'),
[Input('x+y', 'value')])
def divide_by_two(value):
import time; time.sleep(4)
return float(value) / 2.0
@app.callback(Output('display-all-of-the-values', 'children'),
[Input('x', 'value'),
Input('y', 'value'),
Input('x+y', 'value'),
Input('x+y / 2', 'value')])
def display_all(*args):
import time; time.sleep(4)
return '\n'.join([str(a) for a in args])
if __name__ == '__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/my_functions.js (my_functions.js could be named anything) file:

window.clientside = {
mean: function(...args) {
console.warn('mean.args: ', args);
const meanValues = R.mean(args);
console.warn('meanValues: ', meanValues);
return meanValues;
}
}

clientside-chaining

Example 4 - Adding rows & columns to a table via clientside functions

This is where clientside could shine - the simple operations between components: adding rows to tables or updating dropdowns.

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlimportdash_tableimportjsonfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspdapp=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
html.Label('New Column'),
dcc.Input(id='new-column-name', placeholder='name'),
html.Button('Add Column', id='add-column', n_clicks=0),
html.Button('Add Row', id='add-row', n_clicks=1),
dash_table.DataTable(
id='table',
editable=True,
columns=ClientsideFunction(
'clientside',
'tableColumns',
[ClientsideInput('add-column', 'n_clicks'),
ClientsideState('new-column-name', 'value'),
ClientsideState('table', 'columns'),
[{'id': 'column-1', 'name': 'Column 1'}]],
),
data=ClientsideFunction(
'clientside',
'tableData',
[ClientsideInput('table', 'columns'),
ClientsideInput('add-row', 'n_clicks'),
ClientsideState('table', 'data'),
[{'column-1': 9}]]
)
),
html.Div(html.B('Clientside')),
dcc.Graph(
id='graph',
figure=ClientsideFunction(
'clientside',
'graphTable',
[ClientsideInput('table', 'data')]
)
),
html.B('Server Side'),
html.Pre(id='display')
])
@app.callback(Output('display', 'children'), [Input('table', 'columns'),Input('table', 'data')])defdisplay_data(columns, data):
returnhtml.Div([
html.Div(html.B('Columns')),
html.Pre(json.dumps(columns, indent=2)),
html.Div(html.B('Data')),
html.Pre(json.dumps(data, indent=2)),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/you_name_it.js functions:

window.clientside={tableColumns: function(addColumnNClicks,newColumnName,existingColumns,defaultColumns){if(addColumnNClicks===0){returndefaultColumns;}returnR.concat(existingColumns,[{'name': newColumnName,'id': newColumnName}]);},tableData: function(columns,n_clicks,data,initial_data){if(n_clicks===0&&columns.length===1){returninitial_data;}elseif(R.isNil(data)){returninitial_data;}elseif(columns.length>R.values(data[0]).length){returndata.map(row=>{constnewCell={};newCell[columns[columns.length-1].id]=9;returnR.merge(row,newCell)});}elseif(n_clicks>data.length){constnewRow={};columns.forEach(col=>newRow[col.id]=9);returnR.concat(data,[newRow]);}},graphTable(data){return{'data': [{'z': R.map(R.values,data),'type': 'heatmap'}]}}}

clientside-heatmap

@chriddypchriddyp changed the title Dash ClientsideDash Clientside - Sponsored, Due Feb 1Mar 29, 2019
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due Feb 1Dash Clientside - Sponsored, Due March 1Mar 29, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

This was close but not quite there. Consensus discussing this with folks today is that the "functions embedded in layout" is too far away from the way traditional serverside callbacks work, even if there are some advantages in functionality. There are a few advantages to keeping the syntax closer to @app.callback:

  1. Easier story around this being a "escape hatch" - if one of your callbacks is slow, rewrite it in JS. Fundamentally, the architecture of your app won't change.
  2. Similarly, it'll be easier to always start in Python and then "optimize later"
  3. Easier to have parity with other features in the future like wildcards
  4. This doesn't prevent us from adding embedded functions in the layout later. And when we do so, we could do it for both serverside and clientside.

This would be the new syntax:

app.client_callback(
Output('head', 'children'),
[Input('df', 'data')],
ClientFunction(namespace='clientside', function_name='updateFig')
)

An update is forthcoming this weekend.

@chriddypchriddyp mentioned this pull request Mar 30, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

Closing in preference for #143

@chriddyp
chriddyp deleted the clientside branch March 30, 2019 17:14
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due March 1Dash Clientside TransformationsJun 7, 2022
Sign up for freeto subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@chriddyp
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Dash Clientside Transformations by chriddyp · Pull Request #142 · plotly/dash-renderer · GitHub
Skip to content
This repository was archived by the owner on Aug 29, 2025. It is now read-only.

Dash Clientside Transformations - #142

Closed
chriddyp wants to merge 7 commits into
masterfrom
clientside
Closed

Dash Clientside Transformations#142
chriddyp wants to merge 7 commits into
masterfrom
clientside

Conversation

@chriddyp

Copy link
Copy Markdown
Member

This PR enables outputs to be updated clientside with user-defined JavaScript code. It enables users to replace certain Python callbacks with JavaScript callbacks for faster updates, lighter server load, and re-usable components+logic groups.

Unlike the Python callbacks, the JS callback signatures are embedded in the app layout. In this way, it's similar to the approach discussed in https://community.plot.ly/t/could-output-be-moved-inside-the-components-to-improve-readability/17178/2, except done clientside in JavaScript.

Embedding the function signatures in the layout has a couple of main advantages:

  1. It more easily enables re-usable code logic+component blocks.
  2. It enables slightly easier callbacks with dynamic components (e.g. a TODO list), as the IDs or indices of the dynamic components can be embedded directly in the static argument list.
  3. It's relatively easy to read.

This PR introduces two new serializations: the function signatures and the clientside version of Input/State. These objects are serialized within the initial layout. Here's an example of what this looks like:

{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"children": [
{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"id": "my-output",
"children": {
# A simple check for "_dash-type" will indicate to# dash-renderer that this is something "special"# and not user defined."_dash_type": "function",
"function": "my_function",
"namespace": "my_library",
"positional_arguments": [
{
"_dash_type": "input", # or state"id": "my-input",
"property": "value"
},
3# also allow constants
]
}
}
},
{
"type": "Input",
"namespace": "dash_core_components",
"props": {
"id": "my-input",
"value": "my value"
}
}
]
}
}

This implementation differs from previous attempts in a few ways:

  1. We are no longer prescriptive about what clientside libraries or functions are available to you. You are responsible for writing the functions. Of course, you may find yourself very productive with Ramda 😉
  2. We do not allow updating arbitrarily nested properties of components (e.g. figure.layout.title) - only top level properties can be updated. In this way, it mirrors the Python callbacks.
  3. The Python interface is light - it just serializes a lookup to the window[namespace][function] and descriptions the arguments of that function (which can be a combination of constants & deferred-evaluated Input and State objects)

This feels to me like the appropriate level of abstraction: very little "magic", pretty similar to Python callbacks, and still quite fast and powerful. It also requires very little backend integration, so all Dash backends (Python & R) can easily have the same interface and community members will be able to re-use the same clientside snippets.

Here are four examples of apps built with clientside that demonstrate different features.

Serverside initial data + clientside filtering

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
dcc.Store(
id='df',
data=df.to_dict('records')
),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='lines'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideState('df', 'data')]
)
),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following clientside function in assets/my_functions.js:

window.clientside = {
updateFig: function(search, years, mode, rows) {
var filtered_rows = R.filter(
R.allPass([
R.compose(
R.contains(search),
R.prop('country')
),
R.compose(
R.flip(R.contains)(years),
R.prop('year')
),
]), rows);
return {
'data': [{
'x': R.pluck('gdpPercap', filtered_rows),
'y': R.pluck('lifeExp', filtered_rows),
'text': R.map(
R.join(' - '),
R.zip(
R.pluck('year', filtered_rows),
R.pluck('country', filtered_rows)
)
),
'type': 'scatter',
'mode': mode,
'marker': {
'opacity': 0.7
}
}],
'layout': {
'hovermode': 'closest',
'xaxis': {'type': 'log'}
}
}
},
}

clientside-filtering


Example 2 - Serverside "Refresh" button + clientside graphing & filtering

Same as above, but with dynamic data, refreshed via a serverside function

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportnumpyasnpimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Truedf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app.layout=html.Div([
html.Button('Refresh Data', id='refresh', n_clicks=0),
dcc.Store(
id='df',
# data=df.to_dict('records')
),
html.Pre(id='head'),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='markers'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideInput('df', 'data')]
)
),
])
@app.callback(Output('df', 'data'), [Input('refresh', 'n_clicks')])defupdate_data(n_clicks):
df=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
df['lifeExp'] =np.random.randn(len(df))
df['gdpPercap'] =np.random.randn(len(df))
returndf.to_dict('records')
@app.callback(Output('head', 'children'), [Input('df', 'data')])defdisplay_head(data):
returnstr(pd.DataFrame(data).head())
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

clientside-refresh

Example 3 - Chaining clientside + serverside callbacks
Mix and match! The DAG remains alive and well - callbacks, no matter where they are executed, will wait their turn.

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from dash_renderer.clientside import ClientsideFunction, ClientsideInput, ClientsideState
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app = dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
app.layout = html.Div([
html.Label('x'),
dcc.Input(id='x', value=3),
html.Label('y'),
dcc.Input(id='y', value=6),
# clientside
html.Label('x + y (clientside)'),
dcc.Input(
id='x+y',
value=ClientsideFunction(
'R',
'add',
[ClientsideInput('x', 'value'),
ClientsideInput('y', 'value')]
)
),
# server-side
html.Label('x+y / 2 (serverside - takes 5 seconds)'),
dcc.Input(id='x+y / 2'),
# server-side
html.Div([
html.Label('Display x, y, x+y/2 (serverside) - takes 5 seconds'),
html.Pre(id='display-all-of-the-values'),
]),
# clientside
html.Label('Mean(x, y, x+y, x+y/2) (clientside)'),
html.Div(
id='mean-of-all-values',
children=ClientsideFunction(
'clientside',
'mean',
[
ClientsideInput('x', 'value'),
ClientsideInput('y', 'value'),
ClientsideInput('x+y', 'value'),
ClientsideInput('x+y / 2', 'value'),
]
)
),
])
@app.callback(Output('x+y / 2', 'value'),
[Input('x+y', 'value')])
def divide_by_two(value):
import time; time.sleep(4)
return float(value) / 2.0
@app.callback(Output('display-all-of-the-values', 'children'),
[Input('x', 'value'),
Input('y', 'value'),
Input('x+y', 'value'),
Input('x+y / 2', 'value')])
def display_all(*args):
import time; time.sleep(4)
return '\n'.join([str(a) for a in args])
if __name__ == '__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/my_functions.js (my_functions.js could be named anything) file:

window.clientside = {
mean: function(...args) {
console.warn('mean.args: ', args);
const meanValues = R.mean(args);
console.warn('meanValues: ', meanValues);
return meanValues;
}
}

clientside-chaining

Example 4 - Adding rows & columns to a table via clientside functions

This is where clientside could shine - the simple operations between components: adding rows to tables or updating dropdowns.

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlimportdash_tableimportjsonfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspdapp=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
html.Label('New Column'),
dcc.Input(id='new-column-name', placeholder='name'),
html.Button('Add Column', id='add-column', n_clicks=0),
html.Button('Add Row', id='add-row', n_clicks=1),
dash_table.DataTable(
id='table',
editable=True,
columns=ClientsideFunction(
'clientside',
'tableColumns',
[ClientsideInput('add-column', 'n_clicks'),
ClientsideState('new-column-name', 'value'),
ClientsideState('table', 'columns'),
[{'id': 'column-1', 'name': 'Column 1'}]],
),
data=ClientsideFunction(
'clientside',
'tableData',
[ClientsideInput('table', 'columns'),
ClientsideInput('add-row', 'n_clicks'),
ClientsideState('table', 'data'),
[{'column-1': 9}]]
)
),
html.Div(html.B('Clientside')),
dcc.Graph(
id='graph',
figure=ClientsideFunction(
'clientside',
'graphTable',
[ClientsideInput('table', 'data')]
)
),
html.B('Server Side'),
html.Pre(id='display')
])
@app.callback(Output('display', 'children'), [Input('table', 'columns'),Input('table', 'data')])defdisplay_data(columns, data):
returnhtml.Div([
html.Div(html.B('Columns')),
html.Pre(json.dumps(columns, indent=2)),
html.Div(html.B('Data')),
html.Pre(json.dumps(data, indent=2)),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/you_name_it.js functions:

window.clientside={tableColumns: function(addColumnNClicks,newColumnName,existingColumns,defaultColumns){if(addColumnNClicks===0){returndefaultColumns;}returnR.concat(existingColumns,[{'name': newColumnName,'id': newColumnName}]);},tableData: function(columns,n_clicks,data,initial_data){if(n_clicks===0&&columns.length===1){returninitial_data;}elseif(R.isNil(data)){returninitial_data;}elseif(columns.length>R.values(data[0]).length){returndata.map(row=>{constnewCell={};newCell[columns[columns.length-1].id]=9;returnR.merge(row,newCell)});}elseif(n_clicks>data.length){constnewRow={};columns.forEach(col=>newRow[col.id]=9);returnR.concat(data,[newRow]);}},graphTable(data){return{'data': [{'z': R.map(R.values,data),'type': 'heatmap'}]}}}

clientside-heatmap

@chriddypchriddyp changed the title Dash ClientsideDash Clientside - Sponsored, Due Feb 1Mar 29, 2019
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due Feb 1Dash Clientside - Sponsored, Due March 1Mar 29, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

This was close but not quite there. Consensus discussing this with folks today is that the "functions embedded in layout" is too far away from the way traditional serverside callbacks work, even if there are some advantages in functionality. There are a few advantages to keeping the syntax closer to @app.callback:

  1. Easier story around this being a "escape hatch" - if one of your callbacks is slow, rewrite it in JS. Fundamentally, the architecture of your app won't change.
  2. Similarly, it'll be easier to always start in Python and then "optimize later"
  3. Easier to have parity with other features in the future like wildcards
  4. This doesn't prevent us from adding embedded functions in the layout later. And when we do so, we could do it for both serverside and clientside.

This would be the new syntax:

app.client_callback(
Output('head', 'children'),
[Input('df', 'data')],
ClientFunction(namespace='clientside', function_name='updateFig')
)

An update is forthcoming this weekend.

@chriddypchriddyp mentioned this pull request Mar 30, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

Closing in preference for #143

@chriddyp
chriddyp deleted the clientside branch March 30, 2019 17:14
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due March 1Dash Clientside TransformationsJun 7, 2022
Sign up for freeto subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@chriddyp
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Dash Clientside Transformations by chriddyp · Pull Request #142 · plotly/dash-renderer · GitHub
Skip to content
This repository was archived by the owner on Aug 29, 2025. It is now read-only.

Dash Clientside Transformations - #142

Closed
chriddyp wants to merge 7 commits into
masterfrom
clientside
Closed

Dash Clientside Transformations#142
chriddyp wants to merge 7 commits into
masterfrom
clientside

Conversation

@chriddyp

Copy link
Copy Markdown
Member

This PR enables outputs to be updated clientside with user-defined JavaScript code. It enables users to replace certain Python callbacks with JavaScript callbacks for faster updates, lighter server load, and re-usable components+logic groups.

Unlike the Python callbacks, the JS callback signatures are embedded in the app layout. In this way, it's similar to the approach discussed in https://community.plot.ly/t/could-output-be-moved-inside-the-components-to-improve-readability/17178/2, except done clientside in JavaScript.

Embedding the function signatures in the layout has a couple of main advantages:

  1. It more easily enables re-usable code logic+component blocks.
  2. It enables slightly easier callbacks with dynamic components (e.g. a TODO list), as the IDs or indices of the dynamic components can be embedded directly in the static argument list.
  3. It's relatively easy to read.

This PR introduces two new serializations: the function signatures and the clientside version of Input/State. These objects are serialized within the initial layout. Here's an example of what this looks like:

{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"children": [
{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"id": "my-output",
"children": {
# A simple check for "_dash-type" will indicate to# dash-renderer that this is something "special"# and not user defined."_dash_type": "function",
"function": "my_function",
"namespace": "my_library",
"positional_arguments": [
{
"_dash_type": "input", # or state"id": "my-input",
"property": "value"
},
3# also allow constants
]
}
}
},
{
"type": "Input",
"namespace": "dash_core_components",
"props": {
"id": "my-input",
"value": "my value"
}
}
]
}
}

This implementation differs from previous attempts in a few ways:

  1. We are no longer prescriptive about what clientside libraries or functions are available to you. You are responsible for writing the functions. Of course, you may find yourself very productive with Ramda 😉
  2. We do not allow updating arbitrarily nested properties of components (e.g. figure.layout.title) - only top level properties can be updated. In this way, it mirrors the Python callbacks.
  3. The Python interface is light - it just serializes a lookup to the window[namespace][function] and descriptions the arguments of that function (which can be a combination of constants & deferred-evaluated Input and State objects)

This feels to me like the appropriate level of abstraction: very little "magic", pretty similar to Python callbacks, and still quite fast and powerful. It also requires very little backend integration, so all Dash backends (Python & R) can easily have the same interface and community members will be able to re-use the same clientside snippets.

Here are four examples of apps built with clientside that demonstrate different features.

Serverside initial data + clientside filtering

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
dcc.Store(
id='df',
data=df.to_dict('records')
),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='lines'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideState('df', 'data')]
)
),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following clientside function in assets/my_functions.js:

window.clientside = {
updateFig: function(search, years, mode, rows) {
var filtered_rows = R.filter(
R.allPass([
R.compose(
R.contains(search),
R.prop('country')
),
R.compose(
R.flip(R.contains)(years),
R.prop('year')
),
]), rows);
return {
'data': [{
'x': R.pluck('gdpPercap', filtered_rows),
'y': R.pluck('lifeExp', filtered_rows),
'text': R.map(
R.join(' - '),
R.zip(
R.pluck('year', filtered_rows),
R.pluck('country', filtered_rows)
)
),
'type': 'scatter',
'mode': mode,
'marker': {
'opacity': 0.7
}
}],
'layout': {
'hovermode': 'closest',
'xaxis': {'type': 'log'}
}
}
},
}

clientside-filtering


Example 2 - Serverside "Refresh" button + clientside graphing & filtering

Same as above, but with dynamic data, refreshed via a serverside function

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportnumpyasnpimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Truedf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app.layout=html.Div([
html.Button('Refresh Data', id='refresh', n_clicks=0),
dcc.Store(
id='df',
# data=df.to_dict('records')
),
html.Pre(id='head'),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='markers'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideInput('df', 'data')]
)
),
])
@app.callback(Output('df', 'data'), [Input('refresh', 'n_clicks')])defupdate_data(n_clicks):
df=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
df['lifeExp'] =np.random.randn(len(df))
df['gdpPercap'] =np.random.randn(len(df))
returndf.to_dict('records')
@app.callback(Output('head', 'children'), [Input('df', 'data')])defdisplay_head(data):
returnstr(pd.DataFrame(data).head())
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

clientside-refresh

Example 3 - Chaining clientside + serverside callbacks
Mix and match! The DAG remains alive and well - callbacks, no matter where they are executed, will wait their turn.

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from dash_renderer.clientside import ClientsideFunction, ClientsideInput, ClientsideState
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app = dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
app.layout = html.Div([
html.Label('x'),
dcc.Input(id='x', value=3),
html.Label('y'),
dcc.Input(id='y', value=6),
# clientside
html.Label('x + y (clientside)'),
dcc.Input(
id='x+y',
value=ClientsideFunction(
'R',
'add',
[ClientsideInput('x', 'value'),
ClientsideInput('y', 'value')]
)
),
# server-side
html.Label('x+y / 2 (serverside - takes 5 seconds)'),
dcc.Input(id='x+y / 2'),
# server-side
html.Div([
html.Label('Display x, y, x+y/2 (serverside) - takes 5 seconds'),
html.Pre(id='display-all-of-the-values'),
]),
# clientside
html.Label('Mean(x, y, x+y, x+y/2) (clientside)'),
html.Div(
id='mean-of-all-values',
children=ClientsideFunction(
'clientside',
'mean',
[
ClientsideInput('x', 'value'),
ClientsideInput('y', 'value'),
ClientsideInput('x+y', 'value'),
ClientsideInput('x+y / 2', 'value'),
]
)
),
])
@app.callback(Output('x+y / 2', 'value'),
[Input('x+y', 'value')])
def divide_by_two(value):
import time; time.sleep(4)
return float(value) / 2.0
@app.callback(Output('display-all-of-the-values', 'children'),
[Input('x', 'value'),
Input('y', 'value'),
Input('x+y', 'value'),
Input('x+y / 2', 'value')])
def display_all(*args):
import time; time.sleep(4)
return '\n'.join([str(a) for a in args])
if __name__ == '__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/my_functions.js (my_functions.js could be named anything) file:

window.clientside = {
mean: function(...args) {
console.warn('mean.args: ', args);
const meanValues = R.mean(args);
console.warn('meanValues: ', meanValues);
return meanValues;
}
}

clientside-chaining

Example 4 - Adding rows & columns to a table via clientside functions

This is where clientside could shine - the simple operations between components: adding rows to tables or updating dropdowns.

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlimportdash_tableimportjsonfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspdapp=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
html.Label('New Column'),
dcc.Input(id='new-column-name', placeholder='name'),
html.Button('Add Column', id='add-column', n_clicks=0),
html.Button('Add Row', id='add-row', n_clicks=1),
dash_table.DataTable(
id='table',
editable=True,
columns=ClientsideFunction(
'clientside',
'tableColumns',
[ClientsideInput('add-column', 'n_clicks'),
ClientsideState('new-column-name', 'value'),
ClientsideState('table', 'columns'),
[{'id': 'column-1', 'name': 'Column 1'}]],
),
data=ClientsideFunction(
'clientside',
'tableData',
[ClientsideInput('table', 'columns'),
ClientsideInput('add-row', 'n_clicks'),
ClientsideState('table', 'data'),
[{'column-1': 9}]]
)
),
html.Div(html.B('Clientside')),
dcc.Graph(
id='graph',
figure=ClientsideFunction(
'clientside',
'graphTable',
[ClientsideInput('table', 'data')]
)
),
html.B('Server Side'),
html.Pre(id='display')
])
@app.callback(Output('display', 'children'), [Input('table', 'columns'),Input('table', 'data')])defdisplay_data(columns, data):
returnhtml.Div([
html.Div(html.B('Columns')),
html.Pre(json.dumps(columns, indent=2)),
html.Div(html.B('Data')),
html.Pre(json.dumps(data, indent=2)),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/you_name_it.js functions:

window.clientside={tableColumns: function(addColumnNClicks,newColumnName,existingColumns,defaultColumns){if(addColumnNClicks===0){returndefaultColumns;}returnR.concat(existingColumns,[{'name': newColumnName,'id': newColumnName}]);},tableData: function(columns,n_clicks,data,initial_data){if(n_clicks===0&&columns.length===1){returninitial_data;}elseif(R.isNil(data)){returninitial_data;}elseif(columns.length>R.values(data[0]).length){returndata.map(row=>{constnewCell={};newCell[columns[columns.length-1].id]=9;returnR.merge(row,newCell)});}elseif(n_clicks>data.length){constnewRow={};columns.forEach(col=>newRow[col.id]=9);returnR.concat(data,[newRow]);}},graphTable(data){return{'data': [{'z': R.map(R.values,data),'type': 'heatmap'}]}}}

clientside-heatmap

@chriddypchriddyp changed the title Dash ClientsideDash Clientside - Sponsored, Due Feb 1Mar 29, 2019
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due Feb 1Dash Clientside - Sponsored, Due March 1Mar 29, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

This was close but not quite there. Consensus discussing this with folks today is that the "functions embedded in layout" is too far away from the way traditional serverside callbacks work, even if there are some advantages in functionality. There are a few advantages to keeping the syntax closer to @app.callback:

  1. Easier story around this being a "escape hatch" - if one of your callbacks is slow, rewrite it in JS. Fundamentally, the architecture of your app won't change.
  2. Similarly, it'll be easier to always start in Python and then "optimize later"
  3. Easier to have parity with other features in the future like wildcards
  4. This doesn't prevent us from adding embedded functions in the layout later. And when we do so, we could do it for both serverside and clientside.

This would be the new syntax:

app.client_callback(
Output('head', 'children'),
[Input('df', 'data')],
ClientFunction(namespace='clientside', function_name='updateFig')
)

An update is forthcoming this weekend.

@chriddypchriddyp mentioned this pull request Mar 30, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

Closing in preference for #143

@chriddyp
chriddyp deleted the clientside branch March 30, 2019 17:14
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due March 1Dash Clientside TransformationsJun 7, 2022
Sign up for freeto subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@chriddyp
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Dash Clientside Transformations by chriddyp · Pull Request #142 · plotly/dash-renderer · GitHub
Skip to content
This repository was archived by the owner on Aug 29, 2025. It is now read-only.

Dash Clientside Transformations - #142

Closed
chriddyp wants to merge 7 commits into
masterfrom
clientside
Closed

Dash Clientside Transformations#142
chriddyp wants to merge 7 commits into
masterfrom
clientside

Conversation

@chriddyp

Copy link
Copy Markdown
Member

This PR enables outputs to be updated clientside with user-defined JavaScript code. It enables users to replace certain Python callbacks with JavaScript callbacks for faster updates, lighter server load, and re-usable components+logic groups.

Unlike the Python callbacks, the JS callback signatures are embedded in the app layout. In this way, it's similar to the approach discussed in https://community.plot.ly/t/could-output-be-moved-inside-the-components-to-improve-readability/17178/2, except done clientside in JavaScript.

Embedding the function signatures in the layout has a couple of main advantages:

  1. It more easily enables re-usable code logic+component blocks.
  2. It enables slightly easier callbacks with dynamic components (e.g. a TODO list), as the IDs or indices of the dynamic components can be embedded directly in the static argument list.
  3. It's relatively easy to read.

This PR introduces two new serializations: the function signatures and the clientside version of Input/State. These objects are serialized within the initial layout. Here's an example of what this looks like:

{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"children": [
{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"id": "my-output",
"children": {
# A simple check for "_dash-type" will indicate to# dash-renderer that this is something "special"# and not user defined."_dash_type": "function",
"function": "my_function",
"namespace": "my_library",
"positional_arguments": [
{
"_dash_type": "input", # or state"id": "my-input",
"property": "value"
},
3# also allow constants
]
}
}
},
{
"type": "Input",
"namespace": "dash_core_components",
"props": {
"id": "my-input",
"value": "my value"
}
}
]
}
}

This implementation differs from previous attempts in a few ways:

  1. We are no longer prescriptive about what clientside libraries or functions are available to you. You are responsible for writing the functions. Of course, you may find yourself very productive with Ramda 😉
  2. We do not allow updating arbitrarily nested properties of components (e.g. figure.layout.title) - only top level properties can be updated. In this way, it mirrors the Python callbacks.
  3. The Python interface is light - it just serializes a lookup to the window[namespace][function] and descriptions the arguments of that function (which can be a combination of constants & deferred-evaluated Input and State objects)

This feels to me like the appropriate level of abstraction: very little "magic", pretty similar to Python callbacks, and still quite fast and powerful. It also requires very little backend integration, so all Dash backends (Python & R) can easily have the same interface and community members will be able to re-use the same clientside snippets.

Here are four examples of apps built with clientside that demonstrate different features.

Serverside initial data + clientside filtering

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
dcc.Store(
id='df',
data=df.to_dict('records')
),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='lines'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideState('df', 'data')]
)
),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following clientside function in assets/my_functions.js:

window.clientside = {
updateFig: function(search, years, mode, rows) {
var filtered_rows = R.filter(
R.allPass([
R.compose(
R.contains(search),
R.prop('country')
),
R.compose(
R.flip(R.contains)(years),
R.prop('year')
),
]), rows);
return {
'data': [{
'x': R.pluck('gdpPercap', filtered_rows),
'y': R.pluck('lifeExp', filtered_rows),
'text': R.map(
R.join(' - '),
R.zip(
R.pluck('year', filtered_rows),
R.pluck('country', filtered_rows)
)
),
'type': 'scatter',
'mode': mode,
'marker': {
'opacity': 0.7
}
}],
'layout': {
'hovermode': 'closest',
'xaxis': {'type': 'log'}
}
}
},
}

clientside-filtering


Example 2 - Serverside "Refresh" button + clientside graphing & filtering

Same as above, but with dynamic data, refreshed via a serverside function

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportnumpyasnpimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Truedf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app.layout=html.Div([
html.Button('Refresh Data', id='refresh', n_clicks=0),
dcc.Store(
id='df',
# data=df.to_dict('records')
),
html.Pre(id='head'),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='markers'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideInput('df', 'data')]
)
),
])
@app.callback(Output('df', 'data'), [Input('refresh', 'n_clicks')])defupdate_data(n_clicks):
df=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
df['lifeExp'] =np.random.randn(len(df))
df['gdpPercap'] =np.random.randn(len(df))
returndf.to_dict('records')
@app.callback(Output('head', 'children'), [Input('df', 'data')])defdisplay_head(data):
returnstr(pd.DataFrame(data).head())
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

clientside-refresh

Example 3 - Chaining clientside + serverside callbacks
Mix and match! The DAG remains alive and well - callbacks, no matter where they are executed, will wait their turn.

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from dash_renderer.clientside import ClientsideFunction, ClientsideInput, ClientsideState
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app = dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
app.layout = html.Div([
html.Label('x'),
dcc.Input(id='x', value=3),
html.Label('y'),
dcc.Input(id='y', value=6),
# clientside
html.Label('x + y (clientside)'),
dcc.Input(
id='x+y',
value=ClientsideFunction(
'R',
'add',
[ClientsideInput('x', 'value'),
ClientsideInput('y', 'value')]
)
),
# server-side
html.Label('x+y / 2 (serverside - takes 5 seconds)'),
dcc.Input(id='x+y / 2'),
# server-side
html.Div([
html.Label('Display x, y, x+y/2 (serverside) - takes 5 seconds'),
html.Pre(id='display-all-of-the-values'),
]),
# clientside
html.Label('Mean(x, y, x+y, x+y/2) (clientside)'),
html.Div(
id='mean-of-all-values',
children=ClientsideFunction(
'clientside',
'mean',
[
ClientsideInput('x', 'value'),
ClientsideInput('y', 'value'),
ClientsideInput('x+y', 'value'),
ClientsideInput('x+y / 2', 'value'),
]
)
),
])
@app.callback(Output('x+y / 2', 'value'),
[Input('x+y', 'value')])
def divide_by_two(value):
import time; time.sleep(4)
return float(value) / 2.0
@app.callback(Output('display-all-of-the-values', 'children'),
[Input('x', 'value'),
Input('y', 'value'),
Input('x+y', 'value'),
Input('x+y / 2', 'value')])
def display_all(*args):
import time; time.sleep(4)
return '\n'.join([str(a) for a in args])
if __name__ == '__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/my_functions.js (my_functions.js could be named anything) file:

window.clientside = {
mean: function(...args) {
console.warn('mean.args: ', args);
const meanValues = R.mean(args);
console.warn('meanValues: ', meanValues);
return meanValues;
}
}

clientside-chaining

Example 4 - Adding rows & columns to a table via clientside functions

This is where clientside could shine - the simple operations between components: adding rows to tables or updating dropdowns.

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlimportdash_tableimportjsonfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspdapp=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
html.Label('New Column'),
dcc.Input(id='new-column-name', placeholder='name'),
html.Button('Add Column', id='add-column', n_clicks=0),
html.Button('Add Row', id='add-row', n_clicks=1),
dash_table.DataTable(
id='table',
editable=True,
columns=ClientsideFunction(
'clientside',
'tableColumns',
[ClientsideInput('add-column', 'n_clicks'),
ClientsideState('new-column-name', 'value'),
ClientsideState('table', 'columns'),
[{'id': 'column-1', 'name': 'Column 1'}]],
),
data=ClientsideFunction(
'clientside',
'tableData',
[ClientsideInput('table', 'columns'),
ClientsideInput('add-row', 'n_clicks'),
ClientsideState('table', 'data'),
[{'column-1': 9}]]
)
),
html.Div(html.B('Clientside')),
dcc.Graph(
id='graph',
figure=ClientsideFunction(
'clientside',
'graphTable',
[ClientsideInput('table', 'data')]
)
),
html.B('Server Side'),
html.Pre(id='display')
])
@app.callback(Output('display', 'children'), [Input('table', 'columns'),Input('table', 'data')])defdisplay_data(columns, data):
returnhtml.Div([
html.Div(html.B('Columns')),
html.Pre(json.dumps(columns, indent=2)),
html.Div(html.B('Data')),
html.Pre(json.dumps(data, indent=2)),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/you_name_it.js functions:

window.clientside={tableColumns: function(addColumnNClicks,newColumnName,existingColumns,defaultColumns){if(addColumnNClicks===0){returndefaultColumns;}returnR.concat(existingColumns,[{'name': newColumnName,'id': newColumnName}]);},tableData: function(columns,n_clicks,data,initial_data){if(n_clicks===0&&columns.length===1){returninitial_data;}elseif(R.isNil(data)){returninitial_data;}elseif(columns.length>R.values(data[0]).length){returndata.map(row=>{constnewCell={};newCell[columns[columns.length-1].id]=9;returnR.merge(row,newCell)});}elseif(n_clicks>data.length){constnewRow={};columns.forEach(col=>newRow[col.id]=9);returnR.concat(data,[newRow]);}},graphTable(data){return{'data': [{'z': R.map(R.values,data),'type': 'heatmap'}]}}}

clientside-heatmap

@chriddypchriddyp changed the title Dash ClientsideDash Clientside - Sponsored, Due Feb 1Mar 29, 2019
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due Feb 1Dash Clientside - Sponsored, Due March 1Mar 29, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

This was close but not quite there. Consensus discussing this with folks today is that the "functions embedded in layout" is too far away from the way traditional serverside callbacks work, even if there are some advantages in functionality. There are a few advantages to keeping the syntax closer to @app.callback:

  1. Easier story around this being a "escape hatch" - if one of your callbacks is slow, rewrite it in JS. Fundamentally, the architecture of your app won't change.
  2. Similarly, it'll be easier to always start in Python and then "optimize later"
  3. Easier to have parity with other features in the future like wildcards
  4. This doesn't prevent us from adding embedded functions in the layout later. And when we do so, we could do it for both serverside and clientside.

This would be the new syntax:

app.client_callback(
Output('head', 'children'),
[Input('df', 'data')],
ClientFunction(namespace='clientside', function_name='updateFig')
)

An update is forthcoming this weekend.

@chriddypchriddyp mentioned this pull request Mar 30, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

Closing in preference for #143

@chriddyp
chriddyp deleted the clientside branch March 30, 2019 17:14
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due March 1Dash Clientside TransformationsJun 7, 2022
Sign up for freeto subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@chriddyp
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Dash Clientside Transformations by chriddyp · Pull Request #142 · plotly/dash-renderer · GitHub
Skip to content
This repository was archived by the owner on Aug 29, 2025. It is now read-only.

Dash Clientside Transformations - #142

Closed
chriddyp wants to merge 7 commits into
masterfrom
clientside
Closed

Dash Clientside Transformations#142
chriddyp wants to merge 7 commits into
masterfrom
clientside

Conversation

@chriddyp

Copy link
Copy Markdown
Member

This PR enables outputs to be updated clientside with user-defined JavaScript code. It enables users to replace certain Python callbacks with JavaScript callbacks for faster updates, lighter server load, and re-usable components+logic groups.

Unlike the Python callbacks, the JS callback signatures are embedded in the app layout. In this way, it's similar to the approach discussed in https://community.plot.ly/t/could-output-be-moved-inside-the-components-to-improve-readability/17178/2, except done clientside in JavaScript.

Embedding the function signatures in the layout has a couple of main advantages:

  1. It more easily enables re-usable code logic+component blocks.
  2. It enables slightly easier callbacks with dynamic components (e.g. a TODO list), as the IDs or indices of the dynamic components can be embedded directly in the static argument list.
  3. It's relatively easy to read.

This PR introduces two new serializations: the function signatures and the clientside version of Input/State. These objects are serialized within the initial layout. Here's an example of what this looks like:

{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"children": [
{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"id": "my-output",
"children": {
# A simple check for "_dash-type" will indicate to# dash-renderer that this is something "special"# and not user defined."_dash_type": "function",
"function": "my_function",
"namespace": "my_library",
"positional_arguments": [
{
"_dash_type": "input", # or state"id": "my-input",
"property": "value"
},
3# also allow constants
]
}
}
},
{
"type": "Input",
"namespace": "dash_core_components",
"props": {
"id": "my-input",
"value": "my value"
}
}
]
}
}

This implementation differs from previous attempts in a few ways:

  1. We are no longer prescriptive about what clientside libraries or functions are available to you. You are responsible for writing the functions. Of course, you may find yourself very productive with Ramda 😉
  2. We do not allow updating arbitrarily nested properties of components (e.g. figure.layout.title) - only top level properties can be updated. In this way, it mirrors the Python callbacks.
  3. The Python interface is light - it just serializes a lookup to the window[namespace][function] and descriptions the arguments of that function (which can be a combination of constants & deferred-evaluated Input and State objects)

This feels to me like the appropriate level of abstraction: very little "magic", pretty similar to Python callbacks, and still quite fast and powerful. It also requires very little backend integration, so all Dash backends (Python & R) can easily have the same interface and community members will be able to re-use the same clientside snippets.

Here are four examples of apps built with clientside that demonstrate different features.

Serverside initial data + clientside filtering

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
dcc.Store(
id='df',
data=df.to_dict('records')
),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='lines'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideState('df', 'data')]
)
),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following clientside function in assets/my_functions.js:

window.clientside = {
updateFig: function(search, years, mode, rows) {
var filtered_rows = R.filter(
R.allPass([
R.compose(
R.contains(search),
R.prop('country')
),
R.compose(
R.flip(R.contains)(years),
R.prop('year')
),
]), rows);
return {
'data': [{
'x': R.pluck('gdpPercap', filtered_rows),
'y': R.pluck('lifeExp', filtered_rows),
'text': R.map(
R.join(' - '),
R.zip(
R.pluck('year', filtered_rows),
R.pluck('country', filtered_rows)
)
),
'type': 'scatter',
'mode': mode,
'marker': {
'opacity': 0.7
}
}],
'layout': {
'hovermode': 'closest',
'xaxis': {'type': 'log'}
}
}
},
}

clientside-filtering


Example 2 - Serverside "Refresh" button + clientside graphing & filtering

Same as above, but with dynamic data, refreshed via a serverside function

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportnumpyasnpimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Truedf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app.layout=html.Div([
html.Button('Refresh Data', id='refresh', n_clicks=0),
dcc.Store(
id='df',
# data=df.to_dict('records')
),
html.Pre(id='head'),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='markers'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideInput('df', 'data')]
)
),
])
@app.callback(Output('df', 'data'), [Input('refresh', 'n_clicks')])defupdate_data(n_clicks):
df=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
df['lifeExp'] =np.random.randn(len(df))
df['gdpPercap'] =np.random.randn(len(df))
returndf.to_dict('records')
@app.callback(Output('head', 'children'), [Input('df', 'data')])defdisplay_head(data):
returnstr(pd.DataFrame(data).head())
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

clientside-refresh

Example 3 - Chaining clientside + serverside callbacks
Mix and match! The DAG remains alive and well - callbacks, no matter where they are executed, will wait their turn.

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from dash_renderer.clientside import ClientsideFunction, ClientsideInput, ClientsideState
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app = dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
app.layout = html.Div([
html.Label('x'),
dcc.Input(id='x', value=3),
html.Label('y'),
dcc.Input(id='y', value=6),
# clientside
html.Label('x + y (clientside)'),
dcc.Input(
id='x+y',
value=ClientsideFunction(
'R',
'add',
[ClientsideInput('x', 'value'),
ClientsideInput('y', 'value')]
)
),
# server-side
html.Label('x+y / 2 (serverside - takes 5 seconds)'),
dcc.Input(id='x+y / 2'),
# server-side
html.Div([
html.Label('Display x, y, x+y/2 (serverside) - takes 5 seconds'),
html.Pre(id='display-all-of-the-values'),
]),
# clientside
html.Label('Mean(x, y, x+y, x+y/2) (clientside)'),
html.Div(
id='mean-of-all-values',
children=ClientsideFunction(
'clientside',
'mean',
[
ClientsideInput('x', 'value'),
ClientsideInput('y', 'value'),
ClientsideInput('x+y', 'value'),
ClientsideInput('x+y / 2', 'value'),
]
)
),
])
@app.callback(Output('x+y / 2', 'value'),
[Input('x+y', 'value')])
def divide_by_two(value):
import time; time.sleep(4)
return float(value) / 2.0
@app.callback(Output('display-all-of-the-values', 'children'),
[Input('x', 'value'),
Input('y', 'value'),
Input('x+y', 'value'),
Input('x+y / 2', 'value')])
def display_all(*args):
import time; time.sleep(4)
return '\n'.join([str(a) for a in args])
if __name__ == '__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/my_functions.js (my_functions.js could be named anything) file:

window.clientside = {
mean: function(...args) {
console.warn('mean.args: ', args);
const meanValues = R.mean(args);
console.warn('meanValues: ', meanValues);
return meanValues;
}
}

clientside-chaining

Example 4 - Adding rows & columns to a table via clientside functions

This is where clientside could shine - the simple operations between components: adding rows to tables or updating dropdowns.

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlimportdash_tableimportjsonfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspdapp=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
html.Label('New Column'),
dcc.Input(id='new-column-name', placeholder='name'),
html.Button('Add Column', id='add-column', n_clicks=0),
html.Button('Add Row', id='add-row', n_clicks=1),
dash_table.DataTable(
id='table',
editable=True,
columns=ClientsideFunction(
'clientside',
'tableColumns',
[ClientsideInput('add-column', 'n_clicks'),
ClientsideState('new-column-name', 'value'),
ClientsideState('table', 'columns'),
[{'id': 'column-1', 'name': 'Column 1'}]],
),
data=ClientsideFunction(
'clientside',
'tableData',
[ClientsideInput('table', 'columns'),
ClientsideInput('add-row', 'n_clicks'),
ClientsideState('table', 'data'),
[{'column-1': 9}]]
)
),
html.Div(html.B('Clientside')),
dcc.Graph(
id='graph',
figure=ClientsideFunction(
'clientside',
'graphTable',
[ClientsideInput('table', 'data')]
)
),
html.B('Server Side'),
html.Pre(id='display')
])
@app.callback(Output('display', 'children'), [Input('table', 'columns'),Input('table', 'data')])defdisplay_data(columns, data):
returnhtml.Div([
html.Div(html.B('Columns')),
html.Pre(json.dumps(columns, indent=2)),
html.Div(html.B('Data')),
html.Pre(json.dumps(data, indent=2)),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/you_name_it.js functions:

window.clientside={tableColumns: function(addColumnNClicks,newColumnName,existingColumns,defaultColumns){if(addColumnNClicks===0){returndefaultColumns;}returnR.concat(existingColumns,[{'name': newColumnName,'id': newColumnName}]);},tableData: function(columns,n_clicks,data,initial_data){if(n_clicks===0&&columns.length===1){returninitial_data;}elseif(R.isNil(data)){returninitial_data;}elseif(columns.length>R.values(data[0]).length){returndata.map(row=>{constnewCell={};newCell[columns[columns.length-1].id]=9;returnR.merge(row,newCell)});}elseif(n_clicks>data.length){constnewRow={};columns.forEach(col=>newRow[col.id]=9);returnR.concat(data,[newRow]);}},graphTable(data){return{'data': [{'z': R.map(R.values,data),'type': 'heatmap'}]}}}

clientside-heatmap

@chriddypchriddyp changed the title Dash ClientsideDash Clientside - Sponsored, Due Feb 1Mar 29, 2019
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due Feb 1Dash Clientside - Sponsored, Due March 1Mar 29, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

This was close but not quite there. Consensus discussing this with folks today is that the "functions embedded in layout" is too far away from the way traditional serverside callbacks work, even if there are some advantages in functionality. There are a few advantages to keeping the syntax closer to @app.callback:

  1. Easier story around this being a "escape hatch" - if one of your callbacks is slow, rewrite it in JS. Fundamentally, the architecture of your app won't change.
  2. Similarly, it'll be easier to always start in Python and then "optimize later"
  3. Easier to have parity with other features in the future like wildcards
  4. This doesn't prevent us from adding embedded functions in the layout later. And when we do so, we could do it for both serverside and clientside.

This would be the new syntax:

app.client_callback(
Output('head', 'children'),
[Input('df', 'data')],
ClientFunction(namespace='clientside', function_name='updateFig')
)

An update is forthcoming this weekend.

@chriddypchriddyp mentioned this pull request Mar 30, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

Closing in preference for #143

@chriddyp
chriddyp deleted the clientside branch March 30, 2019 17:14
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due March 1Dash Clientside TransformationsJun 7, 2022
Sign up for freeto subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@chriddyp
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Dash Clientside Transformations by chriddyp · Pull Request #142 · plotly/dash-renderer · GitHub
Skip to content
This repository was archived by the owner on Aug 29, 2025. It is now read-only.

Dash Clientside Transformations - #142

Closed
chriddyp wants to merge 7 commits into
masterfrom
clientside
Closed

Dash Clientside Transformations#142
chriddyp wants to merge 7 commits into
masterfrom
clientside

Conversation

@chriddyp

Copy link
Copy Markdown
Member

This PR enables outputs to be updated clientside with user-defined JavaScript code. It enables users to replace certain Python callbacks with JavaScript callbacks for faster updates, lighter server load, and re-usable components+logic groups.

Unlike the Python callbacks, the JS callback signatures are embedded in the app layout. In this way, it's similar to the approach discussed in https://community.plot.ly/t/could-output-be-moved-inside-the-components-to-improve-readability/17178/2, except done clientside in JavaScript.

Embedding the function signatures in the layout has a couple of main advantages:

  1. It more easily enables re-usable code logic+component blocks.
  2. It enables slightly easier callbacks with dynamic components (e.g. a TODO list), as the IDs or indices of the dynamic components can be embedded directly in the static argument list.
  3. It's relatively easy to read.

This PR introduces two new serializations: the function signatures and the clientside version of Input/State. These objects are serialized within the initial layout. Here's an example of what this looks like:

{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"children": [
{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"id": "my-output",
"children": {
# A simple check for "_dash-type" will indicate to# dash-renderer that this is something "special"# and not user defined."_dash_type": "function",
"function": "my_function",
"namespace": "my_library",
"positional_arguments": [
{
"_dash_type": "input", # or state"id": "my-input",
"property": "value"
},
3# also allow constants
]
}
}
},
{
"type": "Input",
"namespace": "dash_core_components",
"props": {
"id": "my-input",
"value": "my value"
}
}
]
}
}

This implementation differs from previous attempts in a few ways:

  1. We are no longer prescriptive about what clientside libraries or functions are available to you. You are responsible for writing the functions. Of course, you may find yourself very productive with Ramda 😉
  2. We do not allow updating arbitrarily nested properties of components (e.g. figure.layout.title) - only top level properties can be updated. In this way, it mirrors the Python callbacks.
  3. The Python interface is light - it just serializes a lookup to the window[namespace][function] and descriptions the arguments of that function (which can be a combination of constants & deferred-evaluated Input and State objects)

This feels to me like the appropriate level of abstraction: very little "magic", pretty similar to Python callbacks, and still quite fast and powerful. It also requires very little backend integration, so all Dash backends (Python & R) can easily have the same interface and community members will be able to re-use the same clientside snippets.

Here are four examples of apps built with clientside that demonstrate different features.

Serverside initial data + clientside filtering

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
dcc.Store(
id='df',
data=df.to_dict('records')
),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='lines'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideState('df', 'data')]
)
),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following clientside function in assets/my_functions.js:

window.clientside = {
updateFig: function(search, years, mode, rows) {
var filtered_rows = R.filter(
R.allPass([
R.compose(
R.contains(search),
R.prop('country')
),
R.compose(
R.flip(R.contains)(years),
R.prop('year')
),
]), rows);
return {
'data': [{
'x': R.pluck('gdpPercap', filtered_rows),
'y': R.pluck('lifeExp', filtered_rows),
'text': R.map(
R.join(' - '),
R.zip(
R.pluck('year', filtered_rows),
R.pluck('country', filtered_rows)
)
),
'type': 'scatter',
'mode': mode,
'marker': {
'opacity': 0.7
}
}],
'layout': {
'hovermode': 'closest',
'xaxis': {'type': 'log'}
}
}
},
}

clientside-filtering


Example 2 - Serverside "Refresh" button + clientside graphing & filtering

Same as above, but with dynamic data, refreshed via a serverside function

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportnumpyasnpimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Truedf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app.layout=html.Div([
html.Button('Refresh Data', id='refresh', n_clicks=0),
dcc.Store(
id='df',
# data=df.to_dict('records')
),
html.Pre(id='head'),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='markers'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideInput('df', 'data')]
)
),
])
@app.callback(Output('df', 'data'), [Input('refresh', 'n_clicks')])defupdate_data(n_clicks):
df=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
df['lifeExp'] =np.random.randn(len(df))
df['gdpPercap'] =np.random.randn(len(df))
returndf.to_dict('records')
@app.callback(Output('head', 'children'), [Input('df', 'data')])defdisplay_head(data):
returnstr(pd.DataFrame(data).head())
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

clientside-refresh

Example 3 - Chaining clientside + serverside callbacks
Mix and match! The DAG remains alive and well - callbacks, no matter where they are executed, will wait their turn.

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from dash_renderer.clientside import ClientsideFunction, ClientsideInput, ClientsideState
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app = dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
app.layout = html.Div([
html.Label('x'),
dcc.Input(id='x', value=3),
html.Label('y'),
dcc.Input(id='y', value=6),
# clientside
html.Label('x + y (clientside)'),
dcc.Input(
id='x+y',
value=ClientsideFunction(
'R',
'add',
[ClientsideInput('x', 'value'),
ClientsideInput('y', 'value')]
)
),
# server-side
html.Label('x+y / 2 (serverside - takes 5 seconds)'),
dcc.Input(id='x+y / 2'),
# server-side
html.Div([
html.Label('Display x, y, x+y/2 (serverside) - takes 5 seconds'),
html.Pre(id='display-all-of-the-values'),
]),
# clientside
html.Label('Mean(x, y, x+y, x+y/2) (clientside)'),
html.Div(
id='mean-of-all-values',
children=ClientsideFunction(
'clientside',
'mean',
[
ClientsideInput('x', 'value'),
ClientsideInput('y', 'value'),
ClientsideInput('x+y', 'value'),
ClientsideInput('x+y / 2', 'value'),
]
)
),
])
@app.callback(Output('x+y / 2', 'value'),
[Input('x+y', 'value')])
def divide_by_two(value):
import time; time.sleep(4)
return float(value) / 2.0
@app.callback(Output('display-all-of-the-values', 'children'),
[Input('x', 'value'),
Input('y', 'value'),
Input('x+y', 'value'),
Input('x+y / 2', 'value')])
def display_all(*args):
import time; time.sleep(4)
return '\n'.join([str(a) for a in args])
if __name__ == '__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/my_functions.js (my_functions.js could be named anything) file:

window.clientside = {
mean: function(...args) {
console.warn('mean.args: ', args);
const meanValues = R.mean(args);
console.warn('meanValues: ', meanValues);
return meanValues;
}
}

clientside-chaining

Example 4 - Adding rows & columns to a table via clientside functions

This is where clientside could shine - the simple operations between components: adding rows to tables or updating dropdowns.

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlimportdash_tableimportjsonfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspdapp=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
html.Label('New Column'),
dcc.Input(id='new-column-name', placeholder='name'),
html.Button('Add Column', id='add-column', n_clicks=0),
html.Button('Add Row', id='add-row', n_clicks=1),
dash_table.DataTable(
id='table',
editable=True,
columns=ClientsideFunction(
'clientside',
'tableColumns',
[ClientsideInput('add-column', 'n_clicks'),
ClientsideState('new-column-name', 'value'),
ClientsideState('table', 'columns'),
[{'id': 'column-1', 'name': 'Column 1'}]],
),
data=ClientsideFunction(
'clientside',
'tableData',
[ClientsideInput('table', 'columns'),
ClientsideInput('add-row', 'n_clicks'),
ClientsideState('table', 'data'),
[{'column-1': 9}]]
)
),
html.Div(html.B('Clientside')),
dcc.Graph(
id='graph',
figure=ClientsideFunction(
'clientside',
'graphTable',
[ClientsideInput('table', 'data')]
)
),
html.B('Server Side'),
html.Pre(id='display')
])
@app.callback(Output('display', 'children'), [Input('table', 'columns'),Input('table', 'data')])defdisplay_data(columns, data):
returnhtml.Div([
html.Div(html.B('Columns')),
html.Pre(json.dumps(columns, indent=2)),
html.Div(html.B('Data')),
html.Pre(json.dumps(data, indent=2)),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/you_name_it.js functions:

window.clientside={tableColumns: function(addColumnNClicks,newColumnName,existingColumns,defaultColumns){if(addColumnNClicks===0){returndefaultColumns;}returnR.concat(existingColumns,[{'name': newColumnName,'id': newColumnName}]);},tableData: function(columns,n_clicks,data,initial_data){if(n_clicks===0&&columns.length===1){returninitial_data;}elseif(R.isNil(data)){returninitial_data;}elseif(columns.length>R.values(data[0]).length){returndata.map(row=>{constnewCell={};newCell[columns[columns.length-1].id]=9;returnR.merge(row,newCell)});}elseif(n_clicks>data.length){constnewRow={};columns.forEach(col=>newRow[col.id]=9);returnR.concat(data,[newRow]);}},graphTable(data){return{'data': [{'z': R.map(R.values,data),'type': 'heatmap'}]}}}

clientside-heatmap

@chriddypchriddyp changed the title Dash ClientsideDash Clientside - Sponsored, Due Feb 1Mar 29, 2019
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due Feb 1Dash Clientside - Sponsored, Due March 1Mar 29, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

This was close but not quite there. Consensus discussing this with folks today is that the "functions embedded in layout" is too far away from the way traditional serverside callbacks work, even if there are some advantages in functionality. There are a few advantages to keeping the syntax closer to @app.callback:

  1. Easier story around this being a "escape hatch" - if one of your callbacks is slow, rewrite it in JS. Fundamentally, the architecture of your app won't change.
  2. Similarly, it'll be easier to always start in Python and then "optimize later"
  3. Easier to have parity with other features in the future like wildcards
  4. This doesn't prevent us from adding embedded functions in the layout later. And when we do so, we could do it for both serverside and clientside.

This would be the new syntax:

app.client_callback(
Output('head', 'children'),
[Input('df', 'data')],
ClientFunction(namespace='clientside', function_name='updateFig')
)

An update is forthcoming this weekend.

@chriddypchriddyp mentioned this pull request Mar 30, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

Closing in preference for #143

@chriddyp
chriddyp deleted the clientside branch March 30, 2019 17:14
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due March 1Dash Clientside TransformationsJun 7, 2022
Sign up for freeto subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@chriddyp
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Dash Clientside Transformations by chriddyp · Pull Request #142 · plotly/dash-renderer · GitHub
Skip to content
This repository was archived by the owner on Aug 29, 2025. It is now read-only.

Dash Clientside Transformations - #142

Closed
chriddyp wants to merge 7 commits into
masterfrom
clientside
Closed

Dash Clientside Transformations#142
chriddyp wants to merge 7 commits into
masterfrom
clientside

Conversation

@chriddyp

Copy link
Copy Markdown
Member

This PR enables outputs to be updated clientside with user-defined JavaScript code. It enables users to replace certain Python callbacks with JavaScript callbacks for faster updates, lighter server load, and re-usable components+logic groups.

Unlike the Python callbacks, the JS callback signatures are embedded in the app layout. In this way, it's similar to the approach discussed in https://community.plot.ly/t/could-output-be-moved-inside-the-components-to-improve-readability/17178/2, except done clientside in JavaScript.

Embedding the function signatures in the layout has a couple of main advantages:

  1. It more easily enables re-usable code logic+component blocks.
  2. It enables slightly easier callbacks with dynamic components (e.g. a TODO list), as the IDs or indices of the dynamic components can be embedded directly in the static argument list.
  3. It's relatively easy to read.

This PR introduces two new serializations: the function signatures and the clientside version of Input/State. These objects are serialized within the initial layout. Here's an example of what this looks like:

{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"children": [
{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"id": "my-output",
"children": {
# A simple check for "_dash-type" will indicate to# dash-renderer that this is something "special"# and not user defined."_dash_type": "function",
"function": "my_function",
"namespace": "my_library",
"positional_arguments": [
{
"_dash_type": "input", # or state"id": "my-input",
"property": "value"
},
3# also allow constants
]
}
}
},
{
"type": "Input",
"namespace": "dash_core_components",
"props": {
"id": "my-input",
"value": "my value"
}
}
]
}
}

This implementation differs from previous attempts in a few ways:

  1. We are no longer prescriptive about what clientside libraries or functions are available to you. You are responsible for writing the functions. Of course, you may find yourself very productive with Ramda 😉
  2. We do not allow updating arbitrarily nested properties of components (e.g. figure.layout.title) - only top level properties can be updated. In this way, it mirrors the Python callbacks.
  3. The Python interface is light - it just serializes a lookup to the window[namespace][function] and descriptions the arguments of that function (which can be a combination of constants & deferred-evaluated Input and State objects)

This feels to me like the appropriate level of abstraction: very little "magic", pretty similar to Python callbacks, and still quite fast and powerful. It also requires very little backend integration, so all Dash backends (Python & R) can easily have the same interface and community members will be able to re-use the same clientside snippets.

Here are four examples of apps built with clientside that demonstrate different features.

Serverside initial data + clientside filtering

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
dcc.Store(
id='df',
data=df.to_dict('records')
),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='lines'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideState('df', 'data')]
)
),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following clientside function in assets/my_functions.js:

window.clientside = {
updateFig: function(search, years, mode, rows) {
var filtered_rows = R.filter(
R.allPass([
R.compose(
R.contains(search),
R.prop('country')
),
R.compose(
R.flip(R.contains)(years),
R.prop('year')
),
]), rows);
return {
'data': [{
'x': R.pluck('gdpPercap', filtered_rows),
'y': R.pluck('lifeExp', filtered_rows),
'text': R.map(
R.join(' - '),
R.zip(
R.pluck('year', filtered_rows),
R.pluck('country', filtered_rows)
)
),
'type': 'scatter',
'mode': mode,
'marker': {
'opacity': 0.7
}
}],
'layout': {
'hovermode': 'closest',
'xaxis': {'type': 'log'}
}
}
},
}

clientside-filtering


Example 2 - Serverside "Refresh" button + clientside graphing & filtering

Same as above, but with dynamic data, refreshed via a serverside function

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportnumpyasnpimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Truedf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app.layout=html.Div([
html.Button('Refresh Data', id='refresh', n_clicks=0),
dcc.Store(
id='df',
# data=df.to_dict('records')
),
html.Pre(id='head'),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='markers'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideInput('df', 'data')]
)
),
])
@app.callback(Output('df', 'data'), [Input('refresh', 'n_clicks')])defupdate_data(n_clicks):
df=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
df['lifeExp'] =np.random.randn(len(df))
df['gdpPercap'] =np.random.randn(len(df))
returndf.to_dict('records')
@app.callback(Output('head', 'children'), [Input('df', 'data')])defdisplay_head(data):
returnstr(pd.DataFrame(data).head())
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

clientside-refresh

Example 3 - Chaining clientside + serverside callbacks
Mix and match! The DAG remains alive and well - callbacks, no matter where they are executed, will wait their turn.

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from dash_renderer.clientside import ClientsideFunction, ClientsideInput, ClientsideState
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app = dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
app.layout = html.Div([
html.Label('x'),
dcc.Input(id='x', value=3),
html.Label('y'),
dcc.Input(id='y', value=6),
# clientside
html.Label('x + y (clientside)'),
dcc.Input(
id='x+y',
value=ClientsideFunction(
'R',
'add',
[ClientsideInput('x', 'value'),
ClientsideInput('y', 'value')]
)
),
# server-side
html.Label('x+y / 2 (serverside - takes 5 seconds)'),
dcc.Input(id='x+y / 2'),
# server-side
html.Div([
html.Label('Display x, y, x+y/2 (serverside) - takes 5 seconds'),
html.Pre(id='display-all-of-the-values'),
]),
# clientside
html.Label('Mean(x, y, x+y, x+y/2) (clientside)'),
html.Div(
id='mean-of-all-values',
children=ClientsideFunction(
'clientside',
'mean',
[
ClientsideInput('x', 'value'),
ClientsideInput('y', 'value'),
ClientsideInput('x+y', 'value'),
ClientsideInput('x+y / 2', 'value'),
]
)
),
])
@app.callback(Output('x+y / 2', 'value'),
[Input('x+y', 'value')])
def divide_by_two(value):
import time; time.sleep(4)
return float(value) / 2.0
@app.callback(Output('display-all-of-the-values', 'children'),
[Input('x', 'value'),
Input('y', 'value'),
Input('x+y', 'value'),
Input('x+y / 2', 'value')])
def display_all(*args):
import time; time.sleep(4)
return '\n'.join([str(a) for a in args])
if __name__ == '__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/my_functions.js (my_functions.js could be named anything) file:

window.clientside = {
mean: function(...args) {
console.warn('mean.args: ', args);
const meanValues = R.mean(args);
console.warn('meanValues: ', meanValues);
return meanValues;
}
}

clientside-chaining

Example 4 - Adding rows & columns to a table via clientside functions

This is where clientside could shine - the simple operations between components: adding rows to tables or updating dropdowns.

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlimportdash_tableimportjsonfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspdapp=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
html.Label('New Column'),
dcc.Input(id='new-column-name', placeholder='name'),
html.Button('Add Column', id='add-column', n_clicks=0),
html.Button('Add Row', id='add-row', n_clicks=1),
dash_table.DataTable(
id='table',
editable=True,
columns=ClientsideFunction(
'clientside',
'tableColumns',
[ClientsideInput('add-column', 'n_clicks'),
ClientsideState('new-column-name', 'value'),
ClientsideState('table', 'columns'),
[{'id': 'column-1', 'name': 'Column 1'}]],
),
data=ClientsideFunction(
'clientside',
'tableData',
[ClientsideInput('table', 'columns'),
ClientsideInput('add-row', 'n_clicks'),
ClientsideState('table', 'data'),
[{'column-1': 9}]]
)
),
html.Div(html.B('Clientside')),
dcc.Graph(
id='graph',
figure=ClientsideFunction(
'clientside',
'graphTable',
[ClientsideInput('table', 'data')]
)
),
html.B('Server Side'),
html.Pre(id='display')
])
@app.callback(Output('display', 'children'), [Input('table', 'columns'),Input('table', 'data')])defdisplay_data(columns, data):
returnhtml.Div([
html.Div(html.B('Columns')),
html.Pre(json.dumps(columns, indent=2)),
html.Div(html.B('Data')),
html.Pre(json.dumps(data, indent=2)),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/you_name_it.js functions:

window.clientside={tableColumns: function(addColumnNClicks,newColumnName,existingColumns,defaultColumns){if(addColumnNClicks===0){returndefaultColumns;}returnR.concat(existingColumns,[{'name': newColumnName,'id': newColumnName}]);},tableData: function(columns,n_clicks,data,initial_data){if(n_clicks===0&&columns.length===1){returninitial_data;}elseif(R.isNil(data)){returninitial_data;}elseif(columns.length>R.values(data[0]).length){returndata.map(row=>{constnewCell={};newCell[columns[columns.length-1].id]=9;returnR.merge(row,newCell)});}elseif(n_clicks>data.length){constnewRow={};columns.forEach(col=>newRow[col.id]=9);returnR.concat(data,[newRow]);}},graphTable(data){return{'data': [{'z': R.map(R.values,data),'type': 'heatmap'}]}}}

clientside-heatmap

@chriddypchriddyp changed the title Dash ClientsideDash Clientside - Sponsored, Due Feb 1Mar 29, 2019
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due Feb 1Dash Clientside - Sponsored, Due March 1Mar 29, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

This was close but not quite there. Consensus discussing this with folks today is that the "functions embedded in layout" is too far away from the way traditional serverside callbacks work, even if there are some advantages in functionality. There are a few advantages to keeping the syntax closer to @app.callback:

  1. Easier story around this being a "escape hatch" - if one of your callbacks is slow, rewrite it in JS. Fundamentally, the architecture of your app won't change.
  2. Similarly, it'll be easier to always start in Python and then "optimize later"
  3. Easier to have parity with other features in the future like wildcards
  4. This doesn't prevent us from adding embedded functions in the layout later. And when we do so, we could do it for both serverside and clientside.

This would be the new syntax:

app.client_callback(
Output('head', 'children'),
[Input('df', 'data')],
ClientFunction(namespace='clientside', function_name='updateFig')
)

An update is forthcoming this weekend.

@chriddypchriddyp mentioned this pull request Mar 30, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

Closing in preference for #143

@chriddyp
chriddyp deleted the clientside branch March 30, 2019 17:14
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due March 1Dash Clientside TransformationsJun 7, 2022
Sign up for freeto subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@chriddyp
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Dash Clientside Transformations by chriddyp · Pull Request #142 · plotly/dash-renderer · GitHub
Skip to content
This repository was archived by the owner on Aug 29, 2025. It is now read-only.

Dash Clientside Transformations - #142

Closed
chriddyp wants to merge 7 commits into
masterfrom
clientside
Closed

Dash Clientside Transformations#142
chriddyp wants to merge 7 commits into
masterfrom
clientside

Conversation

@chriddyp

Copy link
Copy Markdown
Member

This PR enables outputs to be updated clientside with user-defined JavaScript code. It enables users to replace certain Python callbacks with JavaScript callbacks for faster updates, lighter server load, and re-usable components+logic groups.

Unlike the Python callbacks, the JS callback signatures are embedded in the app layout. In this way, it's similar to the approach discussed in https://community.plot.ly/t/could-output-be-moved-inside-the-components-to-improve-readability/17178/2, except done clientside in JavaScript.

Embedding the function signatures in the layout has a couple of main advantages:

  1. It more easily enables re-usable code logic+component blocks.
  2. It enables slightly easier callbacks with dynamic components (e.g. a TODO list), as the IDs or indices of the dynamic components can be embedded directly in the static argument list.
  3. It's relatively easy to read.

This PR introduces two new serializations: the function signatures and the clientside version of Input/State. These objects are serialized within the initial layout. Here's an example of what this looks like:

{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"children": [
{
"type": "Div",
"namespace": "dash_html_components",
"props": {
"id": "my-output",
"children": {
# A simple check for "_dash-type" will indicate to# dash-renderer that this is something "special"# and not user defined."_dash_type": "function",
"function": "my_function",
"namespace": "my_library",
"positional_arguments": [
{
"_dash_type": "input", # or state"id": "my-input",
"property": "value"
},
3# also allow constants
]
}
}
},
{
"type": "Input",
"namespace": "dash_core_components",
"props": {
"id": "my-input",
"value": "my value"
}
}
]
}
}

This implementation differs from previous attempts in a few ways:

  1. We are no longer prescriptive about what clientside libraries or functions are available to you. You are responsible for writing the functions. Of course, you may find yourself very productive with Ramda 😉
  2. We do not allow updating arbitrarily nested properties of components (e.g. figure.layout.title) - only top level properties can be updated. In this way, it mirrors the Python callbacks.
  3. The Python interface is light - it just serializes a lookup to the window[namespace][function] and descriptions the arguments of that function (which can be a combination of constants & deferred-evaluated Input and State objects)

This feels to me like the appropriate level of abstraction: very little "magic", pretty similar to Python callbacks, and still quite fast and powerful. It also requires very little backend integration, so all Dash backends (Python & R) can easily have the same interface and community members will be able to re-use the same clientside snippets.

Here are four examples of apps built with clientside that demonstrate different features.

Serverside initial data + clientside filtering

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
dcc.Store(
id='df',
data=df.to_dict('records')
),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='lines'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideState('df', 'data')]
)
),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following clientside function in assets/my_functions.js:

window.clientside = {
updateFig: function(search, years, mode, rows) {
var filtered_rows = R.filter(
R.allPass([
R.compose(
R.contains(search),
R.prop('country')
),
R.compose(
R.flip(R.contains)(years),
R.prop('year')
),
]), rows);
return {
'data': [{
'x': R.pluck('gdpPercap', filtered_rows),
'y': R.pluck('lifeExp', filtered_rows),
'text': R.map(
R.join(' - '),
R.zip(
R.pluck('year', filtered_rows),
R.pluck('country', filtered_rows)
)
),
'type': 'scatter',
'mode': mode,
'marker': {
'opacity': 0.7
}
}],
'layout': {
'hovermode': 'closest',
'xaxis': {'type': 'log'}
}
}
},
}

clientside-filtering


Example 2 - Serverside "Refresh" button + clientside graphing & filtering

Same as above, but with dynamic data, refreshed via a serverside function

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportnumpyasnpimportpandasaspddf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Truedf=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app.layout=html.Div([
html.Button('Refresh Data', id='refresh', n_clicks=0),
dcc.Store(
id='df',
# data=df.to_dict('records')
),
html.Pre(id='head'),
dcc.Dropdown(
id='country-search',
options=[
{'value': i, 'label': i}
foriindf.country.unique()
],
value='Canada'
),
dcc.Dropdown(
id='year',
options=[
{'value': i, 'label': i}
foriindf.year.unique()
],
multi=True,
value=df.year.unique()
),
dcc.RadioItems(
id='mode',
options=[
{'label': 'Lines', 'value': 'lines'},
{'label': 'Markers', 'value': 'markers'},
],
value='markers'
),
dcc.Graph(
id='my-fig',
figure=ClientsideFunction(
'clientside',
'updateFig',
[ClientsideInput('country-search', 'value'),
ClientsideInput('year', 'value'),
ClientsideInput('mode', 'value'),
ClientsideInput('df', 'data')]
)
),
])
@app.callback(Output('df', 'data'), [Input('refresh', 'n_clicks')])defupdate_data(n_clicks):
df=pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
df['lifeExp'] =np.random.randn(len(df))
df['gdpPercap'] =np.random.randn(len(df))
returndf.to_dict('records')
@app.callback(Output('head', 'children'), [Input('df', 'data')])defdisplay_head(data):
returnstr(pd.DataFrame(data).head())
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

clientside-refresh

Example 3 - Chaining clientside + serverside callbacks
Mix and match! The DAG remains alive and well - callbacks, no matter where they are executed, will wait their turn.

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
from dash_renderer.clientside import ClientsideFunction, ClientsideInput, ClientsideState
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')
app = dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
app.layout = html.Div([
html.Label('x'),
dcc.Input(id='x', value=3),
html.Label('y'),
dcc.Input(id='y', value=6),
# clientside
html.Label('x + y (clientside)'),
dcc.Input(
id='x+y',
value=ClientsideFunction(
'R',
'add',
[ClientsideInput('x', 'value'),
ClientsideInput('y', 'value')]
)
),
# server-side
html.Label('x+y / 2 (serverside - takes 5 seconds)'),
dcc.Input(id='x+y / 2'),
# server-side
html.Div([
html.Label('Display x, y, x+y/2 (serverside) - takes 5 seconds'),
html.Pre(id='display-all-of-the-values'),
]),
# clientside
html.Label('Mean(x, y, x+y, x+y/2) (clientside)'),
html.Div(
id='mean-of-all-values',
children=ClientsideFunction(
'clientside',
'mean',
[
ClientsideInput('x', 'value'),
ClientsideInput('y', 'value'),
ClientsideInput('x+y', 'value'),
ClientsideInput('x+y / 2', 'value'),
]
)
),
])
@app.callback(Output('x+y / 2', 'value'),
[Input('x+y', 'value')])
def divide_by_two(value):
import time; time.sleep(4)
return float(value) / 2.0
@app.callback(Output('display-all-of-the-values', 'children'),
[Input('x', 'value'),
Input('y', 'value'),
Input('x+y', 'value'),
Input('x+y / 2', 'value')])
def display_all(*args):
import time; time.sleep(4)
return '\n'.join([str(a) for a in args])
if __name__ == '__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/my_functions.js (my_functions.js could be named anything) file:

window.clientside = {
mean: function(...args) {
console.warn('mean.args: ', args);
const meanValues = R.mean(args);
console.warn('meanValues: ', meanValues);
return meanValues;
}
}

clientside-chaining

Example 4 - Adding rows & columns to a table via clientside functions

This is where clientside could shine - the simple operations between components: adding rows to tables or updating dropdowns.

importdashfromdash.dependenciesimportInput, Outputimportdash_core_componentsasdccimportdash_html_componentsashtmlimportdash_tableimportjsonfromdash_renderer.clientsideimportClientsideFunction, ClientsideInput, ClientsideStateimportpandasaspdapp=dash.Dash(
__name__,
external_scripts=['https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js']
)
app.css.config.serve_locally=Trueapp.scripts.config.serve_locally=Trueapp.layout=html.Div([
html.Label('New Column'),
dcc.Input(id='new-column-name', placeholder='name'),
html.Button('Add Column', id='add-column', n_clicks=0),
html.Button('Add Row', id='add-row', n_clicks=1),
dash_table.DataTable(
id='table',
editable=True,
columns=ClientsideFunction(
'clientside',
'tableColumns',
[ClientsideInput('add-column', 'n_clicks'),
ClientsideState('new-column-name', 'value'),
ClientsideState('table', 'columns'),
[{'id': 'column-1', 'name': 'Column 1'}]],
),
data=ClientsideFunction(
'clientside',
'tableData',
[ClientsideInput('table', 'columns'),
ClientsideInput('add-row', 'n_clicks'),
ClientsideState('table', 'data'),
[{'column-1': 9}]]
)
),
html.Div(html.B('Clientside')),
dcc.Graph(
id='graph',
figure=ClientsideFunction(
'clientside',
'graphTable',
[ClientsideInput('table', 'data')]
)
),
html.B('Server Side'),
html.Pre(id='display')
])
@app.callback(Output('display', 'children'), [Input('table', 'columns'),Input('table', 'data')])defdisplay_data(columns, data):
returnhtml.Div([
html.Div(html.B('Columns')),
html.Pre(json.dumps(columns, indent=2)),
html.Div(html.B('Data')),
html.Pre(json.dumps(data, indent=2)),
])
if__name__=='__main__':
app.run_server(debug=True, dev_tools_hot_reload=False)

with the following assets/you_name_it.js functions:

window.clientside={tableColumns: function(addColumnNClicks,newColumnName,existingColumns,defaultColumns){if(addColumnNClicks===0){returndefaultColumns;}returnR.concat(existingColumns,[{'name': newColumnName,'id': newColumnName}]);},tableData: function(columns,n_clicks,data,initial_data){if(n_clicks===0&&columns.length===1){returninitial_data;}elseif(R.isNil(data)){returninitial_data;}elseif(columns.length>R.values(data[0]).length){returndata.map(row=>{constnewCell={};newCell[columns[columns.length-1].id]=9;returnR.merge(row,newCell)});}elseif(n_clicks>data.length){constnewRow={};columns.forEach(col=>newRow[col.id]=9);returnR.concat(data,[newRow]);}},graphTable(data){return{'data': [{'z': R.map(R.values,data),'type': 'heatmap'}]}}}

clientside-heatmap

@chriddypchriddyp changed the title Dash ClientsideDash Clientside - Sponsored, Due Feb 1Mar 29, 2019
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due Feb 1Dash Clientside - Sponsored, Due March 1Mar 29, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

This was close but not quite there. Consensus discussing this with folks today is that the "functions embedded in layout" is too far away from the way traditional serverside callbacks work, even if there are some advantages in functionality. There are a few advantages to keeping the syntax closer to @app.callback:

  1. Easier story around this being a "escape hatch" - if one of your callbacks is slow, rewrite it in JS. Fundamentally, the architecture of your app won't change.
  2. Similarly, it'll be easier to always start in Python and then "optimize later"
  3. Easier to have parity with other features in the future like wildcards
  4. This doesn't prevent us from adding embedded functions in the layout later. And when we do so, we could do it for both serverside and clientside.

This would be the new syntax:

app.client_callback(
Output('head', 'children'),
[Input('df', 'data')],
ClientFunction(namespace='clientside', function_name='updateFig')
)

An update is forthcoming this weekend.

@chriddypchriddyp mentioned this pull request Mar 30, 2019
@chriddyp

Copy link
Copy Markdown
MemberAuthor

Closing in preference for #143

@chriddyp
chriddyp deleted the clientside branch March 30, 2019 17:14
@chriddypchriddyp changed the title Dash Clientside - Sponsored, Due March 1Dash Clientside TransformationsJun 7, 2022
Sign up for freeto subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@chriddyp