Skip to content

Commit

Permalink
fix(editor): Type errors in VariablesView.vue (no-changelog) (#9558)
Browse files Browse the repository at this point in the history
  • Loading branch information
RicardoE105 authored Jun 3, 2024
1 parent 08d9c9a commit 631f077
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 56 deletions.
6 changes: 1 addition & 5 deletions packages/editor-ui/src/Interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1661,15 +1661,11 @@ export declare namespace DynamicNodeParameters {
}

export interface EnvironmentVariable {
id: number;
id: string;
key: string;
value: string;
}

export interface TemporaryEnvironmentVariable extends Omit<EnvironmentVariable, 'id'> {
id: string;
}

export type ExecutionFilterMetadata = {
key: string;
value: string;
Expand Down
4 changes: 2 additions & 2 deletions packages/editor-ui/src/api/environments.ee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ export async function getVariable(
export async function createVariable(
context: IRestApiContext,
data: Omit<EnvironmentVariable, 'id'>,
) {
): Promise<EnvironmentVariable> {
return await makeRestApiRequest(context, 'POST', '/variables', data as unknown as IDataObject);
}

export async function updateVariable(
context: IRestApiContext,
{ id, ...data }: EnvironmentVariable,
) {
): Promise<EnvironmentVariable> {
return await makeRestApiRequest(
context,
'PATCH',
Expand Down
31 changes: 16 additions & 15 deletions packages/editor-ui/src/components/VariablesRow.vue
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
<script lang="ts" setup>
import type { ComponentPublicInstance, PropType } from 'vue';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import type { EnvironmentVariable, Rule, RuleGroup } from '@/Interface';
import type { Rule, RuleGroup } from '@/Interface';
import { useI18n } from '@/composables/useI18n';
import { useToast } from '@/composables/useToast';
import { useClipboard } from '@/composables/useClipboard';
import { EnterpriseEditionFeature } from '@/constants';
import { useSettingsStore } from '@/stores/settings.store';
import { useUsersStore } from '@/stores/users.store';
import { getVariablesPermissions } from '@/permissions';
import type { IResource } from './layouts/ResourcesListLayout.vue';
const i18n = useI18n();
const clipboard = useClipboard();
Expand All @@ -20,7 +21,7 @@ const emit = defineEmits(['save', 'cancel', 'edit', 'delete']);
const props = defineProps({
data: {
type: Object as PropType<EnvironmentVariable>,
type: Object as PropType<IResource>,
default: () => ({}),
},
editing: {
Expand All @@ -30,20 +31,20 @@ const props = defineProps({
});
const permissions = computed(() => getVariablesPermissions(usersStore.currentUser));
const modelValue = ref<EnvironmentVariable>({ ...props.data });
const modelValue = ref<IResource>({ ...props.data });
const formValidationStatus = ref<Record<string, boolean>>({
key: false,
value: false,
});
const formValid = computed(() => {
return formValidationStatus.value.key && formValidationStatus.value.value;
return formValidationStatus.value.name && formValidationStatus.value.value;
});
const keyInputRef = ref<ComponentPublicInstance & { inputRef?: HTMLElement }>();
const valueInputRef = ref<HTMLElement>();
const usage = ref(`$vars.${props.data.key}`);
const usage = ref(`$vars.${props.data.name}`);
const isFeatureEnabled = computed(() =>
settingsStore.isEnterpriseFeatureEnabled(EnterpriseEditionFeature.Variables),
Expand Down Expand Up @@ -77,17 +78,17 @@ const valueValidationRules: Array<Rule | RuleGroup> = [
];
watch(
() => modelValue.value.key,
() => modelValue.value.name,
async () => {
await nextTick();
if (formValidationStatus.value.key) {
if (formValidationStatus.value.name) {
updateUsageSyntax();
}
},
);
function updateUsageSyntax() {
usage.value = `$vars.${modelValue.value.key || props.data.key}`;
usage.value = `$vars.${modelValue.value.name || props.data.name}`;
}
async function onCancel() {
Expand All @@ -111,8 +112,8 @@ async function onDelete() {
emit('delete', modelValue.value);
}
function onValidate(key: string, value: boolean) {
formValidationStatus.value[key] = value;
function onValidate(name: string, value: boolean) {
formValidationStatus.value[name] = value;
}
function onUsageClick() {
Expand All @@ -132,19 +133,19 @@ function focusFirstInput() {
<tr :class="$style.variablesRow" data-test-id="variables-row">
<td class="variables-key-column">
<div>
<span v-if="!editing">{{ data.key }}</span>
<span v-if="!editing">{{ data.name }}</span>
<n8n-form-input
v-else
ref="keyInputRef"
v-model="modelValue.key"
v-model="modelValue.name"
label
name="key"
name="name"
data-test-id="variable-row-key-input"
:placeholder="i18n.baseText('variables.editing.key.placeholder')"
required
validate-on-blur
:validation-rules="keyValidationRules"
@validate="(value: boolean) => onValidate('key', value)"
@validate="(value: boolean) => onValidate('name', value)"
/>
</div>
</td>
Expand All @@ -168,7 +169,7 @@ function focusFirstInput() {
<td class="variables-usage-column">
<div>
<n8n-tooltip placement="top">
<span v-if="modelValue.key && usage" :class="$style.usageSyntax" @click="onUsageClick">{{
<span v-if="modelValue.name && usage" :class="$style.usageSyntax" @click="onUsageClick">{{
usage
}}</span>
<template #content>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import VariablesRow from '../VariablesRow.vue';
import type { EnvironmentVariable } from '@/Interface';
import { fireEvent } from '@testing-library/vue';
import { setupServer } from '@/__tests__/server';
import { afterAll, beforeAll } from 'vitest';
Expand Down Expand Up @@ -42,9 +41,9 @@ describe('VariablesRow', () => {
server.shutdown();
});

const environmentVariable: EnvironmentVariable = {
id: 1,
key: 'key',
const environmentVariable = {
id: '1',
name: 'key',
value: 'value',
};

Expand Down Expand Up @@ -83,7 +82,7 @@ describe('VariablesRow', () => {

expect(wrapper.getByTestId('variable-row-key-input')).toBeVisible();
expect(wrapper.getByTestId('variable-row-key-input').querySelector('input')).toHaveValue(
environmentVariable.key,
environmentVariable.name,
);
expect(wrapper.getByTestId('variable-row-value-input')).toBeVisible();
expect(wrapper.getByTestId('variable-row-value-input').querySelector('input')).toHaveValue(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,9 @@ import type { BaseTextKey } from '@/plugins/i18n';
export interface IResource {
id: string;
name: string;
updatedAt: string;
createdAt: string;
value: string;
updatedAt?: string;
createdAt?: string;
homeProject?: ProjectSharingData;
}
Expand Down
78 changes: 51 additions & 27 deletions packages/editor-ui/src/views/VariablesView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,15 @@ import { useTelemetry } from '@/composables/useTelemetry';
import { useToast } from '@/composables/useToast';
import { useMessage } from '@/composables/useMessage';
import type { IResource } from '@/components/layouts/ResourcesListLayout.vue';
import ResourcesListLayout from '@/components/layouts/ResourcesListLayout.vue';
import VariablesRow from '@/components/VariablesRow.vue';
import { EnterpriseEditionFeature, MODAL_CONFIRM } from '@/constants';
import type {
DatatableColumn,
EnvironmentVariable,
TemporaryEnvironmentVariable,
} from '@/Interface';
import type { DatatableColumn, EnvironmentVariable } from '@/Interface';
import { uid } from 'n8n-design-system/utils';
import { getVariablesPermissions } from '@/permissions';
import type { BaseTextKey } from '@/plugins/i18n';
const settingsStore = useSettingsStore();
const environmentsStore = useEnvironmentsStore();
Expand All @@ -38,14 +36,19 @@ const { showError } = useToast();
const TEMPORARY_VARIABLE_UID_BASE = '@tmpvar';
const allVariables = ref<Array<EnvironmentVariable | TemporaryEnvironmentVariable>>([]);
const allVariables = ref<EnvironmentVariable[]>([]);
const editMode = ref<Record<string, boolean>>({});
const permissions = getVariablesPermissions(usersStore.currentUser);
const isFeatureEnabled = computed(() =>
settingsStore.isEnterpriseFeatureEnabled(EnterpriseEditionFeature.Variables),
);
const variablesToResources = computed((): IResource[] =>
allVariables.value.map((v) => ({ id: v.id, name: v.key, value: v.value })),
);
const canCreateVariables = computed(() => isFeatureEnabled.value && permissions.create);
const datatableColumns = computed<DatatableColumn[]>(() => [
Expand Down Expand Up @@ -80,9 +83,9 @@ const datatableColumns = computed<DatatableColumn[]>(() => [
const contextBasedTranslationKeys = computed(() => uiStore.contextBasedTranslationKeys);
const newlyAddedVariableIds = ref<number[]>([]);
const newlyAddedVariableIds = ref<string[]>([]);
const nameSortFn = (a: EnvironmentVariable, b: EnvironmentVariable, direction: 'asc' | 'desc') => {
const nameSortFn = (a: IResource, b: IResource, direction: 'asc' | 'desc') => {
if (`${a.id}`.startsWith(TEMPORARY_VARIABLE_UID_BASE)) {
return -1;
} else if (`${b.id}`.startsWith(TEMPORARY_VARIABLE_UID_BASE)) {
Expand All @@ -103,10 +106,10 @@ const nameSortFn = (a: EnvironmentVariable, b: EnvironmentVariable, direction: '
: displayName(b).trim().localeCompare(displayName(a).trim());
};
const sortFns = {
nameAsc: (a: EnvironmentVariable, b: EnvironmentVariable) => {
nameAsc: (a: IResource, b: IResource) => {
return nameSortFn(a, b, 'asc');
},
nameDesc: (a: EnvironmentVariable, b: EnvironmentVariable) => {
nameDesc: (a: IResource, b: IResource) => {
return nameSortFn(a, b, 'desc');
},
};
Expand All @@ -115,6 +118,14 @@ function resetNewVariablesList() {
newlyAddedVariableIds.value = [];
}
const resourceToEnvironmentVariable = (data: IResource): EnvironmentVariable => {
return {
id: data.id,
key: data.name,
value: data.value,
};
};
async function initialize() {
if (!isFeatureEnabled.value) return;
await environmentsStore.fetchAllVariables();
Expand All @@ -123,7 +134,7 @@ async function initialize() {
}
function addTemporaryVariable() {
const temporaryVariable: TemporaryEnvironmentVariable = {
const temporaryVariable: EnvironmentVariable = {
id: uid(TEMPORARY_VARIABLE_UID_BASE),
key: '',
value: '',
Expand All @@ -132,7 +143,7 @@ function addTemporaryVariable() {
if (layoutRef.value) {
// Reset scroll position
if (layoutRef.value.$refs.listWrapperRef) {
layoutRef.value.$refs.listWrapperRef.scrollTop = 0;
(layoutRef.value.$refs.listWrapperRef as HTMLDivElement).scrollTop = 0;
}
// Reset pagination
Expand All @@ -147,18 +158,19 @@ function addTemporaryVariable() {
telemetry.track('User clicked add variable button');
}
async function saveVariable(data: EnvironmentVariable | TemporaryEnvironmentVariable) {
async function saveVariable(data: IResource) {
let updatedVariable: EnvironmentVariable;
const variable = resourceToEnvironmentVariable(data);
try {
if (typeof data.id === 'string' && data.id.startsWith(TEMPORARY_VARIABLE_UID_BASE)) {
const { id, ...rest } = data;
const { id, ...rest } = variable;
updatedVariable = await environmentsStore.createVariable(rest);
allVariables.value.unshift(updatedVariable);
allVariables.value = allVariables.value.filter((variable) => variable.id !== data.id);
newlyAddedVariableIds.value.unshift(updatedVariable.id);
} else {
updatedVariable = await environmentsStore.updateVariable(data as EnvironmentVariable);
updatedVariable = await environmentsStore.updateVariable(variable);
allVariables.value = allVariables.value.filter((variable) => variable.id !== data.id);
allVariables.value.push(updatedVariable);
toggleEditing(updatedVariable);
Expand All @@ -175,11 +187,11 @@ function toggleEditing(data: EnvironmentVariable) {
};
}
function cancelEditing(data: EnvironmentVariable | TemporaryEnvironmentVariable) {
function cancelEditing(data: EnvironmentVariable) {
if (typeof data.id === 'string' && data.id.startsWith(TEMPORARY_VARIABLE_UID_BASE)) {
allVariables.value = allVariables.value.filter((variable) => variable.id !== data.id);
} else {
toggleEditing(data as EnvironmentVariable);
toggleEditing(data);
}
}
Expand Down Expand Up @@ -209,8 +221,8 @@ function goToUpgrade() {
void uiStore.goToUpgrade('variables', 'upgrade-variables');
}
function displayName(resource: EnvironmentVariable) {
return resource.key;
function displayName(resource: IResource) {
return resource.name;
}
onBeforeMount(() => {
Expand All @@ -234,7 +246,7 @@ onBeforeUnmount(() => {
class="variables-view"
resource-key="variables"
:disabled="!isFeatureEnabled"
:resources="allVariables"
:resources="variablesToResources"
:initialize="initialize"
:shareable="false"
:display-name="displayName"
Expand Down Expand Up @@ -277,11 +289,17 @@ onBeforeUnmount(() => {
class="mb-m"
data-test-id="unavailable-resources-list"
emoji="👋"
:heading="$locale.baseText(contextBasedTranslationKeys.variables.unavailable.title)"
:heading="
$locale.baseText(contextBasedTranslationKeys.variables.unavailable.title as BaseTextKey)
"
:description="
$locale.baseText(contextBasedTranslationKeys.variables.unavailable.description)
$locale.baseText(
contextBasedTranslationKeys.variables.unavailable.description as BaseTextKey,
)
"
:button-text="
$locale.baseText(contextBasedTranslationKeys.variables.unavailable.button as BaseTextKey)
"
:button-text="$locale.baseText(contextBasedTranslationKeys.variables.unavailable.button)"
button-type="secondary"
@click:button="goToUpgrade"
/>
Expand All @@ -291,11 +309,17 @@ onBeforeUnmount(() => {
v-if="!isFeatureEnabled"
data-test-id="unavailable-resources-list"
emoji="👋"
:heading="$locale.baseText(contextBasedTranslationKeys.variables.unavailable.title)"
:heading="
$locale.baseText(contextBasedTranslationKeys.variables.unavailable.title as BaseTextKey)
"
:description="
$locale.baseText(contextBasedTranslationKeys.variables.unavailable.description)
$locale.baseText(
contextBasedTranslationKeys.variables.unavailable.description as BaseTextKey,
)
"
:button-text="
$locale.baseText(contextBasedTranslationKeys.variables.unavailable.button as BaseTextKey)
"
:button-text="$locale.baseText(contextBasedTranslationKeys.variables.unavailable.button)"
button-type="secondary"
@click:button="goToUpgrade"
/>
Expand All @@ -305,7 +329,7 @@ onBeforeUnmount(() => {
emoji="👋"
:heading="
$locale.baseText('variables.empty.notAllowedToCreate.heading', {
interpolate: { name: usersStore.currentUser.firstName },
interpolate: { name: usersStore.currentUser?.firstName ?? '' },
})
"
:description="$locale.baseText('variables.empty.notAllowedToCreate.description')"
Expand Down

0 comments on commit 631f077

Please sign in to comment.