Anchor tabbed modal on tab interaction (#189399)

## Summary

Closes https://github.com/elastic/kibana/issues/189143


This PR introduces changes to address issues with the share modal
getting repositioned when the tabs of the modals get clicked. The
approach here is to cache the coordinates of the tab set as the default
to display and then use said coordinates to position the modal on
subsequent transitions to other tabs.

**Notable mention;**
Given the approach that's been taken to solve this issue, when a tab's
content is lengthy that tab should be favoured as the default so that
tab anchors other tabs.

### Visuals



https://github.com/user-attachments/assets/31951a84-24e1-4d38-8136-b88720b82b23




<!--
### 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
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] 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&mdash;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&mdash;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)
-->
This commit is contained in:
Eyo O. Eyo 2024-07-30 16:39:45 +02:00 committed by GitHub
parent 9e23a0ad06
commit e37995c9c6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 110 additions and 56 deletions

View file

@ -26,7 +26,8 @@ interface IDispatchAction {
export type IDispatchFunction = Dispatch<IDispatchAction>;
export interface IMetaState {
selectedTabId: string | null;
defaultSelectedTabId: string;
selectedTabId: string;
}
type IReducer<S> = (state: S, action: IDispatchAction) => S;
@ -52,7 +53,8 @@ const createStateContext = once(<T extends Array<ITabDeclaration<Record<string,
tabs: [],
state: {
meta: {
selectedTabId: null,
defaultSelectedTabId: '',
selectedTabId: '',
},
},
dispatch: () => {},
@ -104,6 +106,7 @@ export function ModalContextProvider<T extends Array<ITabDeclaration<Record<stri
const initialModalState = useRef<IModalInstanceContext['state']>({
// instantiate state with default meta information
meta: {
defaultSelectedTabId,
selectedTabId: defaultSelectedTabId,
},
});

View file

@ -7,7 +7,10 @@
*/
import React, {
useRef,
useMemo,
useState,
useLayoutEffect,
useCallback,
Fragment,
type ComponentProps,
@ -26,6 +29,7 @@ import {
type EuiTabProps,
type CommonProps,
useGeneratedHtmlId,
EuiSpacer,
} from '@elastic/eui';
import {
ModalContextProvider,
@ -60,6 +64,7 @@ export interface ITabbedModalInner extends Pick<ComponentProps<typeof EuiModal>,
modalWidth?: number;
modalTitle?: string;
anchorElement?: HTMLElement;
'data-test-subj'?: string;
}
const TabbedModalInner: FC<ITabbedModalInner> = ({
@ -67,11 +72,42 @@ const TabbedModalInner: FC<ITabbedModalInner> = ({
modalTitle,
modalWidth,
anchorElement,
...props
}) => {
const { tabs, state, dispatch } =
useModalContext<Array<IModalTabDeclaration<Record<string, any>>>>();
const selectedTabId = state.meta.selectedTabId;
const shareModalHeadingId = useGeneratedHtmlId();
const { selectedTabId, defaultSelectedTabId } = state.meta;
const tabbedModalHTMLId = useGeneratedHtmlId();
const tabbedModalHeadingHTMLId = useGeneratedHtmlId();
const defaultTabCoordinates = useRef(new Map<string, Pick<DOMRect, 'top'>>());
const [translateYValue, setTranslateYValue] = useState(0);
const onTabContentRender = useCallback(() => {
const tabbedModal = document.querySelector(`#${tabbedModalHTMLId}`) as HTMLDivElement;
if (!defaultTabCoordinates.current.get(defaultSelectedTabId)) {
// on initial render the modal animates into it's final position
// hence the need to wait till said animation has completed
tabbedModal.onanimationend = () => {
const { top } = tabbedModal.getBoundingClientRect();
defaultTabCoordinates.current.set(defaultSelectedTabId, { top });
};
} else {
let translateYOverride = 0;
if (defaultSelectedTabId !== selectedTabId) {
const defaultTabData = defaultTabCoordinates.current.get(defaultSelectedTabId);
const rect = tabbedModal.getBoundingClientRect();
translateYOverride = translateYValue + (defaultTabData?.top! - rect.top);
}
if (translateYOverride !== translateYValue) {
setTranslateYValue(translateYOverride);
}
}
}, [tabbedModalHTMLId, defaultSelectedTabId, selectedTabId, translateYValue]);
const selectedTabState = useMemo(
() => (selectedTabId ? state[selectedTabId] : {}),
@ -107,26 +143,44 @@ const TabbedModalInner: FC<ITabbedModalInner> = ({
});
}, [onSelectedTabChanged, selectedTabId, tabs]);
const modalPositionOverrideStyles: React.CSSProperties = {
transform: `translateY(${translateYValue}px)`,
transformOrigin: 'top',
willChange: 'transform',
};
return (
<EuiModal
id={tabbedModalHTMLId}
onClose={() => {
onClose();
setTimeout(() => anchorElement?.focus(), 1);
}}
style={{ ...(modalWidth ? { width: modalWidth } : {}) }}
maxWidth={true}
data-test-subj="shareContextModal"
aria-labelledby={shareModalHeadingId}
data-test-subj={props['data-test-subj']}
css={{
...(modalWidth ? { width: modalWidth } : {}),
...modalPositionOverrideStyles,
}}
aria-labelledby={tabbedModalHeadingHTMLId}
>
<EuiModalHeader>
<EuiModalHeaderTitle id={shareModalHeadingId}>{modalTitle}</EuiModalHeaderTitle>
<EuiModalHeaderTitle id={tabbedModalHeadingHTMLId}>{modalTitle}</EuiModalHeaderTitle>
</EuiModalHeader>
<EuiModalBody>
<Fragment>
<EuiTabs>{renderTabs()}</EuiTabs>
{React.createElement(SelectedTabContent, {
state: selectedTabState,
dispatch,
<EuiSpacer size="m" />
{React.createElement(function RenderSelectedTabContent() {
useLayoutEffect(onTabContentRender, []);
return (
<SelectedTabContent
{...{
state: selectedTabState,
dispatch,
}}
/>
);
})}
</Fragment>
</EuiModalBody>

View file

@ -53,6 +53,7 @@ export const ShareMenuTabs = () => {
modalTitle={objectTypeMeta.title}
defaultSelectedTabId="link"
anchorElement={anchorElement}
data-test-subj="shareContextModal"
/>
);
};

View file

@ -246,7 +246,6 @@ export const EmbedContent = ({
return (
<>
<EuiForm>
<EuiSpacer size="m" />
<EuiText size="s">{helpText}</EuiText>
<EuiSpacer />
{renderUrlParamExtensions()}

View file

@ -218,7 +218,6 @@ const ExportContentUi = ({
return (
<>
<EuiForm>
<EuiSpacer size="l" />
<>{helpText}</>
<EuiSpacer size="m" />
<>{renderRadioOptions()}</>

View file

@ -122,7 +122,6 @@ export const LinkContent = ({
return (
<>
<EuiForm>
<EuiSpacer size="m" />
<EuiText size="s">
<FormattedMessage
id="share.link.helpText"

View file

@ -9,7 +9,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { toMountPoint } from '@kbn/react-kibana-mount';
import { CoreStart, OverlayStart, ThemeServiceStart, ToastsSetup } from '@kbn/core/public';
import { CoreStart, ThemeServiceStart, ToastsSetup } from '@kbn/core/public';
import { ShareMenuItem, ShowShareMenuOptions } from '../types';
import { ShareMenuRegistryStart } from './share_menu_registry';
import { AnonymousAccessServiceContract } from '../../common/anonymous_access';
@ -49,7 +49,6 @@ export class ShareMenuManager {
urlService,
anonymousAccess,
theme: core.theme,
overlays: core.overlays,
i18n: core.i18n,
toasts: core.notifications.toasts,
publicAPIEnabled: !disableEmbed,
@ -82,7 +81,6 @@ export class ShareMenuManager {
snapshotShareWarning,
onClose,
disabledShareUrl,
overlays,
i18n,
isDirty,
toasts,
@ -95,7 +93,6 @@ export class ShareMenuManager {
anonymousAccess: AnonymousAccessServiceContract | undefined;
theme: ThemeServiceStart;
onClose: () => void;
overlays: OverlayStart;
i18n: CoreStart['i18n'];
isDirty: boolean;
toasts: ToastsSetup;
@ -105,47 +102,49 @@ export class ShareMenuManager {
return;
}
this.isOpen = true;
document.body.appendChild(this.container);
// initialize variable that will hold reference for unmount
let unmount: ReturnType<ReturnType<typeof toMountPoint>>;
const mount = toMountPoint(
<ShareMenu
shareContext={{
publicAPIEnabled,
anchorElement,
allowEmbed,
allowShortUrl,
objectId,
objectType,
objectTypeMeta,
sharingData,
shareableUrl,
shareableUrlLocatorParams,
delegatedShareUrlHandler,
embedUrlParamExtensions,
anonymousAccess,
showPublicUrlSwitch,
urlService,
snapshotShareWarning,
disabledShareUrl,
isDirty,
isEmbedded: allowEmbed,
shareMenuItems: menuItems,
toasts,
onClose: () => {
onClose();
unmount();
},
theme,
i18n,
}}
/>,
{ i18n, theme }
);
const openModal = () => {
const session = overlays.openModal(
toMountPoint(
<ShareMenu
shareContext={{
publicAPIEnabled,
anchorElement,
allowEmbed,
allowShortUrl,
objectId,
objectType,
objectTypeMeta,
sharingData,
shareableUrl,
shareableUrlLocatorParams,
delegatedShareUrlHandler,
embedUrlParamExtensions,
anonymousAccess,
showPublicUrlSwitch,
urlService,
snapshotShareWarning,
disabledShareUrl,
isDirty,
isEmbedded: allowEmbed,
shareMenuItems: menuItems,
toasts,
onClose: () => {
onClose();
session.close();
},
theme,
i18n,
}}
/>,
{ i18n, theme }
),
{ 'data-test-subj': 'share-modal' }
);
unmount = mount(this.container);
this.isOpen = true;
};
// @ts-ignore openModal() returns void