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';
interface RadioOption {
label: string;
value: string;
value: Value;
disabled?: boolean;
}
interface RadioButtonsProps {
modelValue?: string;
modelValue?: Value;
options?: RadioOption[];
/** @default medium */
size?: 'small' | 'medium';
@ -22,11 +22,11 @@ const props = withDefaults(defineProps<RadioButtonsProps>(), {
});
const emit = defineEmits<{
'update:modelValue': [value: string, e: MouseEvent];
'update:modelValue': [value: Value, e: MouseEvent];
}>();
const onClick = (
option: { label: string; value: string; disabled?: boolean },
option: { label: string; value: Value; disabled?: boolean },
event: MouseEvent,
) => {
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 type { RouteLocationRaw } from 'vue-router';
import N8nIcon from '../N8nIcon';
interface TabOptions {
value: string;
value: Value;
label?: string;
icon?: string;
href?: string;
@ -15,7 +15,7 @@ interface TabOptions {
}
interface TabsProps {
modelValue?: string;
modelValue?: Value;
options?: TabOptions[];
}
@ -56,12 +56,12 @@ onUnmounted(() => {
});
const emit = defineEmits<{
tooltipClick: [tab: string, e: MouseEvent];
'update:modelValue': [tab: string];
tooltipClick: [tab: Value, e: MouseEvent];
'update:modelValue': [tab: Value];
}>();
const handleTooltipClick = (tab: string, event: MouseEvent) => emit('tooltipClick', tab, event);
const handleTabClick = (tab: string) => emit('update:modelValue', tab);
const handleTooltipClick = (tab: Value, event: MouseEvent) => emit('tooltipClick', tab, event);
const handleTabClick = (tab: Value) => emit('update:modelValue', tab);
const scroll = (left: number) => {
const container = tabs.value;
@ -84,7 +84,7 @@ const scrollRight = () => scroll(50);
<div ref="tabs" :class="$style.tabs">
<div
v-for="option in options"
:id="option.value"
:id="option.value.toString()"
:key="option.value"
:class="{ [$style.alignRight]: option.align === 'right' }"
>

View file

@ -7,6 +7,7 @@ export default {
component: N8nTree,
};
// @ts-expect-error Storybook incorrect slot types
export const Default: StoryFn = (args, { argTypes }) => ({
setup: () => ({ args }),
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';
interface TreeProps {
value?: Record<string, unknown>;
value?: Record<string, Value>;
path?: Array<string | number>;
depth?: number;
nodeClass?: string;
}
defineSlots<{
[key: string]: (props: {
label?: string;
path?: Array<string | number>;
value?: unknown;
}) => never;
label(props: { label: string; path: Array<string | number> }): never;
value(props: { value: Value }): never;
}>();
defineOptions({ name: 'N8nTree' });
@ -29,11 +26,11 @@ const classes = computed((): Record<string, boolean> => {
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;
};
const isSimple = (data: unknown): boolean => {
const isSimple = (data: Value): boolean => {
if (data === null || data === undefined) {
return true;
}
@ -70,16 +67,21 @@ const getPath = (key: string): Array<string | number> => {
<div v-else>
<slot v-if="$slots.label" name="label" :label="label" :path="getPath(label)" />
<span v-else>{{ label }}</span>
<n8n-tree
<N8nTree
v-if="isObject(value[label])"
:path="getPath(label)"
:depth="depth + 1"
:value="value[label] as Record<string, unknown>"
:value="value[label]"
:node-class="nodeClass"
>
<template v-for="(_, name) in $slots" #[name]="data">
<slot :name="name" v-bind="data"></slot>
<template v-if="$slots.label" #label="data">
<slot name="label" v-bind="data" />
</template>
</n8n-tree>
<template v-if="$slots.value" #value="data">
<slot name="value" v-bind="data" />
</template>
</N8nTree>
</div>
</div>
</div>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,16 +1,24 @@
import { waitFor } from '@testing-library/vue';
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 { createTestWorkflowObject, defaultNodeDescriptions } from '@/__tests__/mocks';
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 { useWorkflowsStore } from '@/stores/workflows.store';
import { setActivePinia } from 'pinia';
import { defaultNodeTypes } from '@/__tests__/mocks';
import { createTestingPinia } from '@pinia/testing';
import userEvent from '@testing-library/user-event';
import { waitFor } from '@testing-library/vue';
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 = [
{
@ -112,9 +120,12 @@ describe('RunData', () => {
],
'binary',
);
expect(getByTestId('ndv-view-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument();
await waitFor(() => {
expect(getByTestId('ndv-view-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument();
});
});
it('should not render a view button for unknown content-type', async () => {
@ -132,9 +143,12 @@ describe('RunData', () => {
],
'binary',
);
expect(queryByTestId('ndv-view-binary-data')).not.toBeInTheDocument();
expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument();
await waitFor(() => {
expect(queryByTestId('ndv-view-binary-data')).not.toBeInTheDocument();
expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument();
});
});
it('should not render pin data button when there is no output data', async () => {
@ -201,10 +215,9 @@ describe('RunData', () => {
paneType: NodePanelType = 'output',
) => {
const pinia = createTestingPinia({
stubActions: false,
initialState: {
[STORES.SETTINGS]: {
settings: merge({}, SETTINGS_STORE_DEFAULT_STATE.settings),
},
[STORES.SETTINGS]: SETTINGS_STORE_DEFAULT_STATE,
[STORES.NDV]: {
output: {
displayMode,
@ -248,16 +261,17 @@ describe('RunData', () => {
},
},
},
[STORES.NODE_TYPES]: {
nodeTypes: defaultNodeTypes,
},
},
});
setActivePinia(pinia);
const workflowsStore = useWorkflowsStore();
const nodeTypesStore = useNodeTypesStore();
nodeTypesStore.setNodeTypes(defaultNodeDescriptions);
vi.mocked(workflowsStore).getNodeByName.mockReturnValue(nodes[0]);
if (pinnedData) {
vi.mocked(workflowsStore).pinDataByNodeName.mockReturnValue(pinnedData);
}
@ -267,31 +281,21 @@ describe('RunData', () => {
node: {
name: 'Test Node',
},
workflow: {
workflow: createTestWorkflowObject({
nodes,
},
},
data() {
return {
canPinData: true,
showData: true,
};
}),
},
global: {
stubs: {
RunDataPinButton: { template: '<button data-test-id="ndv-pin-data"></button>' },
},
mocks: {
$route: {
name: VIEWS.WORKFLOW,
},
},
},
})({
props: {
node: {
id: '1',
name: 'Test Node',
type: SET_NODE_TYPE,
position: [0, 0],
},
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 { useI18n } from '@/composables/useI18n';
import type { usePinnedData } from '@/composables/usePinnedData';
import { N8nIconButton, N8nLink, N8nText, N8nTooltip } from 'n8n-design-system';
const locale = useI18n();
@ -27,7 +28,7 @@ const visible = computed(() =>
</script>
<template>
<n8n-tooltip placement="bottom-end" :visible="visible">
<N8nTooltip placement="bottom-end" :visible="visible">
<template #content>
<div v-if="props.tooltipContentsVisibility.binaryDataTooltipContent">
{{ locale.baseText('ndv.pinData.pin.binary') }}
@ -37,16 +38,16 @@ const visible = computed(() =>
</div>
<div v-else>
<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') }}
<n8n-link :to="props.dataPinningDocsUrl" size="small">
<N8nLink :to="props.dataPinningDocsUrl" size="small">
{{ locale.baseText('ndv.pinData.pin.link') }}
</n8n-link>
</n8n-text>
</N8nLink>
</N8nText>
</div>
</template>
<n8n-icon-button
<N8nIconButton
:class="$style.pinDataButton"
type="tertiary"
:active="props.pinnedData.hasData.value"
@ -55,7 +56,7 @@ const visible = computed(() =>
data-test-id="ndv-pin-data"
@click="emit('togglePinData')"
/>
</n8n-tooltip>
</N8nTooltip>
</template>
<style lang="scss" module>

View file

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