Skip to content
Open
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
@@ -0,0 +1,5 @@
---
'@red-hat-developer-hub/backstage-plugin-global-floating-action-button': patch
---

allow custom fab component

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* 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 {
createContext,
PropsWithChildren,
useCallback,
useContext,
useState,
} from 'react';

import ChatIcon from '@mui/icons-material/Chat';
import CloseIcon from '@mui/icons-material/Close';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import Fab from '@mui/material/Fab';
import Tooltip from '@mui/material/Tooltip';

interface ChatPanelContextType {
isOpen: boolean;
togglePanel: () => void;
}

const ChatPanelContext = createContext<ChatPanelContextType | undefined>(
undefined,
);

const useChatPanel = () => {
const context = useContext(ChatPanelContext);
if (!context) {
throw new Error('useChatPanel must be used within ChatPanelProvider');
}
return context;
};

export const ChatPanelProvider = ({ children }: PropsWithChildren<{}>) => {
const [isOpen, setIsOpen] = useState(false);

const togglePanel = useCallback(() => {
setIsOpen(prev => !prev);
}, []);

return (
<ChatPanelContext.Provider value={{ isOpen, togglePanel }}>
{children}
{isOpen && (
<Typography
component="div"
style={{
position: 'fixed',
bottom: '80px',
right: '24px',
width: '350px',
height: '400px',
backgroundColor: 'white',
borderRadius: '8px',
boxShadow: '0 4px 20px rgba(0,0,0,0.15)',
zIndex: 1000,
display: 'flex',
flexDirection: 'column',
}}
>
<Typography
component="div"
style={{
padding: '16px',
borderBottom: '1px solid #eee',
fontWeight: 'bold',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Typography component="span">Chat Panel</Typography>
<Button size="small" onClick={togglePanel}>
Close
</Button>
</Typography>
<Typography
component="div"
style={{ flex: 1, padding: '16px', overflowY: 'auto' }}
>
<Typography component="p">This is a custom chat panel!</Typography>
<Typography component="p">
It demonstrates how a custom FAB component can manage its own
state through context.
</Typography>
<Typography
component="p"
style={{ color: '#666', fontSize: '14px' }}
>
Have a nice day !!
</Typography>
</Typography>
</Typography>
)}
</ChatPanelContext.Provider>
);
};

// Custom FAB Component
export const ChatFABComponent = () => {
const { isOpen, togglePanel } = useChatPanel();

return (
<Tooltip title={isOpen ? 'Close Chat' : 'Open Chat'} placement="left">
<Fab
size="small"
color={isOpen ? 'default' : 'primary'}
onClick={togglePanel}
aria-label={isOpen ? 'Close chat' : 'Open chat'}
sx={{
transition: 'all 0.3s ease',
}}
>
{isOpen ? <CloseIcon /> : <ChatIcon />}
</Fab>
</Tooltip>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
globalFloatingActionButtonPlugin,
globalFloatingActionButtonTranslations,
} from '../src';
import { ChatFABComponent, ChatPanelProvider } from './ChatbotComponent';

const mockFloatingButtons: FloatingActionButton[] = [
{
Expand Down Expand Up @@ -91,6 +92,14 @@ const mockFloatingButtons: FloatingActionButton[] = [
},
];

const mockFloatingButtonsWithCustomComponent: FloatingActionButton[] = [
{
label: 'Chat',
Component: ChatFABComponent,
priority: -1,
},
];

const createPage = ({
navTitle,
path,
Expand Down Expand Up @@ -200,4 +209,15 @@ createDevApp()
component: <ExampleComponent />,
}),
)
.addPage({
element: (
<ChatPanelProvider>
<ExampleComponent
floatingButtons={mockFloatingButtonsWithCustomComponent}
/>
</ChatPanelProvider>
),
title: 'Custom FAB Component',
path: '/test-custom-component-fab',
})
.render();
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
/// <reference types="react" />

import { BackstagePlugin } from '@backstage/core-plugin-api';
import { ComponentType } from 'react';
import { JSX as JSX_2 } from 'react/jsx-runtime';
import { TranslationRef } from '@backstage/core-plugin-api/alpha';
import { TranslationResource } from '@backstage/core-plugin-api/alpha';
Expand Down Expand Up @@ -50,6 +51,10 @@ export type FloatingActionButton = {
priority?: number;
visibleOnPaths?: string[];
excludeOnPaths?: string[];
isDisabled?: boolean;
disabledToolTip?: string;
disabledToolTipKey?: string;
Component?: ComponentType<any>;
};

// @public
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ const useStyles = makeStyles(() => ({
openInNew: { paddingBottom: '5px', paddingTop: '3px' },
}));

const isExternalUri = (uri: string) => /^([a-z+.-]+):/.test(uri);

const getIconOrder = (displayOnRight: boolean, isExternal: boolean) =>
displayOnRight
? { externalIcon: isExternal ? 1 : -1, icon: 3 }
: { externalIcon: isExternal ? 3 : -1, icon: 1 };

const getFabVariant = (
showLabel?: boolean,
isExternal?: boolean,
icon?: string | ReactElement,
): 'extended' | 'circular' =>
showLabel || isExternal || !icon ? 'extended' : 'circular';

const FABLabel = ({
label,
slot,
Expand All @@ -47,6 +61,7 @@ const FABLabel = ({
}) => {
const styles = useStyles();
const marginStyle = getSlotOptions(slot).margin;

return (
<>
{showExternalIcon && (
Expand Down Expand Up @@ -88,11 +103,15 @@ export const CustomFab = ({
t: TranslationFunction<typeof globalFloatingActionButtonTranslationRef.T>;
}) => {
const navigate = useNavigate();
const isExternalUri = (uri: string) => /^([a-z+.-]+):/.test(uri);
const isExternal = isExternalUri(actionButton.to!);
const newWindow = isExternal && !!/^https?:/.exec(actionButton.to!);
const navigateTo = () =>
actionButton.to && !isExternal ? navigate(actionButton.to) : '';

const isExternal = actionButton.to ? isExternalUri(actionButton.to) : false;
const newWindow = isExternal && /^https?:/.test(actionButton.to || '');

const navigateTo = () => {
if (actionButton.to && !isExternal) {
navigate(actionButton.to);
}
};

const resolvedLabel = getTranslatedTextWithFallback(
t,
Expand All @@ -107,6 +126,18 @@ export const CustomFab = ({
)
: undefined;

const resolvedDisabledTooltip = actionButton.disabledToolTip
? getTranslatedTextWithFallback(
t,
actionButton.disabledToolTipKey,
actionButton.disabledToolTip,
)
: undefined;

const currentTooltip = actionButton.isDisabled
? resolvedDisabledTooltip
: resolvedTooltip;

if (!resolvedLabel) {
// eslint-disable-next-line no-console
console.warn(
Expand All @@ -117,58 +148,54 @@ export const CustomFab = ({
}

const labelText =
(resolvedLabel || '').length > 20
resolvedLabel.length > 20
? `${resolvedLabel.slice(0, resolvedLabel.length)}...`
: resolvedLabel;

const getColor = () => {
if (actionButton.color) {
return actionButton.color;
}
return undefined;
};

const displayOnRight =
actionButton.slot === Slot.PAGE_END || !actionButton.slot;

const slot = actionButton.slot || Slot.PAGE_END;
const displayLabel =
actionButton.showLabel || !actionButton.icon ? labelText : '';

const fabElement = (
<Fab
{...(newWindow ? { target: '_blank', rel: 'noopener' } : {})}
className={className}
style={{
color: actionButton.iconColor || '#1f1f1f',
backgroundColor: actionButton.color ? '' : 'white',
}}
variant={getFabVariant(
actionButton.showLabel,
isExternal,
actionButton.icon,
)}
size={size || actionButton.size || 'medium'}
color={actionButton.color}
aria-label={resolvedLabel}
data-testid={resolvedLabel.replace(' ', '-').toLocaleLowerCase('en-US')}
onClick={actionButton.onClick || navigateTo}
disabled={actionButton.isDisabled}
{...(isExternal ? { href: actionButton.to } : {})}
>
<FABLabel
showExternalIcon={isExternal}
icon={actionButton.icon}
label={displayLabel}
order={getIconOrder(displayOnRight, isExternal)}
slot={slot}
/>
</Fab>
);

return (
<Tooltip
title={resolvedTooltip}
title={currentTooltip}
placement={getSlotOptions(actionButton.slot).tooltipDirection}
>
<Fab
{...(newWindow ? { target: '_blank', rel: 'noopener' } : {})}
className={className}
style={{
color: actionButton?.iconColor || '#1f1f1f',
backgroundColor: actionButton.color ? '' : 'white',
}}
variant={
actionButton.showLabel || isExternal || !actionButton.icon
? 'extended'
: 'circular'
}
size={size || actionButton.size || 'medium'}
color={getColor()}
aria-label={resolvedLabel}
data-testid={(resolvedLabel || '')
.replace(' ', '-')
.toLocaleLowerCase('en-US')}
onClick={actionButton.onClick || navigateTo}
{...(isExternal ? { href: actionButton.to } : {})}
>
<FABLabel
showExternalIcon={isExternal}
icon={actionButton.icon}
label={actionButton.showLabel || !actionButton.icon ? labelText : ''}
order={
displayOnRight
? { externalIcon: isExternal ? 1 : -1, icon: 3 }
: { externalIcon: isExternal ? 3 : -1, icon: 1 }
}
slot={actionButton.slot || Slot.PAGE_END}
/>
</Fab>
{fabElement}
</Tooltip>
);
};
Loading