feat(editor): Node creator actions (#4696)

* WIP: Node Actions List UI

* WIP: Recommended Actions and preseting of fields

* WIP: Resource category

* 🎨 Moved actions categorisation to the server

* 🏷️ Add missing INodeAction type

*  Improve SSR categorisation, fix adding of mixed actions

* ♻️ Refactor CategorizedItems to composition api, style fixes

* WIP: Adding multiple nodes

* ♻️ Refactor rest of the NodeCreator component to composition API, conver globalLinkActions to composable

*  Allow actions dragging, fix search and refactor passing of actions to categorized items

* 💄 Fix node actions title

* Migrate to the pinia store, add posthog feature and various fixes

* 🐛 Fix filtering of trigger actions when not merged

* fix: N8N-5439 — Do not use simple node item when at NodeHelperPanel root

* 🐛 Design review fixes

* 🐛 Fix disabling of merged actions

* Fix trigger root filtering

*  Allow for custom node actions parser, introduce hubspot parser

* 🐛 Fix initial node params validation, fix position of second added node

* 🐛 Introduce operations category, removed canvas node names overrride, fix API actions display and prevent dragging of action nodes

*  Prevent NDV auto-open feature flag

* 🐛 Inject recommened action for trigger nodes without actions

* Refactored NodeCreatorNode to Storybook, change filtering of merged nodes for the trigger helper panel, minor fixes

* Improve rendering of app nodes and animation

* Cleanup, any only enable accordion transition on triggerhelperpanel

* Hide node creator scrollbars in Firefox

* Minor styles fixes

* Do not copy the array in rendering method

* Removed unused props

* Fix memory leak

* Fix categorisation of regular nodes with a single resource

* Implement telemetry calls for node actions

* Move categorization to FE

* Fix client side actions categorisation

* Skip custom action show

* Only load tooltip for NodeIcon if necessary

* Fix lodash startCase import

* Remove lodash.startcase

* Cleanup

* Fix node creator autofocus on "tab"

* Prevent posthog getFeatureFlag from crashing

* Debugging preview env search issues

* Remove logs

* Make sure the pre-filled params are update not overwritten

* Get rid of transition in itemiterator

* WIP: Rough version of NodeActions keyboard navigation, replace nodeCreator composable with Pinia store module

* Rewrite to add support for ActionItem to ItemIterator and make CategorizedItems accept items props

* Fix category item counter & cleanup

* Add APIHint to actions search no-result, clean up NodeCreatorNode

* Improve node actions no results message

* Remove logging, fix filtering of recommended placeholder category

* Remove unused NodeActions component and node merging feature falg

* Do not show regular nodes without actions

* Make sure to add manual trigger when adding http node via actions hint

* Fixed api hint footer line height

* Prevent pointer-events od NodeIcon img and remove "this" from template

* Address PR points

* Fix e2e specs

* Make sure canvas ia loaded

* Make sure canvas ia loaded before opening nodeCreator in e2e spec

* Fix flaky workflows tags e2e getter

* Imrpove node creator click outside UX, add manual node to regular nodes added from trigger panel

* Add manual trigger node if dragging regular from trigger panel
This commit is contained in:
OlegIvaniv
2022-12-09 10:56:36 +01:00
committed by GitHub
parent b7c1359090
commit 79fe57dad8
78 changed files with 2498 additions and 1515 deletions

View File

@@ -1,6 +1,192 @@
import { ALL_NODE_FILTER, STORES } from "@/constants";
import { INodeCreatorState } from "@/Interface";
import startCase from 'lodash.startCase';
import { defineStore } from "pinia";
import { INodePropertyCollection, INodePropertyOptions, IDataObject, INodeProperties, INodeTypeDescription, deepCopy, INodeParameters, INodeActionTypeDescription } from 'n8n-workflow';
import { STORES, MANUAL_TRIGGER_NODE_TYPE, CORE_NODES_CATEGORY, CALENDLY_TRIGGER_NODE_TYPE, TRIGGER_NODE_FILTER } from "@/constants";
import { useNodeTypesStore } from '@/stores/nodeTypes';
import { useWorkflowsStore } from './workflows';
import { CUSTOM_API_CALL_KEY, ALL_NODE_FILTER } from '@/constants';
import { INodeCreatorState, INodeFilterType, IUpdateInformation } from '@/Interface';
import { i18n } from '@/plugins/i18n';
import { externalHooks } from '@/mixins/externalHooks';
import { Telemetry } from '@/plugins/telemetry';
const PLACEHOLDER_RECOMMENDED_ACTION_KEY = 'placeholder_recommended';
const customNodeActionsParsers: {[key: string]: (matchedProperty: INodeProperties, nodeTypeDescription: INodeTypeDescription) => INodeActionTypeDescription[] | undefined} = {
['n8n-nodes-base.hubspotTrigger']: (matchedProperty, nodeTypeDescription) => {
const collection = matchedProperty?.options?.[0] as INodePropertyCollection;
return (collection?.values[0]?.options as INodePropertyOptions[])?.map((categoryItem): INodeActionTypeDescription => ({
...getNodeTypeBase(nodeTypeDescription, i18n.baseText('nodeCreator.actionsCategory.recommended')),
actionKey: categoryItem.value as string,
displayName: i18n.baseText('nodeCreator.actionsCategory.onEvent', {
interpolate: {event: startCase(categoryItem.name)},
}),
description: categoryItem.description || '',
displayOptions: matchedProperty.displayOptions,
values: { eventsUi: { eventValues: [{ name: categoryItem.value }] } },
}));
},
};
function filterSinglePlaceholderAction(actions: INodeActionTypeDescription[]) {
return actions.filter((action: INodeActionTypeDescription, _: number, arr: INodeActionTypeDescription[]) => {
const isPlaceholderTriggerAction = action.actionKey === PLACEHOLDER_RECOMMENDED_ACTION_KEY;
return !isPlaceholderTriggerAction || (isPlaceholderTriggerAction && arr.length > 1);
});
}
function getNodeTypeBase(nodeTypeDescription: INodeTypeDescription, category: string) {
return {
name: nodeTypeDescription.name,
group: ['trigger'],
codex: {
categories: [category],
subcategories: {
[nodeTypeDescription.displayName]: [category],
},
},
iconUrl: nodeTypeDescription.iconUrl,
icon: nodeTypeDescription.icon,
version: [1],
defaults: {},
inputs: [],
outputs: [],
properties: [],
};
}
function operationsCategory(nodeTypeDescription: INodeTypeDescription): INodeActionTypeDescription[] {
if (!!nodeTypeDescription.properties.find((property) => property.name === 'resource')) return [];
const matchedProperty = nodeTypeDescription.properties
.find((property) =>property.name?.toLowerCase() === 'operation');
if (!matchedProperty || !matchedProperty.options) return [];
const filteredOutItems = (matchedProperty.options as INodePropertyOptions[]).filter(
(categoryItem: INodePropertyOptions) => !['*', '', ' '].includes(categoryItem.name),
);
const items = filteredOutItems.map((item: INodePropertyOptions) => ({
...getNodeTypeBase(nodeTypeDescription, i18n.baseText('nodeCreator.actionsCategory.operations')),
actionKey: item.value as string,
displayName: item.action ?? startCase(item.name),
description: item.description ?? '',
displayOptions: matchedProperty.displayOptions,
values: {
[matchedProperty.name]: matchedProperty.type === 'multiOptions' ? [item.value] : item.value,
},
}));
// Do not return empty category
if (items.length === 0) return [];
return items;
}
function recommendedCategory(nodeTypeDescription: INodeTypeDescription): INodeActionTypeDescription[] {
const matchingKeys = ['event', 'events', 'trigger on'];
const isTrigger = nodeTypeDescription.displayName?.toLowerCase().includes('trigger');
const matchedProperty = nodeTypeDescription.properties.find((property) =>
matchingKeys.includes(property.displayName?.toLowerCase()),
);
if (!isTrigger) return [];
// Inject placeholder action if no events are available
// so user is able to add node to the canvas from the actions panel
if (!matchedProperty || !matchedProperty.options) {
return [{
...getNodeTypeBase(nodeTypeDescription, i18n.baseText('nodeCreator.actionsCategory.recommended')),
actionKey: PLACEHOLDER_RECOMMENDED_ACTION_KEY,
displayName: i18n.baseText('nodeCreator.actionsCategory.onNewEvent', {
interpolate: {event: nodeTypeDescription.displayName.replace('Trigger', '').trimEnd()},
}),
description: '',
}];
}
const filteredOutItems = (matchedProperty.options as INodePropertyOptions[]).filter(
(categoryItem: INodePropertyOptions) => !['*', '', ' '].includes(categoryItem.name),
);
const customParsedItem = customNodeActionsParsers[nodeTypeDescription.name]?.(matchedProperty, nodeTypeDescription);
const items =
customParsedItem ??
filteredOutItems.map((categoryItem: INodePropertyOptions) => ({
...getNodeTypeBase(nodeTypeDescription, i18n.baseText('nodeCreator.actionsCategory.recommended')),
actionKey: categoryItem.value as string,
displayName: i18n.baseText('nodeCreator.actionsCategory.onEvent', {
interpolate: {event: startCase(categoryItem.name)},
}),
description: categoryItem.description || '',
displayOptions: matchedProperty.displayOptions,
values: {
[matchedProperty.name]:
matchedProperty.type === 'multiOptions' ? [categoryItem.value] : categoryItem.value,
},
}));
return items;
}
function resourceCategories(nodeTypeDescription: INodeTypeDescription): INodeActionTypeDescription[] {
const transformedNodes: INodeActionTypeDescription[] = [];
const matchedProperties = nodeTypeDescription.properties.filter((property) =>property.displayName?.toLowerCase() === 'resource');
matchedProperties.forEach((property) => {
(property.options as INodePropertyOptions[] || [])
.filter((option) => option.value !== CUSTOM_API_CALL_KEY)
.forEach((resourceOption, i, options) => {
const isSingleResource = options.length === 1;
// Match operations for the resource by checking if displayOptions matches or contains the resource name
const operations = nodeTypeDescription.properties.find(
(operation) =>
operation.name === 'operation' &&
(operation.displayOptions?.show?.resource?.includes(resourceOption.value) ||
isSingleResource),
);
if (!operations?.options) return;
const items = (operations.options as INodePropertyOptions[] || []).map(
(operationOption) => {
const displayName =
operationOption.action ??
`${resourceOption.name} ${startCase(operationOption.name)}`;
// We need to manually populate displayOptions as they are not present in the node description
// if the resource has only one option
const displayOptions = isSingleResource
? { show: { resource: [(options as INodePropertyOptions[])[0]?.value] } }
: operations?.displayOptions;
return {
...getNodeTypeBase(nodeTypeDescription, resourceOption.name),
actionKey: operationOption.value as string,
description: operationOption?.description ?? '',
displayOptions,
values: {
operation:
operations?.type === 'multiOptions'
? [operationOption.value]
: operationOption.value,
},
displayName,
group: ['trigger'],
};
},
);
transformedNodes.push(...items);
});
});
return transformedNodes;
}
export const useNodeCreatorStore = defineStore(STORES.NODE_CREATOR, {
state: (): INodeCreatorState => ({
@@ -9,4 +195,112 @@ export const useNodeCreatorStore = defineStore(STORES.NODE_CREATOR, {
showScrim: false,
selectedType: ALL_NODE_FILTER,
}),
actions: {
setShowTabs(isVisible: boolean) {
this.showTabs = isVisible;
},
setShowScrim(isVisible: boolean) {
this.showScrim = isVisible;
},
setSelectedType(selectedNodeType: INodeFilterType) {
this.selectedType = selectedNodeType;
},
setFilter(search: string) {
this.itemsFilter = search;
},
setAddedNodeActionParameters (action: IUpdateInformation, telemetry?: Telemetry, track = true) {
const { $onAction: onWorkflowStoreAction } = useWorkflowsStore();
const storeWatcher = onWorkflowStoreAction(({ name, after, store: { setLastNodeParameters }, args }) => {
if (name !== 'addNode' || args[0].type !== action.key) return;
after(() => {
setLastNodeParameters(action);
if(track) this.trackActionSelected(action, telemetry);
storeWatcher();
});
});
return storeWatcher;
},
trackActionSelected (action: IUpdateInformation, telemetry?: Telemetry) {
const { $externalHooks } = new externalHooks();
const payload = {
node_type: action.key,
action: action.name,
resource: (action.value as INodeParameters).resource || '',
};
$externalHooks().run('nodeCreateList.addAction', payload);
telemetry?.trackNodesPanel('nodeCreateList.addAction', payload);
},
},
getters: {
visibleNodesWithActions(): INodeTypeDescription[] {
const nodes = deepCopy(useNodeTypesStore().visibleNodeTypes);
const nodesWithActions = nodes.map((node) => {
const isCoreNode = node.codex?.categories?.includes(CORE_NODES_CATEGORY);
// Core nodes shouldn't support actions
node.actions = [];
if(isCoreNode) return node;
node.actions.push(
...recommendedCategory(node),
...operationsCategory(node),
...resourceCategories(node),
);
return node;
});
return nodesWithActions;
},
mergedAppNodes(): INodeTypeDescription[] {
const mergedNodes = this.visibleNodesWithActions.reduce((acc: Record<string, INodeTypeDescription>, node: INodeTypeDescription) => {
const clonedNode = deepCopy(node);
const isCoreNode = node.codex?.categories?.includes(CORE_NODES_CATEGORY);
const actions = node.actions || [];
// Do not merge core nodes
const normalizedName = isCoreNode ? node.name : node.name.toLowerCase().replace('trigger', '');
const existingNode = acc[normalizedName];
if(existingNode) existingNode.actions?.push(...actions);
else acc[normalizedName] = clonedNode;
if(!isCoreNode) acc[normalizedName].displayName = node.displayName.replace('Trigger', '');
acc[normalizedName].actions = filterSinglePlaceholderAction(acc[normalizedName].actions || []);
return acc;
}, {});
return Object.values(mergedNodes);
},
getNodeTypesWithManualTrigger: () => (nodeType?: string): string[] => {
if(!nodeType) return [];
const { workflowTriggerNodes } = useWorkflowsStore();
const isTriggerAction = nodeType.toLocaleLowerCase().includes('trigger');
const workflowContainsTrigger = workflowTriggerNodes.length > 0;
const isTriggerPanel = useNodeCreatorStore().selectedType === TRIGGER_NODE_FILTER;
const nodeTypes = !isTriggerAction && !workflowContainsTrigger && isTriggerPanel
? [MANUAL_TRIGGER_NODE_TYPE, nodeType]
: [nodeType];
return nodeTypes;
},
getActionData: () => (actionItem: INodeActionTypeDescription): IUpdateInformation => {
const displayOptions = actionItem.displayOptions ;
const displayConditions = Object.keys(displayOptions?.show || {})
.reduce((acc: IDataObject, showCondition: string) => {
acc[showCondition] = displayOptions?.show?.[showCondition]?.[0];
return acc;
}, {});
return {
name: actionItem.displayName,
key: actionItem.name as string,
value: { ...actionItem.values , ...displayConditions} as INodeParameters,
};
},
},
});

View File

@@ -9,7 +9,7 @@ import Vue from "vue";
import { useCredentialsStore } from "./credentials";
import { useRootStore } from "./n8nRootStore";
import { useUsersStore } from "./users";
import { useNodeCreatorStore } from './nodeCreator';
function getNodeVersions(nodeType: INodeTypeDescription) {
return Array.isArray(nodeType.version) ? nodeType.version : [nodeType.version];
}
@@ -79,17 +79,21 @@ export const useNodeTypesStore = defineStore(STORES.NODE_TYPES, {
}
for (const version of newNodeVersions) {
// Node exists with the same name
if (acc[newNodeType.name]) {
acc[newNodeType.name][version] = newNodeType;
acc[newNodeType.name][version] = Object.assign(acc[newNodeType.name][version] ?? {}, newNodeType);
} else {
acc[newNodeType.name] = { [version]: newNodeType };
acc[newNodeType.name] = Object.assign(acc[newNodeType.name] ?? {}, { [version]: newNodeType });
}
}
return acc;
}, { ...this.nodeTypes });
Vue.set(this, 'nodeTypes', nodeTypes);
// Trigger compute of mergedAppNodes getter so it's ready when user opens the node creator
// tslint:disable-next-line: no-unused-expression
useNodeCreatorStore().mergedAppNodes;
},
removeNodeTypes(nodeTypesToRemove: INodeTypeDescription[]): void {
this.nodeTypes = nodeTypesToRemove.reduce(
@@ -97,7 +101,7 @@ export const useNodeTypesStore = defineStore(STORES.NODE_TYPES, {
this.nodeTypes,
);
},
async getNodesInformation(nodeInfos: INodeTypeNameVersion[]): Promise<void> {
async getNodesInformation(nodeInfos: INodeTypeNameVersion[], replace = true): Promise<INodeTypeDescription[]> {
const rootStore = useRootStore();
const nodesInformation = await getNodesInformation(rootStore.getRestApiContext, nodeInfos);
@@ -111,7 +115,9 @@ export const useNodeTypesStore = defineStore(STORES.NODE_TYPES, {
);
}
});
this.setNodeTypes(nodesInformation);
if(replace) this.setNodeTypes(nodesInformation);
return nodesInformation;
},
async getFullNodesProperties(nodesToBeFetched: INodeTypeNameVersion[]): Promise<void> {
const credentialsStore = useCredentialsStore();

View File

@@ -21,7 +21,7 @@ import {
IWorkflowsMap,
WorkflowsState,
} from "@/Interface";
import {defineStore} from "pinia";
import { defineStore } from "pinia";
import {
deepCopy,
IConnection,
@@ -40,7 +40,7 @@ import {
} from 'n8n-workflow';
import Vue from "vue";
import {useRootStore} from "./n8nRootStore";
import { useRootStore } from "./n8nRootStore";
import {
getActiveWorkflows,
getCurrentExecutions,
@@ -50,7 +50,7 @@ import {
} from "@/api/workflows";
import {useUIStore} from "./ui";
import {dataPinningEventBus} from "@/event-bus/data-pinning-event-bus";
import {isJsonKeyObject, getPairedItemsMapping, stringSizeInBytes} from "@/utils";
import {isJsonKeyObject, getPairedItemsMapping, stringSizeInBytes, isObjectLiteral} from "@/utils";
import {useNDVStore} from "./ndv";
import {useNodeTypesStore} from "./nodeTypes";
import {useWorkflowsEEStore} from "@/stores/workflows.ee";
@@ -720,7 +720,7 @@ export const useWorkflowsStore = defineStore(STORES.WORKFLOWS, {
Vue.set(node, updateInformation.key, updateInformation.value);
},
setNodeParameters(updateInformation: IUpdateInformation): void {
setNodeParameters(updateInformation: IUpdateInformation, append?: boolean): void {
// Find the node that should be updated
const node = this.workflow.nodes.find(node => {
return node.name === updateInformation.name;
@@ -732,7 +732,11 @@ export const useWorkflowsStore = defineStore(STORES.WORKFLOWS, {
const uiStore = useUIStore();
uiStore.stateIsDirty = true;
Vue.set(node, 'parameters', updateInformation.value);
const newParameters = !!append && isObjectLiteral(updateInformation.value)
? {...node.parameters, ...updateInformation.value }
: updateInformation.value;
Vue.set(node, 'parameters', newParameters);
if (!this.nodeMetadata[node.name]) {
Vue.set(this.nodeMetadata, node.name, {});
@@ -740,6 +744,12 @@ export const useWorkflowsStore = defineStore(STORES.WORKFLOWS, {
Vue.set(this.nodeMetadata[node.name], 'parametersLastUpdatedAt', Date.now());
},
setLastNodeParameters(updateInformation: IUpdateInformation) {
const latestNode = this.workflow.nodes.findLast((node) => node.type === updateInformation.key) as INodeUi;
if(latestNode) this.setNodeParameters({...updateInformation, name: latestNode.name}, true);
},
addNodeExecutionData(pushData: IPushDataNodeExecuteAfter): void {
if (this.workflowExecutionData === null || !this.workflowExecutionData.data) {
throw new Error('The "workflowExecutionData" is not initialized!');