Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(editor): Implement canvas zoom UX improvements #7376

Merged
merged 4 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions cypress/e2e/12-canvas.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@ const WorkflowPage = new WorkflowPageClass();
const DEFAULT_ZOOM_FACTOR = 1;
const ZOOM_IN_X1_FACTOR = 1.25; // Zoom in factor after one click
const ZOOM_IN_X2_FACTOR = 1.5625; // Zoom in factor after two clicks
const ZOOM_OUT_X1_FACTOR = 0.8;
const ZOOM_OUT_X2_FACTOR = 0.64;
const ZOOM_OUT_X1_FACTOR = 0.75;
const ZOOM_OUT_X2_FACTOR = 0.5625;

const PINCH_ZOOM_IN_FACTOR = 1.32;
const PINCH_ZOOM_OUT_FACTOR = 0.4752;
const RENAME_NODE_NAME = 'Something else';

describe('Canvas Node Manipulation and Navigation', () => {
Expand Down Expand Up @@ -203,6 +206,26 @@ describe('Canvas Node Manipulation and Navigation', () => {
);
});

it('should zoom using pinch to zoom', () => {
WorkflowPage.actions.pinchToZoom(2, 'zoomIn');
WorkflowPage.getters
.nodeView()
.should(
'have.css',
'transform',
`matrix(${PINCH_ZOOM_IN_FACTOR}, 0, 0, ${PINCH_ZOOM_IN_FACTOR}, 0, 0)`,
);

WorkflowPage.actions.pinchToZoom(4, 'zoomOut');
WorkflowPage.getters
.nodeView()
.should(
'have.css',
'transform',
`matrix(${PINCH_ZOOM_OUT_FACTOR}, 0, 0, ${PINCH_ZOOM_OUT_FACTOR}, 0, 0)`,
);
});

it('should reset zoom', () => {
// Reset zoom should not appear until zoom level changed
WorkflowPage.getters.resetZoomButton().should('not.exist');
Expand Down
29 changes: 20 additions & 9 deletions cypress/pages/workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,14 @@ export class WorkflowPage extends BasePage {
this.getters.nodeCreatorSearchBar().type('{enter}');
if (opts?.action) {
// Expand actions category if it's collapsed
nodeCreator.getters.getCategoryItem('Actions').parent().then(($el) => {
if ($el.attr('data-category-collapsed') === 'true') {
nodeCreator.getters.getCategoryItem('Actions').click();
}
});
nodeCreator.getters
.getCategoryItem('Actions')
.parent()
.then(($el) => {
if ($el.attr('data-category-collapsed') === 'true') {
nodeCreator.getters.getCategoryItem('Actions').click();
}
});
nodeCreator.getters.getCreatorItem(opts.action).click();
} else if (!opts?.keepNdvOpen) {
cy.get('body').type('{esc}');
Expand Down Expand Up @@ -249,6 +252,17 @@ export class WorkflowPage extends BasePage {
zoomToFit: () => {
cy.getByTestId('zoom-to-fit').click();
},
pinchToZoom: (steps: number, mode: 'zoomIn' | 'zoomOut' = 'zoomIn') => {
// Pinch-to-zoom simulates a 'wheel' event with ctrlKey: true (same as zooming by scrolling)
this.getters.nodeViewBackground().trigger('wheel', {
force: true,
bubbles: true,
ctrlKey: true,
pageX: cy.window().innerWidth / 2,
pageY: cy.window().innerHeight / 2,
deltaY: mode === 'zoomOut' ? 16 * steps : -16 * steps,
});
},
hitUndo: () => {
cy.get('body').type(META_KEY, { delay: 500, release: false }).type('z');
},
Expand Down Expand Up @@ -311,10 +325,7 @@ export class WorkflowPage extends BasePage {
this.getters.stickies().dblclick().find('textarea').clear().type(content).type('{esc}');
},
shouldHaveWorkflowName: (name: string) => {
this.getters
.workflowNameInputContainer()
.invoke('attr', 'title')
.should('include', name);
this.getters.workflowNameInputContainer().invoke('attr', 'title').should('include', name);
},
};
}
1 change: 0 additions & 1 deletion packages/editor-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@
"luxon": "^3.3.0",
"n8n-design-system": "workspace:*",
"n8n-workflow": "workspace:*",
"normalize-wheel": "^1.0.1",
"pinia": "^2.1.6",
"prettier": "^3.0.3",
"qrcode.vue": "^3.3.4",
Expand Down
1 change: 1 addition & 0 deletions packages/editor-ui/src/Interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1258,6 +1258,7 @@ export interface IRestApiContext {
export interface IZoomConfig {
scale: number;
offset: XYPosition;
origin?: XYPosition;
}

export interface IBounds {
Expand Down
22 changes: 4 additions & 18 deletions packages/editor-ui/src/composables/useCanvasMouseSelect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,7 @@ import type { INodeUi, XYPosition } from '@/Interface';
import useDeviceSupport from './useDeviceSupport';
import { useUIStore } from '@/stores/ui.store';
import { useWorkflowsStore } from '@/stores/workflows.store';
import {
getMousePosition,
getRelativePosition,
SIDEBAR_WIDTH,
SIDEBAR_WIDTH_EXPANDED,
} from '@/utils/nodeViewUtils';
import { getMousePosition, getRelativePosition } from '@/utils/nodeViewUtils';
import { ref, onMounted, computed } from 'vue';
import { useCanvasStore } from '@/stores/canvas.store';

Expand Down Expand Up @@ -179,18 +174,9 @@ export default function useCanvasMouseSelect() {
}

function getMousePositionWithinNodeView(event: MouseEvent | TouchEvent): XYPosition {
const [mouseX, mouseY] = getMousePosition(event);

const sidebarWidth = canvasStore.isDemo
? 0
: uiStore.sidebarMenuCollapsed
? SIDEBAR_WIDTH
: SIDEBAR_WIDTH_EXPANDED;

const relativeX = mouseX - sidebarWidth;
const relativeY = canvasStore.isDemo
? mouseY
: mouseY - uiStore.bannersHeight - uiStore.headerHeight;
const mousePosition = getMousePosition(event);

const [relativeX, relativeY] = canvasStore.canvasPositionFromPagePosition(mousePosition);
const nodeViewScale = canvasStore.nodeViewScale;
const nodeViewOffsetPosition = uiStore.nodeViewOffsetPosition;

Expand Down
10 changes: 0 additions & 10 deletions packages/editor-ui/src/declarations/normalize-wheel.d.ts

This file was deleted.

65 changes: 47 additions & 18 deletions packages/editor-ui/src/stores/canvas.store.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { computed, ref, watch } from 'vue';
import { defineStore } from 'pinia';
import { v4 as uuid } from 'uuid';
import normalizeWheel from 'normalize-wheel';
import {
useWorkflowsStore,
useNodeTypesStore,
Expand All @@ -10,7 +9,14 @@ import {
useSourceControlStore,
} from '@/stores';
import type { INodeUi, XYPosition } from '@/Interface';
import { scaleBigger, scaleReset, scaleSmaller } from '@/utils';
import {
applyScale,
getScaleFromWheelEventDelta,
normalizeWheelEventDelta,
scaleBigger,
scaleReset,
scaleSmaller,
} from '@/utils';
import { START_NODE_TYPE } from '@/constants';
import type {
BeforeStartEventParams,
Expand All @@ -31,6 +37,9 @@ import {
CONNECTOR_PAINT_STYLE_DEFAULT,
CONNECTOR_PAINT_STYLE_PRIMARY,
CONNECTOR_ARROW_OVERLAYS,
getMousePosition,
SIDEBAR_WIDTH,
SIDEBAR_WIDTH_EXPANDED,
} from '@/utils/nodeViewUtils';
import type { PointXY } from '@jsplumb/util';

Expand Down Expand Up @@ -64,7 +73,7 @@ export const useCanvasStore = defineStore('canvas', () => {
});

const setRecenteredCanvasAddButtonPosition = (offset?: XYPosition) => {
const position = getMidCanvasPosition(nodeViewScale.value, offset || [0, 0]);
const position = getMidCanvasPosition(nodeViewScale.value, offset ?? [0, 0]);

position[0] -= PLACEHOLDER_TRIGGER_NODE_SIZE / 2;
position[1] -= PLACEHOLDER_TRIGGER_NODE_SIZE / 2;
Expand All @@ -85,6 +94,21 @@ export const useCanvasStore = defineStore('canvas', () => {
const getNodesWithPlaceholderNode = (): INodeUi[] =>
triggerNodes.value.length > 0 ? nodes.value : [getPlaceholderTriggerNodeUI(), ...nodes.value];

const canvasPositionFromPagePosition = (position: XYPosition): XYPosition => {
const sidebarWidth = isDemo.value
? 0
: uiStore.sidebarMenuCollapsed
? SIDEBAR_WIDTH
: SIDEBAR_WIDTH_EXPANDED;

const relativeX = position[0] - sidebarWidth;
const relativeY = isDemo.value
? position[1]
: position[1] - uiStore.bannersHeight - uiStore.headerHeight;

return [relativeX, relativeY];
};

const setZoomLevel = (zoomLevel: number, offset: XYPosition) => {
nodeViewScale.value = zoomLevel;
jsPlumbInstanceRef.value?.setZoom(zoomLevel);
Expand All @@ -95,6 +119,7 @@ export const useCanvasStore = defineStore('canvas', () => {
const { scale, offset } = scaleReset({
scale: nodeViewScale.value,
offset: uiStore.nodeViewOffsetPosition,
origin: canvasPositionFromPagePosition([window.innerWidth / 2, window.innerHeight / 2]),
});
setZoomLevel(scale, offset);
};
Expand All @@ -103,6 +128,7 @@ export const useCanvasStore = defineStore('canvas', () => {
const { scale, offset } = scaleBigger({
scale: nodeViewScale.value,
offset: uiStore.nodeViewOffsetPosition,
origin: canvasPositionFromPagePosition([window.innerWidth / 2, window.innerHeight / 2]),
});
setZoomLevel(scale, offset);
};
Expand All @@ -111,6 +137,7 @@ export const useCanvasStore = defineStore('canvas', () => {
const { scale, offset } = scaleSmaller({
scale: nodeViewScale.value,
offset: uiStore.nodeViewOffsetPosition,
origin: canvasPositionFromPagePosition([window.innerWidth / 2, window.innerHeight / 2]),
});
setZoomLevel(scale, offset);
};
Expand All @@ -125,29 +152,30 @@ export const useCanvasStore = defineStore('canvas', () => {
setZoomLevel(zoomLevel, offset);
};

const wheelMoveWorkflow = (e: WheelEvent) => {
const normalized = normalizeWheel(e);
const wheelMoveWorkflow = (deltaX: number, deltaY: number, shiftKeyPressed = false) => {
const offsetPosition = uiStore.nodeViewOffsetPosition;
const nodeViewOffsetPositionX =
offsetPosition[0] - (e.shiftKey ? normalized.pixelY : normalized.pixelX);
const nodeViewOffsetPositionY =
offsetPosition[1] - (e.shiftKey ? normalized.pixelX : normalized.pixelY);
const nodeViewOffsetPositionX = offsetPosition[0] - (shiftKeyPressed ? deltaY : deltaX);
const nodeViewOffsetPositionY = offsetPosition[1] - (shiftKeyPressed ? deltaX : deltaY);
uiStore.nodeViewOffsetPosition = [nodeViewOffsetPositionX, nodeViewOffsetPositionY];
};

const wheelScroll = (e: WheelEvent) => {
//* Control + scroll zoom
if (e.ctrlKey) {
if (e.deltaY > 0) {
zoomOut();
} else {
zoomIn();
}
// Prevent browser back/forward gesture, default pinch to zoom etc.
e.preventDefault();

const { deltaX, deltaY } = normalizeWheelEventDelta(e);

e.preventDefault();
if (e.ctrlKey || e.metaKey) {
const scaleFactor = getScaleFromWheelEventDelta(deltaY);
const { scale, offset } = applyScale(scaleFactor)({
scale: nodeViewScale.value,
offset: uiStore.nodeViewOffsetPosition,
origin: canvasPositionFromPagePosition(getMousePosition(e)),
});
setZoomLevel(scale, offset);
return;
}
wheelMoveWorkflow(e);
wheelMoveWorkflow(deltaX, deltaY, e.shiftKey);
};

function initInstance(container: Element) {
Expand Down Expand Up @@ -268,6 +296,7 @@ export const useCanvasStore = defineStore('canvas', () => {
jsPlumbInstance,
setRecenteredCanvasAddButtonPosition,
getNodesWithPlaceholderNode,
canvasPositionFromPagePosition,
setZoomLevel,
resetZoom,
zoomIn,
Expand Down
79 changes: 45 additions & 34 deletions packages/editor-ui/src/utils/canvasUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,47 +13,42 @@ import type { Route } from 'vue-router';
'@/utils'.
*/

export const scaleSmaller = ({ scale, offset: [xOffset, yOffset] }: IZoomConfig): IZoomConfig => {
scale /= 1.25;
xOffset /= 1.25;
yOffset /= 1.25;
xOffset += window.innerWidth / 10;
yOffset += window.innerHeight / 10;

return {
scale,
offset: [xOffset, yOffset],
};
const SCALE_INCREASE_FACTOR = 1.25;
const SCALE_DECREASE_FACTOR = 0.75;
const MIN_SCALE = 0.2;
const MAX_SCALE = 5;

const clamp = (min: number, max: number) => (num: number) => {
return Math.max(min, Math.min(max, num));
};

export const scaleBigger = ({ scale, offset: [xOffset, yOffset] }: IZoomConfig): IZoomConfig => {
scale *= 1.25;
xOffset -= window.innerWidth / 10;
yOffset -= window.innerHeight / 10;
xOffset *= 1.25;
yOffset *= 1.25;
const clampScale = clamp(MIN_SCALE, MAX_SCALE);

export const applyScale =
(scale: number) =>
({ scale: initialScale, offset: [xOffset, yOffset], origin }: IZoomConfig): IZoomConfig => {
const newScale = clampScale(initialScale * scale);
const scaleChange = newScale / initialScale;

const xOrigin = origin?.[0] ?? window.innerWidth / 2;
const yOrigin = origin?.[1] ?? window.innerHeight / 2;

return {
scale,
offset: [xOffset, yOffset],
// Calculate the new offsets based on the zoom origin
xOffset = xOrigin - scaleChange * (xOrigin - xOffset);
yOffset = yOrigin - scaleChange * (yOrigin - yOffset);

return {
scale: newScale,
offset: [xOffset, yOffset],
};
};
};

export const scaleReset = (config: IZoomConfig): IZoomConfig => {
if (config.scale > 1) {
// zoomed in
while (config.scale > 1) {
config = scaleSmaller(config);
}
} else {
while (config.scale < 1) {
config = scaleBigger(config);
}
}
export const scaleBigger = applyScale(SCALE_INCREASE_FACTOR);

config.scale = 1;
export const scaleSmaller = applyScale(SCALE_DECREASE_FACTOR);

return config;
export const scaleReset = (config: IZoomConfig): IZoomConfig => {
return applyScale(1 / config.scale)(config);
};

export const closestNumberDivisibleBy = (inputNumber: number, divisibleBy: number): number => {
Expand Down Expand Up @@ -112,3 +107,19 @@ export const getConnectionInfo = (
}
return null;
};

export const normalizeWheelEventDelta = (event: WheelEvent): { deltaX: number; deltaY: number } => {
const factorByMode: Record<number, number> = {
[WheelEvent.DOM_DELTA_PIXEL]: 1,
[WheelEvent.DOM_DELTA_LINE]: 8,
[WheelEvent.DOM_DELTA_PAGE]: 24,
};

const factor = factorByMode[event.deltaMode] ?? 1;

return { deltaX: event.deltaX * factor, deltaY: event.deltaY * factor };
};

export const getScaleFromWheelEventDelta = (delta: number): number => {
return 1 - delta / 100;
};
Loading
Loading