Skip to content

Commit 8dbab91

Browse files
authored
Anchor tabbed modal using only CSS (#237431)
## Summary This PR switches the implementation to anchor the tabbed modals to a pure CSS solution, this solution had been suggested [previously](#189399 (review)) however at the time it wasn't apparent we could leverage the `Global` component from emotion, to coordinate insert and removing styles global styles. https://github.com/user-attachments/assets/cb67afea-a63f-40d1-9789-60ea3d99c363 <!-- ### Checklist Check the PR satisfies following conditions. Reviewers should verify this PR satisfies this list as well. - [ ] 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/src/platform/packages/shared/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 - [ ] 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 was checked for breaking HTTP API changes, and any breaking changes have been approved by the breaking-change committee. The `release_note:breaking` label should be applied in these situations. - [ ] [Flaky Test Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was used on any tests changed - [ ] The PR description includes the appropriate Release Notes section, and the correct `release_note:*` label is applied per the [guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process) - [ ] Review the [backport guidelines](https://docs.google.com/document/d/1VyN5k91e5OVumlc0Gb9RPa3h1ewuPE705nRtioPiTvY/edit?usp=sharing) and apply applicable `backport:*` labels. ### Identify risks Does this PR introduce any risks? For example, consider risks like hard to test bugs, performance regression, potential of data loss. Describe the risk, its severity, and mitigation for each identified risk. Invite stakeholders and evaluate how to proceed before merging. - [ ] [See some risk examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) - [ ] ... -->
1 parent 20d1040 commit 8dbab91

File tree

2 files changed

+87
-102
lines changed

2 files changed

+87
-102
lines changed

src/platform/packages/shared/shared-ux/modal/tabbed/src/tabbed_modal.test.tsx

Lines changed: 65 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -16,49 +16,73 @@ import { TabbedModal, type IModalTabDeclaration } from './tabbed_modal';
1616
describe('TabbedModal', () => {
1717
const modalOnCloseHandler = jest.fn();
1818

19+
interface TabState {
20+
inputText: string;
21+
}
22+
23+
const getTabDefinition = (
24+
actionHandlerFn: (args: { state: TabState }) => void
25+
): IModalTabDeclaration<TabState> => ({
26+
id: 'logUserInput',
27+
name: 'log user input',
28+
reducer(state = { inputText: '' }, action) {
29+
switch (action.type) {
30+
case 'UPDATE_TEXT_VALUE':
31+
return {
32+
...state,
33+
inputText: action.payload,
34+
};
35+
default:
36+
return state;
37+
}
38+
},
39+
content: ({ state, dispatch }) => {
40+
const onChange = (e: { target: { value: any } }) => {
41+
dispatch({ type: 'UPDATE_TEXT_VALUE', payload: e.target.value });
42+
};
43+
44+
return (
45+
<EuiFieldText
46+
data-test-subj="log-user-input-field"
47+
placeholder="Placeholder text"
48+
value={state.inputText}
49+
onChange={onChange}
50+
aria-label="Use aria labels when no actual label is in use"
51+
/>
52+
);
53+
},
54+
modalActionBtn: {
55+
id: 'logUserMessage',
56+
dataTestSubj: 'log-user-message',
57+
label: 'log user message',
58+
handler: actionHandlerFn,
59+
},
60+
});
61+
62+
it('renders correctly', () => {
63+
const tabDefinition = getTabDefinition(jest.fn());
64+
65+
render(
66+
<TabbedModal
67+
tabs={[tabDefinition]}
68+
defaultSelectedTabId="logUserInput"
69+
onClose={modalOnCloseHandler}
70+
/>
71+
);
72+
73+
// we assert this value exists because we target this className to override some styles
74+
const overlayMask = document.querySelector('.euiOverlayMask');
75+
76+
expect(overlayMask).toBeInTheDocument();
77+
expect(overlayMask?.querySelector('[id^="tabbedModal"]')).toBeInTheDocument();
78+
});
79+
1980
describe('modal configuration', () => {
2081
const mockedHandlerFn = jest.fn();
2182

22-
const tabDefinition: IModalTabDeclaration<{
23-
inputText: string;
24-
}> = {
25-
id: 'logUserInput',
26-
name: 'log user input',
27-
reducer(state = { inputText: '' }, action) {
28-
switch (action.type) {
29-
case 'UPDATE_TEXT_VALUE':
30-
return {
31-
...state,
32-
inputText: action.payload,
33-
};
34-
default:
35-
return state;
36-
}
37-
},
38-
content: ({ state, dispatch }) => {
39-
const onChange = (e: { target: { value: any } }) => {
40-
dispatch({ type: 'UPDATE_TEXT_VALUE', payload: e.target.value });
41-
};
42-
43-
return (
44-
<EuiFieldText
45-
data-test-subj="log-user-input-field"
46-
placeholder="Placeholder text"
47-
value={state.inputText}
48-
onChange={onChange}
49-
aria-label="Use aria labels when no actual label is in use"
50-
/>
51-
);
52-
},
53-
modalActionBtn: {
54-
id: 'logUserMessage',
55-
dataTestSubj: 'log-user-message',
56-
label: 'log user message',
57-
handler: mockedHandlerFn,
58-
},
59-
};
60-
6183
it("when a single tab definition is passed it simply renders it's content into the modal component without tabs", async () => {
84+
const tabDefinition = getTabDefinition(mockedHandlerFn);
85+
6286
render(
6387
<TabbedModal
6488
tabs={[tabDefinition]}
@@ -77,6 +101,8 @@ describe('TabbedModal', () => {
77101
});
78102

79103
it('renders the tabbed modal with tabs for tab definition with length greater than 1', async () => {
104+
const tabDefinition = getTabDefinition(mockedHandlerFn);
105+
80106
render(
81107
<TabbedModal
82108
tabs={[tabDefinition, { ...tabDefinition, id: 'anotherTab', name: 'another tab' }]}

src/platform/packages/shared/shared-ux/modal/tabbed/src/tabbed_modal.tsx

Lines changed: 22 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,14 @@
88
*/
99

1010
import React, {
11-
useRef,
1211
useMemo,
13-
useState,
14-
useLayoutEffect,
1512
useCallback,
1613
Fragment,
1714
type ComponentProps,
1815
type FC,
1916
type ReactElement,
2017
} from 'react';
18+
import { Global } from '@emotion/react';
2119
import {
2220
EuiButton,
2321
EuiModal,
@@ -77,38 +75,9 @@ const TabbedModalInner: FC<ITabbedModalInner> = ({
7775
}) => {
7876
const { tabs, state, dispatch } =
7977
useModalContext<Array<IModalTabDeclaration<Record<string, any>>>>();
80-
const { selectedTabId, defaultSelectedTabId } = state.meta;
78+
const { selectedTabId } = state.meta;
8179
const tabbedModalHTMLId = useGeneratedHtmlId({ prefix: 'tabbedModal' });
82-
const tabbedModalHeadingHTMLId = useGeneratedHtmlId({ prefix: 'tabbedModal' });
83-
const defaultTabCoordinates = useRef(new Map<string, Pick<DOMRect, 'top'>>());
84-
const [translateYValue, setTranslateYValue] = useState(0);
85-
86-
const onTabContentRender = useCallback(() => {
87-
const tabbedModal = document.querySelector(`[id="${tabbedModalHTMLId}"]`) as HTMLDivElement;
88-
89-
if (!defaultTabCoordinates.current.get(defaultSelectedTabId)) {
90-
// on initial render the modal animates into it's final position
91-
// hence the need to wait till said animation has completed
92-
tabbedModal.onanimationend = () => {
93-
const { top } = tabbedModal.getBoundingClientRect();
94-
defaultTabCoordinates.current.set(defaultSelectedTabId, { top });
95-
};
96-
} else {
97-
let translateYOverride = 0;
98-
99-
if (defaultSelectedTabId !== selectedTabId) {
100-
const defaultTabData = defaultTabCoordinates.current.get(defaultSelectedTabId);
101-
102-
const rect = tabbedModal.getBoundingClientRect();
103-
104-
translateYOverride = translateYValue + (defaultTabData?.top! - rect.top);
105-
}
106-
107-
if (translateYOverride !== translateYValue) {
108-
setTranslateYValue(translateYOverride);
109-
}
110-
}
111-
}, [tabbedModalHTMLId, defaultSelectedTabId, selectedTabId, translateYValue]);
80+
const tabbedModalHeadingHTMLId = useGeneratedHtmlId({ prefix: 'tabbedModalHeading' });
11281

11382
const selectedTabState = useMemo(
11483
() => (selectedTabId ? state[selectedTabId] : {}),
@@ -152,12 +121,6 @@ const TabbedModalInner: FC<ITabbedModalInner> = ({
152121
);
153122
}, [onSelectedTabChanged, selectedTabId, tabs]);
154123

155-
const modalPositionOverrideStyles: React.CSSProperties = {
156-
transform: `translateY(${translateYValue}px)`,
157-
transformOrigin: 'top',
158-
willChange: 'transform',
159-
};
160-
161124
return (
162125
<EuiModal
163126
id={tabbedModalHTMLId}
@@ -169,36 +132,32 @@ const TabbedModalInner: FC<ITabbedModalInner> = ({
169132
data-test-subj={props['data-test-subj']}
170133
css={{
171134
...(modalWidth ? { width: modalWidth } : {}),
172-
...modalPositionOverrideStyles,
173135
}}
174136
aria-labelledby={tabbedModalHeadingHTMLId}
175137
>
138+
<Global
139+
styles={{
140+
// overrides so modal retains a fixed position from top of viewport, despite having content of varying heights
141+
[`.euiOverlayMask:has([id="${tabbedModalHTMLId}"])`]: {
142+
alignItems: 'flex-start',
143+
paddingBlockStart: '20vh',
144+
},
145+
}}
146+
/>
176147
<EuiModalHeader>
177148
<EuiModalHeaderTitle id={tabbedModalHeadingHTMLId}>{modalTitle}</EuiModalHeaderTitle>
178149
</EuiModalHeader>
179150
<EuiModalBody>
180-
<Fragment>
181-
<Fragment>{renderTabs()}</Fragment>
182-
<EuiSpacer size="m" />
183-
{React.createElement(function RenderSelectedTabContent() {
184-
useLayoutEffect(() => {
185-
requestAnimationFrame(onTabContentRender);
186-
}, []);
187-
return (
188-
<div
189-
css={{ display: 'contents' }}
190-
data-test-subj={`tabbedModal-${selectedTabId}-content`}
191-
>
192-
<SelectedTabContent
193-
{...{
194-
state: selectedTabState,
195-
dispatch,
196-
}}
197-
/>
198-
</div>
199-
);
200-
})}
201-
</Fragment>
151+
<Fragment>{renderTabs()}</Fragment>
152+
<EuiSpacer size="m" />
153+
<div css={{ display: 'contents' }} data-test-subj={`tabbedModal-${selectedTabId}-content`}>
154+
<SelectedTabContent
155+
{...{
156+
state: selectedTabState,
157+
dispatch,
158+
}}
159+
/>
160+
</div>
202161
</EuiModalBody>
203162
{modalActionBtn?.id !== undefined && selectedTabState && (
204163
<EuiModalFooter>

0 commit comments

Comments
 (0)