Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add on_action(state, entity) to scenario_dag #938

Merged
merged 1 commit into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
303 changes: 168 additions & 135 deletions frontend/taipy/package-lock.json

Large diffs are not rendered by default.

11 changes: 8 additions & 3 deletions frontend/taipy/src/ScenarioDag.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { DisplayModel, TaskStatuses } from "./utils/types";
import { addStatusToDisplayModel, createDagreEngine, initDiagram, populateModel, relayoutDiagram } from "./utils/diagram";
import {
createRequestUpdateAction,
createSendActionNameAction,
createSendUpdateAction,
getUpdateVar,
useDispatch,
Expand All @@ -38,6 +39,8 @@ interface ScenarioDagProps {
libClassName?: string;
className?: string;
dynamicClassName?: string;
onAction?: string;
onSelect?: string;
}

const titleSx = { ml: 2, flex: 1 };
Expand Down Expand Up @@ -67,7 +70,7 @@ const getValidScenario = (scenar: DisplayModel | DisplayModel[]) =>
: undefined;

const ScenarioDag = (props: ScenarioDagProps) => {
const { showToolbar = true } = props;
const { showToolbar = true, onSelect, onAction } = props;
const [scenarioId, setScenarioId] = useState("");
const [engine] = useState(createEngine);
const [dagreEngine] = useState(createDagreEngine);
Expand Down Expand Up @@ -121,8 +124,10 @@ const ScenarioDag = (props: ScenarioDagProps) => {

const zoomToFit = useCallback(() => engine.zoomToFit(), [engine]);

const onClick = useCallback((id: string) => onAction && dispatch(createSendActionNameAction(props.id, module, onSelect, id, onAction)), [props.id, onAction, onSelect, module, dispatch]);

useEffect(() => {
const model = new TaipyDiagramModel();
const model = new TaipyDiagramModel(onClick);
initDiagram(engine);
let doLayout = false;
if (displayModel) {
Expand All @@ -135,7 +140,7 @@ const ScenarioDag = (props: ScenarioDagProps) => {
//engine.getActionEventBus().registerAction(new DeleteItemsAction({ keyCodes: [1] }));
model.setLocked(true);
doLayout && setTimeout(relayout, 500);
}, [displayModel, engine, relayout]);
}, [displayModel, engine, relayout, onClick]);

useEffect(() => {
const showVar = getUpdateVar(props.updateVars, "show");
Expand Down
4 changes: 4 additions & 0 deletions frontend/taipy/src/projectstorm/NodeWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ namespace S {
interface NodeProps {
node: TaipyNodeModel;
engine: DiagramEngine;
onAction?: string;
}

const getStatusLabel = (status?: TaskStatus) => status == TaskStatus.Running ? "Running" : status == TaskStatus.Pending ? "Pending" : undefined
Expand All @@ -110,13 +111,16 @@ const NodeWidget = ({ node, engine }: NodeProps) => {
[engine]
);

const onClick = useCallback(() => node.onClick && node.onClick(node.getID()), [node]);

return (
<S.Node
data-default-node-name={node.getOptions().name}
selected={node.isSelected()}
background={node.getOptions().color}
title={getStatusLabel(node.status)}
$status={node.status}
onClick={onClick}
>
<S.Title>
<S.TitleIcon className="icon" title={node.getType()}>
Expand Down
17 changes: 13 additions & 4 deletions frontend/taipy/src/projectstorm/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,30 @@ import { DefaultNodeModel, DefaultNodeModelOptions, DefaultPortModel, DefaultPor
import { IN_PORT_NAME, OUT_PORT_NAME } from "../utils/diagram";
import { getChildType } from "../utils/childtype";
import { DataNode, Task } from "../utils/names";
import { TaskStatus } from "../utils/types";
import { OnClick, TaskStatus } from "../utils/types";

export class TaipyDiagramModel extends DiagramModel {}
export class TaipyDiagramModel extends DiagramModel {
onClick?: OnClick;
constructor(onClick?: OnClick) {
super();
this.onClick = onClick
}
}

export interface TaipyNodeModelOptions extends DefaultNodeModelOptions {
subtype?: string;
status?: TaskStatus;
onClick?: OnClick;
}
export class TaipyNodeModel extends DefaultNodeModel {
subtype: string | undefined;
status: TaskStatus | undefined;
subtype?: string;
status?: TaskStatus;
onClick?: OnClick;
constructor(options?: TaipyNodeModelOptions) {
super(options);
this.subtype = options?.subtype;
this.status = options?.status
this.onClick = options?.onClick;
}
}

Expand Down
7 changes: 4 additions & 3 deletions frontend/taipy/src/utils/diagram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { getNodeColor } from "./config";
import { TaipyDiagramModel, TaipyNodeModel } from "../projectstorm/models";
import { TaipyNodeFactory, TaipyPortFactory } from "../projectstorm/factories";
import { nodeTypes } from "./config";
import { DisplayModel, TaskStatus, TaskStatuses } from "./types";
import { DisplayModel, OnClick, TaskStatus, TaskStatuses } from "./types";

export const createDagreEngine = () =>
new DagreEngine({
Expand Down Expand Up @@ -59,14 +59,15 @@ export const getLinkId = (link: LinkModel) =>
)}`;
export const getNodeId = (node: DefaultNodeModel) => `${node.getType()}.${node.getID()}`;

export const createNode = (nodeType: string, id: string, name: string, subtype: string, status?: TaskStatus) =>
export const createNode = (nodeType: string, id: string, name: string, subtype: string, status?: TaskStatus, onClick?: OnClick) =>
new TaipyNodeModel({
id: id,
type: nodeType,
name: name,
color: getNodeColor(nodeType),
subtype: subtype,
status: status,
onClick: onClick,
});

export const createLink = (outPort: DefaultPortModel, inPort: DefaultPortModel) =>
Expand Down Expand Up @@ -147,7 +148,7 @@ export const populateModel = (displayModel: DisplayModel, model: TaipyDiagramMod
displayModel[1] &&
Object.entries(displayModel[1]).forEach(([nodeType, n]) => {
Object.entries(n).forEach(([id, detail]) => {
const node = createNode(nodeType, id, detail.name, detail.type, detail.status);
const node = createNode(nodeType, id, detail.name, detail.type, detail.status, model.onClick);
nodeModels[nodeType] = nodeModels[nodeType] || {};
nodeModels[nodeType][id] = node;
});
Expand Down
4 changes: 4 additions & 0 deletions frontend/taipy/src/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,7 @@ export enum TaskStatus {
}

export type TaskStatuses = Record<string, TaskStatus>;

export interface OnClick {
(id: string): void;
}
2 changes: 2 additions & 0 deletions taipy/gui_core/_GuiCoreLib.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,11 @@ class _GuiCore(ElementLibrary):
"width": ElementProperty(PropertyType.string),
"height": ElementProperty(PropertyType.string),
"class_name": ElementProperty(PropertyType.dynamic_string),
"on_action": ElementProperty(PropertyType.function),
},
inner_properties={
"core_changed": ElementProperty(PropertyType.broadcast, _GuiCoreContext._CORE_CHANGED_NAME),
"on_select": ElementProperty(PropertyType.function, f"{{{__CTX_VAR_NAME}.on_dag_select}}"),
},
),
"data_node_selector": Element(
Expand Down
19 changes: 19 additions & 0 deletions taipy/gui_core/_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -939,3 +939,22 @@ def select_id(self, state: State, id: str, payload: t.Dict[str, str]):
state.assign(_GuiCoreContext._DATANODE_VIZ_DATA_ID_VAR, data_id)
elif chart_id := data.get("chart_id"):
state.assign(_GuiCoreContext._DATANODE_VIZ_DATA_CHART_ID_VAR, chart_id)

def on_dag_select(self, state: State, id: str, payload: t.Dict[str, str]):
args = payload.get("args")
if args is None or not isinstance(args, list) or len(args) < 2:
return
on_action_function = self.gui._get_user_function(args[1]) if args[1] else None
if callable(on_action_function):
try:
entity = core_get(args[0]) if is_readable(args[0]) else f"unredable({args[0]})"
self.gui._call_function_with_state(
on_action_function,
[entity],
)
except Exception as e:
if not self.gui._call_on_exception(args[1], e):
_warn(f"dag.on_action(): Exception raised in '{args[1]}()' with '{args[0]}'", e)
elif args[1]:
_warn(f"dag.on_action(): Invalid function '{args[1]}()'.")

6 changes: 6 additions & 0 deletions taipy/gui_core/viselements.json
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,12 @@
"type": "str",
"default_value": "\"100%\"",
"doc": "The maximum width, in CSS units, of the control."
},
{
"name": "on_action",
"type": "Callback",
"doc": "The name of the function that is triggered when a a node is selected.<br/><br/>All the parameters of that function are optional:\n<ul>\n<li>state (<code>State^</code>): the state instance.</li>\n<li>entity (DataNode | Task): the entity (DataNode or Task) that was selected.</li>\n</ul>",
"signature": [["state", "State"], ["entity", "Task | DataNode"]]
}
]
}
Expand Down
Loading