Canvas: Improve placement when adding an element via context menu (#61071)

This commit is contained in:
Adela Almasan 2023-01-05 16:09:04 -06:00 committed by GitHub
parent dc20b776bb
commit 97e25d70e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 6 deletions

View File

@ -2,6 +2,7 @@ import { css } from '@emotion/css';
import React, { useCallback, useEffect, useState } from 'react';
import { first } from 'rxjs/operators';
import { SelectableValue } from '@grafana/data';
import { ContextMenu, MenuItem, MenuItemProps } from '@grafana/ui';
import { Scene } from 'app/features/canvas/runtime/scene';
@ -108,13 +109,26 @@ export const CanvasContextMenu = ({ scene, panel }: Props) => {
const submenuItems: Array<
React.ReactElement<MenuItemProps<unknown>, string | React.JSXElementConstructor<unknown>>
> = [];
const onClickItem = (option: SelectableValue<string>) => {
let offsetY = anchorPoint.y;
let offsetX = anchorPoint.x;
if (scene.div) {
const sceneContainerDimensions = scene.div.getBoundingClientRect();
offsetY = offsetY - sceneContainerDimensions.top;
offsetX = offsetX - sceneContainerDimensions.left;
}
onAddItem(option, rootLayer, {
...anchorPoint,
y: offsetY,
x: offsetX,
});
};
typeOptions.map((option) => {
submenuItems.push(
<MenuItem
key={option.value}
label={option.label ?? 'Canvas item'}
onClick={() => onAddItem(option, rootLayer)}
/>
<MenuItem key={option.value} label={option.label ?? 'Canvas item'} onClick={() => onClickItem(option)} />
);
});

View File

@ -14,6 +14,8 @@ import { ElementState } from '../../../features/canvas/runtime/element';
import { FrameState } from '../../../features/canvas/runtime/frame';
import { Scene, SelectionParams } from '../../../features/canvas/runtime/scene';
import { AnchorPoint } from './types';
export function doSelect(scene: Scene, element: ElementState | FrameState) {
try {
let selection: SelectionParams = { targets: [] };
@ -74,10 +76,15 @@ export function getElementTypesOptions(items: CanvasElementItem[], current: stri
return selectables;
}
export function onAddItem(sel: SelectableValue<string>, rootLayer: FrameState | undefined) {
export function onAddItem(sel: SelectableValue<string>, rootLayer: FrameState | undefined, anchorPoint?: AnchorPoint) {
const newItem = canvasElementRegistry.getIfExists(sel.value) ?? notFoundItem;
const newElementOptions = newItem.getNewOptions() as CanvasElementOptions;
newElementOptions.type = newItem.id;
if (anchorPoint) {
newElementOptions.placement = { ...newElementOptions.placement, top: anchorPoint.y, left: anchorPoint.x };
}
if (newItem.defaultSize) {
newElementOptions.placement = { ...newElementOptions.placement, ...newItem.defaultSize };
}