refactor(editor): RunData components to composition API (no-changelog) (#11545)

This commit is contained in:
Elias Meire 2024-11-07 15:29:02 +01:00 committed by GitHub
parent 28ad66cc12
commit 6e2809b490
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 2044 additions and 2070 deletions

View file

@ -1,14 +1,14 @@
<script lang="ts" setup> <script lang="ts" setup generic="Value extends string">
import RadioButton from './RadioButton.vue'; import RadioButton from './RadioButton.vue';
interface RadioOption { interface RadioOption {
label: string; label: string;
value: string; value: Value;
disabled?: boolean; disabled?: boolean;
} }
interface RadioButtonsProps { interface RadioButtonsProps {
modelValue?: string; modelValue?: Value;
options?: RadioOption[]; options?: RadioOption[];
/** @default medium */ /** @default medium */
size?: 'small' | 'medium'; size?: 'small' | 'medium';
@ -22,11 +22,11 @@ const props = withDefaults(defineProps<RadioButtonsProps>(), {
}); });
const emit = defineEmits<{ const emit = defineEmits<{
'update:modelValue': [value: string, e: MouseEvent]; 'update:modelValue': [value: Value, e: MouseEvent];
}>(); }>();
const onClick = ( const onClick = (
option: { label: string; value: string; disabled?: boolean }, option: { label: string; value: Value; disabled?: boolean },
event: MouseEvent, event: MouseEvent,
) => { ) => {
if (props.disabled || option.disabled) { if (props.disabled || option.disabled) {

View file

@ -1,11 +1,11 @@
<script lang="ts" setup> <script lang="ts" setup generic="Value extends string | number">
import { onMounted, onUnmounted, ref } from 'vue'; import { onMounted, onUnmounted, ref } from 'vue';
import type { RouteLocationRaw } from 'vue-router'; import type { RouteLocationRaw } from 'vue-router';
import N8nIcon from '../N8nIcon'; import N8nIcon from '../N8nIcon';
interface TabOptions { interface TabOptions {
value: string; value: Value;
label?: string; label?: string;
icon?: string; icon?: string;
href?: string; href?: string;
@ -15,7 +15,7 @@ interface TabOptions {
} }
interface TabsProps { interface TabsProps {
modelValue?: string; modelValue?: Value;
options?: TabOptions[]; options?: TabOptions[];
} }
@ -56,12 +56,12 @@ onUnmounted(() => {
}); });
const emit = defineEmits<{ const emit = defineEmits<{
tooltipClick: [tab: string, e: MouseEvent]; tooltipClick: [tab: Value, e: MouseEvent];
'update:modelValue': [tab: string]; 'update:modelValue': [tab: Value];
}>(); }>();
const handleTooltipClick = (tab: string, event: MouseEvent) => emit('tooltipClick', tab, event); const handleTooltipClick = (tab: Value, event: MouseEvent) => emit('tooltipClick', tab, event);
const handleTabClick = (tab: string) => emit('update:modelValue', tab); const handleTabClick = (tab: Value) => emit('update:modelValue', tab);
const scroll = (left: number) => { const scroll = (left: number) => {
const container = tabs.value; const container = tabs.value;
@ -84,7 +84,7 @@ const scrollRight = () => scroll(50);
<div ref="tabs" :class="$style.tabs"> <div ref="tabs" :class="$style.tabs">
<div <div
v-for="option in options" v-for="option in options"
:id="option.value" :id="option.value.toString()"
:key="option.value" :key="option.value"
:class="{ [$style.alignRight]: option.align === 'right' }" :class="{ [$style.alignRight]: option.align === 'right' }"
> >

View file

@ -7,6 +7,7 @@ export default {
component: N8nTree, component: N8nTree,
}; };
// @ts-expect-error Storybook incorrect slot types
export const Default: StoryFn = (args, { argTypes }) => ({ export const Default: StoryFn = (args, { argTypes }) => ({
setup: () => ({ args }), setup: () => ({ args }),
props: Object.keys(argTypes), props: Object.keys(argTypes),

View file

@ -1,19 +1,16 @@
<script lang="ts" setup> <script lang="ts" setup generic="Value extends unknown = unknown">
import { computed, useCssModule } from 'vue'; import { computed, useCssModule } from 'vue';
interface TreeProps { interface TreeProps {
value?: Record<string, unknown>; value?: Record<string, Value>;
path?: Array<string | number>; path?: Array<string | number>;
depth?: number; depth?: number;
nodeClass?: string; nodeClass?: string;
} }
defineSlots<{ defineSlots<{
[key: string]: (props: { label(props: { label: string; path: Array<string | number> }): never;
label?: string; value(props: { value: Value }): never;
path?: Array<string | number>;
value?: unknown;
}) => never;
}>(); }>();
defineOptions({ name: 'N8nTree' }); defineOptions({ name: 'N8nTree' });
@ -29,11 +26,11 @@ const classes = computed((): Record<string, boolean> => {
return { [props.nodeClass]: !!props.nodeClass, [$style.indent]: props.depth > 0 }; return { [props.nodeClass]: !!props.nodeClass, [$style.indent]: props.depth > 0 };
}); });
const isObject = (data: unknown): data is Record<string, unknown> => { const isObject = (data: unknown): data is Record<string, Value> => {
return typeof data === 'object' && data !== null; return typeof data === 'object' && data !== null;
}; };
const isSimple = (data: unknown): boolean => { const isSimple = (data: Value): boolean => {
if (data === null || data === undefined) { if (data === null || data === undefined) {
return true; return true;
} }
@ -70,16 +67,21 @@ const getPath = (key: string): Array<string | number> => {
<div v-else> <div v-else>
<slot v-if="$slots.label" name="label" :label="label" :path="getPath(label)" /> <slot v-if="$slots.label" name="label" :label="label" :path="getPath(label)" />
<span v-else>{{ label }}</span> <span v-else>{{ label }}</span>
<n8n-tree <N8nTree
v-if="isObject(value[label])"
:path="getPath(label)" :path="getPath(label)"
:depth="depth + 1" :depth="depth + 1"
:value="value[label] as Record<string, unknown>" :value="value[label]"
:node-class="nodeClass" :node-class="nodeClass"
> >
<template v-for="(_, name) in $slots" #[name]="data"> <template v-if="$slots.label" #label="data">
<slot :name="name" v-bind="data"></slot> <slot name="label" v-bind="data" />
</template> </template>
</n8n-tree>
<template v-if="$slots.value" #value="data">
<slot name="value" v-bind="data" />
</template>
</N8nTree>
</div> </div>
</div> </div>
</div> </div>

View file

@ -1129,8 +1129,8 @@ export interface IInviteResponse {
error?: string; error?: string;
} }
export interface ITab { export interface ITab<Value extends string | number = string | number> {
value: string | number; value: Value;
label?: string; label?: string;
href?: string; href?: string;
icon?: string; icon?: string;

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script setup lang="ts">
import type { INodeUi } from '@/Interface'; import { useI18n } from '@/composables/useI18n';
import { import {
CRON_NODE_TYPE, CRON_NODE_TYPE,
INTERVAL_NODE_TYPE, INTERVAL_NODE_TYPE,
@ -10,331 +10,326 @@ import { useNDVStore } from '@/stores/ndv.store';
import { useNodeTypesStore } from '@/stores/nodeTypes.store'; import { useNodeTypesStore } from '@/stores/nodeTypes.store';
import { useUIStore } from '@/stores/ui.store'; import { useUIStore } from '@/stores/ui.store';
import { useWorkflowsStore } from '@/stores/workflows.store'; import { useWorkflowsStore } from '@/stores/workflows.store';
import type { import { waitingNodeTooltip } from '@/utils/executionUtils';
IConnectedNode, import { uniqBy } from 'lodash-es';
INodeInputConfiguration, import type { INodeInputConfiguration, INodeOutputConfiguration, Workflow } from 'n8n-workflow';
INodeOutputConfiguration,
INodeTypeDescription,
Workflow,
} from 'n8n-workflow';
import { NodeConnectionType, NodeHelpers } from 'n8n-workflow'; import { NodeConnectionType, NodeHelpers } from 'n8n-workflow';
import { mapStores } from 'pinia'; import { computed, ref, watch } from 'vue';
import { defineComponent, type PropType } from 'vue';
import InputNodeSelect from './InputNodeSelect.vue'; import InputNodeSelect from './InputNodeSelect.vue';
import NodeExecuteButton from './NodeExecuteButton.vue'; import NodeExecuteButton from './NodeExecuteButton.vue';
import RunData from './RunData.vue'; import RunData from './RunData.vue';
import WireMeUp from './WireMeUp.vue'; import WireMeUp from './WireMeUp.vue';
import { waitingNodeTooltip } from '@/utils/executionUtils'; import { useTelemetry } from '@/composables/useTelemetry';
import { N8nRadioButtons, N8nTooltip, N8nText } from 'n8n-design-system';
import { storeToRefs } from 'pinia';
type MappingMode = 'debugging' | 'mapping'; type MappingMode = 'debugging' | 'mapping';
export default defineComponent({ type Props = {
name: 'InputPanel', runIndex: number;
components: { RunData, NodeExecuteButton, WireMeUp, InputNodeSelect }, workflow: Workflow;
props: { pushRef: string;
currentNodeName: { currentNodeName?: string;
type: String, canLinkRuns?: boolean;
}, linkedRuns?: boolean;
runIndex: { readOnly?: boolean;
type: Number, isProductionExecutionPreview?: boolean;
required: true, isPaneActive?: boolean;
}, };
linkedRuns: {
type: Boolean, const props = withDefaults(defineProps<Props>(), {
}, currentNodeName: '',
workflow: { canLinkRuns: false,
type: Object as PropType<Workflow>, readOnly: false,
required: true, isProductionExecutionPreview: false,
}, isPaneActive: false,
canLinkRuns: { });
type: Boolean,
}, const emit = defineEmits<{
pushRef: { itemHover: [
type: String, {
required: true, outputIndex: number;
}, itemIndex: number;
readOnly: { } | null,
type: Boolean,
},
isProductionExecutionPreview: {
type: Boolean,
default: false,
},
isPaneActive: {
type: Boolean,
default: false,
},
},
emits: [
'itemHover',
'tableMounted',
'linkRun',
'unlinkRun',
'runChange',
'search',
'changeInputNode',
'execute',
'activatePane',
],
data() {
return {
showDraggableHintWithDelay: false,
draggableHintShown: false,
inputMode: 'debugging' as MappingMode,
mappedNode: null as string | null,
inputModes: [
{ value: 'mapping', label: this.$locale.baseText('ndv.input.mapping') },
{ value: 'debugging', label: this.$locale.baseText('ndv.input.debugging') },
],
};
},
computed: {
...mapStores(useNodeTypesStore, useNDVStore, useWorkflowsStore, useUIStore),
focusedMappableInput(): string {
return this.ndvStore.focusedMappableInput;
},
isUserOnboarded(): boolean {
return this.ndvStore.isMappingOnboarded;
},
isMappingMode(): boolean {
return this.isActiveNodeConfig && this.inputMode === 'mapping';
},
showDraggableHint(): boolean {
const toIgnore = [
START_NODE_TYPE,
MANUAL_TRIGGER_NODE_TYPE,
CRON_NODE_TYPE,
INTERVAL_NODE_TYPE,
]; ];
if (!this.currentNode || toIgnore.includes(this.currentNode.type)) { tableMounted: [
{
avgRowHeight: number;
},
];
linkRun: [];
unlinkRun: [];
runChange: [runIndex: number];
search: [search: string];
changeInputNode: [nodeName: string, index: number];
execute: [];
activatePane: [];
}>();
const i18n = useI18n();
const telemetry = useTelemetry();
const showDraggableHintWithDelay = ref(false);
const draggableHintShown = ref(false);
const inputMode = ref<MappingMode>('debugging');
const mappedNode = ref<string | null>(null);
const inputModes = [
{ value: 'mapping', label: i18n.baseText('ndv.input.mapping') },
{ value: 'debugging', label: i18n.baseText('ndv.input.debugging') },
];
const nodeTypesStore = useNodeTypesStore();
const ndvStore = useNDVStore();
const workflowsStore = useWorkflowsStore();
const uiStore = useUIStore();
const {
activeNode,
focusedMappableInput,
isMappingOnboarded: isUserOnboarded,
} = storeToRefs(ndvStore);
const isMappingMode = computed(() => isActiveNodeConfig.value && inputMode.value === 'mapping');
const showDraggableHint = computed(() => {
const toIgnore = [START_NODE_TYPE, MANUAL_TRIGGER_NODE_TYPE, CRON_NODE_TYPE, INTERVAL_NODE_TYPE];
if (!currentNode.value || toIgnore.includes(currentNode.value.type)) {
return false; return false;
} }
return !!this.focusedMappableInput && !this.isUserOnboarded; return !!focusedMappableInput.value && !isUserOnboarded.value;
}, });
isActiveNodeConfig(): boolean {
let inputs = this.activeNodeType?.inputs ?? []; const isActiveNodeConfig = computed(() => {
let outputs = this.activeNodeType?.outputs ?? []; let inputs = activeNodeType.value?.inputs ?? [];
if (this.activeNode !== null && this.workflow !== null) { let outputs = activeNodeType.value?.outputs ?? [];
const node = this.workflow.getNode(this.activeNode.name);
inputs = NodeHelpers.getNodeInputs(this.workflow, node!, this.activeNodeType!); if (props.workflow && activeNode.value) {
outputs = NodeHelpers.getNodeOutputs(this.workflow, node!, this.activeNodeType!); const node = props.workflow.getNode(activeNode.value.name);
} else {
if (node && activeNodeType.value) {
inputs = NodeHelpers.getNodeInputs(props.workflow, node, activeNodeType.value);
outputs = NodeHelpers.getNodeOutputs(props.workflow, node, activeNodeType.value);
}
}
// If we can not figure out the node type we set no outputs // If we can not figure out the node type we set no outputs
if (!Array.isArray(inputs)) { if (!Array.isArray(inputs)) {
inputs = [] as NodeConnectionType[]; inputs = [];
} }
if (!Array.isArray(outputs)) { if (!Array.isArray(outputs)) {
outputs = [] as NodeConnectionType[]; outputs = [];
}
} }
if ( return (
inputs.length === 0 || inputs.length === 0 ||
(inputs.every((input) => this.filterOutConnectionType(input, NodeConnectionType.Main)) && (inputs.every((input) => filterOutConnectionType(input, NodeConnectionType.Main)) &&
outputs.find((output) => this.filterOutConnectionType(output, NodeConnectionType.Main))) outputs.find((output) => filterOutConnectionType(output, NodeConnectionType.Main)))
) { );
return true; });
}
return false; const isMappingEnabled = computed(() => {
}, if (props.readOnly) return false;
isMappingEnabled(): boolean {
if (this.readOnly) return false;
// Mapping is only enabled in mapping mode for config nodes and if node to map is selected // Mapping is only enabled in mapping mode for config nodes and if node to map is selected
if (this.isActiveNodeConfig) return this.isMappingMode && this.mappedNode !== null; if (isActiveNodeConfig.value) return isMappingMode.value && mappedNode.value !== null;
return true; return true;
}, });
isExecutingPrevious(): boolean { const isExecutingPrevious = computed(() => {
if (!this.workflowRunning) { if (!workflowRunning.value) {
return false; return false;
} }
const triggeredNode = this.workflowsStore.executedNode; const triggeredNode = workflowsStore.executedNode;
const executingNode = this.workflowsStore.executingNode; const executingNode = workflowsStore.executingNode;
if ( if (
this.activeNode && activeNode.value &&
triggeredNode === this.activeNode.name && triggeredNode === activeNode.value.name &&
!this.workflowsStore.isNodeExecuting(this.activeNode.name) !workflowsStore.isNodeExecuting(activeNode.value.name)
) { ) {
return true; return true;
} }
if (executingNode.length || triggeredNode) { if (executingNode.length || triggeredNode) {
return !!this.parentNodes.find( return !!parentNodes.value.find(
(node) => this.workflowsStore.isNodeExecuting(node.name) || node.name === triggeredNode, (node) => workflowsStore.isNodeExecuting(node.name) || node.name === triggeredNode,
); );
} }
return false; return false;
}, });
workflowRunning(): boolean { const workflowRunning = computed(() => uiStore.isActionActive.workflowRunning);
return this.uiStore.isActionActive['workflowRunning'];
},
activeNode(): INodeUi | null { const rootNode = computed(() => {
return this.ndvStore.activeNode; if (!activeNode.value) return null;
},
rootNode(): string { return props.workflow.getChildNodes(activeNode.value.name, 'ALL').at(0) ?? null;
const workflow = this.workflow; });
const rootNodes = workflow.getChildNodes(this.activeNode?.name ?? '', 'ALL');
return rootNodes[0]; const rootNodesParents = computed(() => {
}, if (!rootNode.value) return [];
rootNodesParents() { return props.workflow.getParentNodesByDepth(rootNode.value);
const workflow = this.workflow; });
const parentNodes = [...workflow.getParentNodes(this.rootNode, NodeConnectionType.Main)]
.reverse()
.map((parent): IConnectedNode => ({ name: parent, depth: 1, indicies: [] }));
return parentNodes; const currentNode = computed(() => {
}, if (isActiveNodeConfig.value) {
currentNode(): INodeUi | null {
if (this.isActiveNodeConfig) {
// if we're mapping node we want to show the output of the mapped node // if we're mapping node we want to show the output of the mapped node
if (this.mappedNode) { if (mappedNode.value) {
return this.workflowsStore.getNodeByName(this.mappedNode); return workflowsStore.getNodeByName(mappedNode.value);
} }
// in debugging mode data does get set manually and is only for debugging // in debugging mode data does get set manually and is only for debugging
// so we want to force the node to be the active node to make sure we show the correct data // so we want to force the node to be the active node to make sure we show the correct data
return this.activeNode; return activeNode.value;
} }
return this.workflowsStore.getNodeByName(this.currentNodeName ?? ''); return workflowsStore.getNodeByName(props.currentNodeName ?? '');
}, });
connectedCurrentNodeOutputs(): number[] | undefined {
const search = this.parentNodes.find(({ name }) => name === this.currentNodeName); const connectedCurrentNodeOutputs = computed(() => {
if (search) { const search = parentNodes.value.find(({ name }) => name === props.currentNodeName);
return search.indicies; return search?.indicies;
} });
return undefined; const parentNodes = computed(() => {
}, if (!activeNode.value) {
parentNodes(): IConnectedNode[] {
if (!this.activeNode) {
return []; return [];
} }
const nodes = this.workflow.getParentNodesByDepth(this.activeNode.name);
return nodes.filter( const parents = props.workflow
({ name }, i) => .getParentNodesByDepth(activeNode.value.name)
this.activeNode && .filter((parent) => parent.name !== activeNode.value?.name);
name !== this.activeNode.name && return uniqBy(parents, (parent) => parent.name);
nodes.findIndex((node) => node.name === name) === i, });
);
},
currentNodeDepth(): number {
const node = this.parentNodes.find(
(parent) => this.currentNode && parent.name === this.currentNode.name,
);
return node ? node.depth : -1;
},
activeNodeType(): INodeTypeDescription | null {
if (!this.activeNode) return null;
return this.nodeTypesStore.getNodeType(this.activeNode.type, this.activeNode.typeVersion); const currentNodeDepth = computed(() => {
}, const node = parentNodes.value.find(
isMultiInputNode(): boolean { (parent) => currentNode.value && parent.name === currentNode.value.name,
return this.activeNodeType !== null && this.activeNodeType.inputs.length > 1; );
}, return node?.depth ?? -1;
waitingMessage(): string { });
return waitingNodeTooltip();
}, const activeNodeType = computed(() => {
}, if (!activeNode.value) return null;
watch: { return nodeTypesStore.getNodeType(activeNode.value.type, activeNode.value.typeVersion);
inputMode: { });
handler(val) {
this.onRunIndexChange(-1); const waitingMessage = computed(() => waitingNodeTooltip());
if (val === 'mapping') {
this.onUnlinkRun(); watch(
this.mappedNode = this.rootNodesParents[0]?.name ?? null; inputMode,
(mode) => {
onRunIndexChange(-1);
if (mode === 'mapping') {
onUnlinkRun();
mappedNode.value = rootNodesParents.value[0]?.name ?? null;
} else { } else {
this.mappedNode = null; mappedNode.value = null;
} }
}, },
immediate: true, { immediate: true },
}, );
showDraggableHint(curr: boolean, prev: boolean) {
watch(showDraggableHint, (curr, prev) => {
if (curr && !prev) { if (curr && !prev) {
setTimeout(() => { setTimeout(() => {
if (this.draggableHintShown) { if (draggableHintShown.value) {
return; return;
} }
this.showDraggableHintWithDelay = this.showDraggableHint; showDraggableHintWithDelay.value = showDraggableHint.value;
if (this.showDraggableHintWithDelay) { if (showDraggableHintWithDelay.value) {
this.draggableHintShown = true; draggableHintShown.value = true;
this.$telemetry.track('User viewed data mapping tooltip', { telemetry.track('User viewed data mapping tooltip', {
type: 'unexecuted input pane', type: 'unexecuted input pane',
}); });
} }
}, 1000); }, 1000);
} else if (!curr) { } else if (!curr) {
this.showDraggableHintWithDelay = false; showDraggableHintWithDelay.value = false;
} }
}, });
},
methods: { function filterOutConnectionType(
filterOutConnectionType(
item: NodeConnectionType | INodeOutputConfiguration | INodeInputConfiguration, item: NodeConnectionType | INodeOutputConfiguration | INodeInputConfiguration,
type: NodeConnectionType, type: NodeConnectionType,
) { ) {
if (!item) return false; if (!item) return false;
return typeof item === 'string' ? item !== type : item.type !== type; return typeof item === 'string' ? item !== type : item.type !== type;
}, }
onInputModeChange(val: MappingMode) {
this.inputMode = val;
},
onMappedNodeSelected(val: string) {
this.mappedNode = val;
this.onRunIndexChange(0); function onInputModeChange(val: string) {
this.onUnlinkRun(); inputMode.value = val as MappingMode;
}, }
onNodeExecute() {
this.$emit('execute'); function onMappedNodeSelected(val: string) {
if (this.activeNode) { mappedNode.value = val;
this.$telemetry.track('User clicked ndv button', {
node_type: this.activeNode.type, onRunIndexChange(0);
workflow_id: this.workflowsStore.workflowId, onUnlinkRun();
push_ref: this.pushRef, }
function onNodeExecute() {
emit('execute');
if (activeNode.value) {
telemetry.track('User clicked ndv button', {
node_type: activeNode.value.type,
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
pane: 'input', pane: 'input',
type: 'executePrevious', type: 'executePrevious',
}); });
} }
}, }
onRunIndexChange(run: number) {
this.$emit('runChange', run); function onRunIndexChange(run: number) {
}, emit('runChange', run);
onLinkRun() { }
this.$emit('linkRun');
}, function onLinkRun() {
onUnlinkRun() { emit('linkRun');
this.$emit('unlinkRun'); }
},
onInputNodeChange(value: string) { function onUnlinkRun() {
const index = this.parentNodes.findIndex((node) => node.name === value) + 1; emit('unlinkRun');
this.$emit('changeInputNode', value, index); }
},
onConnectionHelpClick() { function onSearch(search: string) {
if (this.activeNode) { emit('search', search);
this.$telemetry.track('User clicked ndv link', { }
node_type: this.activeNode.type,
workflow_id: this.workflowsStore.workflowId, function onItemHover(
push_ref: this.pushRef, item: {
outputIndex: number;
itemIndex: number;
} | null,
) {
emit('itemHover', item);
}
function onTableMounted(event: { avgRowHeight: number }) {
emit('tableMounted', event);
}
function onInputNodeChange(value: string) {
const index = parentNodes.value.findIndex((node) => node.name === value) + 1;
emit('changeInputNode', value, index);
}
function onConnectionHelpClick() {
if (activeNode.value) {
telemetry.track('User clicked ndv link', {
node_type: activeNode.value.type,
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
pane: 'input', pane: 'input',
type: 'not-connected-help', type: 'not-connected-help',
}); });
} }
}, }
activatePane() {
this.$emit('activatePane'); function activatePane() {
}, emit('activatePane');
}, }
});
</script> </script>
<template> <template>
@ -358,18 +353,19 @@ export default defineComponent({
pane-type="input" pane-type="input"
data-test-id="ndv-input-panel" data-test-id="ndv-input-panel"
@activate-pane="activatePane" @activate-pane="activatePane"
@item-hover="$emit('itemHover', $event)" @item-hover="onItemHover"
@link-run="onLinkRun" @link-run="onLinkRun"
@unlink-run="onUnlinkRun" @unlink-run="onUnlinkRun"
@run-change="onRunIndexChange" @run-change="onRunIndexChange"
@table-mounted="$emit('tableMounted', $event)" @table-mounted="onTableMounted"
@search="$emit('search', $event)" @search="onSearch"
> >
<template #header> <template #header>
<div :class="$style.titleSection"> <div :class="$style.titleSection">
<span :class="$style.title">{{ $locale.baseText('ndv.input') }}</span> <span :class="$style.title">{{ $locale.baseText('ndv.input') }}</span>
<n8n-radio-buttons <N8nRadioButtons
v-if="isActiveNodeConfig && !readOnly" v-if="isActiveNodeConfig && !readOnly"
data-test-id="input-panel-mode"
:options="inputModes" :options="inputModes"
:model-value="inputMode" :model-value="inputMode"
@update:model-value="onInputModeChange" @update:model-value="onInputModeChange"
@ -405,10 +401,10 @@ export default defineComponent({
v-if="(isActiveNodeConfig && rootNode) || parentNodes.length" v-if="(isActiveNodeConfig && rootNode) || parentNodes.length"
:class="$style.noOutputData" :class="$style.noOutputData"
> >
<n8n-text tag="div" :bold="true" color="text-dark" size="large">{{ <N8nText tag="div" :bold="true" color="text-dark" size="large">{{
$locale.baseText('ndv.input.noOutputData.title') $locale.baseText('ndv.input.noOutputData.title')
}}</n8n-text> }}</N8nText>
<n8n-tooltip v-if="!readOnly" :visible="showDraggableHint && showDraggableHintWithDelay"> <N8nTooltip v-if="!readOnly" :visible="showDraggableHint && showDraggableHintWithDelay">
<template #content> <template #content>
<div <div
v-n8n-html=" v-n8n-html="
@ -422,25 +418,25 @@ export default defineComponent({
type="secondary" type="secondary"
hide-icon hide-icon
:transparent="true" :transparent="true"
:node-name="isActiveNodeConfig ? rootNode : (currentNodeName ?? '')" :node-name="(isActiveNodeConfig ? rootNode : currentNodeName) ?? ''"
:label="$locale.baseText('ndv.input.noOutputData.executePrevious')" :label="$locale.baseText('ndv.input.noOutputData.executePrevious')"
telemetry-source="inputs" telemetry-source="inputs"
data-test-id="execute-previous-node" data-test-id="execute-previous-node"
@execute="onNodeExecute" @execute="onNodeExecute"
/> />
</n8n-tooltip> </N8nTooltip>
<n8n-text v-if="!readOnly" tag="div" size="small"> <N8nText v-if="!readOnly" tag="div" size="small">
{{ $locale.baseText('ndv.input.noOutputData.hint') }} {{ $locale.baseText('ndv.input.noOutputData.hint') }}
</n8n-text> </N8nText>
</div> </div>
<div v-else :class="$style.notConnected"> <div v-else :class="$style.notConnected">
<div> <div>
<WireMeUp /> <WireMeUp />
</div> </div>
<n8n-text tag="div" :bold="true" color="text-dark" size="large">{{ <N8nText tag="div" :bold="true" color="text-dark" size="large">{{
$locale.baseText('ndv.input.notConnected.title') $locale.baseText('ndv.input.notConnected.title')
}}</n8n-text> }}</N8nText>
<n8n-text tag="div"> <N8nText tag="div">
{{ $locale.baseText('ndv.input.notConnected.message') }} {{ $locale.baseText('ndv.input.notConnected.message') }}
<a <a
href="https://docs.n8n.io/workflows/connections/" href="https://docs.n8n.io/workflows/connections/"
@ -449,29 +445,29 @@ export default defineComponent({
> >
{{ $locale.baseText('ndv.input.notConnected.learnMore') }} {{ $locale.baseText('ndv.input.notConnected.learnMore') }}
</a> </a>
</n8n-text> </N8nText>
</div> </div>
</template> </template>
<template #node-waiting> <template #node-waiting>
<n8n-text :bold="true" color="text-dark" size="large">Waiting for input</n8n-text> <N8nText :bold="true" color="text-dark" size="large">Waiting for input</N8nText>
<n8n-text v-n8n-html="waitingMessage"></n8n-text> <N8nText v-n8n-html="waitingMessage"></N8nText>
</template> </template>
<template #no-output-data> <template #no-output-data>
<n8n-text tag="div" :bold="true" color="text-dark" size="large">{{ <N8nText tag="div" :bold="true" color="text-dark" size="large">{{
$locale.baseText('ndv.input.noOutputData') $locale.baseText('ndv.input.noOutputData')
}}</n8n-text> }}</N8nText>
</template> </template>
<template #recovered-artificial-output-data> <template #recovered-artificial-output-data>
<div :class="$style.recoveredOutputData"> <div :class="$style.recoveredOutputData">
<n8n-text tag="div" :bold="true" color="text-dark" size="large">{{ <N8nText tag="div" :bold="true" color="text-dark" size="large">{{
$locale.baseText('executionDetails.executionFailed.recoveredNodeTitle') $locale.baseText('executionDetails.executionFailed.recoveredNodeTitle')
}}</n8n-text> }}</N8nText>
<n8n-text> <N8nText>
{{ $locale.baseText('executionDetails.executionFailed.recoveredNodeMessage') }} {{ $locale.baseText('executionDetails.executionFailed.recoveredNodeMessage') }}
</n8n-text> </N8nText>
</div> </div>
</template> </template>
</RunData> </RunData>

View file

@ -16,6 +16,14 @@ import { setupServer } from '@/__tests__/server';
import { defaultNodeDescriptions, mockNodes } from '@/__tests__/mocks'; import { defaultNodeDescriptions, mockNodes } from '@/__tests__/mocks';
import { cleanupAppModals, createAppModals } from '@/__tests__/utils'; import { cleanupAppModals, createAppModals } from '@/__tests__/utils';
vi.mock('vue-router', () => {
return {
useRouter: () => ({}),
useRoute: () => ({ meta: {} }),
RouterLink: vi.fn(),
};
});
async function createPiniaWithActiveNode() { async function createPiniaWithActiveNode() {
const node = mockNodes[0]; const node = mockNodes[0];
const workflow = mock<IWorkflowDb>({ const workflow = mock<IWorkflowDb>({

View file

@ -387,7 +387,7 @@ const onWorkflowActivate = () => {
}, 1000); }, 1000);
}; };
const onOutputItemHover = (e: { itemIndex: number; outputIndex: number }) => { const onOutputItemHover = (e: { itemIndex: number; outputIndex: number } | null) => {
if (e === null || !activeNode.value || !isPairedItemHoveringEnabled.value) { if (e === null || !activeNode.value || !isPairedItemHoveringEnabled.value) {
ndvStore.setHoveringItem(null); ndvStore.setHoveringItem(null);
return; return;

View file

@ -15,10 +15,11 @@ import { usePinnedData } from '@/composables/usePinnedData';
import { useTelemetry } from '@/composables/useTelemetry'; import { useTelemetry } from '@/composables/useTelemetry';
import { useI18n } from '@/composables/useI18n'; import { useI18n } from '@/composables/useI18n';
import { waitingNodeTooltip } from '@/utils/executionUtils'; import { waitingNodeTooltip } from '@/utils/executionUtils';
import { N8nRadioButtons, N8nText } from 'n8n-design-system';
// Types // Types
type RunDataRef = InstanceType<typeof RunData> | null; type RunDataRef = InstanceType<typeof RunData>;
const OUTPUT_TYPE = { const OUTPUT_TYPE = {
REGULAR: 'regular', REGULAR: 'regular',
@ -55,7 +56,7 @@ const emit = defineEmits<{
runChange: [number]; runChange: [number];
activatePane: []; activatePane: [];
tableMounted: [{ avgRowHeight: number }]; tableMounted: [{ avgRowHeight: number }];
itemHover: [{ itemIndex: number; outputIndex: number }]; itemHover: [item: { itemIndex: number; outputIndex: number } | null];
search: [string]; search: [string];
openSettings: []; openSettings: [];
}>(); }>();
@ -87,7 +88,7 @@ const outputTypes = ref([
{ label: i18n.baseText('ndv.output.outType.regular'), value: OUTPUT_TYPE.REGULAR }, { label: i18n.baseText('ndv.output.outType.regular'), value: OUTPUT_TYPE.REGULAR },
{ label: i18n.baseText('ndv.output.outType.logs'), value: OUTPUT_TYPE.LOGS }, { label: i18n.baseText('ndv.output.outType.logs'), value: OUTPUT_TYPE.LOGS },
]); ]);
const runDataRef = ref<RunDataRef>(null); const runDataRef = ref<RunDataRef>();
// Computed // Computed
@ -127,9 +128,7 @@ const isNodeRunning = computed(() => {
return workflowRunning.value && !!node.value && workflowsStore.isNodeExecuting(node.value.name); return workflowRunning.value && !!node.value && workflowsStore.isNodeExecuting(node.value.name);
}); });
const workflowRunning = computed(() => { const workflowRunning = computed(() => uiStore.isActionActive.workflowRunning);
return uiStore.isActionActive['workflowRunning'];
});
const workflowExecution = computed(() => { const workflowExecution = computed(() => {
return workflowsStore.getWorkflowExecution; return workflowsStore.getWorkflowExecution;
@ -253,8 +252,8 @@ const onRunIndexChange = (run: number) => {
emit('runChange', run); emit('runChange', run);
}; };
const onUpdateOutputMode = (outputMode: OutputType) => { const onUpdateOutputMode = (newOutputMode: OutputType) => {
if (outputMode === OUTPUT_TYPE.LOGS) { if (newOutputMode === OUTPUT_TYPE.LOGS) {
ndvEventBus.emit('setPositionByName', 'minLeft'); ndvEventBus.emit('setPositionByName', 'minLeft');
} else { } else {
ndvEventBus.emit('setPositionByName', 'initial'); ndvEventBus.emit('setPositionByName', 'initial');
@ -288,10 +287,10 @@ const activatePane = () => {
:run-index="runIndex" :run-index="runIndex"
:linked-runs="linkedRuns" :linked-runs="linkedRuns"
:can-link-runs="canLinkRuns" :can-link-runs="canLinkRuns"
:too-much-data-title="$locale.baseText('ndv.output.tooMuchData.title')" :too-much-data-title="i18n.baseText('ndv.output.tooMuchData.title')"
:no-data-in-branch-message="$locale.baseText('ndv.output.noOutputDataInBranch')" :no-data-in-branch-message="i18n.baseText('ndv.output.noOutputDataInBranch')"
:is-executing="isNodeRunning" :is-executing="isNodeRunning"
:executing-message="$locale.baseText('ndv.output.executing')" :executing-message="i18n.baseText('ndv.output.executing')"
:push-ref="pushRef" :push-ref="pushRef"
:block-u-i="blockUI" :block-u-i="blockUI"
:is-production-execution-preview="isProductionExecutionPreview" :is-production-execution-preview="isProductionExecutionPreview"
@ -310,15 +309,15 @@ const activatePane = () => {
<template #header> <template #header>
<div :class="$style.titleSection"> <div :class="$style.titleSection">
<template v-if="hasAiMetadata"> <template v-if="hasAiMetadata">
<n8n-radio-buttons <N8nRadioButtons
data-test-id="ai-output-mode-select"
v-model="outputMode" v-model="outputMode"
data-test-id="ai-output-mode-select"
:options="outputTypes" :options="outputTypes"
@update:model-value="onUpdateOutputMode" @update:model-value="onUpdateOutputMode"
/> />
</template> </template>
<span v-else :class="$style.title"> <span v-else :class="$style.title">
{{ $locale.baseText(outputPanelEditMode.enabled ? 'ndv.output.edit' : 'ndv.output') }} {{ i18n.baseText(outputPanelEditMode.enabled ? 'ndv.output.edit' : 'ndv.output') }}
</span> </span>
<RunInfo <RunInfo
v-if="hasNodeRun && !pinnedData.hasData.value && runsCount === 1" v-if="hasNodeRun && !pinnedData.hasData.value && runsCount === 1"
@ -331,42 +330,40 @@ const activatePane = () => {
</template> </template>
<template #node-not-run> <template #node-not-run>
<n8n-text v-if="workflowRunning && !isTriggerNode" data-test-id="ndv-output-waiting">{{ <N8nText v-if="workflowRunning && !isTriggerNode" data-test-id="ndv-output-waiting">{{
$locale.baseText('ndv.output.waitingToRun') i18n.baseText('ndv.output.waitingToRun')
}}</n8n-text> }}</N8nText>
<n8n-text v-if="!workflowRunning" data-test-id="ndv-output-run-node-hint"> <N8nText v-if="!workflowRunning" data-test-id="ndv-output-run-node-hint">
<template v-if="isSubNodeType"> <template v-if="isSubNodeType">
{{ $locale.baseText('ndv.output.runNodeHintSubNode') }} {{ i18n.baseText('ndv.output.runNodeHintSubNode') }}
</template> </template>
<template v-else> <template v-else>
{{ $locale.baseText('ndv.output.runNodeHint') }} {{ i18n.baseText('ndv.output.runNodeHint') }}
<span v-if="canPinData" @click="insertTestData"> <span v-if="canPinData" @click="insertTestData">
<br /> <br />
{{ $locale.baseText('generic.or') }} {{ i18n.baseText('generic.or') }}
<n8n-text tag="a" size="medium" color="primary"> <N8nText tag="a" size="medium" color="primary">
{{ $locale.baseText('ndv.output.insertTestData') }} {{ i18n.baseText('ndv.output.insertTestData') }}
</n8n-text> </N8nText>
</span> </span>
</template> </template>
</n8n-text> </N8nText>
</template> </template>
<template #node-waiting> <template #node-waiting>
<n8n-text :bold="true" color="text-dark" size="large">Waiting for input</n8n-text> <N8nText :bold="true" color="text-dark" size="large">Waiting for input</N8nText>
<n8n-text v-n8n-html="waitingNodeTooltip()"></n8n-text> <N8nText v-n8n-html="waitingNodeTooltip()"></N8nText>
</template> </template>
<template #no-output-data> <template #no-output-data>
<n8n-text :bold="true" color="text-dark" size="large">{{ <N8nText :bold="true" color="text-dark" size="large">{{
$locale.baseText('ndv.output.noOutputData.title') i18n.baseText('ndv.output.noOutputData.title')
}}</n8n-text> }}</N8nText>
<n8n-text> <N8nText>
{{ $locale.baseText('ndv.output.noOutputData.message') }} {{ i18n.baseText('ndv.output.noOutputData.message') }}
<a @click="openSettings">{{ <a @click="openSettings">{{ i18n.baseText('ndv.output.noOutputData.message.settings') }}</a>
$locale.baseText('ndv.output.noOutputData.message.settings') {{ i18n.baseText('ndv.output.noOutputData.message.settingsOption') }}
}}</a> </N8nText>
{{ $locale.baseText('ndv.output.noOutputData.message.settingsOption') }}
</n8n-text>
</template> </template>
<template v-if="outputMode === 'logs' && node" #content> <template v-if="outputMode === 'logs' && node" #content>
@ -375,12 +372,12 @@ const activatePane = () => {
<template #recovered-artificial-output-data> <template #recovered-artificial-output-data>
<div :class="$style.recoveredOutputData"> <div :class="$style.recoveredOutputData">
<n8n-text tag="div" :bold="true" color="text-dark" size="large">{{ <N8nText tag="div" :bold="true" color="text-dark" size="large">{{
$locale.baseText('executionDetails.executionFailed.recoveredNodeTitle') i18n.baseText('executionDetails.executionFailed.recoveredNodeTitle')
}}</n8n-text> }}</N8nText>
<n8n-text> <N8nText>
{{ $locale.baseText('executionDetails.executionFailed.recoveredNodeMessage') }} {{ i18n.baseText('executionDetails.executionFailed.recoveredNodeMessage') }}
</n8n-text> </N8nText>
</div> </div>
</template> </template>

View file

@ -1,16 +1,24 @@
import { waitFor } from '@testing-library/vue'; import { createTestWorkflowObject, defaultNodeDescriptions } from '@/__tests__/mocks';
import userEvent from '@testing-library/user-event';
import { createTestingPinia } from '@pinia/testing';
import { merge } from 'lodash-es';
import RunData from '@/components/RunData.vue';
import { SET_NODE_TYPE, STORES, VIEWS } from '@/constants';
import { SETTINGS_STORE_DEFAULT_STATE } from '@/__tests__/utils';
import { createComponentRenderer } from '@/__tests__/render'; import { createComponentRenderer } from '@/__tests__/render';
import { SETTINGS_STORE_DEFAULT_STATE } from '@/__tests__/utils';
import RunData from '@/components/RunData.vue';
import { SET_NODE_TYPE, STORES } from '@/constants';
import type { INodeUi, IRunDataDisplayMode, NodePanelType } from '@/Interface'; import type { INodeUi, IRunDataDisplayMode, NodePanelType } from '@/Interface';
import { useWorkflowsStore } from '@/stores/workflows.store'; import { useWorkflowsStore } from '@/stores/workflows.store';
import { setActivePinia } from 'pinia'; import { createTestingPinia } from '@pinia/testing';
import { defaultNodeTypes } from '@/__tests__/mocks'; import userEvent from '@testing-library/user-event';
import { waitFor } from '@testing-library/vue';
import type { INodeExecutionData } from 'n8n-workflow'; import type { INodeExecutionData } from 'n8n-workflow';
import { setActivePinia } from 'pinia';
import { useNodeTypesStore } from '../stores/nodeTypes.store';
vi.mock('vue-router', () => {
return {
useRouter: () => ({}),
useRoute: () => ({ meta: {} }),
RouterLink: vi.fn(),
};
});
const nodes = [ const nodes = [
{ {
@ -112,10 +120,13 @@ describe('RunData', () => {
], ],
'binary', 'binary',
); );
await waitFor(() => {
expect(getByTestId('ndv-view-binary-data')).toBeInTheDocument(); expect(getByTestId('ndv-view-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument(); expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument(); expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument();
}); });
});
it('should not render a view button for unknown content-type', async () => { it('should not render a view button for unknown content-type', async () => {
const { getByTestId, queryByTestId } = render( const { getByTestId, queryByTestId } = render(
@ -132,10 +143,13 @@ describe('RunData', () => {
], ],
'binary', 'binary',
); );
await waitFor(() => {
expect(queryByTestId('ndv-view-binary-data')).not.toBeInTheDocument(); expect(queryByTestId('ndv-view-binary-data')).not.toBeInTheDocument();
expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument(); expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument(); expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument();
}); });
});
it('should not render pin data button when there is no output data', async () => { it('should not render pin data button when there is no output data', async () => {
const { queryByTestId } = render([], 'table'); const { queryByTestId } = render([], 'table');
@ -201,10 +215,9 @@ describe('RunData', () => {
paneType: NodePanelType = 'output', paneType: NodePanelType = 'output',
) => { ) => {
const pinia = createTestingPinia({ const pinia = createTestingPinia({
stubActions: false,
initialState: { initialState: {
[STORES.SETTINGS]: { [STORES.SETTINGS]: SETTINGS_STORE_DEFAULT_STATE,
settings: merge({}, SETTINGS_STORE_DEFAULT_STATE.settings),
},
[STORES.NDV]: { [STORES.NDV]: {
output: { output: {
displayMode, displayMode,
@ -248,16 +261,17 @@ describe('RunData', () => {
}, },
}, },
}, },
[STORES.NODE_TYPES]: {
nodeTypes: defaultNodeTypes,
},
}, },
}); });
setActivePinia(pinia); setActivePinia(pinia);
const workflowsStore = useWorkflowsStore(); const workflowsStore = useWorkflowsStore();
const nodeTypesStore = useNodeTypesStore();
nodeTypesStore.setNodeTypes(defaultNodeDescriptions);
vi.mocked(workflowsStore).getNodeByName.mockReturnValue(nodes[0]); vi.mocked(workflowsStore).getNodeByName.mockReturnValue(nodes[0]);
if (pinnedData) { if (pinnedData) {
vi.mocked(workflowsStore).pinDataByNodeName.mockReturnValue(pinnedData); vi.mocked(workflowsStore).pinDataByNodeName.mockReturnValue(pinnedData);
} }
@ -267,31 +281,21 @@ describe('RunData', () => {
node: { node: {
name: 'Test Node', name: 'Test Node',
}, },
workflow: { workflow: createTestWorkflowObject({
nodes, nodes,
}, }),
},
data() {
return {
canPinData: true,
showData: true,
};
}, },
global: { global: {
stubs: { stubs: {
RunDataPinButton: { template: '<button data-test-id="ndv-pin-data"></button>' }, RunDataPinButton: { template: '<button data-test-id="ndv-pin-data"></button>' },
}, },
mocks: {
$route: {
name: VIEWS.WORKFLOW,
},
},
}, },
})({ })({
props: { props: {
node: { node: {
id: '1', id: '1',
name: 'Test Node', name: 'Test Node',
type: SET_NODE_TYPE,
position: [0, 0], position: [0, 0],
}, },
nodes: [{ name: 'Test Node', indicies: [], depth: 1 }], nodes: [{ name: 'Test Node', indicies: [], depth: 1 }],

File diff suppressed because it is too large Load diff

View file

@ -2,6 +2,7 @@
import { computed } from 'vue'; import { computed } from 'vue';
import { useI18n } from '@/composables/useI18n'; import { useI18n } from '@/composables/useI18n';
import type { usePinnedData } from '@/composables/usePinnedData'; import type { usePinnedData } from '@/composables/usePinnedData';
import { N8nIconButton, N8nLink, N8nText, N8nTooltip } from 'n8n-design-system';
const locale = useI18n(); const locale = useI18n();
@ -27,7 +28,7 @@ const visible = computed(() =>
</script> </script>
<template> <template>
<n8n-tooltip placement="bottom-end" :visible="visible"> <N8nTooltip placement="bottom-end" :visible="visible">
<template #content> <template #content>
<div v-if="props.tooltipContentsVisibility.binaryDataTooltipContent"> <div v-if="props.tooltipContentsVisibility.binaryDataTooltipContent">
{{ locale.baseText('ndv.pinData.pin.binary') }} {{ locale.baseText('ndv.pinData.pin.binary') }}
@ -37,16 +38,16 @@ const visible = computed(() =>
</div> </div>
<div v-else> <div v-else>
<strong>{{ locale.baseText('ndv.pinData.pin.title') }}</strong> <strong>{{ locale.baseText('ndv.pinData.pin.title') }}</strong>
<n8n-text size="small" tag="p"> <N8nText size="small" tag="p">
{{ locale.baseText('ndv.pinData.pin.description') }} {{ locale.baseText('ndv.pinData.pin.description') }}
<n8n-link :to="props.dataPinningDocsUrl" size="small"> <N8nLink :to="props.dataPinningDocsUrl" size="small">
{{ locale.baseText('ndv.pinData.pin.link') }} {{ locale.baseText('ndv.pinData.pin.link') }}
</n8n-link> </N8nLink>
</n8n-text> </N8nText>
</div> </div>
</template> </template>
<n8n-icon-button <N8nIconButton
:class="$style.pinDataButton" :class="$style.pinDataButton"
type="tertiary" type="tertiary"
:active="props.pinnedData.hasData.value" :active="props.pinnedData.hasData.value"
@ -55,7 +56,7 @@ const visible = computed(() =>
data-test-id="ndv-pin-data" data-test-id="ndv-pin-data"
@click="emit('togglePinData')" @click="emit('togglePinData')"
/> />
</n8n-tooltip> </N8nTooltip>
</template> </template>
<style lang="scss" module> <style lang="scss" module>

View file

@ -1,194 +1,179 @@
<script lang="ts"> <script setup lang="ts">
import { defineComponent } from 'vue';
import type { PropType } from 'vue';
import { mapStores } from 'pinia';
import type { INodeUi, ITableData, NDVState } from '@/Interface';
import { shorten } from '@/utils/typesUtils';
import { getPairedItemId } from '@/utils/pairedItemUtils';
import type { GenericValue, IDataObject, INodeExecutionData } from 'n8n-workflow';
import Draggable from './Draggable.vue';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { useNDVStore } from '@/stores/ndv.store';
import MappingPill from './MappingPill.vue';
import { getMappedExpression } from '@/utils/mappingUtils';
import { useExternalHooks } from '@/composables/useExternalHooks'; import { useExternalHooks } from '@/composables/useExternalHooks';
import type { INodeUi, IRunDataDisplayMode, ITableData } from '@/Interface';
import { useNDVStore } from '@/stores/ndv.store';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { getMappedExpression } from '@/utils/mappingUtils';
import { getPairedItemId } from '@/utils/pairedItemUtils';
import { shorten } from '@/utils/typesUtils';
import type { GenericValue, IDataObject, INodeExecutionData } from 'n8n-workflow';
import { computed, onMounted, ref, watch } from 'vue';
import Draggable from './Draggable.vue';
import MappingPill from './MappingPill.vue';
import TextWithHighlights from './TextWithHighlights.vue'; import TextWithHighlights from './TextWithHighlights.vue';
import { useI18n } from '@/composables/useI18n';
import { useTelemetry } from '@/composables/useTelemetry';
import { N8nInfoTip, N8nTooltip, N8nTree } from 'n8n-design-system';
import { storeToRefs } from 'pinia';
const MAX_COLUMNS_LIMIT = 40; const MAX_COLUMNS_LIMIT = 40;
type DraggableRef = InstanceType<typeof Draggable>; type DraggableRef = InstanceType<typeof Draggable>;
export default defineComponent({ type Props = {
name: 'RunDataTable', node: INodeUi;
components: { Draggable, MappingPill, TextWithHighlights }, inputData: INodeExecutionData[];
props: { distanceFromActive: number;
node: { pageOffset: number;
type: Object as PropType<INodeUi>, runIndex?: number;
required: true, outputIndex?: number;
}, totalRuns?: number;
inputData: { mappingEnabled?: boolean;
type: Array as PropType<INodeExecutionData[]>, hasDefaultHoverState?: boolean;
required: true, search?: string;
}, };
mappingEnabled: {
type: Boolean, const props = withDefaults(defineProps<Props>(), {
}, runIndex: 0,
distanceFromActive: { outputIndex: 0,
type: Number, totalRuns: 0,
required: true, mappingEnabled: false,
}, hasDefaultHoverState: false,
runIndex: { search: '',
type: Number, });
}, const emit = defineEmits<{
outputIndex: { activeRowChanged: [row: number | null];
type: Number, displayModeChange: [mode: IRunDataDisplayMode];
}, mounted: [data: { avgRowHeight: number }];
totalRuns: { }>();
type: Number,
}, const externalHooks = useExternalHooks();
pageOffset: { const activeColumn = ref(-1);
type: Number, const forceShowGrip = ref(false);
required: true, const draggedColumn = ref(false);
}, const draggingPath = ref<string | null>(null);
hasDefaultHoverState: { const hoveringPath = ref<string | null>(null);
type: Boolean, const activeRow = ref<number | null>(null);
}, const columnLimit = ref(MAX_COLUMNS_LIMIT);
search: { const columnLimitExceeded = ref(false);
type: String, const draggableRef = ref<DraggableRef>();
},
}, const ndvStore = useNDVStore();
setup() { const workflowsStore = useWorkflowsStore();
const externalHooks = useExternalHooks();
return { const i18n = useI18n();
externalHooks, const telemetry = useTelemetry();
};
}, const {
data() { hoveringItem,
return { focusedMappableInput,
activeColumn: -1, highlightDraggables: highlight,
forceShowGrip: false, } = storeToRefs(ndvStore);
draggedColumn: false, const pairedItemMappings = computed(() => workflowsStore.workflowExecutionPairedItemMappings);
draggingPath: null as null | string, const tableData = computed(() => convertToTable(props.inputData));
hoveringPath: null as null | string,
mappingHintVisible: false, onMounted(() => {
activeRow: null as number | null, if (tableData.value?.columns && draggableRef.value) {
columnLimit: MAX_COLUMNS_LIMIT, const tbody = draggableRef.value.$refs.wrapper as HTMLElement;
columnLimitExceeded: false,
};
},
mounted() {
if (this.tableData && this.tableData.columns && this.$refs.draggable) {
const tbody = (this.$refs.draggable as DraggableRef).$refs.wrapper as HTMLElement;
if (tbody) { if (tbody) {
this.$emit('mounted', { emit('mounted', {
avgRowHeight: tbody.offsetHeight / this.tableData.data.length, avgRowHeight: tbody.offsetHeight / tableData.value.data.length,
}); });
} }
} }
}, });
computed: {
...mapStores(useNDVStore, useWorkflowsStore), function isHoveringRow(row: number): boolean {
hoveringItem(): NDVState['hoveringItem'] { if (row === activeRow.value) {
return this.ndvStore.hoveringItem;
},
pairedItemMappings(): { [itemId: string]: Set<string> } {
return this.workflowsStore.workflowExecutionPairedItemMappings;
},
tableData(): ITableData {
return this.convertToTable(this.inputData);
},
focusedMappableInput(): string {
return this.ndvStore.focusedMappableInput;
},
highlight(): boolean {
return this.ndvStore.highlightDraggables;
},
},
methods: {
shorten,
isHoveringRow(row: number): boolean {
if (row === this.activeRow) {
return true; return true;
} }
const itemIndex = this.pageOffset + row; const itemIndex = props.pageOffset + row;
if ( if (
itemIndex === 0 && itemIndex === 0 &&
!this.hoveringItem && !hoveringItem.value &&
this.hasDefaultHoverState && props.hasDefaultHoverState &&
this.distanceFromActive === 1 props.distanceFromActive === 1
) { ) {
return true; return true;
} }
const itemNodeId = getPairedItemId( const itemNodeId = getPairedItemId(
this.node?.name ?? '', props.node?.name ?? '',
this.runIndex || 0, props.runIndex || 0,
this.outputIndex || 0, props.outputIndex || 0,
itemIndex, itemIndex,
); );
if (!this.hoveringItem || !this.pairedItemMappings[itemNodeId]) { if (!hoveringItem.value || !pairedItemMappings.value[itemNodeId]) {
return false; return false;
} }
const hoveringItemId = getPairedItemId( const hoveringItemId = getPairedItemId(
this.hoveringItem.nodeName, hoveringItem.value.nodeName,
this.hoveringItem.runIndex, hoveringItem.value.runIndex,
this.hoveringItem.outputIndex, hoveringItem.value.outputIndex,
this.hoveringItem.itemIndex, hoveringItem.value.itemIndex,
); );
return this.pairedItemMappings[itemNodeId].has(hoveringItemId); return pairedItemMappings.value[itemNodeId].has(hoveringItemId);
}, }
onMouseEnterCell(e: MouseEvent) {
function onMouseEnterCell(e: MouseEvent) {
const target = e.target; const target = e.target;
if (target && this.mappingEnabled) { if (target && props.mappingEnabled) {
const col = (target as HTMLElement).dataset.col; const col = (target as HTMLElement).dataset.col;
if (col && !isNaN(parseInt(col, 10))) { if (col && !isNaN(parseInt(col, 10))) {
this.activeColumn = parseInt(col, 10); activeColumn.value = parseInt(col, 10);
} }
} }
if (target) { if (target) {
const row = (target as HTMLElement).dataset.row; const row = (target as HTMLElement).dataset.row;
if (row && !isNaN(parseInt(row, 10))) { if (row && !isNaN(parseInt(row, 10))) {
this.activeRow = parseInt(row, 10); activeRow.value = parseInt(row, 10);
this.$emit('activeRowChanged', this.pageOffset + this.activeRow); emit('activeRowChanged', props.pageOffset + activeRow.value);
} }
} }
}, }
onMouseLeaveCell() {
this.activeColumn = -1;
this.activeRow = null;
this.$emit('activeRowChanged', null);
},
onMouseEnterKey(path: string[], colIndex: number) {
this.hoveringPath = this.getCellExpression(path, colIndex);
},
onMouseLeaveKey() {
this.hoveringPath = null;
},
isHovering(path: string[], colIndex: number) {
const expr = this.getCellExpression(path, colIndex);
return this.hoveringPath === expr; function onMouseLeaveCell() {
}, activeColumn.value = -1;
getExpression(column: string) { activeRow.value = null;
if (!this.node) { emit('activeRowChanged', null);
}
function onMouseEnterKey(path: Array<string | number>, colIndex: number) {
hoveringPath.value = getCellExpression(path, colIndex);
}
function onMouseLeaveKey() {
hoveringPath.value = null;
}
function isHovering(path: Array<string | number>, colIndex: number) {
const expr = getCellExpression(path, colIndex);
return hoveringPath.value === expr;
}
function getExpression(column: string) {
if (!props.node) {
return ''; return '';
} }
return getMappedExpression({ return getMappedExpression({
nodeName: this.node.name, nodeName: props.node.name,
distanceFromActive: this.distanceFromActive, distanceFromActive: props.distanceFromActive,
path: [column], path: [column],
}); });
}, }
getPathNameFromTarget(el?: HTMLElement) {
function getPathNameFromTarget(el?: HTMLElement) {
if (!el) { if (!el) {
return ''; return '';
} }
return el.dataset.name; return el.dataset.name;
}, }
getCellPathName(path: Array<string | number>, colIndex: number) {
function getCellPathName(path: Array<string | number>, colIndex: number) {
const lastKey = path[path.length - 1]; const lastKey = path[path.length - 1];
if (typeof lastKey === 'string') { if (typeof lastKey === 'string') {
return lastKey; return lastKey;
@ -197,21 +182,23 @@ export default defineComponent({
const prevKey = path[path.length - 2]; const prevKey = path[path.length - 2];
return `${prevKey}[${lastKey}]`; return `${prevKey}[${lastKey}]`;
} }
const column = this.tableData.columns[colIndex]; const column = tableData.value.columns[colIndex];
return `${column}[${lastKey}]`; return `${column}[${lastKey}]`;
}, }
getCellExpression(path: Array<string | number>, colIndex: number) {
if (!this.node) { function getCellExpression(path: Array<string | number>, colIndex: number) {
if (!props.node) {
return ''; return '';
} }
const column = this.tableData.columns[colIndex]; const column = tableData.value.columns[colIndex];
return getMappedExpression({ return getMappedExpression({
nodeName: this.node.name, nodeName: props.node.name,
distanceFromActive: this.distanceFromActive, distanceFromActive: props.distanceFromActive,
path: [column, ...path], path: [column, ...path],
}); });
}, }
isEmpty(value: unknown): boolean {
function isEmpty(value: unknown): boolean {
return ( return (
value === '' || value === '' ||
(Array.isArray(value) && value.length === 0) || (Array.isArray(value) && value.length === 0) ||
@ -219,19 +206,20 @@ export default defineComponent({
value === null || value === null ||
value === undefined value === undefined
); );
}, }
getValueToRender(value: unknown): string {
function getValueToRender(value: unknown): string {
if (value === '') { if (value === '') {
return this.$locale.baseText('runData.emptyString'); return i18n.baseText('runData.emptyString');
} }
if (typeof value === 'string') { if (typeof value === 'string') {
return value; return value;
} }
if (Array.isArray(value) && value.length === 0) { if (Array.isArray(value) && value.length === 0) {
return this.$locale.baseText('runData.emptyArray'); return i18n.baseText('runData.emptyArray');
} }
if (typeof value === 'object' && value !== null && Object.keys(value).length === 0) { if (typeof value === 'object' && value !== null && Object.keys(value).length === 0) {
return this.$locale.baseText('runData.emptyObject'); return i18n.baseText('runData.emptyObject');
} }
if (value === null || value === undefined) { if (value === null || value === undefined) {
return `[${value}]`; return `[${value}]`;
@ -240,39 +228,44 @@ export default defineComponent({
return value.toString(); return value.toString();
} }
return JSON.stringify(value); return JSON.stringify(value);
}, }
onDragStart() {
this.draggedColumn = true; function onDragStart() {
this.ndvStore.resetMappingTelemetry(); draggedColumn.value = true;
}, ndvStore.resetMappingTelemetry();
onCellDragStart(el: HTMLElement) { }
function onCellDragStart(el: HTMLElement) {
if (el?.dataset.value) { if (el?.dataset.value) {
this.draggingPath = el.dataset.value; draggingPath.value = el.dataset.value;
} }
this.onDragStart(); onDragStart();
}, }
onCellDragEnd(el: HTMLElement) {
this.draggingPath = null;
this.onDragEnd(el.dataset.name || '', 'tree', el.dataset.depth || '0'); function onCellDragEnd(el: HTMLElement) {
}, draggingPath.value = null;
isDraggingKey(path: Array<string | number>, colIndex: number) {
if (!this.draggingPath) { onDragEnd(el.dataset.name ?? '', 'tree', el.dataset.depth ?? '0');
}
function isDraggingKey(path: Array<string | number>, colIndex: number) {
if (!draggingPath.value) {
return; return;
} }
return this.draggingPath === this.getCellExpression(path, colIndex); return draggingPath.value === getCellExpression(path, colIndex);
}, }
onDragEnd(column: string, src: string, depth = '0') {
function onDragEnd(column: string, src: string, depth = '0') {
setTimeout(() => { setTimeout(() => {
const mappingTelemetry = this.ndvStore.mappingTelemetry; const mappingTelemetry = ndvStore.mappingTelemetry;
const telemetryPayload = { const telemetryPayload = {
src_node_type: this.node.type, src_node_type: props.node.type,
src_field_name: column, src_field_name: column,
src_nodes_back: this.distanceFromActive, src_nodes_back: props.distanceFromActive,
src_run_index: this.runIndex, src_run_index: props.runIndex,
src_runs_total: this.totalRuns, src_runs_total: props.totalRuns,
src_field_nest_level: parseInt(depth, 10), src_field_nest_level: parseInt(depth, 10),
src_view: 'table', src_view: 'table',
src_element: src, src_element: src,
@ -280,26 +273,33 @@ export default defineComponent({
...mappingTelemetry, ...mappingTelemetry,
}; };
void this.externalHooks.run('runDataTable.onDragEnd', telemetryPayload); void externalHooks.run('runDataTable.onDragEnd', telemetryPayload);
this.$telemetry.track('User dragged data for mapping', telemetryPayload, { telemetry.track('User dragged data for mapping', telemetryPayload, {
withPostHog: true, withPostHog: true,
}); });
}, 1000); // ensure dest data gets set if drop }, 1000); // ensure dest data gets set if drop
}, }
isSimple(data: unknown): boolean {
function isSimple(data: GenericValue): data is string | number | boolean | null | undefined {
return ( return (
typeof data !== 'object' || typeof data !== 'object' ||
data === null || data === null ||
(Array.isArray(data) && data.length === 0) || (Array.isArray(data) && data.length === 0) ||
(typeof data === 'object' && Object.keys(data).length === 0) (typeof data === 'object' && Object.keys(data).length === 0)
); );
}, }
hasJsonInColumn(colIndex: number): boolean {
return this.tableData.hasJson[this.tableData.columns[colIndex]]; function isObject(data: GenericValue): data is Record<string, unknown> {
}, return !isSimple(data);
convertToTable(inputData: INodeExecutionData[]): ITableData { }
const tableData: GenericValue[][] = [];
function hasJsonInColumn(colIndex: number): boolean {
return tableData.value.hasJson[tableData.value.columns[colIndex]];
}
function convertToTable(inputData: INodeExecutionData[]): ITableData {
const resultTableData: GenericValue[][] = [];
const tableColumns: string[] = []; const tableColumns: string[] = [];
let leftEntryColumns: string[], entryRows: GenericValue[]; let leftEntryColumns: string[], entryRows: GenericValue[];
// Go over all entries // Go over all entries
@ -316,7 +316,7 @@ export default defineComponent({
const entryColumns = Object.keys(entry || {}); const entryColumns = Object.keys(entry || {});
if (entryColumns.length > MAX_COLUMNS_LIMIT) { if (entryColumns.length > MAX_COLUMNS_LIMIT) {
this.columnLimitExceeded = true; columnLimitExceeded.value = true;
leftEntryColumns = entryColumns.slice(0, MAX_COLUMNS_LIMIT); leftEntryColumns = entryColumns.slice(0, MAX_COLUMNS_LIMIT);
} else { } else {
leftEntryColumns = entryColumns; leftEntryColumns = entryColumns;
@ -332,7 +332,7 @@ export default defineComponent({
hasJson[key] = hasJson[key] =
hasJson[key] || hasJson[key] ||
(typeof entry[key] === 'object' && Object.keys(entry[key] || {}).length > 0) || (typeof entry[key] === 'object' && Object.keys(entry[key] ?? {}).length > 0) ||
false; false;
} else { } else {
// Entry does not have key so add undefined // Entry does not have key so add undefined
@ -348,42 +348,40 @@ export default defineComponent({
entryRows.push(entry[key]); entryRows.push(entry[key]);
hasJson[key] = hasJson[key] =
hasJson[key] || hasJson[key] ||
(typeof entry[key] === 'object' && Object.keys(entry[key] || {}).length > 0) || (typeof entry[key] === 'object' && Object.keys(entry[key] ?? {}).length > 0) ||
false; false;
}); });
// Add the data of the entry // Add the data of the entry
tableData.push(entryRows); resultTableData.push(entryRows);
}); });
// Make sure that all entry-rows have the same length // Make sure that all entry-rows have the same length
tableData.forEach((entryRows) => { resultTableData.forEach((rows) => {
if (tableColumns.length > entryRows.length) { if (tableColumns.length > rows.length) {
// Has fewer entries so add the missing ones // Has fewer entries so add the missing ones
entryRows.push(...new Array(tableColumns.length - entryRows.length)); rows.push(...new Array(tableColumns.length - rows.length));
} }
}); });
return { return {
hasJson, hasJson,
columns: tableColumns, columns: tableColumns,
data: tableData, data: resultTableData,
}; };
}, }
switchToJsonView() {
this.$emit('displayModeChange', 'json'); function switchToJsonView() {
}, emit('displayModeChange', 'json');
}, }
watch: {
focusedMappableInput(curr: boolean) { watch(focusedMappableInput, (curr) => {
setTimeout( setTimeout(
() => { () => {
this.forceShowGrip = !!this.focusedMappableInput; forceShowGrip.value = !!focusedMappableInput.value;
}, },
curr ? 300 : 150, curr ? 300 : 150,
); );
},
},
}); });
</script> </script>
@ -408,7 +406,7 @@ export default defineComponent({
@mouseenter="onMouseEnterCell" @mouseenter="onMouseEnterCell"
@mouseleave="onMouseLeaveCell" @mouseleave="onMouseLeaveCell"
> >
<n8n-info-tip>{{ $locale.baseText('runData.emptyItemHint') }}</n8n-info-tip> <N8nInfoTip>{{ i18n.baseText('runData.emptyItemHint') }}</N8nInfoTip>
</td> </td>
<td :class="$style.tableRightMargin"></td> <td :class="$style.tableRightMargin"></td>
</tr> </tr>
@ -418,11 +416,11 @@ export default defineComponent({
<thead> <thead>
<tr> <tr>
<th v-for="(column, i) in tableData.columns || []" :key="column"> <th v-for="(column, i) in tableData.columns || []" :key="column">
<n8n-tooltip placement="bottom-start" :disabled="!mappingEnabled" :show-after="1000"> <N8nTooltip placement="bottom-start" :disabled="!mappingEnabled" :show-after="1000">
<template #content> <template #content>
<div> <div>
<img src="/static/data-mapping-gif.gif" /> <img src="/static/data-mapping-gif.gif" />
{{ $locale.baseText('dataMapping.dragColumnToFieldHint') }} {{ i18n.baseText('dataMapping.dragColumnToFieldHint') }}
</div> </div>
</template> </template>
<Draggable <Draggable
@ -455,17 +453,17 @@ export default defineComponent({
</div> </div>
</template> </template>
</Draggable> </Draggable>
</n8n-tooltip> </N8nTooltip>
</th> </th>
<th v-if="columnLimitExceeded" :class="$style.header"> <th v-if="columnLimitExceeded" :class="$style.header">
<n8n-tooltip placement="bottom-end"> <N8nTooltip placement="bottom-end">
<template #content> <template #content>
<div> <div>
<i18n-t tag="span" keypath="dataMapping.tableView.tableColumnsExceeded.tooltip"> <i18n-t tag="span" keypath="dataMapping.tableView.tableColumnsExceeded.tooltip">
<template #columnLimit>{{ columnLimit }}</template> <template #columnLimit>{{ columnLimit }}</template>
<template #link> <template #link>
<a @click="switchToJsonView">{{ <a @click="switchToJsonView">{{
$locale.baseText('dataMapping.tableView.tableColumnsExceeded.tooltip.link') i18n.baseText('dataMapping.tableView.tableColumnsExceeded.tooltip.link')
}}</a> }}</a>
</template> </template>
</i18n-t> </i18n-t>
@ -476,15 +474,15 @@ export default defineComponent({
:class="$style['warningTooltip']" :class="$style['warningTooltip']"
icon="exclamation-triangle" icon="exclamation-triangle"
></font-awesome-icon> ></font-awesome-icon>
{{ $locale.baseText('dataMapping.tableView.tableColumnsExceeded') }} {{ i18n.baseText('dataMapping.tableView.tableColumnsExceeded') }}
</span> </span>
</n8n-tooltip> </N8nTooltip>
</th> </th>
<th :class="$style.tableRightMargin"></th> <th :class="$style.tableRightMargin"></th>
</tr> </tr>
</thead> </thead>
<Draggable <Draggable
ref="draggable" ref="draggableRef"
tag="tbody" tag="tbody"
type="mapping" type="mapping"
target-data-key="mappable" target-data-key="mappable"
@ -519,7 +517,7 @@ export default defineComponent({
:search="search" :search="search"
:class="{ [$style.value]: true, [$style.empty]: isEmpty(data) }" :class="{ [$style.value]: true, [$style.empty]: isEmpty(data) }"
/> />
<n8n-tree v-else :node-class="$style.nodeClass" :value="data"> <N8nTree v-else-if="isObject(data)" :node-class="$style.nodeClass" :value="data">
<template #label="{ label, path }"> <template #label="{ label, path }">
<span <span
:class="{ :class="{
@ -534,9 +532,10 @@ export default defineComponent({
:data-depth="path.length" :data-depth="path.length"
@mouseenter="() => onMouseEnterKey(path, index2)" @mouseenter="() => onMouseEnterKey(path, index2)"
@mouseleave="onMouseLeaveKey" @mouseleave="onMouseLeaveKey"
>{{ label || $locale.baseText('runData.unnamedField') }}</span >{{ label || i18n.baseText('runData.unnamedField') }}</span
> >
</template> </template>
<template #value="{ value }"> <template #value="{ value }">
<TextWithHighlights <TextWithHighlights
:content="getValueToRender(value)" :content="getValueToRender(value)"
@ -544,7 +543,7 @@ export default defineComponent({
:class="{ [$style.nestedValue]: true, [$style.empty]: isEmpty(value) }" :class="{ [$style.nestedValue]: true, [$style.empty]: isEmpty(value) }"
/> />
</template> </template>
</n8n-tree> </N8nTree>
</td> </td>
<td v-if="columnLimitExceeded"></td> <td v-if="columnLimitExceeded"></td>
<td :class="$style.tableRightMargin"></td> <td :class="$style.tableRightMargin"></td>