Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ const useStyles = makeStyles(theme => ({
right: `calc(${theme?.spacing?.(2) ?? '16px'} + 1.5em)`,
alignItems: 'end',

// When quickstart drawer is open, adjust margin
'.quickstart-drawer-open &': {
// When drawer is docked, adjust margin
'.docked-drawer-open &': {
transition: 'margin-right 0.3s ease',
marginRight: 'var(--quickstart-drawer-width, 500px) ',
marginRight: 'var(--docked-drawer-width, 500px) ',
},
},
'bottom-left': {
Expand Down
2 changes: 2 additions & 0 deletions workspaces/quickstart/packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@
"@material-ui/icons": "^4.9.1",
"@mui/icons-material": "5.18.0",
"@mui/material": "5.18.0",
"@red-hat-developer-hub/backstage-plugin-application-drawer": "workspace:^",
"@red-hat-developer-hub/backstage-plugin-global-header": "^1.17.1",
"@red-hat-developer-hub/backstage-plugin-quickstart": "workspace:^",
"@red-hat-developer-hub/backstage-plugin-test-drawer": "workspace:^",
"@red-hat-developer-hub/backstage-plugin-theme": "^0.11.0",
"react": "^18.0.2",
"react-dom": "^18.0.2",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
/*
* Copyright Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {
ComponentType,
useState,
useCallback,
useMemo,
useEffect,
} from 'react';
import { ResizableDrawer } from './ResizableDrawer';

/**
* Partial drawer state exposed by drawer plugins
*
* @public
*/
export interface DrawerPartialState {
id: string;
isDrawerOpen: boolean;
drawerWidth: number;
setDrawerWidth: (width: number) => void;
}

/**
* Props for drawer state exposer components
*
* @public
*/
export interface DrawerStateExposerProps {
onStateChange: (state: DrawerPartialState) => void;
onUnmount?: (id: string) => void;
}

/**
* Drawer content configuration
*/
type DrawerContentType = {
id: string;
Component: ComponentType<any>;
priority?: number;
resizable?: boolean;
};

/**
* State exposer component type
*/
type StateExposerType = {
Component: ComponentType<DrawerStateExposerProps>;
};

export interface ApplicationDrawerProps {
/**
* Array of drawer content configurations
* Maps drawer IDs to their content components
*/
drawerContents: DrawerContentType[];
/**
* Array of state exposer components from drawer plugins
* These are typically mounted via `application/drawer-state` mount point
*
* In RHDH dynamic plugins, this would come from:
* ```yaml
* mountPoints:
* - mountPoint: application/drawer-state
* importName: TestDrawerStateExposer
* ```
*/
stateExposers?: StateExposerType[];
}

export const ApplicationDrawer = ({
drawerContents,
stateExposers = [],
}: ApplicationDrawerProps) => {
// Collect drawer states from all state exposers
const [drawerStates, setDrawerStates] = useState<
Record<string, DrawerPartialState>
>({});

// Callback for state exposers to report their state
const handleStateChange = useCallback((state: DrawerPartialState) => {
setDrawerStates(prev => {
// Only update if something actually changed
const existing = prev[state.id];
if (
existing &&
existing.isDrawerOpen === state.isDrawerOpen &&
existing.drawerWidth === state.drawerWidth &&
existing.setDrawerWidth === state.setDrawerWidth
) {
return prev;
}
return { ...prev, [state.id]: state };
});
}, []);

// Convert states record to array
const statesArray = useMemo(
() => Object.values(drawerStates),
[drawerStates],
);

// Get active drawer - find the open drawer with highest priority
const activeDrawer = useMemo(() => {
return statesArray
.filter(state => state.isDrawerOpen)
.map(state => {
const content = drawerContents.find(c => c.id === state.id);
if (!content) return null;
return { ...state, ...content };
})
.filter(Boolean)
.sort((a, b) => (b?.priority ?? -1) - (a?.priority ?? -1))[0];
}, [statesArray, drawerContents]);

// Manage CSS classes and variables for layout adjustments
useEffect(() => {
if (activeDrawer) {
const className = `docked-drawer-open`;
const cssVar = `--docked-drawer-width`;

document.body.classList.add(className);
document.body.style.setProperty(cssVar, `${activeDrawer.drawerWidth}px`);

return () => {
document.body.classList.remove(className);
document.body.style.removeProperty(cssVar);
};
}
return undefined;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeDrawer?.id, activeDrawer?.drawerWidth]);

// Wrapper to handle the width change callback type
const handleWidthChange = useCallback(
(width: number) => {
activeDrawer?.setDrawerWidth(width);
},
[activeDrawer],
);

return (
<>
{/* Render all state exposers - they return null but report their state */}
{stateExposers.map(({ Component }, index) => (
<Component key={index} onStateChange={handleStateChange} />
))}

{/* Render the active drawer */}
{activeDrawer && (
<ResizableDrawer
isDrawerOpen
isResizable={activeDrawer.resizable}
drawerWidth={activeDrawer.drawerWidth}
onWidthChange={handleWidthChange}
>
<activeDrawer.Component />
</ResizableDrawer>
)}
</>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/*
* Copyright Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { useCallback, useEffect, useRef, useState } from 'react';

import Box from '@mui/material/Box';
import Drawer from '@mui/material/Drawer';
import { styled } from '@mui/material/styles';

import { ThemeConfig } from '@red-hat-developer-hub/backstage-plugin-theme';

const Handle = styled('div')(({ theme }) => ({
width: 6,
cursor: 'col-resize',
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
zIndex: 1201,
backgroundColor: theme.palette.divider,
}));

export type ResizableDrawerProps = {
children: React.ReactNode;
minWidth?: number;
maxWidth?: number;
initialWidth?: number;
isDrawerOpen: boolean;
drawerWidth?: number;
onWidthChange?: (width: number) => void;
isResizable?: boolean;
[key: string]: any;
};

export const ResizableDrawer = (props: ResizableDrawerProps) => {
const {
children,
minWidth = 400,
maxWidth = 800,
initialWidth = 400,
isDrawerOpen,
isResizable = false,
drawerWidth: externalDrawerWidth,
onWidthChange,
...drawerProps
} = props;

// Ensure width is never below minWidth
const clampedInitialWidth = Math.max(
externalDrawerWidth || initialWidth,
minWidth,
);

const [width, setWidth] = useState(clampedInitialWidth);
const resizingRef = useRef(false);

// Sync with external drawerWidth when it changes
useEffect(() => {
if (externalDrawerWidth !== undefined) {
const clampedWidth = Math.max(externalDrawerWidth, minWidth);
if (clampedWidth !== width) {
setWidth(clampedWidth);
// If the external width was below min, update the parent
if (externalDrawerWidth < minWidth && onWidthChange && isResizable) {
onWidthChange(clampedWidth);
}
}
}
}, [externalDrawerWidth, width, minWidth, onWidthChange, isResizable]);

const onMouseDown = () => {
resizingRef.current = true;
};

const onMouseMove = useCallback(
(e: MouseEvent) => {
if (!resizingRef.current) return;
// For right-anchored drawer, calculate width from the right edge
const newWidth = window.innerWidth - e.clientX;

if (newWidth >= minWidth && newWidth <= maxWidth) {
setWidth(newWidth);
if (onWidthChange) {
onWidthChange(newWidth);
}
}
},
[maxWidth, minWidth, onWidthChange],
);

const onMouseUp = () => {
resizingRef.current = false;
};

useEffect(() => {
if (isResizable) {
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
return () => {
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
};
}
return () => {};
}, [onMouseMove, isResizable]);

// Ensure anchor is always 'right' and not overridden by drawerProps
const { anchor: _, ...restDrawerProps } = drawerProps;

return (
<Drawer
{...restDrawerProps}
anchor="right"
sx={{
'& .v5-MuiDrawer-paper': {
width: width,
boxSizing: 'border-box',
backgroundColor: theme => {
const themeConfig = theme as ThemeConfig;
return (
themeConfig.palette?.rhdh?.general?.sidebarBackgroundColor ||
theme.palette.background.paper
);
},
justifyContent: 'space-between',
},
// Only apply header offset when global header exists
'body:has(#global-header) &': {
'& .v5-MuiDrawer-paper': {
top: '64px !important',
height: 'calc(100vh - 64px) !important',
},
},
}}
variant="persistent"
open={isDrawerOpen}
>
<Box sx={{ height: '100%', position: 'relative' }}>
{children}
{isResizable && <Handle onMouseDown={onMouseDown} />}
</Box>
</Drawer>
);
};
Loading
Loading