feat(editor): Workflow history [WIP]- Add workflow history opening button to main header component (no-changelog) (#7310)

Co-authored-by: Iván Ovejero <ivov.src@gmail.com>
This commit is contained in:
Csaba Tuncsik 2023-10-04 16:45:18 +02:00 committed by GitHub
parent b59b9086d7
commit 4bc9164032
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 334 additions and 113 deletions

View file

@ -91,6 +91,19 @@ export const SETTINGS_STORE_DEFAULT_STATE: ISettingsState = {
variables: { variables: {
limit: 100, limit: 100,
}, },
expressions: {
evaluator: 'tournament',
},
banners: {
dismissed: [],
},
ai: {
enabled: false,
},
workflowHistory: {
pruneTime: -1,
licensePruneTime: -1,
},
}, },
promptsData: { promptsData: {
message: '', message: '',

View file

@ -101,6 +101,13 @@
data-test-id="workflow-save-button" data-test-id="workflow-save-button"
@click="onSaveButtonClick" @click="onSaveButtonClick"
/> />
<router-link
v-if="isWorkflowHistoryFeatureEnabled"
:to="workflowHistoryRoute"
:class="$style.workflowHistoryButton"
>
<n8n-icon icon="history" size="medium" />
</router-link>
<div :class="$style.workflowMenuContainer"> <div :class="$style.workflowMenuContainer">
<input <input
:class="$style.hiddenInput" :class="$style.hiddenInput"
@ -335,6 +342,19 @@ export default defineComponent({
return actions; return actions;
}, },
isWorkflowHistoryFeatureEnabled(): boolean {
return this.settingsStore.isEnterpriseFeatureEnabled(
EnterpriseEditionFeature.WorkflowHistory,
);
},
workflowHistoryRoute(): { name: string; params: { workflowId: string } } {
return {
name: VIEWS.WORKFLOW_HISTORY,
params: {
workflowId: this.currentWorkflowId,
},
};
},
}, },
methods: { methods: {
async onSaveButtonClick() { async onSaveButtonClick() {
@ -389,7 +409,7 @@ export default defineComponent({
const saved = await this.saveCurrentWorkflow({ tags }); const saved = await this.saveCurrentWorkflow({ tags });
this.$telemetry.track('User edited workflow tags', { this.$telemetry.track('User edited workflow tags', {
workflow_id: this.currentWorkflowId as string, workflow_id: this.currentWorkflowId,
new_tag_count: tags.length, new_tag_count: tags.length,
}); });
@ -690,4 +710,9 @@ $--header-spacing: 20px;
.disabledShareButton { .disabledShareButton {
cursor: not-allowed; cursor: not-allowed;
} }
.workflowHistoryButton {
margin-left: var(--spacing-l);
color: var(--color-text-dark);
}
</style> </style>

View file

@ -14,6 +14,11 @@ const props = defineProps<{
<style module lang="scss"> <style module lang="scss">
.content { .content {
position: absolute;
display: block; display: block;
left: 0;
top: 0;
width: 100%;
height: 100%;
} }
</style> </style>

View file

@ -10,21 +10,17 @@ import type {
} from '@/types/workflowHistory'; } from '@/types/workflowHistory';
import WorkflowHistoryListItem from '@/components/WorkflowHistory/WorkflowHistoryListItem.vue'; import WorkflowHistoryListItem from '@/components/WorkflowHistory/WorkflowHistoryListItem.vue';
const props = withDefaults( const props = defineProps<{
defineProps<{ items: WorkflowHistory[];
items: WorkflowHistory[]; activeItem: WorkflowHistory | null;
activeItem: WorkflowHistory | null; actionTypes: WorkflowHistoryActionTypes;
actionTypes: WorkflowHistoryActionTypes; requestNumberOfItems: number;
requestNumberOfItems: number; lastReceivedItemsLength: number;
shouldUpgrade: boolean; evaluatedPruneTime: number;
maxRetentionPeriod: number; shouldUpgrade?: boolean;
}>(), isListLoading?: boolean;
{ }>();
items: () => [],
shouldUpgrade: false,
maxRetentionPeriod: 0,
},
);
const emit = defineEmits<{ const emit = defineEmits<{
( (
event: 'action', event: 'action',
@ -98,7 +94,10 @@ const onItemMounted = ({
listElement.value?.scrollTo({ top: offsetTop, behavior: 'smooth' }); listElement.value?.scrollTo({ top: offsetTop, behavior: 'smooth' });
} }
if (index === props.items.length - 1 && props.items.length >= props.requestNumberOfItems) { if (
index === props.items.length - 1 &&
props.lastReceivedItemsLength === props.requestNumberOfItems
) {
observeElement(listElement.value?.children[index] as Element); observeElement(listElement.value?.children[index] as Element);
} }
}; };
@ -117,16 +116,28 @@ const onItemMounted = ({
@preview="onPreview" @preview="onPreview"
@mounted="onItemMounted" @mounted="onItemMounted"
/> />
<li v-if="!props.items.length" :class="$style.empty"> <li v-if="!props.items.length && !props.isListLoading" :class="$style.empty">
{{ i18n.baseText('workflowHistory.empty') }} {{ i18n.baseText('workflowHistory.empty') }}
<br /> <br />
{{ i18n.baseText('workflowHistory.hint') }} {{ i18n.baseText('workflowHistory.hint') }}
</li> </li>
<li v-if="props.shouldUpgrade && props.maxRetentionPeriod > 0" :class="$style.retention"> <li
v-if="props.isListLoading"
:class="$style.loader"
role="status"
aria-live="polite"
aria-busy="true"
:aria-label="i18n.baseText('generic.loading')"
>
<n8n-loading :rows="3" class="mb-xs" />
<n8n-loading :rows="3" class="mb-xs" />
<n8n-loading :rows="3" class="mb-xs" />
</li>
<li v-if="props.shouldUpgrade" :class="$style.retention">
<span> <span>
{{ {{
i18n.baseText('workflowHistory.limit', { i18n.baseText('workflowHistory.limit', {
interpolate: { maxRetentionPeriod: props.maxRetentionPeriod }, interpolate: { evaluatedPruneTime: props.evaluatedPruneTime },
}) })
}} }}
</span> </span>
@ -143,19 +154,12 @@ const onItemMounted = ({
<style module lang="scss"> <style module lang="scss">
.list { .list {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%; height: 100%;
overflow: auto; overflow: auto;
position: relative;
&::before {
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: var(--border-width-base);
background-color: var(--color-foreground-base);
}
} }
.empty { .empty {
@ -171,6 +175,10 @@ const onItemMounted = ({
line-height: var(--font-line-height-loose); line-height: var(--font-line-height-loose);
} }
.loader {
padding: 0 var(--spacing-s);
}
.retention { .retention {
display: grid; display: grid;
padding: var(--spacing-s); padding: var(--spacing-s);

View file

@ -28,6 +28,8 @@ const i18n = useI18n();
const actionsVisible = ref(false); const actionsVisible = ref(false);
const itemElement = ref<HTMLElement | null>(null); const itemElement = ref<HTMLElement | null>(null);
const authorElement = ref<HTMLElement | null>(null);
const isAuthorElementTruncated = ref(false);
const formattedCreatedAtDate = computed<string>(() => { const formattedCreatedAtDate = computed<string>(() => {
const currentYear = new Date().getFullYear().toString(); const currentYear = new Date().getFullYear().toString();
@ -75,6 +77,8 @@ onMounted(() => {
offsetTop: itemElement.value?.offsetTop ?? 0, offsetTop: itemElement.value?.offsetTop ?? 0,
isActive: props.isActive, isActive: props.isActive,
}); });
isAuthorElementTruncated.value =
authorElement.value?.scrollWidth > authorElement.value?.clientWidth;
}); });
</script> </script>
<template> <template>
@ -89,9 +93,9 @@ onMounted(() => {
> >
<p @click="onItemClick"> <p @click="onItemClick">
<time :datetime="item.createdAt">{{ formattedCreatedAtDate }}</time> <time :datetime="item.createdAt">{{ formattedCreatedAtDate }}</time>
<n8n-tooltip placement="right-end" :disabled="authors.size < 2"> <n8n-tooltip placement="right-end" :disabled="authors.size < 2 && !isAuthorElementTruncated">
<template #content>{{ props.item.authors }}</template> <template #content>{{ props.item.authors }}</template>
<span>{{ authors.label }}</span> <span ref="authorElement">{{ authors.label }}</span>
</n8n-tooltip> </n8n-tooltip>
<data :value="item.versionId">{{ idLabel }}</data> <data :value="item.versionId">{{ idLabel }}</data>
</p> </p>
@ -128,17 +132,15 @@ onMounted(() => {
cursor: pointer; cursor: pointer;
time { time {
padding: 0 0 var(--spacing-2xs); padding: 0 0 var(--spacing-3xs);
color: var(--color-text-dark); color: var(--color-text-dark);
font-size: var(--font-size-s); font-size: var(--font-size-s);
font-weight: var(--font-weight-bold); font-weight: var(--font-weight-bold);
} }
span { span,
justify-self: start;
}
data { data {
justify-self: start;
max-width: 160px; max-width: 160px;
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;

View file

@ -4,7 +4,8 @@ import { createPinia, setActivePinia } from 'pinia';
import { faker } from '@faker-js/faker'; import { faker } from '@faker-js/faker';
import { createComponentRenderer } from '@/__tests__/render'; import { createComponentRenderer } from '@/__tests__/render';
import WorkflowHistoryList from '@/components/WorkflowHistory/WorkflowHistoryList.vue'; import WorkflowHistoryList from '@/components/WorkflowHistory/WorkflowHistoryList.vue';
import type { WorkflowHistory, WorkflowHistoryActionTypes } from '@/types/workflowHistory'; import type { WorkflowHistoryActionTypes } from '@/types/workflowHistory';
import { workflowHistoryDataFactory } from '@/stores/__tests__/utils/workflowHistoryTestUtils';
vi.stubGlobal( vi.stubGlobal(
'IntersectionObserver', 'IntersectionObserver',
@ -16,14 +17,6 @@ vi.stubGlobal(
})), })),
); );
const workflowHistoryDataFactory: () => WorkflowHistory = () => ({
versionId: faker.string.nanoid(),
createdAt: faker.date.past().toDateString(),
authors: Array.from({ length: faker.number.int({ min: 1, max: 5 }) }, faker.person.fullName).join(
', ',
),
});
const actionTypes: WorkflowHistoryActionTypes = ['restore', 'clone', 'open', 'download']; const actionTypes: WorkflowHistoryActionTypes = ['restore', 'clone', 'open', 'download'];
const renderComponent = createComponentRenderer(WorkflowHistoryList); const renderComponent = createComponentRenderer(WorkflowHistoryList);
@ -40,34 +33,59 @@ describe('WorkflowHistoryList', () => {
setActivePinia(pinia); setActivePinia(pinia);
}); });
it('should render empty list', () => { it('should render empty list when not loading and no items', () => {
const { getByText } = renderComponent({ const { getByText, queryByRole } = renderComponent({
pinia, pinia,
props: { props: {
items: [], items: [],
actionTypes, actionTypes,
activeItem: null, activeItem: null,
requestNumberOfItems: 20, requestNumberOfItems: 20,
lastReceivedItemsLength: 0,
evaluatedPruneTime: -1,
}, },
}); });
expect(queryByRole('status')).not.toBeInTheDocument();
expect(getByText(/No versions yet/)).toBeInTheDocument(); expect(getByText(/No versions yet/)).toBeInTheDocument();
}); });
it('should show loader but no empty list message when loading', () => {
const { queryByText, getByRole } = renderComponent({
pinia,
props: {
items: [],
actionTypes,
activeItem: null,
requestNumberOfItems: 20,
lastReceivedItemsLength: 0,
evaluatedPruneTime: -1,
isListLoading: true,
},
});
expect(getByRole('status')).toBeInTheDocument();
expect(queryByText(/No versions yet/)).not.toBeInTheDocument();
});
it('should render list and delegate preview event', async () => { it('should render list and delegate preview event', async () => {
const numberOfItems = faker.number.int({ min: 10, max: 50 }); const numberOfItems = faker.number.int({ min: 10, max: 50 });
const items = Array.from({ length: numberOfItems }, workflowHistoryDataFactory); const items = Array.from({ length: numberOfItems }, workflowHistoryDataFactory);
const { getAllByTestId, emitted } = renderComponent({ const { getAllByTestId, emitted, queryByRole } = renderComponent({
pinia, pinia,
props: { props: {
items, items,
actionTypes, actionTypes,
activeItem: null, activeItem: null,
requestNumberOfItems: 20, requestNumberOfItems: 20,
lastReceivedItemsLength: 20,
evaluatedPruneTime: -1,
}, },
}); });
expect(queryByRole('link', { name: /upgrade/i })).not.toBeInTheDocument();
const listItems = getAllByTestId('workflow-history-list-item'); const listItems = getAllByTestId('workflow-history-list-item');
const listItem = listItems[items.length - 1]; const listItem = listItems[items.length - 1];
await userEvent.click(within(listItem).getByText(/ID: /)); await userEvent.click(within(listItem).getByText(/ID: /));
@ -93,6 +111,8 @@ describe('WorkflowHistoryList', () => {
actionTypes, actionTypes,
activeItem: items[0], activeItem: items[0],
requestNumberOfItems: 20, requestNumberOfItems: 20,
lastReceivedItemsLength: 20,
evaluatedPruneTime: -1,
}, },
}); });
@ -109,6 +129,8 @@ describe('WorkflowHistoryList', () => {
actionTypes, actionTypes,
activeItem: null, activeItem: null,
requestNumberOfItems: 20, requestNumberOfItems: 20,
lastReceivedItemsLength: 20,
evaluatedPruneTime: -1,
}, },
}); });
@ -121,4 +143,23 @@ describe('WorkflowHistoryList', () => {
await userEvent.click(within(actionsDropdown).getByTestId(`action-${action}`)); await userEvent.click(within(actionsDropdown).getByTestId(`action-${action}`));
expect(emitted().action).toEqual([[{ action, id: items[index].versionId }]]); expect(emitted().action).toEqual([[{ action, id: items[index].versionId }]]);
}); });
it('should show upgrade message', async () => {
const items = Array.from({ length: 5 }, workflowHistoryDataFactory);
const { getByRole } = renderComponent({
pinia,
props: {
items,
actionTypes,
activeItem: items[0],
requestNumberOfItems: 20,
lastReceivedItemsLength: 20,
evaluatedPruneTime: -1,
shouldUpgrade: true,
},
});
expect(getByRole('link', { name: /upgrade/i })).toBeInTheDocument();
});
}); });

View file

@ -1,18 +1,10 @@
import { createPinia, setActivePinia } from 'pinia'; import { createPinia, setActivePinia } from 'pinia';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { faker } from '@faker-js/faker';
import type { UserAction } from 'n8n-design-system'; import type { UserAction } from 'n8n-design-system';
import { createComponentRenderer } from '@/__tests__/render'; import { createComponentRenderer } from '@/__tests__/render';
import WorkflowHistoryListItem from '@/components/WorkflowHistory/WorkflowHistoryListItem.vue'; import WorkflowHistoryListItem from '@/components/WorkflowHistory/WorkflowHistoryListItem.vue';
import type { WorkflowHistory } from '@/types/workflowHistory'; import type { WorkflowHistoryActionTypes } from '@/types/workflowHistory';
import { workflowHistoryDataFactory } from '@/stores/__tests__/utils/workflowHistoryTestUtils';
const workflowHistoryDataFactory: () => WorkflowHistory = () => ({
versionId: faker.string.nanoid(),
createdAt: faker.date.past().toDateString(),
authors: Array.from({ length: faker.number.int({ min: 2, max: 5 }) }, faker.person.fullName).join(
', ',
),
});
const actionTypes: WorkflowHistoryActionTypes = ['restore', 'clone', 'open', 'download']; const actionTypes: WorkflowHistoryActionTypes = ['restore', 'clone', 'open', 'download'];
const actions: UserAction[] = actionTypes.map((value) => ({ const actions: UserAction[] = actionTypes.map((value) => ({

View file

@ -62,6 +62,7 @@
"generic.workflowSaved": "Workflow changes saved", "generic.workflowSaved": "Workflow changes saved",
"generic.editor": "Editor", "generic.editor": "Editor",
"generic.seePlans": "See plans", "generic.seePlans": "See plans",
"generic.loading": "Loading",
"about.aboutN8n": "About n8n", "about.aboutN8n": "About n8n",
"about.close": "Close", "about.close": "Close",
"about.license": "License", "about.license": "License",
@ -1855,7 +1856,7 @@
"workflowHistory.item.latest": "Latest saved", "workflowHistory.item.latest": "Latest saved",
"workflowHistory.empty": "No versions yet.", "workflowHistory.empty": "No versions yet.",
"workflowHistory.hint": "Save the workflow to create the first version!", "workflowHistory.hint": "Save the workflow to create the first version!",
"workflowHistory.limit": "Version history is limited to {maxRetentionPeriod} days", "workflowHistory.limit": "Version history is limited to {evaluatedPruneTime} days",
"workflowHistory.upgrade": "{link} to activate full history", "workflowHistory.upgrade": "{link} to activate full history",
"workflowHistory.upgrade.link": "Upgrade plan", "workflowHistory.upgrade.link": "Upgrade plan",
"workflows.heading": "Workflows", "workflows.heading": "Workflows",

View file

@ -78,6 +78,7 @@ import {
faHandPointLeft, faHandPointLeft,
faHashtag, faHashtag,
faHdd, faHdd,
faHistory,
faHome, faHome,
faHourglass, faHourglass,
faImage, faImage,
@ -236,6 +237,7 @@ export const FontAwesomePlugin: Plugin<{}> = {
addIcon(faHandPointLeft); addIcon(faHandPointLeft);
addIcon(faHashtag); addIcon(faHashtag);
addIcon(faHdd); addIcon(faHdd);
addIcon(faHistory);
addIcon(faHome); addIcon(faHome);
addIcon(faHourglass); addIcon(faHourglass);
addIcon(faImage); addIcon(faImage);

View file

@ -303,7 +303,6 @@ export const routes = [
sidebar: MainSidebar, sidebar: MainSidebar,
}, },
meta: { meta: {
keepWorkflowAlive: true,
permissions: { permissions: {
allow: { allow: {
loginStatus: [LOGIN_STATUS.LoggedIn], loginStatus: [LOGIN_STATUS.LoggedIn],

View file

@ -0,0 +1,17 @@
import { faker } from '@faker-js/faker';
import type { WorkflowHistory } from '@/types/workflowHistory';
export const workflowHistoryDataFactory: () => WorkflowHistory = () => ({
versionId: faker.string.nanoid(),
createdAt: faker.date.past().toDateString(),
authors: Array.from({ length: faker.number.int({ min: 2, max: 5 }) }, faker.person.fullName).join(
', ',
),
});
export const workflowVersionDataFactory: () => WorkflowHistory = () => ({
...workflowHistoryDataFactory(),
workflow: {
name: faker.lorem.words(3),
},
});

View file

@ -0,0 +1,57 @@
import { createPinia, setActivePinia } from 'pinia';
import { useWorkflowHistoryStore } from '@/stores/workflowHistory.store';
import { useSettingsStore } from '@/stores/settings.store';
import {
workflowHistoryDataFactory,
workflowVersionDataFactory,
} from '@/stores/__tests__/utils/workflowHistoryTestUtils';
const historyData = Array.from({ length: 5 }, workflowHistoryDataFactory);
const versionData = {
...workflowVersionDataFactory(),
...historyData[0],
};
describe('Workflow history store', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('should reset data', () => {
const workflowHistoryStore = useWorkflowHistoryStore();
workflowHistoryStore.addWorkflowHistory(historyData);
workflowHistoryStore.setActiveWorkflowVersion(versionData);
expect(workflowHistoryStore.workflowHistory).toEqual(historyData);
expect(workflowHistoryStore.activeWorkflowVersion).toEqual(versionData);
workflowHistoryStore.reset();
expect(workflowHistoryStore.workflowHistory).toEqual([]);
expect(workflowHistoryStore.activeWorkflowVersion).toEqual(null);
});
test.each([
[true, 1, 1],
[true, 2, 2],
[false, 1, 2],
[false, 2, 1],
[false, -1, 2],
[false, 2, -1],
])(
'should set `shouldUpgrade` to %s when pruneTime is %s and licensePruneTime is %s',
(shouldUpgrade, pruneTime, licensePruneTime) => {
const workflowHistoryStore = useWorkflowHistoryStore();
const settingsStore = useSettingsStore();
settingsStore.settings = {
workflowHistory: {
pruneTime,
licensePruneTime,
},
};
expect(workflowHistoryStore.shouldUpgrade).toBe(shouldUpgrade);
},
);
});

View file

@ -2,6 +2,7 @@ import { ref, computed } from 'vue';
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
import * as whApi from '@/api/workflowHistory'; import * as whApi from '@/api/workflowHistory';
import { useRootStore } from '@/stores/n8nRoot.store'; import { useRootStore } from '@/stores/n8nRoot.store';
import { useSettingsStore } from '@/stores/settings.store';
import type { import type {
WorkflowHistory, WorkflowHistory,
WorkflowVersion, WorkflowVersion,
@ -10,12 +11,21 @@ import type {
export const useWorkflowHistoryStore = defineStore('workflowHistory', () => { export const useWorkflowHistoryStore = defineStore('workflowHistory', () => {
const rootStore = useRootStore(); const rootStore = useRootStore();
const settingsStore = useSettingsStore();
const workflowHistory = ref<WorkflowHistory[]>([]); const workflowHistory = ref<WorkflowHistory[]>([]);
const activeWorkflowVersion = ref<WorkflowVersion | null>(null); const activeWorkflowVersion = ref<WorkflowVersion | null>(null);
const maxRetentionPeriod = ref(0); const licensePruneTime = computed(() => settingsStore.settings.workflowHistory.licensePruneTime);
const retentionPeriod = ref(0); const pruneTime = computed(() => settingsStore.settings.workflowHistory.pruneTime);
const shouldUpgrade = computed(() => maxRetentionPeriod.value === retentionPeriod.value); const evaluatedPruneTime = computed(() => Math.min(pruneTime.value, licensePruneTime.value));
const shouldUpgrade = computed(
() => licensePruneTime.value !== -1 && licensePruneTime.value === pruneTime.value,
);
const reset = () => {
workflowHistory.value = [];
activeWorkflowVersion.value = null;
};
const getWorkflowHistory = async ( const getWorkflowHistory = async (
workflowId: string, workflowId: string,
@ -44,13 +54,14 @@ export const useWorkflowHistoryStore = defineStore('workflowHistory', () => {
}; };
return { return {
reset,
getWorkflowHistory, getWorkflowHistory,
addWorkflowHistory, addWorkflowHistory,
getWorkflowVersion, getWorkflowVersion,
setActiveWorkflowVersion, setActiveWorkflowVersion,
workflowHistory, workflowHistory,
activeWorkflowVersion, activeWorkflowVersion,
evaluatedPruneTime,
shouldUpgrade, shouldUpgrade,
maxRetentionPeriod,
}; };
}); });

View file

@ -1,7 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import { saveAs } from 'file-saver'; import { saveAs } from 'file-saver';
import { onBeforeMount, ref, watchEffect } from 'vue'; import { onBeforeMount, onUnmounted, ref, watchEffect, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import type { IWorkflowDb } from '@/Interface';
import { VIEWS } from '@/constants'; import { VIEWS } from '@/constants';
import { useI18n } from '@/composables'; import { useI18n } from '@/composables';
import type { import type {
@ -13,6 +14,7 @@ import WorkflowHistoryList from '@/components/WorkflowHistory/WorkflowHistoryLis
import WorkflowHistoryContent from '@/components/WorkflowHistory/WorkflowHistoryContent.vue'; import WorkflowHistoryContent from '@/components/WorkflowHistory/WorkflowHistoryContent.vue';
import { useWorkflowHistoryStore } from '@/stores/workflowHistory.store'; import { useWorkflowHistoryStore } from '@/stores/workflowHistory.store';
import { useUIStore } from '@/stores/ui.store'; import { useUIStore } from '@/stores/ui.store';
import { useWorkflowsStore } from '@/stores/workflows.store';
type WorkflowHistoryActionRecord = { type WorkflowHistoryActionRecord = {
[K in Uppercase<WorkflowHistoryActionTypes[number]>]: Lowercase<K>; [K in Uppercase<WorkflowHistoryActionTypes[number]>]: Lowercase<K>;
@ -34,21 +36,47 @@ const router = useRouter();
const i18n = useI18n(); const i18n = useI18n();
const workflowHistoryStore = useWorkflowHistoryStore(); const workflowHistoryStore = useWorkflowHistoryStore();
const uiStore = useUIStore(); const uiStore = useUIStore();
const workflowsStore = useWorkflowsStore();
const isListLoading = ref(true);
const requestNumberOfItems = ref(20); const requestNumberOfItems = ref(20);
const lastReceivedItemsLength = ref(0);
const editorRoute = computed(() => ({
name: VIEWS.WORKFLOW,
params: {
name: route.params.workflowId,
},
}));
const activeWorkflow = ref<IWorkflowDb | null>(null);
const activeWorkflowVersionPreview = computed<IWorkflowDb | null>(() => {
if (workflowHistoryStore.activeWorkflowVersion && activeWorkflow.value) {
return {
...activeWorkflow.value,
nodes: workflowHistoryStore.activeWorkflowVersion.nodes,
connections: workflowHistoryStore.activeWorkflowVersion.connections,
};
}
return null;
});
const loadMore = async (queryParams: WorkflowHistoryRequestParams) => { const loadMore = async (queryParams: WorkflowHistoryRequestParams) => {
const history = await workflowHistoryStore.getWorkflowHistory( const history = await workflowHistoryStore.getWorkflowHistory(
route.params.workflowId, route.params.workflowId,
queryParams, queryParams,
); );
lastReceivedItemsLength.value = history.length;
workflowHistoryStore.addWorkflowHistory(history); workflowHistoryStore.addWorkflowHistory(history);
}; };
onBeforeMount(async () => { onBeforeMount(async () => {
await loadMore({ take: requestNumberOfItems.value }); const [workflow] = await Promise.all([
workflowsStore.fetchWorkflow(route.params.workflowId),
loadMore({ take: requestNumberOfItems.value }),
]);
activeWorkflow.value = workflow;
isListLoading.value = false;
if (!route.params.versionId) { if (!route.params.versionId && workflowHistoryStore.workflowHistory.length) {
await router.replace({ await router.replace({
name: VIEWS.WORKFLOW_HISTORY, name: VIEWS.WORKFLOW_HISTORY,
params: { params: {
@ -59,6 +87,10 @@ onBeforeMount(async () => {
} }
}); });
onUnmounted(() => {
workflowHistoryStore.reset();
});
const openInNewTab = (id: WorkflowVersionId) => { const openInNewTab = (id: WorkflowVersionId) => {
const { href } = router.resolve({ const { href } = router.resolve({
name: VIEWS.WORKFLOW_HISTORY, name: VIEWS.WORKFLOW_HISTORY,
@ -75,12 +107,20 @@ const downloadVersion = async (id: WorkflowVersionId) => {
route.params.workflowId, route.params.workflowId,
id, id,
); );
if (workflowVersion?.workflow) { if (workflowVersion?.nodes && workflowVersion?.connections && activeWorkflow.value) {
const { workflow } = workflowVersion; const { connections, nodes } = workflowVersion;
const blob = new Blob([JSON.stringify(workflow, null, 2)], { const blob = new Blob(
type: 'application/json;charset=utf-8', [JSON.stringify({ ...activeWorkflow.value, nodes, connections }, null, 2)],
}); {
saveAs(blob, workflow.name.replace(/[^a-z0-9]/gi, '_') + '.json'); type: 'application/json;charset=utf-8',
},
);
saveAs(
blob,
`${activeWorkflow.value.name.replace(/[^a-zA-Z0-9]/gi, '_')}-${
workflowVersion.versionId
}.json`,
);
} }
}; };
@ -132,35 +172,40 @@ watchEffect(async () => {
<template> <template>
<div :class="$style.view"> <div :class="$style.view">
<n8n-heading :class="$style.header" tag="h2" size="medium" bold> <n8n-heading :class="$style.header" tag="h2" size="medium" bold>
{{ workflowHistoryStore.activeWorkflowVersion?.workflow?.name }} {{ activeWorkflow?.name }}
</n8n-heading> </n8n-heading>
<div :class="$style.corner"> <div :class="$style.corner">
<n8n-heading tag="h2" size="medium" bold> <n8n-heading tag="h2" size="medium" bold>
{{ i18n.baseText('workflowHistory.title') }} {{ i18n.baseText('workflowHistory.title') }}
</n8n-heading> </n8n-heading>
<n8n-button type="tertiary" icon="times" size="small" text square /> <router-link :to="editorRoute">
<n8n-button type="tertiary" icon="times" size="small" text square />
</router-link>
</div>
<div :class="$style.contentComponentWrapper">
<workflow-history-content :workflow-version="activeWorkflowVersionPreview" />
</div>
<div :class="$style.listComponentWrapper">
<workflow-history-list
:items="workflowHistoryStore.workflowHistory"
:lastReceivedItemsLength="lastReceivedItemsLength"
:activeItem="workflowHistoryStore.activeWorkflowVersion"
:actionTypes="workflowHistoryActionTypes"
:requestNumberOfItems="requestNumberOfItems"
:shouldUpgrade="workflowHistoryStore.shouldUpgrade"
:evaluatedPruneTime="workflowHistoryStore.evaluatedPruneTime"
:isListLoading="isListLoading"
@action="onAction"
@preview="onPreview"
@load-more="loadMore"
@upgrade="onUpgrade"
/>
</div> </div>
<workflow-history-content
:class="$style.contentComponent"
:workflow-version="workflowHistoryStore.activeWorkflowVersion"
/>
<workflow-history-list
:class="$style.listComponent"
:items="workflowHistoryStore.workflowHistory"
:active-item="workflowHistoryStore.activeWorkflowVersion"
:action-types="workflowHistoryActionTypes"
:request-number-of-items="requestNumberOfItems"
:shouldUpgrade="workflowHistoryStore.shouldUpgrade"
:maxRetentionPeriod="workflowHistoryStore.maxRetentionPeriod"
@action="onAction"
@preview="onPreview"
@load-more="loadMore"
@upgrade="onUpgrade"
/>
</div> </div>
</template> </template>
<style module lang="scss"> <style module lang="scss">
.view { .view {
position: relative;
display: grid; display: grid;
width: 100%; width: 100%;
grid-template-areas: 'header corner' 'content list'; grid-template-areas: 'header corner' 'content list';
@ -188,12 +233,26 @@ watchEffect(async () => {
border-left: var(--border-width-base) var(--border-style-base) var(--color-foreground-base); border-left: var(--border-width-base) var(--border-style-base) var(--color-foreground-base);
} }
.contentComponent { .contentComponentWrapper {
grid-area: content; grid-area: content;
position: relative;
z-index: 1;
} }
.listComponent { .listComponentWrapper {
grid-area: list;
grid-area: list; grid-area: list;
position: relative;
z-index: 2;
&::before {
content: '';
display: block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: var(--border-width-base);
background-color: var(--color-foreground-base);
}
} }
</style> </style>

View file

@ -10,7 +10,10 @@ import { SETTINGS_STORE_DEFAULT_STATE } from '@/__tests__/utils';
import WorkflowHistoryPage from '@/views/WorkflowHistory.vue'; import WorkflowHistoryPage from '@/views/WorkflowHistory.vue';
import { useWorkflowHistoryStore } from '@/stores/workflowHistory.store'; import { useWorkflowHistoryStore } from '@/stores/workflowHistory.store';
import { STORES, VIEWS } from '@/constants'; import { STORES, VIEWS } from '@/constants';
import type { WorkflowHistory } from '@/types/workflowHistory'; import {
workflowHistoryDataFactory,
workflowVersionDataFactory,
} from '@/stores/__tests__/utils/workflowHistoryTestUtils';
vi.mock('vue-router', () => { vi.mock('vue-router', () => {
const params = {}; const params = {};
@ -29,21 +32,6 @@ vi.mock('vue-router', () => {
}; };
}); });
const workflowHistoryDataFactory: () => WorkflowHistory = () => ({
versionId: faker.string.nanoid(),
createdAt: faker.date.past().toDateString(),
authors: Array.from({ length: faker.number.int({ min: 2, max: 5 }) }, faker.person.fullName).join(
', ',
),
});
const workflowVersionDataFactory: () => WorkflowHistory = () => ({
...workflowHistoryDataFactory(),
workflow: {
name: faker.lorem.words(3),
},
});
const workflowId = faker.string.nanoid(); const workflowId = faker.string.nanoid();
const historyData = Array.from({ length: 5 }, workflowHistoryDataFactory); const historyData = Array.from({ length: 5 }, workflowHistoryDataFactory);
const versionData = { const versionData = {
@ -87,6 +75,7 @@ describe('WorkflowHistory', () => {
route = useRoute(); route = useRoute();
router = useRouter(); router = useRouter();
vi.spyOn(workflowHistoryStore, 'getWorkflowHistory').mockResolvedValue(historyData);
vi.spyOn(workflowHistoryStore, 'workflowHistory', 'get').mockReturnValue(historyData); vi.spyOn(workflowHistoryStore, 'workflowHistory', 'get').mockReturnValue(historyData);
vi.spyOn(workflowHistoryStore, 'activeWorkflowVersion', 'get').mockReturnValue(versionData); vi.spyOn(workflowHistoryStore, 'activeWorkflowVersion', 'get').mockReturnValue(versionData);
windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null); windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null);