feat(editor): Add variables and context section to schema view (#13875)

This commit is contained in:
Elias Meire
2025-03-19 17:18:54 +01:00
committed by GitHub
parent 3f10a50b21
commit c06ce765f1
12 changed files with 1573 additions and 122 deletions

View File

@@ -3,6 +3,9 @@ import 'fake-indexeddb/auto';
import { configure } from '@testing-library/vue'; import { configure } from '@testing-library/vue';
import 'core-js/proposals/set-methods-v2'; import 'core-js/proposals/set-methods-v2';
// Avoid tests failing because of difference between local and GitHub actions timezone
process.env.TZ = 'UTC';
configure({ testIdAttribute: 'data-test-id' }); configure({ testIdAttribute: 'data-test-id' });
window.ResizeObserver = window.ResizeObserver =

View File

@@ -3,6 +3,9 @@ import { cleanupAppModals, createAppModals } from '@/__tests__/utils';
import ExpressionEditModal from '@/components/ExpressionEditModal.vue'; import ExpressionEditModal from '@/components/ExpressionEditModal.vue';
import { createTestingPinia } from '@pinia/testing'; import { createTestingPinia } from '@pinia/testing';
import { waitFor, within } from '@testing-library/vue'; import { waitFor, within } from '@testing-library/vue';
import { setActivePinia, type Pinia } from 'pinia';
import { defaultSettings } from '../__tests__/defaults';
import { useSettingsStore } from '../stores/settings.store';
vi.mock('vue-router', () => { vi.mock('vue-router', () => {
const push = vi.fn(); const push = vi.fn();
@@ -15,11 +18,21 @@ vi.mock('vue-router', () => {
}; };
}); });
vi.mock('@/composables/useWorkflowHelpers', async (importOriginal) => {
const actual: object = await importOriginal();
return { ...actual, resolveParameter: vi.fn(() => 123) };
});
const renderModal = createComponentRenderer(ExpressionEditModal); const renderModal = createComponentRenderer(ExpressionEditModal);
describe('ExpressionEditModal', () => { describe('ExpressionEditModal', () => {
let pinia: Pinia;
beforeEach(() => { beforeEach(() => {
createAppModals(); createAppModals();
pinia = createTestingPinia({ stubActions: false });
setActivePinia(pinia);
useSettingsStore().setSettings(defaultSettings);
}); });
afterEach(() => { afterEach(() => {
@@ -28,8 +41,6 @@ describe('ExpressionEditModal', () => {
}); });
it('renders correctly', async () => { it('renders correctly', async () => {
const pinia = createTestingPinia();
const { getByTestId } = renderModal({ const { getByTestId } = renderModal({
pinia, pinia,
props: { props: {
@@ -52,8 +63,6 @@ describe('ExpressionEditModal', () => {
}); });
it('is read only', async () => { it('is read only', async () => {
const pinia = createTestingPinia();
const { getByTestId } = renderModal({ const { getByTestId } = renderModal({
pinia, pinia,
props: { props: {

View File

@@ -34,6 +34,11 @@ vi.mock('@/composables/useExecutionHelpers', () => ({
}), }),
})); }));
vi.mock('@/composables/useWorkflowHelpers', async (importOriginal) => {
const actual: object = await importOriginal();
return { ...actual, resolveParameter: vi.fn(() => 123) };
});
describe('RunData', () => { describe('RunData', () => {
beforeAll(() => { beforeAll(() => {
resolveRelatedExecutionUrl.mockReturnValue('execution.url/123'); resolveRelatedExecutionUrl.mockReturnValue('execution.url/123');

View File

@@ -20,11 +20,14 @@ import {
type INodeExecutionData, type INodeExecutionData,
} from 'n8n-workflow'; } from 'n8n-workflow';
import * as nodeHelpers from '@/composables/useNodeHelpers'; import * as nodeHelpers from '@/composables/useNodeHelpers';
import * as workflowHelpers from '@/composables/useWorkflowHelpers';
import { useNDVStore } from '@/stores/ndv.store'; import { useNDVStore } from '@/stores/ndv.store';
import { fireEvent } from '@testing-library/dom'; import { fireEvent } from '@testing-library/dom';
import { useTelemetry } from '@/composables/useTelemetry'; import { useTelemetry } from '@/composables/useTelemetry';
import { useSchemaPreviewStore } from '../stores/schemaPreview.store'; import { useSchemaPreviewStore } from '../stores/schemaPreview.store';
import { usePostHog } from '../stores/posthog.store'; import { usePostHog } from '../stores/posthog.store';
import { useSettingsStore } from '../stores/settings.store';
import { defaultSettings } from '../__tests__/defaults';
const mockNode1 = createTestNode({ const mockNode1 = createTestNode({
name: 'Manual Trigger', name: 'Manual Trigger',
@@ -86,6 +89,8 @@ async function setupStore() {
const workflowsStore = useWorkflowsStore(); const workflowsStore = useWorkflowsStore();
const nodeTypesStore = useNodeTypesStore(); const nodeTypesStore = useNodeTypesStore();
const settingsStore = useSettingsStore();
settingsStore.setSettings(defaultSettings);
nodeTypesStore.setNodeTypes([ nodeTypesStore.setNodeTypes([
...defaultNodeDescriptions, ...defaultNodeDescriptions,
@@ -141,6 +146,8 @@ describe('VirtualSchema.vue', () => {
beforeEach(async () => { beforeEach(async () => {
cleanup(); cleanup();
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValue(123);
vi.setSystemTime('2025-01-01');
renderComponent = createComponentRenderer(VirtualSchema, { renderComponent = createComponentRenderer(VirtualSchema, {
global: { global: {
stubs: { stubs: {
@@ -195,7 +202,7 @@ describe('VirtualSchema.vue', () => {
const { getAllByTestId } = renderComponent(); const { getAllByTestId } = renderComponent();
await waitFor(() => { await waitFor(() => {
const headers = getAllByTestId('run-data-schema-header'); const headers = getAllByTestId('run-data-schema-header');
expect(headers.length).toBe(2); expect(headers.length).toBe(3);
expect(headers[0]).toHaveTextContent('Manual Trigger'); expect(headers[0]).toHaveTextContent('Manual Trigger');
expect(headers[0]).toHaveTextContent('2 items'); expect(headers[0]).toHaveTextContent('2 items');
expect(headers[1]).toHaveTextContent('Set2'); expect(headers[1]).toHaveTextContent('Set2');
@@ -286,16 +293,15 @@ describe('VirtualSchema.vue', () => {
}); });
it('renders disabled nodes correctly', async () => { it('renders disabled nodes correctly', async () => {
const { getByTestId } = renderComponent({ const { getAllByTestId } = renderComponent({
props: { props: {
nodes: [{ name: disabledNode.name, indicies: [], depth: 1 }], nodes: [{ name: disabledNode.name, indicies: [], depth: 1 }],
}, },
}); });
await waitFor(() => await waitFor(() => {
expect(getByTestId('run-data-schema-header')).toHaveTextContent( const headers = getAllByTestId('run-data-schema-header');
`${disabledNode.name} (Deactivated)`, expect(headers[0]).toHaveTextContent(`${disabledNode.name} (Deactivated)`);
), });
);
}); });
it('renders schema for correct output branch', async () => { it('renders schema for correct output branch', async () => {
@@ -307,16 +313,17 @@ describe('VirtualSchema.vue', () => {
], ],
1, 1,
); );
const { getByTestId } = renderComponent({ const { getAllByTestId } = renderComponent({
props: { props: {
nodes: [{ name: 'If', indicies: [1], depth: 2 }], nodes: [{ name: 'If', indicies: [1], depth: 2 }],
}, },
}); });
await waitFor(() => { await waitFor(() => {
expect(getByTestId('run-data-schema-header')).toHaveTextContent('If'); const headers = getAllByTestId('run-data-schema-header');
expect(getByTestId('run-data-schema-header')).toHaveTextContent('2 items'); expect(headers[0]).toHaveTextContent('If');
expect(getByTestId('run-data-schema-header')).toMatchSnapshot(); expect(headers[0]).toHaveTextContent('2 items');
expect(headers[0]).toMatchSnapshot();
}); });
}); });
@@ -329,7 +336,7 @@ describe('VirtualSchema.vue', () => {
], ],
0, 0,
); );
const { getByTestId } = renderComponent({ const { getAllByTestId } = renderComponent({
props: { props: {
nodes: [ nodes: [
{ {
@@ -343,9 +350,10 @@ describe('VirtualSchema.vue', () => {
}); });
await waitFor(() => { await waitFor(() => {
expect(getByTestId('run-data-schema-header')).toHaveTextContent('If'); const headers = getAllByTestId('run-data-schema-header');
expect(getByTestId('run-data-schema-header')).toHaveTextContent('2 items'); expect(headers[0]).toHaveTextContent('If');
expect(getByTestId('run-data-schema-header')).toMatchSnapshot(); expect(headers[0]).toHaveTextContent('2 items');
expect(headers[0]).toMatchSnapshot();
}); });
}); });
@@ -414,7 +422,7 @@ describe('VirtualSchema.vue', () => {
await waitFor(() => { await waitFor(() => {
const headers = getAllByTestId('run-data-schema-header'); const headers = getAllByTestId('run-data-schema-header');
expect(headers.length).toBe(2); expect(headers.length).toBe(3);
expect(headers[0]).toHaveTextContent('Input 0'); expect(headers[0]).toHaveTextContent('Input 0');
expect(headers[1]).toHaveTextContent('Inputs 0, 1, 2'); expect(headers[1]).toHaveTextContent('Inputs 0, 1, 2');
}); });
@@ -428,6 +436,7 @@ describe('VirtualSchema.vue', () => {
fireEvent(window, new MouseEvent('mousemove', { bubbles: true })); fireEvent(window, new MouseEvent('mousemove', { bubbles: true }));
expect(reset).toHaveBeenCalled(); expect(reset).toHaveBeenCalled();
vi.useRealTimers();
vi.useFakeTimers({ toFake: ['setTimeout'] }); vi.useFakeTimers({ toFake: ['setTimeout'] });
fireEvent(window, new MouseEvent('mouseup', { bubbles: true })); fireEvent(window, new MouseEvent('mouseup', { bubbles: true }));
vi.advanceTimersByTime(250); vi.advanceTimersByTime(250);
@@ -538,18 +547,22 @@ describe('VirtualSchema.vue', () => {
}); });
const { getAllByTestId, queryAllByTestId, rerender } = renderComponent(); const { getAllByTestId, queryAllByTestId, rerender } = renderComponent();
let headers: HTMLElement[] = [];
await waitFor(async () => { await waitFor(async () => {
const headers = getAllByTestId('run-data-schema-header'); headers = getAllByTestId('run-data-schema-header');
expect(headers.length).toBe(2); expect(headers.length).toBe(3);
expect(getAllByTestId('run-data-schema-item').length).toBe(2);
// Collapse all nodes
await Promise.all(headers.map(async ($header) => await userEvent.click($header)));
expect(queryAllByTestId('run-data-schema-item').length).toBe(0);
await rerender({ search: 'John' });
expect(getAllByTestId('run-data-schema-item').length).toBe(2); expect(getAllByTestId('run-data-schema-item').length).toBe(2);
}); });
// Collapse all nodes (Variables & context is collapsed by default)
await Promise.all(headers.slice(0, -1).map(async (header) => await userEvent.click(header)));
expect(queryAllByTestId('run-data-schema-item').length).toBe(0);
await rerender({ search: 'John' });
expect(getAllByTestId('run-data-schema-item').length).toBe(13);
}); });
it('renders preview schema when enabled and available', async () => { it('renders preview schema when enabled and available', async () => {
@@ -583,11 +596,47 @@ describe('VirtualSchema.vue', () => {
const { getAllByTestId, queryAllByText, container } = renderComponent({}); const { getAllByTestId, queryAllByText, container } = renderComponent({});
await waitFor(() => { await waitFor(() => {
expect(getAllByTestId('run-data-schema-header')).toHaveLength(2); expect(getAllByTestId('run-data-schema-header')).toHaveLength(3);
}); });
expect(queryAllByText("No fields - item(s) exist, but they're empty")).toHaveLength(0); expect(queryAllByText("No fields - item(s) exist, but they're empty")).toHaveLength(0);
expect(getAllByTestId('schema-preview-warning')).toHaveLength(2); expect(getAllByTestId('schema-preview-warning')).toHaveLength(2);
expect(container).toMatchSnapshot(); expect(container).toMatchSnapshot();
}); });
it('renders variables and context section', async () => {
useWorkflowsStore().pinData({
node: mockNode1,
data: [],
});
const { getAllByTestId, container } = renderComponent({
props: {
nodes: [{ name: mockNode1.name, indicies: [], depth: 1 }],
},
});
let headers: HTMLElement[] = [];
await waitFor(() => {
headers = getAllByTestId('run-data-schema-header');
expect(headers).toHaveLength(2);
expect(headers[1]).toHaveTextContent('Variables and context');
});
await userEvent.click(headers[1]);
await waitFor(() => {
const items = getAllByTestId('run-data-schema-item');
expect(items).toHaveLength(11);
expect(items[0]).toHaveTextContent('$now');
expect(items[1]).toHaveTextContent('$today');
expect(items[2]).toHaveTextContent('$vars');
expect(items[3]).toHaveTextContent('$execution');
expect(items[7]).toHaveTextContent('$workflow');
});
expect(container).toMatchSnapshot();
});
}); });

View File

@@ -1,38 +1,53 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed, watch, ref } from 'vue';
import type { INodeUi } from '@/Interface'; import type { INodeUi } from '@/Interface';
import VirtualSchemaItem from '@/components/VirtualSchemaItem.vue';
import VirtualSchemaHeader from '@/components/VirtualSchemaHeader.vue';
import { N8nText } from '@n8n/design-system';
import Draggable from '@/components/Draggable.vue'; import Draggable from '@/components/Draggable.vue';
import { useNDVStore } from '@/stores/ndv.store'; import VirtualSchemaHeader from '@/components/VirtualSchemaHeader.vue';
import VirtualSchemaItem from '@/components/VirtualSchemaItem.vue';
import {
useDataSchema,
useFlattenSchema,
type RenderHeader,
type RenderNotice,
type Renders,
type SchemaNode,
} from '@/composables/useDataSchema';
import { useExternalHooks } from '@/composables/useExternalHooks';
import { useI18n } from '@/composables/useI18n';
import { useNodeHelpers } from '@/composables/useNodeHelpers';
import { useTelemetry } from '@/composables/useTelemetry'; import { useTelemetry } from '@/composables/useTelemetry';
import { useNDVStore } from '@/stores/ndv.store';
import { useNodeTypesStore } from '@/stores/nodeTypes.store';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { executionDataToJson } from '@/utils/nodeTypesUtils';
import { N8nText } from '@n8n/design-system';
import { import {
createResultError, createResultError,
NodeConnectionType, NodeConnectionType,
type IConnectedNode, type IConnectedNode,
type IDataObject, type IDataObject,
} from 'n8n-workflow'; } from 'n8n-workflow';
import { useExternalHooks } from '@/composables/useExternalHooks'; import { computed, ref, watch } from 'vue';
import { useI18n } from '@/composables/useI18n';
import MappingPill from './MappingPill.vue';
import { useDataSchema, useFlattenSchema, type SchemaNode } from '@/composables/useDataSchema';
import { useNodeTypesStore } from '@/stores/nodeTypes.store';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { executionDataToJson } from '@/utils/nodeTypesUtils';
import { useNodeHelpers } from '@/composables/useNodeHelpers';
import { import {
DynamicScroller, DynamicScroller,
DynamicScrollerItem, DynamicScrollerItem,
type RecycleScrollerInstance, type RecycleScrollerInstance,
} from 'vue-virtual-scroller'; } from 'vue-virtual-scroller';
import MappingPill from './MappingPill.vue';
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'; import {
import { useSchemaPreviewStore } from '@/stores/schemaPreview.store'; EnterpriseEditionFeature,
import { asyncComputed } from '@vueuse/core'; PLACEHOLDER_FILLED_AT_EXECUTION_TIME,
SCHEMA_PREVIEW_EXPERIMENT,
} from '@/constants';
import useEnvironmentsStore from '@/stores/environments.ee.store';
import { usePostHog } from '@/stores/posthog.store'; import { usePostHog } from '@/stores/posthog.store';
import { SCHEMA_PREVIEW_EXPERIMENT } from '@/constants'; import { useSchemaPreviewStore } from '@/stores/schemaPreview.store';
import { useSettingsStore } from '@/stores/settings.store';
import { isEmpty } from '@/utils/typesUtils'; import { isEmpty } from '@/utils/typesUtils';
import { asyncComputed } from '@vueuse/core';
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css';
import { pick } from 'lodash-es';
import { DateTime } from 'luxon';
type Props = { type Props = {
nodes?: IConnectedNode[]; nodes?: IConnectedNode[];
@@ -66,8 +81,11 @@ const ndvStore = useNDVStore();
const nodeTypesStore = useNodeTypesStore(); const nodeTypesStore = useNodeTypesStore();
const workflowsStore = useWorkflowsStore(); const workflowsStore = useWorkflowsStore();
const schemaPreviewStore = useSchemaPreviewStore(); const schemaPreviewStore = useSchemaPreviewStore();
const environmentsStore = useEnvironmentsStore();
const settingsStore = useSettingsStore();
const posthogStore = usePostHog(); const posthogStore = usePostHog();
const { getSchemaForExecutionData, getSchemaForJsonSchema, filterSchema } = useDataSchema(); const { getSchemaForExecutionData, getSchemaForJsonSchema, getSchema, filterSchema } =
useDataSchema();
const { closedNodes, flattenSchema, flattenMultipleSchemas, toggleLeaf, toggleNode } = const { closedNodes, flattenSchema, flattenMultipleSchemas, toggleLeaf, toggleNode } =
useFlattenSchema(); useFlattenSchema();
const { getNodeInputData } = useNodeHelpers(); const { getNodeInputData } = useNodeHelpers();
@@ -83,14 +101,6 @@ const toggleNodeAndScrollTop = (id: string) => {
scroller.value?.scrollToItem(0); scroller.value?.scrollToItem(0);
}; };
watch(
() => props.search,
(newSearch) => {
if (!newSearch) return;
closedNodes.value.clear();
},
);
const getNodeSchema = async (fullNode: INodeUi, connectedNode: IConnectedNode) => { const getNodeSchema = async (fullNode: INodeUi, connectedNode: IConnectedNode) => {
const pinData = workflowsStore.pinDataByNodeName(connectedNode.name); const pinData = workflowsStore.pinDataByNodeName(connectedNode.name);
const connectedOutputIndexes = connectedNode.indicies.length > 0 ? connectedNode.indicies : [0]; const connectedOutputIndexes = connectedNode.indicies.length > 0 ? connectedNode.indicies : [0];
@@ -133,6 +143,74 @@ const isSchemaPreviewEnabled = computed(() =>
posthogStore.isVariantEnabled(SCHEMA_PREVIEW_EXPERIMENT.name, SCHEMA_PREVIEW_EXPERIMENT.variant), posthogStore.isVariantEnabled(SCHEMA_PREVIEW_EXPERIMENT.name, SCHEMA_PREVIEW_EXPERIMENT.variant),
); );
const isVariablesEnabled = computed(
() => settingsStore.isEnterpriseFeatureEnabled[EnterpriseEditionFeature.Variables],
);
const contextSchema = computed(() => {
const $vars = environmentsStore.variablesAsObject;
const schemaSource: Record<string, unknown> = {
$now: DateTime.now().toISO(),
$today: DateTime.now().set({ hour: 0, minute: 0, second: 0, millisecond: 0 }).toISO(),
$vars,
$execution: {
id: PLACEHOLDER_FILLED_AT_EXECUTION_TIME,
mode: 'test',
resumeUrl: i18n.baseText('dataMapping.schemaView.execution.resumeUrl'),
},
$workflow: pick(workflowsStore.workflow, ['id', 'name', 'active']),
};
return getSchema(schemaSource);
});
const contextItems = computed(() => {
const header: RenderHeader = {
id: 'variables',
type: 'header',
title: i18n.baseText('dataMapping.schemaView.variablesContextTitle'),
collapsable: true,
itemCount: null,
};
if (closedNodes.value.has(header.id)) return [header];
const fields: Renders[] = flattenSchema({
schema: contextSchema.value,
depth: 1,
}).flatMap((renderItem) => {
const isVars =
renderItem.type === 'item' && renderItem.depth === 1 && renderItem.title === '$vars';
if (isVars) {
const isVarsOpen = !closedNodes.value.has(renderItem.id);
if (!isVariablesEnabled.value) {
renderItem.collapsable = false;
renderItem.locked = true;
renderItem.lockedTooltip = i18n.baseText('dataMapping.schemaView.variablesUpgrade');
return renderItem;
}
if (isVarsOpen && environmentsStore.variables.length === 0) {
const variablesEmptyNotice: RenderNotice = {
type: 'notice',
id: 'notice-variablesEmpty',
level: renderItem.level ?? 0,
message: i18n.baseText('dataMapping.schemaView.variablesEmpty'),
};
return [renderItem, variablesEmptyNotice];
}
}
return renderItem;
});
return [header as Renders].concat(fields);
});
const nodeSchema = asyncComputed(async () => { const nodeSchema = asyncComputed(async () => {
const search = props.search; const search = props.search;
if (props.data.length === 0 && isSchemaPreviewEnabled.value) { if (props.data.length === 0 && isSchemaPreviewEnabled.value) {
@@ -231,13 +309,34 @@ const items = computed(() => {
return flattenNodeSchema.value; return flattenNodeSchema.value;
} }
return flattenedNodes.value; return flattenedNodes.value.concat(contextItems.value);
}); });
const noSearchResults = computed(() => { const noSearchResults = computed(() => {
return Boolean(props.search.trim()) && !Boolean(items.value.length); return Boolean(props.search.trim()) && !Boolean(items.value.length);
}); });
watch(
() => props.search,
(newSearch) => {
if (!newSearch) return;
closedNodes.value.clear();
},
);
// Variables & context items should be collapsed by default
watch(
contextItems,
(currentContextItems) => {
currentContextItems
.filter((item) => item.type === 'header')
.forEach((item) => {
closedNodes.value.add(item.id);
});
},
{ once: true, immediate: true },
);
const onDragStart = () => { const onDragStart = () => {
ndvStore.resetMappingTelemetry(); ndvStore.resetMappingTelemetry();
}; };
@@ -332,6 +431,13 @@ const onDragEnd = (el: HTMLElement) => {
<N8nTooltip v-else-if="item.type === 'icon'" :content="item.tooltip" placement="top"> <N8nTooltip v-else-if="item.type === 'icon'" :content="item.tooltip" placement="top">
<N8nIcon :size="14" :icon="item.icon" class="icon" /> <N8nIcon :size="14" :icon="item.icon" class="icon" />
</N8nTooltip> </N8nTooltip>
<div
v-else-if="item.type === 'notice'"
v-n8n-html="item.message"
class="notice"
:style="{ marginLeft: `calc(var(--spacing-l) + var(--spacing-l) * ${item.level})` }"
/>
</DynamicScrollerItem> </DynamicScrollerItem>
</template> </template>
</DynamicScroller> </DynamicScroller>
@@ -370,4 +476,11 @@ const onDragEnd = (el: HTMLElement) => {
color: var(--color-text-light); color: var(--color-text-light);
margin-bottom: var(--spacing-s); margin-bottom: var(--spacing-s);
} }
.notice {
padding-bottom: var(--spacing-xs);
color: var(--color-text-base);
font-size: var(--font-size-2xs);
line-height: var(--font-line-height-loose);
}
</style> </style>

View File

@@ -8,16 +8,16 @@ import { SCHEMA_PREVIEW_DOCS_URL } from '@/constants';
const props = defineProps<{ const props = defineProps<{
title: string; title: string;
info?: string;
collapsable: boolean; collapsable: boolean;
collapsed: boolean; collapsed: boolean;
nodeType: INodeTypeDescription;
itemCount: number | null; itemCount: number | null;
info?: string;
nodeType?: INodeTypeDescription;
preview?: boolean; preview?: boolean;
}>(); }>();
const i18n = useI18n(); const i18n = useI18n();
const isTrigger = computed(() => props.nodeType.group.includes('trigger')); const isTrigger = computed(() => Boolean(props.nodeType?.group.includes('trigger')));
const emit = defineEmits<{ const emit = defineEmits<{
'click:toggle': []; 'click:toggle': [];
}>(); }>();
@@ -31,6 +31,7 @@ const emit = defineEmits<{
</div> </div>
<NodeIcon <NodeIcon
v-if="nodeType"
class="icon" class="icon"
:class="{ ['icon-trigger']: isTrigger }" :class="{ ['icon-trigger']: isTrigger }"
:node-type="nodeType" :node-type="nodeType"
@@ -51,7 +52,6 @@ const emit = defineEmits<{
<div <div
v-if="preview && !collapsed" v-if="preview && !collapsed"
class="notice" class="notice"
theme="warning"
data-test-id="schema-preview-warning" data-test-id="schema-preview-warning"
@click.stop @click.stop
> >

View File

@@ -1,4 +1,5 @@
<script lang="ts" setup> <script lang="ts" setup>
import { N8nTooltip } from '@n8n/design-system';
import TextWithHighlights from './TextWithHighlights.vue'; import TextWithHighlights from './TextWithHighlights.vue';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
@@ -19,6 +20,8 @@ type Props = {
collapsed?: boolean; collapsed?: boolean;
search?: string; search?: string;
preview?: boolean; preview?: boolean;
locked?: boolean;
lockedTooltip?: string;
}; };
const props = defineProps<Props>(); const props = defineProps<Props>();
@@ -43,18 +46,27 @@ const emit = defineEmits<{
:data-nest-level="level" :data-nest-level="level"
:data-value="expression" :data-value="expression"
:data-node-type="nodeType" :data-node-type="nodeType"
:data-target="!locked && 'mappable'"
:data-node-name="nodeName" :data-node-name="nodeName"
data-target="mappable"
class="pill" class="pill"
:class="{ :class="{
'pill--highlight': highlight, 'pill--highlight': highlight,
'pill--preview': preview, 'pill--preview': preview,
'pill--locked': locked,
}" }"
data-test-id="run-data-schema-node-name" data-test-id="run-data-schema-node-name"
> >
<FontAwesomeIcon class="type-icon" :icon size="sm" /> <FontAwesomeIcon class="type-icon" :icon size="sm" />
<TextWithHighlights class="title" :content="title" :search="props.search" /> <TextWithHighlights class="title" :content="title" :search="props.search" />
</div> </div>
<N8nTooltip v-if="locked" :disabled="!lockedTooltip" :popper-class="$style.tooltip">
<template #content>
<span v-n8n-html="lockedTooltip" />
</template>
<N8nIcon class="locked-icon" icon="lock" size="small" />
</N8nTooltip>
<TextWithHighlights <TextWithHighlights
data-test-id="run-data-schema-item-value" data-test-id="run-data-schema-item-value"
class="text" class="text"
@@ -140,11 +152,11 @@ const emit = defineEmits<{
color: var(--color-primary); color: var(--color-primary);
} }
.draggable .pill { .draggable .pill:not(.pill--locked) {
cursor: grab; cursor: grab;
} }
.draggable .pill:hover { .draggable .pill:not(.pill--locked):hover {
background-color: var(--color-background-light); background-color: var(--color-background-light);
border-color: var(--color-foreground-base); border-color: var(--color-foreground-base);
} }
@@ -153,6 +165,11 @@ const emit = defineEmits<{
color: var(--color-text-light); color: var(--color-text-light);
} }
.locked-icon {
color: var(--color-text-light);
margin-left: var(--spacing-2xs);
}
.title { .title {
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
@@ -173,4 +190,14 @@ const emit = defineEmits<{
.collapsed { .collapsed {
transform: rotateZ(-90deg); transform: rotateZ(-90deg);
} }
.tooltip {
max-width: 260px;
}
</style>
<style lang="css" module>
.tooltip {
max-width: 260px;
}
</style> </style>

View File

@@ -828,11 +828,8 @@ describe('useFlattenSchema', () => {
}, },
], ],
}; };
const node1 = { name: 'First Node', type: 'any' }; const node1Schema = flattenSchema({ schema, expressionPrefix: '$("First Node")', depth: 1 });
const node2 = { name: 'Second Node', type: 'any' }; const node2Schema = flattenSchema({ schema, expressionPrefix: '$("Second Node")', depth: 1 });
const node1Schema = flattenSchema({ schema, node: node1, depth: 1 });
const node2Schema = flattenSchema({ schema, node: node2, depth: 1 });
expect(node1Schema[0].id).not.toBe(node2Schema[0].id); expect(node1Schema[0].id).not.toBe(node2Schema[0].id);
}); });

View File

@@ -1,20 +1,20 @@
import { ref } from 'vue'; import { useI18n } from '@/composables/useI18n';
import type { Optional, Primitives, Schema, INodeUi, SchemaType } from '@/Interface'; import type { INodeUi, Optional, Primitives, Schema, SchemaType } from '@/Interface';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { generatePath, getNodeParentExpression } from '@/utils/mappingUtils';
import { isObject } from '@/utils/objectUtils';
import { isObj } from '@/utils/typeGuards';
import { isPresent, shorten } from '@/utils/typesUtils';
import type { JSONSchema7, JSONSchema7Definition, JSONSchema7TypeName } from 'json-schema';
import { merge } from 'lodash-es';
import { import {
type ITaskDataConnections,
type IDataObject, type IDataObject,
type INodeExecutionData, type INodeExecutionData,
type INodeTypeDescription, type INodeTypeDescription,
type ITaskDataConnections,
NodeConnectionType, NodeConnectionType,
} from 'n8n-workflow'; } from 'n8n-workflow';
import { merge } from 'lodash-es'; import { ref } from 'vue';
import { generatePath, getMappedExpression } from '@/utils/mappingUtils';
import { isObj } from '@/utils/typeGuards';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { isPresent, shorten } from '@/utils/typesUtils';
import { useI18n } from '@/composables/useI18n';
import type { JSONSchema7, JSONSchema7Definition, JSONSchema7TypeName } from 'json-schema';
import { isObject } from '@/utils/objectUtils';
export function useDataSchema() { export function useDataSchema() {
function getSchema( function getSchema(
@@ -236,29 +236,31 @@ export type SchemaNode = {
}; };
export type RenderItem = { export type RenderItem = {
type: 'item';
id: string;
icon: string;
title?: string; title?: string;
path?: string; path?: string;
level?: number; level?: number;
depth?: number; depth?: number;
expression?: string; expression?: string;
value?: string; value?: string;
id: string;
icon: string;
collapsable?: boolean; collapsable?: boolean;
nodeName?: string; nodeName?: string;
nodeType?: INodeUi['type']; nodeType?: INodeUi['type'];
preview?: boolean; preview?: boolean;
type: 'item'; locked?: boolean;
lockedTooltip?: string;
}; };
export type RenderHeader = { export type RenderHeader = {
type: 'header';
id: string; id: string;
title: string; title: string;
info?: string;
collapsable: boolean; collapsable: boolean;
nodeType: INodeTypeDescription;
itemCount: number | null; itemCount: number | null;
type: 'header'; info?: string;
nodeType?: INodeTypeDescription;
preview?: boolean; preview?: boolean;
}; };
@@ -269,7 +271,14 @@ export type RenderIcon = {
tooltip: string; tooltip: string;
}; };
type Renders = RenderHeader | RenderItem | RenderIcon; export type RenderNotice = {
id: string;
type: 'notice';
level: number;
message: string;
};
export type Renders = RenderHeader | RenderItem | RenderIcon | RenderNotice;
const icons = { const icons = {
object: 'cube', object: 'cube',
@@ -333,14 +342,18 @@ export const useFlattenSchema = () => {
const flattenSchema = ({ const flattenSchema = ({
schema, schema,
node = { name: '', type: '' }, nodeType,
nodeName,
expressionPrefix = '',
depth = 0, depth = 0,
prefix = '', prefix = '',
level = 0, level = 0,
preview, preview,
}: { }: {
schema: Schema; schema: Schema;
node?: { name: string; type: string }; expressionPrefix?: string;
nodeType?: string;
nodeName?: string;
depth?: number; depth?: number;
prefix?: string; prefix?: string;
level?: number; level?: number;
@@ -351,13 +364,9 @@ export const useFlattenSchema = () => {
return [emptyItem()]; return [emptyItem()];
} }
const expression = getMappedExpression({ const expression = `{{ ${expressionPrefix ? expressionPrefix + schema.path : schema.path.slice(1)} }}`;
nodeName: node.name,
distanceFromActive: depth,
path: schema.path,
});
const id = `${node.name}-${expression}`; const id = expression;
if (Array.isArray(schema.value)) { if (Array.isArray(schema.value)) {
const items: RenderItem[] = []; const items: RenderItem[] = [];
@@ -372,8 +381,8 @@ export const useFlattenSchema = () => {
icon: getIconBySchemaType(schema.type), icon: getIconBySchemaType(schema.type),
id, id,
collapsable: true, collapsable: true,
nodeName: node.name, nodeType,
nodeType: node.type, nodeName,
type: 'item', type: 'item',
preview, preview,
}); });
@@ -389,7 +398,9 @@ export const useFlattenSchema = () => {
const itemPrefix = schema.type === 'array' ? schema.key : ''; const itemPrefix = schema.type === 'array' ? schema.key : '';
return flattenSchema({ return flattenSchema({
schema: item, schema: item,
node, expressionPrefix,
nodeType,
nodeName,
depth, depth,
prefix: itemPrefix, prefix: itemPrefix,
level: level + 1, level: level + 1,
@@ -410,8 +421,8 @@ export const useFlattenSchema = () => {
id, id,
icon: getIconBySchemaType(schema.type), icon: getIconBySchemaType(schema.type),
collapsable: false, collapsable: false,
nodeType: node.type, nodeType,
nodeName: node.name, nodeName,
type: 'item', type: 'item',
preview, preview,
}, },
@@ -450,7 +461,19 @@ export const useFlattenSchema = () => {
return acc; return acc;
} }
acc.push(...flattenSchema(item)); acc = acc.concat(
flattenSchema({
schema: item.schema,
depth: item.depth,
nodeType: item.node.type,
nodeName: item.node.name,
preview: item.preview,
expressionPrefix: getNodeParentExpression({
nodeName: item.node.name,
distanceFromActive: item.depth,
}),
}),
);
if (item.preview) { if (item.preview) {
acc.push(moreFieldsItem()); acc.push(moreFieldsItem());

View File

@@ -669,6 +669,10 @@
"dataMapping.schemaView.preview": "Usually outputs the following fields. Execute the node to see the actual ones. {link}", "dataMapping.schemaView.preview": "Usually outputs the following fields. Execute the node to see the actual ones. {link}",
"dataMapping.schemaView.previewExtraFields": "There may be more fields. Execute the node to be sure.", "dataMapping.schemaView.previewExtraFields": "There may be more fields. Execute the node to be sure.",
"dataMapping.schemaView.previewNode": "Preview", "dataMapping.schemaView.previewNode": "Preview",
"dataMapping.schemaView.variablesContextTitle": "Variables and context",
"dataMapping.schemaView.execution.resumeUrl": "The URL for resuming a 'Wait' node",
"dataMapping.schemaView.variablesUpgrade": "Set global variables and use them across workflows with the Pro or Enterprise plan. <a href=\"https://docs.n8n.io/environments/variables/\" target=\"_blank\">Details</a>",
"dataMapping.schemaView.variablesEmpty": "Create variables that can be used across workflows <a href=\"/variables\" target=\"_blank\">here</a>",
"displayWithChange.cancelEdit": "Cancel Edit", "displayWithChange.cancelEdit": "Cancel Edit",
"displayWithChange.clickToChange": "Click to Change", "displayWithChange.clickToChange": "Click to Change",
"displayWithChange.setValue": "Set Value", "displayWithChange.setValue": "Set Value",

View File

@@ -35,10 +35,7 @@ export function getMappedExpression({
distanceFromActive: number; distanceFromActive: number;
path: Array<string | number> | string; path: Array<string | number> | string;
}) { }) {
const root = const root = getNodeParentExpression({ nodeName, distanceFromActive });
distanceFromActive === 1
? '$json'
: generatePath(`$('${escapeMappingString(nodeName)}')`, ['item', 'json']);
if (typeof path === 'string') { if (typeof path === 'string') {
return `{{ ${root}${path} }}`; return `{{ ${root}${path} }}`;
@@ -47,6 +44,18 @@ export function getMappedExpression({
return `{{ ${generatePath(root, path)} }}`; return `{{ ${generatePath(root, path)} }}`;
} }
export function getNodeParentExpression({
nodeName,
distanceFromActive,
}: {
nodeName: string;
distanceFromActive: number;
}) {
return distanceFromActive === 1
? '$json'
: generatePath(`$('${escapeMappingString(nodeName)}')`, ['item', 'json']);
}
const unquote = (str: string) => { const unquote = (str: string) => {
if (str.startsWith('"') && str.endsWith('"')) { if (str.startsWith('"') && str.endsWith('"')) {
return str.slice(1, -1).replace(/\\"/g, '"'); return str.slice(1, -1).replace(/\\"/g, '"');