feat: Add variables feature (#5602)

* feat: add variables db models and migrations

* feat: variables api endpoints

* feat: add $variables to expressions

* test: fix ActiveWorkflowRunner tests failing

* test: a different fix for the tests broken by $variables

* feat: variables licensing

* fix: could create one extra variable than licensed for

* feat: Add Variables UI page and $vars global property (#5750)

* feat: add support for row slot to datatable

* feat: add variables create, read, update, delete

* feat: add vars autocomplete

* chore: remove alert

* feat: add variables autocomplete for code and expressions

* feat: add tests for variable components

* feat: add variables search and sort

* test: update tests for variables view

* chore: fix test and linting issue

* refactor: review changes

* feat: add variable creation telemetry

* fix: Improve variables listing and disabled case, fix resource sorting (no-changelog) (#5903)

* fix: Improve variables disabled experience and fix sorting

* fix: update action box margin

* test: update tests for variables row and datatable

* fix: Add ee controller to base controller

* fix: variables.ee routes not being added

* feat: add variables validation

* fix: fix vue-fragment bug that breaks everything

* chore: Update lock

* feat: Add variables input validation and permissions (no-changelog) (#5910)

* feat: add input validation

* feat: handle variables view for non-instance-owner users

* test: update variables tests

* fix: fix data-testid pattern

* feat: improve overflow styles

* test: fix variables row snapshot

* feat: update sorting to take newly created variables into account

* fix: fix list layout overflow

* fix: fix adding variables on page other than 1. fix validation

* feat: add docs link

* fix: fix default displayName function for resource-list-layout

* feat: improve vars expressions ux, cm-tooltip

* test: fix datatable test

* feat: add MATCH_REGEX validation rule

* fix: overhaul how datatable pagination selector works

* feat: update  completer description

* fix: conditionally update usage syntax based on key validation

* test: update datatable snapshot

* fix: fix variables-row button margins

* fix: fix pagination overflow

* test: Fix broken test

* test: Update snapshot

* fix: Remove duplicate declaration

* feat: add custom variables icon

---------

Co-authored-by: Alex Grozav <alex@grozav.com>
Co-authored-by: Omar Ajoue <krynble@gmail.com>
This commit is contained in:
Val
2023-04-18 11:41:55 +01:00
committed by GitHub
parent 1555387ece
commit 1bb987140a
94 changed files with 2925 additions and 200 deletions

View File

@@ -135,6 +135,7 @@ export default mixins(genericHelpers, workflowHelpers).extend({
'$mode',
'$parameter',
'$resumeWebhookUrl',
'$vars',
'$workflow',
'$now',
'$today',

View File

@@ -13,6 +13,7 @@ import { luxonCompletions } from './completions/luxon.completions';
import { itemIndexCompletions } from './completions/itemIndex.completions';
import { itemFieldCompletions } from './completions/itemField.completions';
import { jsonFieldCompletions } from './completions/jsonField.completions';
import { variablesCompletions } from './completions/variables.completions';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import type { Extension } from '@codemirror/state';
@@ -24,6 +25,7 @@ export const completerExtension = mixins(
requireCompletions,
executionCompletions,
workflowCompletions,
variablesCompletions,
prevNodeCompletions,
luxonCompletions,
itemIndexCompletions,
@@ -49,6 +51,7 @@ export const completerExtension = mixins(
this.nodeSelectorCompletions,
this.prevNodeCompletions,
this.workflowCompletions,
this.variablesCompletions,
this.executionCompletions,
// luxon
@@ -167,6 +170,7 @@ export const completerExtension = mixins(
// core
if (value === '$execution') return this.executionCompletions(context, variable);
if (value === '$vars') return this.variablesCompletions(context, variable);
if (value === '$workflow') return this.workflowCompletions(context, variable);
if (value === '$prevNode') return this.prevNodeCompletions(context, variable);

View File

@@ -67,6 +67,10 @@ export const baseCompletions = (Vue as CodeNodeEditorMixin).extend({
label: '$workflow',
info: this.$locale.baseText('codeNodeEditor.completer.$workflow'),
},
{
label: '$vars',
info: this.$locale.baseText('codeNodeEditor.completer.$vars'),
},
{
label: '$now',
info: this.$locale.baseText('codeNodeEditor.completer.$now'),

View File

@@ -0,0 +1,33 @@
import Vue from 'vue';
import { addVarType } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import type { CodeNodeEditorMixin } from '../types';
import { useEnvironmentsStore } from '@/stores';
const escape = (str: string) => str.replace('$', '\\$');
export const variablesCompletions = (Vue as CodeNodeEditorMixin).extend({
methods: {
/**
* Complete `$workflow.` to `.id .name .active`.
*/
variablesCompletions(context: CompletionContext, matcher = '$vars'): CompletionResult | null {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const environmentsStore = useEnvironmentsStore();
const options: Completion[] = environmentsStore.variables.map((variable) => ({
label: `${matcher}.${variable.key}`,
info: variable.value,
}));
return {
from: preCursor.from,
options: options.map(addVarType),
};
},
},
});

View File

@@ -226,6 +226,14 @@ export default mixins(
position: 'top',
activateOnRouteNames: [VIEWS.CREDENTIALS],
},
{
id: 'variables',
icon: 'variable',
label: this.$locale.baseText('mainSidebar.variables'),
customIconSize: 'medium',
position: 'top',
activateOnRouteNames: [VIEWS.VARIABLES],
},
{
id: 'executions',
icon: 'tasks',
@@ -374,6 +382,12 @@ export default mixins(
}
break;
}
case 'variables': {
if (this.$router.currentRoute.name !== VIEWS.VARIABLES) {
this.goToRoute({ name: VIEWS.VARIABLES });
}
break;
}
case 'executions': {
if (this.$router.currentRoute.name !== VIEWS.EXECUTIONS) {
this.goToRoute({ name: VIEWS.EXECUTIONS });

View File

@@ -0,0 +1,272 @@
<script lang="ts" setup>
import { ComponentPublicInstance, computed, nextTick, onMounted, PropType, ref, watch } from 'vue';
import { EnvironmentVariable, IValidator, Rule, RuleGroup, Validatable } from '@/Interface';
import { useI18n, useToast, useCopyToClipboard } from '@/composables';
import { EnterpriseEditionFeature } from '@/constants';
import { useSettingsStore, useUsersStore } from '@/stores';
import { getVariablesPermissions } from '@/permissions';
const i18n = useI18n();
const copyToClipboard = useCopyToClipboard();
const { showMessage } = useToast();
const settingsStore = useSettingsStore();
const usersStore = useUsersStore();
const emit = defineEmits(['save', 'cancel', 'edit', 'delete']);
const props = defineProps({
data: {
type: Object as PropType<EnvironmentVariable>,
default: () => ({}),
},
editing: {
type: Boolean,
default: false,
},
});
const permissions = getVariablesPermissions(usersStore.currentUser);
const modelValue = ref<EnvironmentVariable>({ ...props.data });
const formValidationStatus = ref<Record<string, boolean>>({
key: false,
value: false,
});
const formValid = computed(() => {
return formValidationStatus.value.key && formValidationStatus.value.value;
});
const keyInputRef = ref<ComponentPublicInstance & { inputRef?: HTMLElement }>();
const valueInputRef = ref<HTMLElement>();
const usage = ref(`$vars.${props.data.key}`);
const isFeatureEnabled = computed(() =>
settingsStore.isEnterpriseFeatureEnabled(EnterpriseEditionFeature.Variables),
);
const showActions = computed(
() => isFeatureEnabled.value && (permissions.edit || permissions.delete),
);
onMounted(() => {
focusFirstInput();
});
const keyValidationRules: Array<Rule | RuleGroup> = [
{ name: 'REQUIRED' },
{ name: 'MAX_LENGTH', config: { maximum: 50 } },
{
name: 'MATCH_REGEX',
config: {
regex: /^[a-zA-Z]/,
message: i18n.baseText('variables.editing.key.error.startsWithLetter'),
},
},
{
name: 'MATCH_REGEX',
config: {
regex: /^[a-zA-Z][a-zA-Z0-9_]*$/,
message: i18n.baseText('variables.editing.key.error.jsonKey'),
},
},
];
const valueValidationRules: Array<Rule | RuleGroup> = [
{ name: 'MAX_LENGTH', config: { maximum: 220 } },
];
watch(
() => modelValue.value.key,
() => {
nextTick(() => {
if (formValidationStatus.value.key) {
updateUsageSyntax();
}
});
},
);
function updateUsageSyntax() {
usage.value = `$vars.${modelValue.value.key || props.data.key}`;
}
async function onCancel() {
modelValue.value = { ...props.data };
emit('cancel', modelValue.value);
}
async function onSave() {
emit('save', modelValue.value);
}
async function onEdit() {
emit('edit', modelValue.value);
await nextTick();
focusFirstInput();
}
async function onDelete() {
emit('delete', modelValue.value);
}
function onValidate(key: string, value: boolean) {
formValidationStatus.value[key] = value;
}
function onUsageClick() {
copyToClipboard(usage.value);
showMessage({
title: i18n.baseText('variables.row.usage.copiedToClipboard'),
type: 'success',
});
}
function focusFirstInput() {
keyInputRef.value?.inputRef?.focus?.();
}
</script>
<template>
<tr :class="$style.variablesRow">
<td class="variables-key-column">
<div>
<span v-if="!editing">{{ data.key }}</span>
<n8n-form-input
v-else
label
name="key"
data-test-id="variable-row-key-input"
:placeholder="i18n.baseText('variables.editing.key.placeholder')"
required
validateOnBlur
:validationRules="keyValidationRules"
v-model="modelValue.key"
ref="keyInputRef"
@validate="(value) => onValidate('key', value)"
/>
</div>
</td>
<td class="variables-value-column">
<div>
<span v-if="!editing">{{ data.value }}</span>
<n8n-form-input
v-else
label
name="value"
data-test-id="variable-row-value-input"
:placeholder="i18n.baseText('variables.editing.value.placeholder')"
validateOnBlur
:validationRules="valueValidationRules"
v-model="modelValue.value"
ref="valueInputRef"
@validate="(value) => onValidate('value', value)"
/>
</div>
</td>
<td class="variables-usage-column">
<div>
<n8n-tooltip placement="top">
<span v-if="modelValue.key && usage" :class="$style.usageSyntax" @click="onUsageClick">{{
usage
}}</span>
<template #content>
{{ i18n.baseText('variables.row.usage.copyToClipboard') }}
</template>
</n8n-tooltip>
</div>
</td>
<td v-if="isFeatureEnabled">
<div v-if="editing" :class="$style.buttons">
<n8n-button
data-test-id="variable-row-cancel-button"
type="tertiary"
class="mr-xs"
@click="onCancel"
>
{{ i18n.baseText('variables.row.button.cancel') }}
</n8n-button>
<n8n-button
data-test-id="variable-row-save-button"
:disabled="!formValid"
type="primary"
@click="onSave"
>
{{ i18n.baseText('variables.row.button.save') }}
</n8n-button>
</div>
<div v-else :class="[$style.buttons, $style.hoverButtons]">
<n8n-tooltip :disabled="permissions.edit" placement="top">
<div>
<n8n-button
data-test-id="variable-row-edit-button"
type="tertiary"
class="mr-xs"
:disabled="!permissions.edit"
@click="onEdit"
>
{{ i18n.baseText('variables.row.button.edit') }}
</n8n-button>
</div>
<template #content>
{{ i18n.baseText('variables.row.button.edit.onlyOwnerCanSave') }}
</template>
</n8n-tooltip>
<n8n-tooltip :disabled="permissions.delete" placement="top">
<div>
<n8n-button
data-test-id="variable-row-delete-button"
type="tertiary"
:disabled="!permissions.delete"
@click="onDelete"
>
{{ i18n.baseText('variables.row.button.delete') }}
</n8n-button>
</div>
<template #content>
{{ i18n.baseText('variables.row.button.delete.onlyOwnerCanDelete') }}
</template>
</n8n-tooltip>
</div>
</td>
</tr>
</template>
<style lang="scss" module>
.variablesRow {
&:hover {
.hoverButtons {
opacity: 1;
}
}
td {
> div {
display: flex;
align-items: center;
min-height: 40px;
}
}
}
.buttons {
display: flex;
flex-wrap: nowrap;
justify-content: flex-end;
}
.hoverButtons {
opacity: 0;
transition: opacity 0.2s ease;
}
.usageSyntax {
cursor: pointer;
background: var(--color-success-tint-2);
color: var(--color-success);
font-family: var(--font-family-monospace);
font-size: var(--font-size-s);
}
</style>

View File

@@ -0,0 +1,98 @@
import VariablesRow from '../VariablesRow.vue';
import { EnvironmentVariable } from '@/Interface';
import { fireEvent, render } from '@testing-library/vue';
import { createPinia, setActivePinia } from 'pinia';
import { setupServer } from '@/__tests__/server';
import { afterAll, beforeAll } from 'vitest';
import { useSettingsStore, useUsersStore } from '@/stores';
describe('VariablesRow', () => {
let server: ReturnType<typeof setupServer>;
beforeAll(() => {
server = setupServer();
});
beforeEach(async () => {
setActivePinia(createPinia());
await useSettingsStore().getSettings();
await useUsersStore().loginWithCookie();
});
afterAll(() => {
server.shutdown();
});
const stubs = ['n8n-tooltip'];
const environmentVariable: EnvironmentVariable = {
id: 1,
key: 'key',
value: 'value',
};
it('should render correctly', () => {
const wrapper = render(VariablesRow, {
props: {
data: environmentVariable,
},
stubs,
});
expect(wrapper.html()).toMatchSnapshot();
expect(wrapper.container.querySelectorAll('td')).toHaveLength(4);
});
it('should show edit and delete buttons on hover', async () => {
const wrapper = render(VariablesRow, {
props: {
data: environmentVariable,
},
stubs,
});
await fireEvent.mouseEnter(wrapper.container);
expect(wrapper.getByTestId('variable-row-edit-button')).toBeVisible();
expect(wrapper.getByTestId('variable-row-delete-button')).toBeVisible();
});
it('should show key and value inputs in edit mode', async () => {
const wrapper = render(VariablesRow, {
props: {
data: environmentVariable,
editing: true,
},
stubs,
});
await fireEvent.mouseEnter(wrapper.container);
expect(wrapper.getByTestId('variable-row-key-input')).toBeVisible();
expect(wrapper.getByTestId('variable-row-key-input').querySelector('input')).toHaveValue(
environmentVariable.key,
);
expect(wrapper.getByTestId('variable-row-value-input')).toBeVisible();
expect(wrapper.getByTestId('variable-row-value-input').querySelector('input')).toHaveValue(
environmentVariable.value,
);
expect(wrapper.html()).toMatchSnapshot();
});
it('should show cancel and save buttons in edit mode', async () => {
const wrapper = render(VariablesRow, {
props: {
data: environmentVariable,
editing: true,
},
stubs,
});
await fireEvent.mouseEnter(wrapper.container);
expect(wrapper.getByTestId('variable-row-cancel-button')).toBeVisible();
expect(wrapper.getByTestId('variable-row-save-button')).toBeVisible();
});
});

View File

@@ -0,0 +1,78 @@
// Vitest Snapshot v1
exports[`VariablesRow > should render correctly 1`] = `
"<tr class=\\"variablesRow\\">
<td class=\\"variables-key-column\\">
<div><span>key</span></div>
</td>
<td class=\\"variables-value-column\\">
<div><span>value</span></div>
</td>
<td class=\\"variables-usage-column\\">
<div>
<n8n-tooltip-stub justifybuttons=\\"flex-end\\" buttons=\\"\\" placement=\\"top\\"><span class=\\"usageSyntax\\">$vars.key</span></n8n-tooltip-stub>
</div>
</td>
<td>
<div class=\\"buttons hoverButtons\\">
<n8n-tooltip-stub justifybuttons=\\"flex-end\\" buttons=\\"\\" placement=\\"top\\">
<div><button disabled=\\"disabled\\" aria-disabled=\\"true\\" aria-live=\\"polite\\" class=\\"mr-xs button button tertiary medium disabled\\" data-test-id=\\"variable-row-edit-button\\">
<!----><span> Edit </span></button></div>
</n8n-tooltip-stub>
<n8n-tooltip-stub justifybuttons=\\"flex-end\\" buttons=\\"\\" placement=\\"top\\">
<div><button disabled=\\"disabled\\" aria-disabled=\\"true\\" aria-live=\\"polite\\" class=\\"button button tertiary medium disabled\\" data-test-id=\\"variable-row-delete-button\\">
<!----><span> Delete </span></button></div>
</n8n-tooltip-stub>
</div>
</td>
</tr>"
`;
exports[`VariablesRow > should show key and value inputs in edit mode 1`] = `
"<tr class=\\"variablesRow\\">
<td class=\\"variables-key-column\\">
<div>
<div class=\\"container\\" data-test-id=\\"variable-row-key-input\\">
<!---->
<div class=\\"\\">
<div class=\\"el-input el-input--large n8n-input\\">
<!----><input type=\\"text\\" autocomplete=\\"off\\" name=\\"key\\" placeholder=\\"Enter a name\\" class=\\"el-input__inner\\">
<!---->
<!---->
<!---->
<!---->
</div>
</div>
<!---->
</div>
</div>
</td>
<td class=\\"variables-value-column\\">
<div>
<div class=\\"container\\" data-test-id=\\"variable-row-value-input\\">
<!---->
<div class=\\"\\">
<div class=\\"el-input el-input--large n8n-input\\">
<!----><input type=\\"text\\" autocomplete=\\"off\\" name=\\"value\\" placeholder=\\"Enter a value\\" class=\\"el-input__inner\\">
<!---->
<!---->
<!---->
<!---->
</div>
</div>
<!---->
</div>
</div>
</td>
<td class=\\"variables-usage-column\\">
<div>
<n8n-tooltip-stub justifybuttons=\\"flex-end\\" buttons=\\"\\" placement=\\"top\\"><span class=\\"usageSyntax\\">$vars.key</span></n8n-tooltip-stub>
</div>
</td>
<td>
<div class=\\"buttons\\"><button aria-live=\\"polite\\" class=\\"mr-xs button button tertiary medium\\" data-test-id=\\"variable-row-cancel-button\\">
<!----><span> Cancel </span></button><button aria-live=\\"polite\\" class=\\"button button primary medium\\" data-test-id=\\"variable-row-save-button\\">
<!----><span> Save </span></button></div>
</td>
</tr>"
`;

View File

@@ -1,5 +1,18 @@
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
props: {
overflow: {
type: Boolean,
default: false,
},
},
});
</script>
<template>
<div :class="$style.wrapper">
<div :class="{ [$style.wrapper]: true, [$style.overflow]: overflow }">
<div :class="$style.list">
<div v-if="$slots.header" :class="$style.header">
<slot name="header" />
@@ -18,6 +31,14 @@
height: 100%;
}
.overflow {
.list {
.body {
overflow: auto;
}
}
}
.list {
display: flex;
flex-direction: column;

View File

@@ -8,14 +8,17 @@
</div>
<div class="mt-xs mb-l">
<n8n-button
size="large"
block
@click="$emit('click:add', $event)"
data-test-id="resources-list-add"
>
{{ $locale.baseText(`${resourceKey}.add`) }}
</n8n-button>
<slot name="add-button">
<n8n-button
size="large"
block
:disabled="disabled"
@click="$emit('click:add', $event)"
data-test-id="resources-list-add"
>
{{ $locale.baseText(`${resourceKey}.add`) }}
</n8n-button>
</slot>
</div>
<enterprise-edition :features="[EnterpriseEditionFeature.Sharing]" v-if="shareable">
@@ -55,7 +58,7 @@
/>
</slot>
</div>
<page-view-layout-list v-else>
<page-view-layout-list :overflow="type !== 'list'" v-else>
<template #header>
<div class="mb-xs">
<div :class="$style['filters-row']">
@@ -75,23 +78,14 @@
<div :class="$style['sort-and-filter']">
<n8n-select v-model="sortBy" size="medium" data-test-id="resources-list-sort">
<n8n-option
value="lastUpdated"
:label="$locale.baseText(`${resourceKey}.sort.lastUpdated`)"
/>
<n8n-option
value="lastCreated"
:label="$locale.baseText(`${resourceKey}.sort.lastCreated`)"
/>
<n8n-option
value="nameAsc"
:label="$locale.baseText(`${resourceKey}.sort.nameAsc`)"
/>
<n8n-option
value="nameDesc"
:label="$locale.baseText(`${resourceKey}.sort.nameDesc`)"
v-for="sortOption in sortOptions"
:key="sortOption"
:value="sortOption"
:label="$locale.baseText(`${resourceKey}.sort.${sortOption}`)"
/>
</n8n-select>
<resource-filters-dropdown
v-if="showFiltersDropdown"
:keys="filterKeys"
:reset="resetFilters"
:value="filters"
@@ -121,18 +115,41 @@
<div class="pb-xs" />
</template>
<n8n-recycle-scroller
<slot name="preamble" />
<div
v-if="filteredAndSortedSubviewResources.length > 0"
data-test-id="resources-list"
:class="[$style.list, 'list-style-none']"
:items="filteredAndSortedSubviewResources"
:item-size="itemSize"
item-key="id"
:class="$style.listWrapper"
ref="listWrapperRef"
>
<template #default="{ item, updateItemSize }">
<slot :data="item" :updateItemSize="updateItemSize" />
</template>
</n8n-recycle-scroller>
<n8n-recycle-scroller
v-if="type === 'list'"
data-test-id="resources-list"
:class="[$style.list, 'list-style-none']"
:items="filteredAndSortedSubviewResources"
:item-size="typeProps.itemSize"
item-key="id"
>
<template #default="{ item, updateItemSize }">
<slot :data="item" :updateItemSize="updateItemSize" />
</template>
</n8n-recycle-scroller>
<n8n-datatable
v-if="typeProps.columns"
data-test-id="resources-table"
:class="$style.datatable"
:columns="typeProps.columns"
:rows="filteredAndSortedSubviewResources"
:currentPage="currentPage"
:rowsPerPage="rowsPerPage"
@update:currentPage="setCurrentPage"
@update:rowsPerPage="setRowsPerPage"
>
<template #row="{ columns, row }">
<slot :data="row" :columns="columns" />
</template>
</n8n-datatable>
</div>
<n8n-text color="text-base" size="medium" data-test-id="resources-list-empty" v-else>
{{ $locale.baseText(`${resourceKey}.noResults`) }}
@@ -156,6 +173,8 @@
</span>
</template>
</n8n-text>
<slot name="postamble" />
</page-view-layout-list>
</template>
</page-view-layout>
@@ -177,6 +196,7 @@ import ResourceFiltersDropdown from '@/components/forms/ResourceFiltersDropdown.
import { mapStores } from 'pinia';
import { useSettingsStore } from '@/stores/settings';
import { useUsersStore } from '@/stores/users';
import { DatatableColumn } from 'n8n-design-system';
export interface IResource {
id: string;
@@ -213,13 +233,17 @@ export default mixins(showMessage, debounceHelper).extend({
type: String,
default: '' as IResourceKeyType,
},
displayName: {
type: Function as PropType<(resource: IResource) => string>,
default: (resource: IResource) => resource.name,
},
resources: {
type: Array,
default: (): IResource[] => [],
},
itemSize: {
type: Number,
default: 80,
disabled: {
type: Boolean,
default: false,
},
initialize: {
type: Function as PropType<() => Promise<void>>,
@@ -240,13 +264,37 @@ export default mixins(showMessage, debounceHelper).extend({
type: Boolean,
default: true,
},
showFiltersDropdown: {
type: Boolean,
default: true,
},
sortFns: {
type: Object as PropType<Record<string, (a: IResource, b: IResource) => number>>,
default: (): Record<string, (a: IResource, b: IResource) => number> => ({}),
},
sortOptions: {
type: Array as PropType<string[]>,
default: () => ['lastUpdated', 'lastCreated', 'nameAsc', 'nameDesc'],
},
type: {
type: String as PropType<'datatable' | 'list'>,
default: 'list',
},
typeProps: {
type: Object as PropType<{ itemSize: number } | { columns: DatatableColumn[] }>,
default: () => ({
itemSize: 0,
}),
},
},
data() {
return {
loading: true,
isOwnerSubview: false,
sortBy: 'lastUpdated',
sortBy: this.sortOptions[0],
hasFilters: false,
currentPage: 1,
rowsPerPage: 10 as number | '*',
resettingFilters: false,
EnterpriseEditionFeature,
};
@@ -292,7 +340,7 @@ export default mixins(showMessage, debounceHelper).extend({
if (this.filters.search) {
const searchString = this.filters.search.toLowerCase();
matches = matches && resource.name.toLowerCase().includes(searchString);
matches = matches && this.displayName(resource).toLowerCase().includes(searchString);
}
if (this.additionalFiltersHandler) {
@@ -305,15 +353,23 @@ export default mixins(showMessage, debounceHelper).extend({
return filtered.sort((a, b) => {
switch (this.sortBy) {
case 'lastUpdated':
return new Date(b.updatedAt).valueOf() - new Date(a.updatedAt).valueOf();
return this.sortFns['lastUpdated']
? this.sortFns['lastUpdated'](a, b)
: new Date(b.updatedAt).valueOf() - new Date(a.updatedAt).valueOf();
case 'lastCreated':
return new Date(b.createdAt).valueOf() - new Date(a.createdAt).valueOf();
return this.sortFns['lastCreated']
? this.sortFns['lastCreated'](a, b)
: new Date(b.createdAt).valueOf() - new Date(a.createdAt).valueOf();
case 'nameAsc':
return a.name.trim().localeCompare(b.name.trim());
return this.sortFns['nameAsc']
? this.sortFns['nameAsc'](a, b)
: this.displayName(a).trim().localeCompare(this.displayName(b).trim());
case 'nameDesc':
return b.name.localeCompare(a.name);
return this.sortFns['nameDesc']
? this.sortFns['nameDesc'](a, b)
: this.displayName(b).trim().localeCompare(this.displayName(a).trim());
default:
return 0;
return this.sortFns[this.sortBy] ? this.sortFns[this.sortBy](a, b) : 0;
}
});
},
@@ -333,6 +389,12 @@ export default mixins(showMessage, debounceHelper).extend({
this.loading = false;
this.$nextTick(this.focusSearchInput);
},
setCurrentPage(page: number) {
this.currentPage = page;
},
setRowsPerPage(rowsPerPage: number | '*') {
this.rowsPerPage = rowsPerPage;
},
resetFilters() {
Object.keys(this.filters).forEach((key) => {
this.filters[key] = Array.isArray(this.filters[key]) ? [] : '';
@@ -418,7 +480,8 @@ export default mixins(showMessage, debounceHelper).extend({
'filters.search'() {
this.callDebounced('sendFiltersTelemetry', { debounceTime: 1000, trailing: true }, 'search');
},
sortBy() {
sortBy(newValue) {
this.$emit('sort', newValue);
this.sendSortingTelemetry();
},
},
@@ -446,6 +509,10 @@ export default mixins(showMessage, debounceHelper).extend({
//flex-direction: column;
}
.listWrapper {
height: 100%;
}
.sort-and-filter {
display: flex;
flex-direction: row;
@@ -460,4 +527,8 @@ export default mixins(showMessage, debounceHelper).extend({
.card-loading {
height: 69px;
}
.datatable {
padding-bottom: var(--spacing-s);
}
</style>