[Dashboard] Scroll to new panel (#152056)

## Summary

Closes #97064.

This scrolls to a newly added panel on a dashboard instead of remaining
at the top. The user can see the new panel without having to manually
scroll to the bottom.

~This also scrolls to the maximized panel when you minimize instead of
just throwing you back to the top of the dashboard.~ Note: Scrolling on
minimize will be addressed in a future PR.

This scrolling behavior also seems to work with portable dashboards
embedded in another apps, but it may require additional work on the
consumer to call `scrollToPanel` in the appropriate callbacks when
adding panels.

#### Scrolls to newly added panel and shows a success border animation

![Apr-18-2023
07-40-41](https://user-images.githubusercontent.com/1697105/232812491-5bf3ee3a-c81d-4dd3-8b04-67978da3b9a8.gif)

#### Scrolls to panel on return from editor
![Apr-18-2023
07-56-35](https://user-images.githubusercontent.com/1697105/232817401-6cfd7085-91b6-4f05-be1c-e47f6cc3edab.gif)

#### Scrolls to panel clone
![Apr-18-2023
07-54-43](https://user-images.githubusercontent.com/1697105/232816928-2b473778-76e1-4781-8e51-f9e46ab74b9b.gif)

#### Scrolling in portable dashboards example

![Apr-18-2023
08-13-14](https://user-images.githubusercontent.com/1697105/232822632-ffcbd9ad-9cad-4185-931c-a68fbf7e0fbe.gif)



### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: Hannah Mudge <Heenawter@users.noreply.github.com>
This commit is contained in:
Catherine Liu 2023-04-24 12:40:48 -07:00 committed by GitHub
parent e46cb1ab8a
commit 32de23bdb3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
21 changed files with 188 additions and 32 deletions

View file

@ -133,7 +133,7 @@ export const EditExample = () => {
iconType="plusInCircle"
isDisabled={controlGroupAPI === undefined}
onClick={() => {
controlGroupAPI!.openAddDataControlFlyout(controlInputTransform);
controlGroupAPI!.openAddDataControlFlyout({ controlInputTransform });
}}
>
Add control

View file

@ -8,6 +8,7 @@
import React from 'react';
import { toMountPoint } from '@kbn/kibana-react-plugin/public';
import { isErrorEmbeddable } from '@kbn/embeddable-plugin/public';
import {
ControlGroupContainer,
@ -32,8 +33,12 @@ import { DataControlInput, OPTIONS_LIST_CONTROL, RANGE_SLIDER_CONTROL } from '..
export function openAddDataControlFlyout(
this: ControlGroupContainer,
controlInputTransform?: ControlInputTransform
options?: {
controlInputTransform?: ControlInputTransform;
onSave?: (id: string) => void;
}
) {
const { controlInputTransform, onSave } = options || {};
const {
overlays: { openFlyout, openConfirm },
controls: { getControlFactory },
@ -71,7 +76,7 @@ export function openAddDataControlFlyout(
updateTitle={(newTitle) => (controlInput.title = newTitle)}
updateWidth={(defaultControlWidth) => this.updateInput({ defaultControlWidth })}
updateGrow={(defaultControlGrow: boolean) => this.updateInput({ defaultControlGrow })}
onSave={(type) => {
onSave={async (type) => {
this.closeAllFlyouts();
if (!type) {
return;
@ -86,17 +91,28 @@ export function openAddDataControlFlyout(
controlInput = controlInputTransform({ ...controlInput }, type);
}
if (type === OPTIONS_LIST_CONTROL) {
this.addOptionsListControl(controlInput as AddOptionsListControlProps);
return;
let newControl;
switch (type) {
case OPTIONS_LIST_CONTROL:
newControl = await this.addOptionsListControl(
controlInput as AddOptionsListControlProps
);
break;
case RANGE_SLIDER_CONTROL:
newControl = await this.addRangeSliderControl(
controlInput as AddRangeSliderControlProps
);
break;
default:
newControl = await this.addDataControlFromField(
controlInput as AddDataControlProps
);
}
if (type === RANGE_SLIDER_CONTROL) {
this.addRangeSliderControl(controlInput as AddRangeSliderControlProps);
return;
if (onSave && !isErrorEmbeddable(newControl)) {
onSave(newControl.id);
}
this.addDataControlFromField(controlInput as AddDataControlProps);
}}
onCancel={onCancel}
onTypeEditorChange={(partialInput) =>

View file

@ -95,6 +95,7 @@ export class ClonePanelAction implements Action<ClonePanelActionContext> {
height: panelToClone.gridData.h,
currentPanels: dashboard.getInput().panels,
placeBesideId: panelToClone.explicitInput.id,
scrollToPanel: true,
} as IPanelPlacementBesideArgs
);
}

View file

@ -64,5 +64,9 @@ export class ExpandPanelAction implements Action<ExpandPanelActionContext> {
}
const newValue = isExpanded(embeddable) ? undefined : embeddable.id;
(embeddable.parent as DashboardContainer).setExpandedPanelId(newValue);
if (!newValue) {
(embeddable.parent as DashboardContainer).setScrollToPanelId(embeddable.id);
}
}
}

View file

@ -21,6 +21,7 @@ import { Toast } from '@kbn/core/public';
import { DashboardPanelState } from '../../common';
import { pluginServices } from '../services/plugin_services';
import { dashboardReplacePanelActionStrings } from './_dashboard_actions_strings';
import { DashboardContainer } from '../dashboard_container';
interface Props {
container: IContainer;
@ -82,6 +83,7 @@ export class ReplacePanelFlyout extends React.Component<Props> {
},
});
(container as DashboardContainer).setHighlightPanelId(id);
this.showToast(name);
this.props.onClose();
};

View file

@ -10,6 +10,7 @@ import React from 'react';
import { EuiContextMenuItem } from '@elastic/eui';
import { ControlGroupContainer } from '@kbn/controls-plugin/public';
import { getAddControlButtonTitle } from '../../_dashboard_app_strings';
import { useDashboardAPI } from '../../dashboard_app';
interface Props {
closePopover: () => void;
@ -17,6 +18,11 @@ interface Props {
}
export const AddDataControlButton = ({ closePopover, controlGroup, ...rest }: Props) => {
const dashboard = useDashboardAPI();
const onSave = () => {
dashboard.scrollToTop();
};
return (
<EuiContextMenuItem
{...rest}
@ -24,7 +30,7 @@ export const AddDataControlButton = ({ closePopover, controlGroup, ...rest }: Pr
data-test-subj="controls-create-button"
aria-label={getAddControlButtonTitle()}
onClick={() => {
controlGroup.openAddDataControlFlyout();
controlGroup.openAddDataControlFlyout({ onSave });
closePopover();
}}
>

View file

@ -13,6 +13,7 @@ import {
getAddTimeSliderControlButtonTitle,
getOnlyOneTimeSliderControlMsg,
} from '../../_dashboard_app_strings';
import { useDashboardAPI } from '../../dashboard_app';
interface Props {
closePopover: () => void;
@ -21,6 +22,7 @@ interface Props {
export const AddTimeSliderControlButton = ({ closePopover, controlGroup, ...rest }: Props) => {
const [hasTimeSliderControl, setHasTimeSliderControl] = useState(false);
const dashboard = useDashboardAPI();
useEffect(() => {
const subscription = controlGroup.getInput$().subscribe(() => {
@ -42,8 +44,9 @@ export const AddTimeSliderControlButton = ({ closePopover, controlGroup, ...rest
<EuiContextMenuItem
{...rest}
icon="plusInCircle"
onClick={() => {
controlGroup.addTimeSliderControl();
onClick={async () => {
await controlGroup.addTimeSliderControl();
dashboard.scrollToTop();
closePopover();
}}
data-test-subj="controls-create-timeslider-button"

View file

@ -110,6 +110,8 @@ export function DashboardEditingToolbar() {
const newEmbeddable = await dashboard.addNewEmbeddable(embeddableFactory.type, explicitInput);
if (newEmbeddable) {
dashboard.setScrollToPanelId(newEmbeddable.id);
dashboard.setHighlightPanelId(newEmbeddable.id);
toasts.addSuccess({
title: dashboardReplacePanelActionStrings.getSuccessMessage(newEmbeddable.getTitle()),
'data-test-subj': 'addEmbeddableToDashboardSuccess',

View file

@ -36,10 +36,13 @@
}
/**
* When a single panel is expanded, all the other panels are hidden in the grid.
* When a single panel is expanded, all the other panels moved offscreen.
* Shifting the rendered panels offscreen prevents a quick flash when redrawing the panels on minimize
*/
.dshDashboardGrid__item--hidden {
display: none;
position: absolute;
top: -9999px;
left: -9999px;
}
/**
@ -53,11 +56,12 @@
* 1. We need to mark this as important because react grid layout sets the width and height of the panels inline.
*/
.dshDashboardGrid__item--expanded {
position: absolute;
height: 100% !important; /* 1 */
width: 100% !important; /* 1 */
top: 0 !important; /* 1 */
left: 0 !important; /* 1 */
transform: translate(0, 0) !important; /* 1 */
transform: none !important;
padding: $euiSizeS;
// Altered panel styles can be found in ../panel

View file

@ -12,7 +12,7 @@ import 'react-grid-layout/css/styles.css';
import { pick } from 'lodash';
import classNames from 'classnames';
import { useEffectOnce } from 'react-use/lib';
import React, { useState, useMemo, useCallback } from 'react';
import React, { useState, useMemo, useCallback, useEffect } from 'react';
import { Layout, Responsive as ResponsiveReactGridLayout } from 'react-grid-layout';
import { ViewMode } from '@kbn/embeddable-plugin/public';
@ -38,6 +38,15 @@ export const DashboardGrid = ({ viewportWidth }: { viewportWidth: number }) => {
setTimeout(() => setAnimatePanelTransforms(true), 500);
});
useEffect(() => {
if (expandedPanelId) {
setAnimatePanelTransforms(false);
} else {
// delaying enabling CSS transforms to the next tick prevents a panel slide animation on minimize
setTimeout(() => setAnimatePanelTransforms(true), 0);
}
}, [expandedPanelId]);
const { onPanelStatusChange } = useDashboardPerformanceTracker({
panelCount: Object.keys(panels).length,
});
@ -98,7 +107,7 @@ export const DashboardGrid = ({ viewportWidth }: { viewportWidth: number }) => {
'dshLayout-withoutMargins': !useMargins,
'dshLayout--viewing': viewMode === ViewMode.VIEW,
'dshLayout--editing': viewMode !== ViewMode.VIEW,
'dshLayout--noAnimation': !animatePanelTransforms,
'dshLayout--noAnimation': !animatePanelTransforms || expandedPanelId,
'dshLayout-isMaximizedPanel': expandedPanelId !== undefined,
});

View file

@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
import React, { useState, useRef, useEffect } from 'react';
import React, { useState, useRef, useEffect, useLayoutEffect } from 'react';
import { EuiLoadingChart } from '@elastic/eui';
import classNames from 'classnames';
@ -56,6 +56,8 @@ const Item = React.forwardRef<HTMLDivElement, Props>(
embeddable: { EmbeddablePanel: PanelComponent },
} = pluginServices.getServices();
const container = useDashboardContainer();
const scrollToPanelId = container.select((state) => state.componentState.scrollToPanelId);
const highlightPanelId = container.select((state) => state.componentState.highlightPanelId);
const expandPanel = expandedPanelId !== undefined && expandedPanelId === id;
const hidePanel = expandedPanelId !== undefined && expandedPanelId !== id;
@ -66,11 +68,23 @@ const Item = React.forwardRef<HTMLDivElement, Props>(
printViewport__vis: container.getInput().viewMode === ViewMode.PRINT,
});
useLayoutEffect(() => {
if (typeof ref !== 'function' && ref?.current) {
if (scrollToPanelId === id) {
container.scrollToPanel(ref.current);
}
if (highlightPanelId === id) {
container.highlightPanel(ref.current);
}
}
}, [id, container, scrollToPanelId, highlightPanelId, ref]);
return (
<div
style={{ ...style, zIndex: focusedPanelId === id ? 2 : 'auto' }}
className={[classes, className].join(' ')}
data-test-subj="dashboardPanel"
id={`panel-${id}`}
ref={ref}
{...rest}
>

View file

@ -11,6 +11,10 @@
box-shadow: none;
border-radius: 0;
}
.dshDashboardGrid__item--highlighted {
border-radius: 0;
}
}
// Remove border color unless in editing mode
@ -25,3 +29,24 @@
cursor: default;
}
}
@keyframes highlightOutline {
0% {
outline: solid $euiSizeXS transparentize($euiColorSuccess, 1);
}
25% {
outline: solid $euiSizeXS transparentize($euiColorSuccess, .5);
}
100% {
outline: solid $euiSizeXS transparentize($euiColorSuccess, 1);
}
}
.dshDashboardGrid__item--highlighted {
border-radius: $euiSizeXS;
animation-name: highlightOutline;
animation-duration: 4s;
animation-timing-function: ease-out;
// keeps outline from getting cut off by other panels without margins
z-index: 999 !important;
}

View file

@ -24,6 +24,7 @@ export interface IPanelPlacementArgs {
width: number;
height: number;
currentPanels: { [key: string]: DashboardPanelState };
scrollToPanel?: boolean;
}
export interface IPanelPlacementBesideArgs extends IPanelPlacementArgs {

View file

@ -41,6 +41,10 @@ export function addFromLibrary(this: DashboardContainer) {
notifications,
overlays,
theme,
onAddPanel: (id: string) => {
this.setScrollToPanelId(id);
this.setHighlightPanelId(id);
},
})
);
}

View file

@ -128,7 +128,12 @@ export function showPlaceholderUntil<TPlacementMethodArgs extends IPanelPlacemen
// this is useful as sometimes panels can load faster than the placeholder one (i.e. by value embeddables)
this.untilEmbeddableLoaded(originalPanelState.explicitInput.id)
.then(() => newStateComplete)
.then((newPanelState: Partial<PanelState>) =>
this.replacePanel(placeholderPanelState, newPanelState)
);
.then(async (newPanelState: Partial<PanelState>) => {
const panelId = await this.replacePanel(placeholderPanelState, newPanelState);
if (placementArgs?.scrollToPanel) {
this.setScrollToPanelId(panelId);
this.setHighlightPanelId(panelId);
}
});
}

View file

@ -181,12 +181,13 @@ export const createDashboard = async (
const incomingEmbeddable = creationOptions?.incomingEmbeddable;
if (incomingEmbeddable) {
initialInput.viewMode = ViewMode.EDIT; // view mode must always be edit to recieve an embeddable.
if (
const panelExists =
incomingEmbeddable.embeddableId &&
Boolean(initialInput.panels[incomingEmbeddable.embeddableId])
) {
Boolean(initialInput.panels[incomingEmbeddable.embeddableId]);
if (panelExists) {
// this embeddable already exists, we will update the explicit input.
const panelToUpdate = initialInput.panels[incomingEmbeddable.embeddableId];
const panelToUpdate = initialInput.panels[incomingEmbeddable.embeddableId as string];
const sameType = panelToUpdate.type === incomingEmbeddable.type;
panelToUpdate.type = incomingEmbeddable.type;
@ -195,17 +196,22 @@ export const createDashboard = async (
...(sameType ? panelToUpdate.explicitInput : {}),
...incomingEmbeddable.input,
id: incomingEmbeddable.embeddableId,
id: incomingEmbeddable.embeddableId as string,
// maintain hide panel titles setting.
hidePanelTitles: panelToUpdate.explicitInput.hidePanelTitles,
};
} else {
// otherwise this incoming embeddable is brand new and can be added via the default method after the dashboard container is created.
untilDashboardReady().then((container) =>
container.addNewEmbeddable(incomingEmbeddable.type, incomingEmbeddable.input)
);
untilDashboardReady().then(async (container) => {
container.addNewEmbeddable(incomingEmbeddable.type, incomingEmbeddable.input);
});
}
untilDashboardReady().then(async (container) => {
container.setScrollToPanelId(incomingEmbeddable.embeddableId);
container.setHighlightPanelId(incomingEmbeddable.embeddableId);
});
}
// --------------------------------------------------------------------------------------

View file

@ -398,4 +398,41 @@ export class DashboardContainer extends Container<InheritedChildInput, Dashboard
}
return titles;
}
public setScrollToPanelId = (id: string | undefined) => {
this.dispatch.setScrollToPanelId(id);
};
public scrollToPanel = async (panelRef: HTMLDivElement) => {
const id = this.getState().componentState.scrollToPanelId;
if (!id) return;
this.untilEmbeddableLoaded(id).then(() => {
this.setScrollToPanelId(undefined);
panelRef.scrollIntoView({ block: 'center' });
});
};
public scrollToTop = () => {
window.scroll(0, 0);
};
public setHighlightPanelId = (id: string | undefined) => {
this.dispatch.setHighlightPanelId(id);
};
public highlightPanel = (panelRef: HTMLDivElement) => {
const id = this.getState().componentState.highlightPanelId;
if (id && panelRef) {
this.untilEmbeddableLoaded(id).then(() => {
panelRef.classList.add('dshDashboardGrid__item--highlighted');
// Removes the class after the highlight animation finishes
setTimeout(() => {
panelRef.classList.remove('dshDashboardGrid__item--highlighted');
}, 5000);
});
}
this.setHighlightPanelId(undefined);
};
}

View file

@ -209,4 +209,12 @@ export const dashboardContainerReducers = {
setHasOverlays: (state: DashboardReduxState, action: PayloadAction<boolean>) => {
state.componentState.hasOverlays = action.payload;
},
setScrollToPanelId: (state: DashboardReduxState, action: PayloadAction<string | undefined>) => {
state.componentState.scrollToPanelId = action.payload;
},
setHighlightPanelId: (state: DashboardReduxState, action: PayloadAction<string | undefined>) => {
state.componentState.highlightPanelId = action.payload;
},
};

View file

@ -33,6 +33,8 @@ export interface DashboardPublicState {
fullScreenMode?: boolean;
savedQueryId?: string;
lastSavedId?: string;
scrollToPanelId?: string;
highlightPanelId?: string;
}
export interface DashboardRenderPerformanceStats {

View file

@ -30,6 +30,7 @@ interface Props {
SavedObjectFinder: React.ComponentType<any>;
showCreateNewMenu?: boolean;
reportUiCounter?: UsageCollectionStart['reportUiCounter'];
onAddPanel?: (id: string) => void;
}
interface State {
@ -101,7 +102,7 @@ export class AddPanelFlyout extends React.Component<Props, State> {
throw new EmbeddableFactoryNotFoundError(savedObjectType);
}
this.props.container.addNewEmbeddable<SavedObjectEmbeddableInput>(
const embeddable = await this.props.container.addNewEmbeddable<SavedObjectEmbeddableInput>(
factoryForSavedObjectType.type,
{ savedObjectId }
);
@ -109,6 +110,9 @@ export class AddPanelFlyout extends React.Component<Props, State> {
this.doTelemetryForAddEvent(this.props.container.type, factoryForSavedObjectType, so);
this.showToast(name);
if (this.props.onAddPanel) {
this.props.onAddPanel(embeddable.id);
}
};
private doTelemetryForAddEvent(

View file

@ -24,6 +24,7 @@ export function openAddPanelFlyout(options: {
showCreateNewMenu?: boolean;
reportUiCounter?: UsageCollectionStart['reportUiCounter'];
theme: ThemeServiceStart;
onAddPanel?: (id: string) => void;
}): OverlayRef {
const {
embeddable,
@ -35,11 +36,13 @@ export function openAddPanelFlyout(options: {
showCreateNewMenu,
reportUiCounter,
theme,
onAddPanel,
} = options;
const flyoutSession = overlays.openFlyout(
toMountPoint(
<AddPanelFlyout
container={embeddable}
onAddPanel={onAddPanel}
onClose={() => {
if (flyoutSession) {
flyoutSession.close();