Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions dash/_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def __init__(self) -> None:
"callback": [],
"index": [],
"custom_data": [],
"dev_tools": [],
}
self._js_dist = []
self._css_dist = []
Expand Down Expand Up @@ -216,6 +217,24 @@ def wrap(func: _t.Callable[[_t.Dict], _t.Any]):

return wrap

def devtool(self, namespace: str, component_type: str, props=None):
"""
Add a component to be rendered inside the dev tools.

If it's a dash component, it can be used in callbacks provided
that it has an id and the dependency is set with allow_optional=True.

`props` can be a function, in which case it will be called before
sending the component to the frontend.
"""
self._ns["dev_tools"].append(
{
"namespace": namespace,
"type": component_type,
"props": props or {},
}
)


hooks = _Hooks()

Expand Down
19 changes: 12 additions & 7 deletions dash/dash-renderer/src/APIController.react.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,22 +103,22 @@ const UnconnectedContainer = props => {

content = (
<>
{Array.isArray(layout) ? (
layout.map((c, i) =>
{Array.isArray(layout.components) ? (
layout.components.map((c, i) =>
isSimpleComponent(c) ? (
c
) : (
<DashWrapper
_dashprivate_error={error}
componentPath={[i]}
componentPath={['components', i]}
key={i}
/>
)
)
) : (
<DashWrapper
_dashprivate_error={error}
componentPath={[]}
componentPath={['components']}
/>
)}
</>
Expand Down Expand Up @@ -153,7 +153,7 @@ function storeEffect(props, events, setErrorLoading) {
}
dispatch(apiThunk('_dash-layout', 'GET', 'layoutRequest'));
} else if (layoutRequest.status === STATUS.OK) {
if (isEmpty(layout)) {
if (isEmpty(layout.components)) {
if (typeof hooks.layout_post === 'function') {
hooks.layout_post(layoutRequest.content);
}
Expand All @@ -163,7 +163,12 @@ function storeEffect(props, events, setErrorLoading) {
);
dispatch(
setPaths(
computePaths(finalLayout, [], null, events.current)
computePaths(
finalLayout,
['components'],
null,
events.current
)
)
);
dispatch(setLayout(finalLayout));
Expand Down Expand Up @@ -194,7 +199,7 @@ function storeEffect(props, events, setErrorLoading) {
!isEmpty(graphs) &&
// LayoutRequest and its computed stores
layoutRequest.status === STATUS.OK &&
!isEmpty(layout) &&
!isEmpty(layout.components) &&
// Hasn't already hydrated
appLifecycle === getAppState('STARTED')
) {
Expand Down
13 changes: 12 additions & 1 deletion dash/dash-renderer/src/actions/dependencies.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
any,
ap,
assoc,
concat,
difference,
equals,
evolve,
Expand Down Expand Up @@ -568,10 +569,20 @@ export function validateCallbacksToLayout(state_, dispatchError) {
function validateMap(map, cls, doState) {
for (const id in map) {
const idProps = map[id];
const fcb = flatten(values(idProps));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm trying to guess what fcb stands for…

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flatten callbacks?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

aahh... thanks

const optional = all(
({allow_optional}) => allow_optional,
flatten(fcb.map(cb => concat(cb.outputs, cb.inputs))).filter(
dep => dep.id === id
)
);
if (optional) {
continue;
}
const idPath = getPath(paths, id);
if (!idPath) {
if (validateIds) {
missingId(id, cls, flatten(values(idProps)));
missingId(id, cls, fcb);
}
} else {
for (const property in idProps) {
Expand Down
23 changes: 23 additions & 0 deletions dash/dash-renderer/src/components/error/menu/DebugMenu.react.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import Expand from '../icons/Expand.svg';
import {VersionInfo} from './VersionInfo.react';
import {CallbackGraphContainer} from '../CallbackGraph/CallbackGraphContainer.react';
import {FrontEndErrorContainer} from '../FrontEnd/FrontEndErrorContainer.react';
import ExternalWrapper from '../../../wrapper/ExternalWrapper';
import {useSelector} from 'react-redux';

const classes = (base, variant, variant2) =>
`${base} ${base}--${variant}` + (variant2 ? ` ${base}--${variant2}` : '');
Expand All @@ -35,6 +37,7 @@ const MenuContent = ({
toggleCallbackGraph,
config
}) => {
const ready = useSelector(state => state.appLifecycle === 'HYDRATED');
const _StatusIcon = hotReload
? connected
? CheckIcon
Expand All @@ -47,6 +50,25 @@ const MenuContent = ({
: 'unavailable'
: 'cold';

let custom = null;
if (config.dev_tools?.length && ready) {
custom = (
<>
{config.dev_tools.map((devtool, i) => (
<ExternalWrapper
component={devtool}
componentPath={['__dash_devtools', i]}
key={devtool?.props?.id ? devtool.props.id : i}
/>
))}
<div
className='dash-debug-menu__divider'
style={{marginRight: 0}}
/>
</>
);
}

return (
<div className='dash-debug-menu__content'>
<button
Expand Down Expand Up @@ -91,6 +113,7 @@ const MenuContent = ({
className='dash-debug-menu__divider'
style={{marginRight: 0}}
/>
{custom}
</div>
);
};
Expand Down
9 changes: 6 additions & 3 deletions dash/dash-renderer/src/reducers/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@ import {

import {getAction} from '../actions/constants';

const layout = (state = {}, action) => {
const layout = (state = {components: []}, action) => {
if (action.type === getAction('SET_LAYOUT')) {
if (Array.isArray(action.payload)) {
return [...action.payload];
state.components = [...action.payload];
} else {
state.components = {...action.payload};
}
return {...action.payload};

return state;
} else if (
includes(action.type, [
'UNDO_PROP_CHANGE',
Expand Down
10 changes: 10 additions & 0 deletions dash/dash.py
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,16 @@ def _config(self):

config["validation_layout"] = validation_layout

if self._dev_tools.ui:
# Add custom dev tools hooks if the ui is activated.
custom_dev_tools = []
for hook_dev_tools in self._hooks.get_hooks("dev_tools"):
props = hook_dev_tools.get("props", {})
if callable(props):
props = props()
custom_dev_tools.append({**hook_dev_tools, "props": props})
config["dev_tools"] = custom_dev_tools

return config

def serve_reload_hash(self):
Expand Down
30 changes: 30 additions & 0 deletions tests/integration/test_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def hook_cleanup():
hooks._ns["callback"] = []
hooks._ns["index"] = []
hooks._ns["custom_data"] = []
hooks._ns["dev_tools"] = []
hooks._css_dist = []
hooks._js_dist = []
hooks._finals = {}
Expand Down Expand Up @@ -210,3 +211,32 @@ def cb(_):
dash_duo.start_server(app)
dash_duo.wait_for_element("#btn").click()
dash_duo.wait_for_text_to_equal("#output", "custom-data")


def test_hook011_devtool_hook(hook_cleanup, dash_duo):
hooks.devtool(
"dash_html_components", "Button", {"children": "devtool", "id": "devtool"}
)

app = Dash()
app.layout = html.Div(["hooked", html.Div(id="output")])

@app.callback(
Output("output", "children"),
Input("devtool", "n_clicks", allow_optional=True),
prevent_initial_call=True,
)
def cb(_):
return "hooked from devtools"

dash_duo.start_server(
app,
debug=True,
use_reloader=False,
use_debugger=True,
dev_tools_hot_reload=False,
dev_tools_props_check=False,
dev_tools_disable_version_check=True,
)
dash_duo.wait_for_element("#devtool").click()
dash_duo.wait_for_text_to_equal("#output", "hooked from devtools")
Loading