From 6dd28514deee3781ad17cc5bffb5348cd616a8ec Mon Sep 17 00:00:00 2001 From: Debsmita Santra Date: Thu, 12 Nov 2026 22:40:52 +0530 Subject: [PATCH 1/5] feat(app-defaults): migrate global-header plugin into app-defaults --- .../split-global-header-extensions.md | 21 + .../app-defaults/packages/app/package.json | 1 - .../app-defaults/packages/app/src/App.tsx | 11 +- .../drawer-demo/HelpDrawerMenuItem.tsx | 4 +- .../app/src/modules/drawer-demo/index.tsx | 12 +- .../plugins/app-defaults/README.md | 169 ++++++- .../plugins/app-defaults/config.d.ts | 68 +++ .../plugins/app-defaults/package.json | 22 +- .../report-global-header-components.api.md | 76 +++ .../report-global-header-module.api.md | 13 + ...t-global-header-translations-module.api.md | 13 + .../plugins/app-defaults/report.api.md | 419 ++++++++++++++++ .../ApplicationLauncherDropdown.tsx | 52 ++ .../CompanyLogo/CompanyLogo.test.tsx | 119 +++++ .../components/CompanyLogo/CompanyLogo.tsx | 130 +++++ .../CompanyLogo/RedHatDeveloperHubLogo.tsx | 99 ++++ .../components/Divider/Divider.test.tsx | 27 + .../components/Divider/Divider.tsx | 38 ++ .../components/GlobalHeader.test.tsx | 99 ++++ .../global-header/components/GlobalHeader.tsx | 123 +++++ .../components/GlobalHeaderDropdown.test.tsx | 474 ++++++++++++++++++ .../components/GlobalHeaderDropdown.tsx | 221 ++++++++ .../GlobalHeaderDropdownContent.test.tsx | 145 ++++++ .../GlobalHeaderDropdownContent.tsx | 82 +++ .../components/GlobalHeaderMenuItem.tsx | 104 ++++ .../HeaderButton/HeaderButton.test.tsx | 46 ++ .../components/HeaderButton/HeaderButton.tsx | 83 +++ .../DropdownEmptyState.tsx | 71 +++ .../DropdownMenuLoading.tsx | 37 ++ .../HeaderDropdownComponent.test.tsx | 152 ++++++ .../HeaderDropdownComponent.tsx | 166 ++++++ .../HeaderDropdownComponent/MenuSection.tsx | 163 ++++++ .../StarredDropdown.test.tsx | 178 +++++++ .../StarredDropdown.tsx | 65 +++ .../StarredDropdownMenu.tsx | 155 ++++++ .../components/HeaderIcon/HeaderIcon.test.tsx | 77 +++ .../components/HeaderIcon/HeaderIcon.tsx | 93 ++++ .../HeaderIconButton/HeaderIconButton.tsx | 96 ++++ .../global-header/components/HelpDropdown.tsx | 51 ++ .../components/LogoutButton/LogoutButton.tsx | 61 +++ .../components/MenuItemLink/MenuItemLink.tsx | 73 +++ .../MenuItemLink/MenuItemLinkContent.tsx | 103 ++++ .../components/MyProfileMenuItem.tsx | 87 ++++ .../components/NotificationBanner.tsx | 126 +++++ .../NotificationButton.test.tsx | 78 +++ .../NotificationButton/NotificationButton.tsx | 106 ++++ .../components/ProfileDropdown.tsx | 134 +++++ .../SearchComponent/SearchBar.module.css | 12 + .../SearchComponent/SearchBar.test.tsx | 207 ++++++++ .../components/SearchComponent/SearchBar.tsx | 151 ++++++ .../SearchComponent/SearchComponent.test.tsx | 99 ++++ .../SearchComponent/SearchComponent.tsx | 41 ++ .../SearchComponent/SearchInput.test.tsx | 63 +++ .../SearchComponent/SearchInput.tsx | 58 +++ .../SearchComponent/SearchOption.test.tsx | 102 ++++ .../SearchComponent/SearchOption.tsx | 85 ++++ .../SearchComponent/SearchResultItem.test.tsx | 137 +++++ .../SearchComponent/SearchResultItem.tsx | 77 +++ .../components/Spacer/Spacer.test.tsx | 56 +++ .../components/Spacer/Spacer.tsx | 44 ++ .../SupportButton/SupportButton.test.tsx | 126 +++++ .../SupportButton/SupportButton.tsx | 84 ++++ .../src/global-header/components/Trans.tsx | 35 ++ .../components/criticalHeaderBundle.ts | 46 ++ .../globalHeaderDialogOffset.test.ts | 51 ++ .../components/globalHeaderDialogOffset.ts | 62 +++ .../src/global-header/components/loaders.ts | 71 +++ .../src/global-header/componentsExport.ts | 62 +++ .../global-header/configureMuiClassName.ts | 26 + .../src/global-header/defaults/index.ts | 70 +++ .../defaults/menuItemExtensions.tsx | 121 +++++ .../defaults/toolbarExtensions.tsx | 137 +++++ .../extensions/globalHeaderModule.tsx | 149 ++++++ .../global-header/globalHeaderModuleExport.ts | 16 + .../globalHeaderTranslationsModule.tsx | 36 ++ .../globalHeaderTranslationsModuleExport.ts | 17 + .../src/global-header/hooks/index.ts | 20 + .../hooks/useDebouncedCallback.ts | 43 ++ .../global-header/hooks/useDropdownManager.ts | 45 ++ .../src/global-header/hooks/useLanguage.ts | 25 + .../hooks/useNotificationCount.ts | 75 +++ .../hooks/useRetainMenuContent.ts | 42 ++ .../src/global-header/hooks/useTranslation.ts | 26 + .../hooks/useValidComponentTracker.ts | 58 +++ .../icons/ShapesOutlinedIcon.tsx | 27 + .../icons/globalHeaderSystemIcons.tsx | 51 ++ .../global-header/icons/headerToolbarIcon.ts | 22 + .../src/global-header/icons/remixIconSize.ts | 34 ++ .../app-defaults/src/global-header/plugin.ts | 66 +++ .../test-utils/mockTranslations.ts | 72 +++ .../src/global-header/translations/de.ts | 70 +++ .../src/global-header/translations/es.ts | 70 +++ .../src/global-header/translations/fr.ts | 69 +++ .../src/global-header/translations/index.ts | 36 ++ .../src/global-header/translations/it.ts | 69 +++ .../src/global-header/translations/ja.ts | 71 +++ .../src/global-header/translations/ref.ts | 88 ++++ .../utils/menuItemGrouping.test.ts | 176 +++++++ .../global-header/utils/menuItemGrouping.ts | 99 ++++ .../utils/readConfigComponents.test.tsx | 83 +++ .../utils/readConfigComponents.tsx | 71 +++ .../utils/readConfigMenuItems.test.ts | 102 ++++ .../utils/readConfigMenuItems.ts | 44 ++ .../utils/resolveDataDrivenComponents.tsx | 113 +++++ .../global-header/utils/stringUtils.test.tsx | 62 +++ .../src/global-header/utils/stringUtils.tsx | 62 +++ .../global-header/utils/translationUtils.ts | 37 ++ .../plugins/app-defaults/src/index.ts | 23 +- .../app-defaults/plugins/app-react/README.md | 26 + .../plugins/app-react/report.api.md | 158 ++++++ .../GlobalHeaderComponentBlueprint.ts | 144 ++++++ .../extensions/GlobalHeaderContext.test.tsx | 79 +++ .../extensions/GlobalHeaderContext.tsx | 110 ++++ .../GlobalHeaderMenuItemBlueprint.ts | 162 ++++++ .../src/globalHeader/extensions/dataRefs.ts | 44 ++ .../extensions/resolveExtensionComponent.tsx | 54 ++ .../app-react/src/globalHeader/index.ts | 33 ++ .../app-react/src/globalHeader/types.ts | 115 +++++ .../plugins/app-react/src/index.ts | 18 + workspaces/app-defaults/yarn.lock | 50 +- 120 files changed, 9861 insertions(+), 67 deletions(-) create mode 100644 workspaces/app-defaults/.changeset/split-global-header-extensions.md create mode 100644 workspaces/app-defaults/plugins/app-defaults/report-global-header-components.api.md create mode 100644 workspaces/app-defaults/plugins/app-defaults/report-global-header-module.api.md create mode 100644 workspaces/app-defaults/plugins/app-defaults/report-global-header-translations-module.api.md create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/ApplicationLauncherDropdown.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/CompanyLogo.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/CompanyLogo.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/RedHatDeveloperHubLogo.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Divider/Divider.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Divider/Divider.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeader.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeader.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdown.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdown.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdownContent.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdownContent.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderMenuItem.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderButton/HeaderButton.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderButton/HeaderButton.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/DropdownEmptyState.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/DropdownMenuLoading.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/HeaderDropdownComponent.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/HeaderDropdownComponent.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/MenuSection.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/StarredDropdown.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/StarredDropdown.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/StarredDropdownMenu.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderIcon/HeaderIcon.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderIcon/HeaderIcon.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderIconButton/HeaderIconButton.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HelpDropdown.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/LogoutButton/LogoutButton.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/MenuItemLink/MenuItemLink.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/MenuItemLink/MenuItemLinkContent.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/MyProfileMenuItem.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/NotificationBanner.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/NotificationButton/NotificationButton.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/NotificationButton/NotificationButton.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/ProfileDropdown.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchBar.module.css create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchBar.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchBar.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchComponent.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchComponent.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchInput.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchInput.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchOption.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchOption.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchResultItem.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SearchComponent/SearchResultItem.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Spacer/Spacer.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Spacer/Spacer.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SupportButton/SupportButton.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/SupportButton/SupportButton.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Trans.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/criticalHeaderBundle.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/globalHeaderDialogOffset.test.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/globalHeaderDialogOffset.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/components/loaders.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/componentsExport.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/configureMuiClassName.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/defaults/index.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/defaults/menuItemExtensions.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/defaults/toolbarExtensions.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/extensions/globalHeaderModule.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/globalHeaderModuleExport.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/globalHeaderTranslationsModule.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/globalHeaderTranslationsModuleExport.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/hooks/index.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/hooks/useDebouncedCallback.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/hooks/useDropdownManager.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/hooks/useLanguage.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/hooks/useNotificationCount.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/hooks/useRetainMenuContent.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/hooks/useTranslation.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/hooks/useValidComponentTracker.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/icons/ShapesOutlinedIcon.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/icons/globalHeaderSystemIcons.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/icons/headerToolbarIcon.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/icons/remixIconSize.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/plugin.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/test-utils/mockTranslations.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/translations/de.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/translations/es.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/translations/fr.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/translations/index.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/translations/it.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/translations/ja.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/translations/ref.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/utils/menuItemGrouping.test.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/utils/menuItemGrouping.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/utils/readConfigComponents.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/utils/readConfigComponents.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/utils/readConfigMenuItems.test.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/utils/readConfigMenuItems.ts create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/utils/resolveDataDrivenComponents.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/utils/stringUtils.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/utils/stringUtils.tsx create mode 100644 workspaces/app-defaults/plugins/app-defaults/src/global-header/utils/translationUtils.ts create mode 100644 workspaces/app-defaults/plugins/app-react/src/globalHeader/extensions/GlobalHeaderComponentBlueprint.ts create mode 100644 workspaces/app-defaults/plugins/app-react/src/globalHeader/extensions/GlobalHeaderContext.test.tsx create mode 100644 workspaces/app-defaults/plugins/app-react/src/globalHeader/extensions/GlobalHeaderContext.tsx create mode 100644 workspaces/app-defaults/plugins/app-react/src/globalHeader/extensions/GlobalHeaderMenuItemBlueprint.ts create mode 100644 workspaces/app-defaults/plugins/app-react/src/globalHeader/extensions/dataRefs.ts create mode 100644 workspaces/app-defaults/plugins/app-react/src/globalHeader/extensions/resolveExtensionComponent.tsx create mode 100644 workspaces/app-defaults/plugins/app-react/src/globalHeader/index.ts create mode 100644 workspaces/app-defaults/plugins/app-react/src/globalHeader/types.ts diff --git a/workspaces/app-defaults/.changeset/split-global-header-extensions.md b/workspaces/app-defaults/.changeset/split-global-header-extensions.md new file mode 100644 index 00000000000..48f4d7acd99 --- /dev/null +++ b/workspaces/app-defaults/.changeset/split-global-header-extensions.md @@ -0,0 +1,21 @@ +--- +'@red-hat-developer-hub/backstage-plugin-app-react': minor +'@red-hat-developer-hub/backstage-plugin-app-defaults': minor +--- + +Split global-header extension APIs into app-react and the default implementation into app-defaults. + +`app-react` now exports `GlobalHeaderComponentBlueprint`, `GlobalHeaderMenuItemBlueprint`, related data refs, types, and context hooks so plugins can contribute header items without depending on the default implementation. + +`app-defaults` now hosts the default global-header module, plugin, translations, and configuration, and loads them through the app-defaults feature loader. + +Building-block UI (`GlobalHeaderMenuItem`, `GlobalHeaderIconButton`, +`GlobalHeaderDropdown`, `GlobalHeaderCompanyLogo`) is exported from +`@red-hat-developer-hub/backstage-plugin-app-defaults/global-header-components`. +The header logo export is named `GlobalHeaderCompanyLogo` so it does not +collide with the sidebar `CompanyLogo` on the package root. + +Hosts that enable the app-defaults feature loader but do not want the masthead +can disable `app-root-wrapper:app/global-header`. Custom header/dropdown UI +must read extension data through the `app-react` hooks +(`useGlobalHeaderComponents` / `useGlobalHeaderMenuItems`). diff --git a/workspaces/app-defaults/packages/app/package.json b/workspaces/app-defaults/packages/app/package.json index 09478774dbe..55a6a9b4ec2 100644 --- a/workspaces/app-defaults/packages/app/package.json +++ b/workspaces/app-defaults/packages/app/package.json @@ -47,7 +47,6 @@ "@red-hat-developer-hub/backstage-plugin-app-defaults": "workspace:^", "@red-hat-developer-hub/backstage-plugin-app-integrations": "workspace:^", "@red-hat-developer-hub/backstage-plugin-app-react": "workspace:^", - "@red-hat-developer-hub/backstage-plugin-global-header": "^3.2.1", "@red-hat-developer-hub/backstage-plugin-theme": "^1.4.1", "material-icons": "^1.13.14", "react": "^18.0.2", diff --git a/workspaces/app-defaults/packages/app/src/App.tsx b/workspaces/app-defaults/packages/app/src/App.tsx index 35feb67062f..26d307c773e 100644 --- a/workspaces/app-defaults/packages/app/src/App.tsx +++ b/workspaces/app-defaults/packages/app/src/App.tsx @@ -18,10 +18,6 @@ import { createApp } from '@backstage/frontend-defaults'; import { appAuthModule } from '@red-hat-developer-hub/backstage-plugin-app-auth'; import appDefaultsFeatureLoader from '@red-hat-developer-hub/backstage-plugin-app-defaults'; import { appIntegrationsModule } from '@red-hat-developer-hub/backstage-plugin-app-integrations'; -import { - globalHeaderModule, - globalHeaderTranslationsModule, -} from '@red-hat-developer-hub/backstage-plugin-global-header'; import { drawerDemoModule } from './modules/drawer-demo'; import { sidebarDemoModule } from './modules/sidebar-demo'; import { templateCardDemoModule } from './modules/template-card-demo'; @@ -29,15 +25,14 @@ import { templateCardDemoModule } from './modules/template-card-demo'; export default createApp({ features: [ // Production path: feature loader with the app defaults module - // (drawer + sidebar + template card + common icons) plus the catalog, - // catalog graph, scaffolder, API docs, and TechDocs empty-state overrides. + // (drawer + sidebar + template card + common icons + global header) + // plus the catalog, catalog graph, scaffolder, API docs, and TechDocs + // empty-state overrides. appDefaultsFeatureLoader, appAuthModule, appIntegrationsModule, drawerDemoModule, sidebarDemoModule, templateCardDemoModule, - globalHeaderModule, - globalHeaderTranslationsModule, ], }); diff --git a/workspaces/app-defaults/packages/app/src/modules/drawer-demo/HelpDrawerMenuItem.tsx b/workspaces/app-defaults/packages/app/src/modules/drawer-demo/HelpDrawerMenuItem.tsx index 2d396c2bd8a..c215f73d750 100644 --- a/workspaces/app-defaults/packages/app/src/modules/drawer-demo/HelpDrawerMenuItem.tsx +++ b/workspaces/app-defaults/packages/app/src/modules/drawer-demo/HelpDrawerMenuItem.tsx @@ -14,8 +14,8 @@ * limitations under the License. */ +import { GlobalHeaderMenuItem } from '@red-hat-developer-hub/backstage-plugin-app-defaults/global-header-components'; import { useAppDrawer } from '@red-hat-developer-hub/backstage-plugin-app-react'; -import { GlobalHeaderMenuItem } from '@red-hat-developer-hub/backstage-plugin-global-header/components'; /** * Help-dropdown menu item that toggles the demo help drawer. @@ -33,6 +33,6 @@ export const HelpDrawerMenuItem = ({ }; return ( - + ); }; diff --git a/workspaces/app-defaults/packages/app/src/modules/drawer-demo/index.tsx b/workspaces/app-defaults/packages/app/src/modules/drawer-demo/index.tsx index d60491122f3..329440743fb 100644 --- a/workspaces/app-defaults/packages/app/src/modules/drawer-demo/index.tsx +++ b/workspaces/app-defaults/packages/app/src/modules/drawer-demo/index.tsx @@ -15,10 +15,11 @@ */ import { createFrontendModule } from '@backstage/frontend-plugin-api'; -import { AppDrawerContentBlueprint } from '@red-hat-developer-hub/backstage-plugin-app-react'; -import { GlobalHeaderMenuItemBlueprint } from '@red-hat-developer-hub/backstage-plugin-global-header'; +import { + AppDrawerContentBlueprint, + GlobalHeaderMenuItemBlueprint, +} from '@red-hat-developer-hub/backstage-plugin-app-react'; import { ChatDrawerContent, HelpDrawerContent } from './DrawerDemoContent'; -import { HelpDrawerMenuItem } from './HelpDrawerMenuItem'; const chatDrawer = AppDrawerContentBlueprint.make({ name: 'demo-chat', @@ -43,8 +44,11 @@ const helpMenuItem = GlobalHeaderMenuItemBlueprint.make({ name: 'demo-help', params: { target: 'help', - component: HelpDrawerMenuItem, priority: 50, + // Import building blocks from `/global-header-components` inside the + // loader so they stay off the root Module Federation sync chunk. + loader: () => + import('./HelpDrawerMenuItem').then(m => m.HelpDrawerMenuItem), }, }); diff --git a/workspaces/app-defaults/plugins/app-defaults/README.md b/workspaces/app-defaults/plugins/app-defaults/README.md index a5c2b120eb3..768244137c3 100644 --- a/workspaces/app-defaults/plugins/app-defaults/README.md +++ b/workspaces/app-defaults/plugins/app-defaults/README.md @@ -26,6 +26,7 @@ The module provides: - Common RHDH icon catalog via `IconBundleBlueprint` (`icon-bundle:app/common`) — same IDs as the legacy `CommonIcons` map (`home`, `group`, `category`, `extension`, `school`, `add`, `developerHub`, …) - **Plugin overrides** (via the default feature loader) for catalog, catalog-graph, API docs, TechDocs, and scaffolder — including empty-state pages and **RHDH catalog entity page defaults** (see below) - Learning Paths page at `/learning-paths` (`learningPathsModule`) with proxy-backed data and static JSON fallback +- Global header masthead (wrapper module, default toolbar/menu items, and translations) loaded by the default feature loader — see [Global header](#global-header) ## Customizing Learning Paths @@ -152,13 +153,167 @@ For apps that need only the app layout and drawer wrapper, import `appLayoutModu Override entry points (for advanced installs): -| Export | Role | -| --------------------------------- | ------------------------------------------------------------------------------------------------ | -| `./catalog-plugin-override` | Catalog index empty state, overview layout, Dependencies / System Diagram tabs, card attachments | -| `./catalog-graph-plugin-override` | Graph empty state, RHDH relations graph cards | -| `./api-docs-plugin-override` | API docs empty state, definition card hidden on Overview, API cards on Dependencies | -| `./scaffolder-plugin-override` | Scaffolder empty state | -| `./docs-plugin-override` | TechDocs empty state | +| Export | Role | +| ------------------------------------- | ------------------------------------------------------------------------------------------------ | +| `./catalog-plugin-override` | Catalog index empty state, overview layout, Dependencies / System Diagram tabs, card attachments | +| `./catalog-graph-plugin-override` | Graph empty state, RHDH relations graph cards | +| `./api-docs-plugin-override` | API docs empty state, definition card hidden on Overview, API cards on Dependencies | +| `./scaffolder-plugin-override` | Scaffolder empty state | +| `./docs-plugin-override` | TechDocs empty state | +| `./global-header-module` | Global header wrapper + system icons only (no default toolbar/menu items) | +| `./global-header-translations-module` | Global header translation resource | +| `./global-header-components` | Global-header building-block UI (`GlobalHeaderMenuItem`, …) | + +## Global header + +The default feature loader registers: + +1. `globalHeaderModule` — `app-root-wrapper:app/global-header` plus header system icons +2. `globalHeaderPlugin` — default toolbar widgets and dropdown menu items (`pluginId: 'global-header'`) +3. `globalHeaderTranslationsModule` — masthead translation resource + +Extension APIs for contributing items (`GlobalHeaderComponentBlueprint`, +`GlobalHeaderMenuItemBlueprint`, context hooks) live in +`@red-hat-developer-hub/backstage-plugin-app-react`. + +### Enable in an app + +With the feature loader (typical RHDH / sample app path): + +```typescript +import { createApp } from '@backstage/frontend-defaults'; +import appDefaultsFeatureLoader from '@red-hat-developer-hub/backstage-plugin-app-defaults'; + +export default createApp({ + features: [appDefaultsFeatureLoader /* … */], +}); +``` + +Or register the pieces yourself: + +```typescript +import { + globalHeaderModule, + globalHeaderPlugin, + globalHeaderTranslationsModule, +} from '@red-hat-developer-hub/backstage-plugin-app-defaults'; + +export default createApp({ + features: [ + globalHeaderModule, + globalHeaderPlugin, + globalHeaderTranslationsModule, + // … + ], +}); +``` + +Focused subpaths: `./global-header-module` and +`./global-header-translations-module` (wrapper/icons and translations only; +add `globalHeaderPlugin` from the package root when you want the default +toolbar/menu items). + +### Disable or customize defaults + +Turn off the whole masthead: + +```yaml +app: + extensions: + - app-root-wrapper:app/global-header: + disabled: true +``` + +Disable or reorder individual defaults (`gh-component:global-header/`, +`gh-menu-item:global-header/`): + +```yaml +app: + extensions: + - gh-component:global-header/notification-button: + disabled: true + - gh-component:global-header/search: + config: + priority: 50 + - gh-menu-item:global-header/settings: + disabled: true +``` + +Default toolbar names: `company-logo`, `search`, `spacer`, `self-service-button`, +`starred-dropdown`, `app-launcher-dropdown`, `help-dropdown`, +`notification-button`, `divider`, `profile-dropdown`. + +Default menu item names: `settings`, `my-profile`, `logout` (profile); +`support-button` (help); `app-launcher-devhub`, `app-launcher-rhdh-local` +(app launcher). + +### Config-driven extras + +Add simple toolbar buttons and dropdown links without writing a plugin: + +```yaml +globalHeader: + components: + - title: Dashboard + icon: dashboard + link: /dashboard + priority: 75 + menuItems: + - target: help + title: Docs + icon: article + link: https://docs.example.com + priority: 80 +``` + +### Contribute from a plugin + +```typescript +import { createFrontendPlugin } from '@backstage/frontend-plugin-api'; +import { GlobalHeaderMenuItemBlueprint } from '@red-hat-developer-hub/backstage-plugin-app-react'; + +const docsItem = GlobalHeaderMenuItemBlueprint.make({ + name: 'docs', + params: { + target: 'help', + priority: 50, + loader: () => import('./DocsMenuItem').then(m => m.DocsMenuItem), + }, +}); + +export default createFrontendPlugin({ + pluginId: 'my-plugin', + extensions: [docsItem], +}); +``` + +Prefer a blueprint `loader` and import building-block UI only from +`/global-header-components` inside that lazy file so MUI stays off the root +NFS sync chunk. Read collected items with `useGlobalHeaderComponents` / +`useGlobalHeaderMenuItems` from `app-react` (do not invent a private React +context). + +### Building-block UI + +```typescript +import { + GlobalHeaderMenuItem, + GlobalHeaderIconButton, + GlobalHeaderDropdown, + GlobalHeaderCompanyLogo, +} from '@red-hat-developer-hub/backstage-plugin-app-defaults/global-header-components'; +``` + +| Export | Role | +| ------------------------- | -------------------------------------- | +| `GlobalHeaderMenuItem` | Dropdown menu item with link + icon | +| `GlobalHeaderIconButton` | Toolbar icon button | +| `GlobalHeaderDropdown` | Dropdown that collects `gh-menu-item`s | +| `GlobalHeaderCompanyLogo` | Header masthead logo (`logo` prop) | + +Do **not** confuse `GlobalHeaderCompanyLogo` with the package-root sidebar +`CompanyLogo` (`fullLogo` / `iconLogo`). Both read `app.branding.fullLogo`, but +the prop APIs differ on purpose. ## Catalog entity pages (NFS) diff --git a/workspaces/app-defaults/plugins/app-defaults/config.d.ts b/workspaces/app-defaults/plugins/app-defaults/config.d.ts index b94f317304e..48762f483f5 100644 --- a/workspaces/app-defaults/plugins/app-defaults/config.d.ts +++ b/workspaces/app-defaults/plugins/app-defaults/config.d.ts @@ -16,6 +16,27 @@ export interface Config { app?: { + /** + * Branding options shared with the global header masthead. + * @visibility frontend + */ + branding?: { + /** + * Base64 URI for the full logo. + * If the value is a string it is used as the logo for all themes. + * You can also specific a theme for each theme-id or variant (light/dark). + * @deepVisibility frontend + */ + fullLogo?: string | { [themeIdOrVariant: string]: string }; + /** + * Fallback width for the full logo in the global header. + * Accepts any valid CSS length (e.g. `'200px'`, `'12rem'`). + * Used only when a `width` prop isn't supplied through the extension configuration. + * @visibility frontend + */ + fullLogoWidth?: string | number; + }; + /** * Sidebar entries declared by deployers and merged with entries * contributed through SidebarItemBlueprint and SidebarItemGroupBlueprint. @@ -227,4 +248,51 @@ export interface Config { }; }; }; + + globalHeader?: { + /** + * Simple icon-button toolbar components that deployers can add without + * writing a plugin. Each entry renders a clickable icon in the header bar. + * @visibility frontend + */ + components?: Array<{ + /** @visibility frontend */ + title: string; + /** @visibility frontend */ + titleKey?: string; + /** @visibility frontend */ + icon: string; + /** @visibility frontend */ + link: string; + /** @visibility frontend */ + tooltip?: string; + /** @visibility frontend */ + priority?: number; + }>; + /** + * Simple link menu items that deployers can add without writing a plugin. + * Each item is injected into the dropdown identified by `target`. + * @visibility frontend + */ + menuItems?: Array<{ + /** @visibility frontend */ + target: string; + /** @visibility frontend */ + title: string; + /** @visibility frontend */ + titleKey?: string; + /** @visibility frontend */ + icon?: string; + /** @visibility frontend */ + link: string; + /** @visibility frontend */ + sectionLabel?: string; + /** @visibility frontend */ + sectionLink?: string; + /** @visibility frontend */ + sectionLinkLabel?: string; + /** @visibility frontend */ + priority?: number; + }>; + }; } diff --git a/workspaces/app-defaults/plugins/app-defaults/package.json b/workspaces/app-defaults/plugins/app-defaults/package.json index 2fc863ac6da..681a1b8d867 100644 --- a/workspaces/app-defaults/plugins/app-defaults/package.json +++ b/workspaces/app-defaults/plugins/app-defaults/package.json @@ -12,6 +12,9 @@ "./app-drawer-module": "./src/appDrawerModuleExport.ts", "./app-sidebar-module": "./src/appSidebarModuleExport.ts", "./app-defaults-translations-module": "./src/appDefaultsTranslationsModuleExport.ts", + "./global-header-module": "./src/global-header/globalHeaderModuleExport.ts", + "./global-header-translations-module": "./src/global-header/globalHeaderTranslationsModuleExport.ts", + "./global-header-components": "./src/global-header/componentsExport.ts", "./catalog-plugin-override": "./src/catalogPluginOverrideExport.ts", "./catalog-module": "./src/catalogModuleExport.ts", "./catalog-graph-plugin-override": "./src/catalogGraphPluginOverrideExport.ts", @@ -38,6 +41,15 @@ "app-defaults-translations-module": [ "src/appDefaultsTranslationsModuleExport.ts" ], + "global-header-module": [ + "src/global-header/globalHeaderModuleExport.ts" + ], + "global-header-translations-module": [ + "src/global-header/globalHeaderTranslationsModuleExport.ts" + ], + "global-header-components": [ + "src/global-header/componentsExport.ts" + ], "catalog-plugin-override": [ "src/catalogPluginOverrideExport.ts" ], @@ -80,7 +92,9 @@ "@red-hat-developer-hub/backstage-plugin-app-react" ] }, - "sideEffects": false, + "sideEffects": [ + "./src/global-header/configureMuiClassName.ts" + ], "configSchema": "config.d.ts", "scripts": { "start": "backstage-cli package start", @@ -107,13 +121,17 @@ "@backstage/plugin-catalog-import": "^0.13.17", "@backstage/plugin-catalog-react": "^3.2.2", "@backstage/plugin-notifications": "^0.5.20", + "@backstage/plugin-notifications-common": "^0.2.3", "@backstage/plugin-permission-common": "^0.9.4", "@backstage/plugin-permission-react": "^0.5.4", "@backstage/plugin-scaffolder": "^1.38.2", "@backstage/plugin-search": "^1.7.7", + "@backstage/plugin-search-common": "^1.2.24", "@backstage/plugin-search-react": "^1.11.8", + "@backstage/plugin-signals-react": "^0.0.25", "@backstage/plugin-techdocs": "^1.18.0", "@backstage/plugin-techdocs-common": "^0.1.1", + "@backstage/plugin-user-settings": "^0.9.6", "@backstage/ui": "^0.17.1", "@mui/icons-material": "^5.17.1", "@mui/material": "5.18.0", @@ -127,10 +145,12 @@ }, "devDependencies": { "@backstage/cli": "^0.36.5", + "@backstage/config": "^1.3.8", "@backstage/frontend-test-utils": "^0.6.3", "@backstage/test-utils": "^1.7.21", "@testing-library/jest-dom": "^6.0.0", "@testing-library/react": "^16.0.0", + "@testing-library/user-event": "^14.0.0", "@types/react": "^18", "@types/react-dom": "^18", "cross-fetch": "^4.0.0", diff --git a/workspaces/app-defaults/plugins/app-defaults/report-global-header-components.api.md b/workspaces/app-defaults/plugins/app-defaults/report-global-header-components.api.md new file mode 100644 index 00000000000..9b64f133dfa --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/report-global-header-components.api.md @@ -0,0 +1,76 @@ +## API Report File for "@red-hat-developer-hub/backstage-plugin-app-defaults" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts +import type Button from '@mui/material/Button'; +import type { ComponentProps } from 'react'; +import { JSX as JSX_2 } from 'react/jsx-runtime'; +import type { ReactNode } from 'react'; + +// @public +export const GlobalHeaderCompanyLogo: ( + props: GlobalHeaderCompanyLogoProps, +) => JSX_2.Element; + +// @public +export interface GlobalHeaderCompanyLogoProps { + height?: string | number; + logo?: LogoURLs; + to?: string; + width?: string | number; +} + +// @public +export const GlobalHeaderDropdown: ( + input: GlobalHeaderDropdownProps, +) => JSX_2.Element | null; + +// @public +export interface GlobalHeaderDropdownProps { + buttonContent: ReactNode; + buttonProps?: ComponentProps; + emptyState?: ReactNode; + isIconButton?: boolean; + target: string; + tooltip?: string; + trackValidity?: boolean; +} + +// @public +export const GlobalHeaderIconButton: ( + input: HeaderIconButtonProps, +) => JSX_2.Element; + +// @public +export const GlobalHeaderMenuItem: ( + input: GlobalHeaderMenuItemProps, +) => JSX_2.Element; + +// @public +export interface GlobalHeaderMenuItemProps { + icon?: string; + onClick?: () => void; + subTitle?: string; + subTitleKey?: string; + title?: string; + titleKey?: string; + to?: string; + tooltip?: string; +} + +// @public +export interface HeaderIconButtonProps { + ariaLabel?: string; + color?: 'inherit' | 'primary' | 'secondary' | 'default'; + icon: string; + size?: 'small' | 'medium' | 'large'; + title: string; + titleKey?: string; + to: string; + tooltip?: string; +} + +// @public +export type LogoURLs = Record | string; +``` diff --git a/workspaces/app-defaults/plugins/app-defaults/report-global-header-module.api.md b/workspaces/app-defaults/plugins/app-defaults/report-global-header-module.api.md new file mode 100644 index 00000000000..4554e47eb1b --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/report-global-header-module.api.md @@ -0,0 +1,13 @@ +## API Report File for "@red-hat-developer-hub/backstage-plugin-app-defaults" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts +import { FrontendModule } from '@backstage/frontend-plugin-api'; + +// @public +const globalHeaderModule: FrontendModule; +export default globalHeaderModule; + +// (No @packageDocumentation comment for this package) +``` diff --git a/workspaces/app-defaults/plugins/app-defaults/report-global-header-translations-module.api.md b/workspaces/app-defaults/plugins/app-defaults/report-global-header-translations-module.api.md new file mode 100644 index 00000000000..8d21c24f7c4 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/report-global-header-translations-module.api.md @@ -0,0 +1,13 @@ +## API Report File for "@red-hat-developer-hub/backstage-plugin-app-defaults" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts +import { FrontendModule } from '@backstage/frontend-plugin-api'; + +// @public +const globalHeaderTranslationsModule: FrontendModule; +export default globalHeaderTranslationsModule; + +// (No @packageDocumentation comment for this package) +``` diff --git a/workspaces/app-defaults/plugins/app-defaults/report.api.md b/workspaces/app-defaults/plugins/app-defaults/report.api.md index c4b384852b9..454eda33b70 100644 --- a/workspaces/app-defaults/plugins/app-defaults/report.api.md +++ b/workspaces/app-defaults/plugins/app-defaults/report.api.md @@ -10,16 +10,21 @@ import { ExtensionDataRef } from '@backstage/frontend-plugin-api'; import { ExtensionInput } from '@backstage/frontend-plugin-api'; import { FrontendFeatureLoader } from '@backstage/frontend-plugin-api'; import { FrontendModule } from '@backstage/frontend-plugin-api'; +import { GlobalHeaderComponentData } from '@red-hat-developer-hub/backstage-plugin-app-react'; +import { GlobalHeaderMenuItemData } from '@red-hat-developer-hub/backstage-plugin-app-react'; import { JSX as JSX_2 } from 'react'; import { JSX as JSX_3 } from 'react/jsx-runtime'; +import { MenuItemParams } from '@red-hat-developer-hub/backstage-plugin-app-react'; import { NavContentComponent } from '@backstage/plugin-app-react'; import type { NavContentNavItems } from '@backstage/plugin-app-react'; import { OverridableExtensionDefinition } from '@backstage/frontend-plugin-api'; +import { OverridableFrontendPlugin } from '@backstage/frontend-plugin-api'; import { ReactNode } from 'react'; import { SidebarElementData } from '@red-hat-developer-hub/backstage-plugin-app-react'; import { SidebarItemData } from '@red-hat-developer-hub/backstage-plugin-app-react'; import { SidebarItemGroupData } from '@red-hat-developer-hub/backstage-plugin-app-react'; import { SwappableComponentRef } from '@backstage/frontend-plugin-api'; +import { ToolbarComponentParams } from '@red-hat-developer-hub/backstage-plugin-app-react'; import { TranslationRef } from '@backstage/frontend-plugin-api'; import { TranslationResource } from '@backstage/frontend-plugin-api'; @@ -213,6 +218,420 @@ export interface CompanyLogoProps { const _default: FrontendFeatureLoader; export default _default; +// @public +export const globalHeaderModule: FrontendModule; + +// @public +export const globalHeaderPlugin: OverridableFrontendPlugin< + {}, + {}, + { + 'gh-component:global-header/app-launcher-dropdown': OverridableExtensionDefinition<{ + kind: 'gh-component'; + name: 'app-launcher-dropdown'; + config: { + priority: number | undefined; + }; + configInput: { + priority?: number | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderComponentData, + 'global-header.component', + {} + >; + inputs: {}; + params: ToolbarComponentParams; + }>; + 'gh-component:global-header/company-logo': OverridableExtensionDefinition<{ + kind: 'gh-component'; + name: 'company-logo'; + config: { + priority: number | undefined; + }; + configInput: { + priority?: number | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderComponentData, + 'global-header.component', + {} + >; + inputs: {}; + params: ToolbarComponentParams; + }>; + 'gh-component:global-header/divider': OverridableExtensionDefinition<{ + kind: 'gh-component'; + name: 'divider'; + config: { + priority: number | undefined; + }; + configInput: { + priority?: number | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderComponentData, + 'global-header.component', + {} + >; + inputs: {}; + params: ToolbarComponentParams; + }>; + 'gh-component:global-header/help-dropdown': OverridableExtensionDefinition<{ + kind: 'gh-component'; + name: 'help-dropdown'; + config: { + priority: number | undefined; + }; + configInput: { + priority?: number | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderComponentData, + 'global-header.component', + {} + >; + inputs: {}; + params: ToolbarComponentParams; + }>; + 'gh-component:global-header/notification-button': OverridableExtensionDefinition<{ + kind: 'gh-component'; + name: 'notification-button'; + config: { + priority: number | undefined; + }; + configInput: { + priority?: number | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderComponentData, + 'global-header.component', + {} + >; + inputs: {}; + params: ToolbarComponentParams; + }>; + 'gh-component:global-header/profile-dropdown': OverridableExtensionDefinition<{ + kind: 'gh-component'; + name: 'profile-dropdown'; + config: { + priority: number | undefined; + }; + configInput: { + priority?: number | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderComponentData, + 'global-header.component', + {} + >; + inputs: {}; + params: ToolbarComponentParams; + }>; + 'gh-component:global-header/search': OverridableExtensionDefinition<{ + kind: 'gh-component'; + name: 'search'; + config: { + priority: number | undefined; + }; + configInput: { + priority?: number | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderComponentData, + 'global-header.component', + {} + >; + inputs: {}; + params: ToolbarComponentParams; + }>; + 'gh-component:global-header/self-service-button': OverridableExtensionDefinition<{ + kind: 'gh-component'; + name: 'self-service-button'; + config: { + priority: number | undefined; + }; + configInput: { + priority?: number | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderComponentData, + 'global-header.component', + {} + >; + inputs: {}; + params: ToolbarComponentParams; + }>; + 'gh-component:global-header/spacer': OverridableExtensionDefinition<{ + kind: 'gh-component'; + name: 'spacer'; + config: { + priority: number | undefined; + }; + configInput: { + priority?: number | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderComponentData, + 'global-header.component', + {} + >; + inputs: {}; + params: ToolbarComponentParams; + }>; + 'gh-component:global-header/starred-dropdown': OverridableExtensionDefinition<{ + kind: 'gh-component'; + name: 'starred-dropdown'; + config: { + priority: number | undefined; + }; + configInput: { + priority?: number | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderComponentData, + 'global-header.component', + {} + >; + inputs: {}; + params: ToolbarComponentParams; + }>; + 'gh-menu-item:global-header/app-launcher-devhub': OverridableExtensionDefinition<{ + kind: 'gh-menu-item'; + name: 'app-launcher-devhub'; + config: { + priority: number | undefined; + title: string | undefined; + titleKey: string | undefined; + icon: string | undefined; + link: string | undefined; + sectionLabel: string | undefined; + sectionLink: string | undefined; + sectionLinkLabel: string | undefined; + }; + configInput: { + priority?: number | undefined; + title?: string | undefined; + titleKey?: string | undefined; + icon?: string | undefined; + link?: string | undefined; + sectionLabel?: string | undefined; + sectionLink?: string | undefined; + sectionLinkLabel?: string | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderMenuItemData, + 'global-header.menu-item', + {} + >; + inputs: {}; + params: MenuItemParams; + }>; + 'gh-menu-item:global-header/app-launcher-rhdh-local': OverridableExtensionDefinition<{ + kind: 'gh-menu-item'; + name: 'app-launcher-rhdh-local'; + config: { + priority: number | undefined; + title: string | undefined; + titleKey: string | undefined; + icon: string | undefined; + link: string | undefined; + sectionLabel: string | undefined; + sectionLink: string | undefined; + sectionLinkLabel: string | undefined; + }; + configInput: { + priority?: number | undefined; + title?: string | undefined; + titleKey?: string | undefined; + icon?: string | undefined; + link?: string | undefined; + sectionLabel?: string | undefined; + sectionLink?: string | undefined; + sectionLinkLabel?: string | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderMenuItemData, + 'global-header.menu-item', + {} + >; + inputs: {}; + params: MenuItemParams; + }>; + 'gh-menu-item:global-header/logout': OverridableExtensionDefinition<{ + kind: 'gh-menu-item'; + name: 'logout'; + config: { + priority: number | undefined; + title: string | undefined; + titleKey: string | undefined; + icon: string | undefined; + link: string | undefined; + sectionLabel: string | undefined; + sectionLink: string | undefined; + sectionLinkLabel: string | undefined; + }; + configInput: { + priority?: number | undefined; + title?: string | undefined; + titleKey?: string | undefined; + icon?: string | undefined; + link?: string | undefined; + sectionLabel?: string | undefined; + sectionLink?: string | undefined; + sectionLinkLabel?: string | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderMenuItemData, + 'global-header.menu-item', + {} + >; + inputs: {}; + params: MenuItemParams; + }>; + 'gh-menu-item:global-header/my-profile': OverridableExtensionDefinition<{ + kind: 'gh-menu-item'; + name: 'my-profile'; + config: { + priority: number | undefined; + title: string | undefined; + titleKey: string | undefined; + icon: string | undefined; + link: string | undefined; + sectionLabel: string | undefined; + sectionLink: string | undefined; + sectionLinkLabel: string | undefined; + }; + configInput: { + priority?: number | undefined; + title?: string | undefined; + titleKey?: string | undefined; + icon?: string | undefined; + link?: string | undefined; + sectionLabel?: string | undefined; + sectionLink?: string | undefined; + sectionLinkLabel?: string | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderMenuItemData, + 'global-header.menu-item', + {} + >; + inputs: {}; + params: MenuItemParams; + }>; + 'gh-menu-item:global-header/settings': OverridableExtensionDefinition<{ + kind: 'gh-menu-item'; + name: 'settings'; + config: { + priority: number | undefined; + title: string | undefined; + titleKey: string | undefined; + icon: string | undefined; + link: string | undefined; + sectionLabel: string | undefined; + sectionLink: string | undefined; + sectionLinkLabel: string | undefined; + }; + configInput: { + priority?: number | undefined; + title?: string | undefined; + titleKey?: string | undefined; + icon?: string | undefined; + link?: string | undefined; + sectionLabel?: string | undefined; + sectionLink?: string | undefined; + sectionLinkLabel?: string | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderMenuItemData, + 'global-header.menu-item', + {} + >; + inputs: {}; + params: MenuItemParams; + }>; + 'gh-menu-item:global-header/support-button': OverridableExtensionDefinition<{ + kind: 'gh-menu-item'; + name: 'support-button'; + config: { + priority: number | undefined; + title: string | undefined; + titleKey: string | undefined; + icon: string | undefined; + link: string | undefined; + sectionLabel: string | undefined; + sectionLink: string | undefined; + sectionLinkLabel: string | undefined; + }; + configInput: { + priority?: number | undefined; + title?: string | undefined; + titleKey?: string | undefined; + icon?: string | undefined; + link?: string | undefined; + sectionLabel?: string | undefined; + sectionLink?: string | undefined; + sectionLinkLabel?: string | undefined; + }; + output: ExtensionDataRef< + GlobalHeaderMenuItemData, + 'global-header.menu-item', + {} + >; + inputs: {}; + params: MenuItemParams; + }>; + } +>; + +// @public +export const globalHeaderTranslationRef: TranslationRef< + 'plugin.global-header', + { + readonly 'search.clear': string; + readonly 'search.placeholder': string; + readonly 'search.noResults': string; + readonly 'search.errorFetching': string; + readonly 'search.allResults': string; + readonly 'profile.picture': string; + readonly 'profile.settings': string; + readonly 'profile.myProfile': string; + readonly 'profile.signOut': string; + readonly 'help.tooltip': string; + readonly 'help.noSupportLinks': string; + readonly 'help.noSupportLinksSubtitle': string; + readonly 'help.quickStart': string; + readonly 'help.supportTitle': string; + readonly 'notifications.title': string; + readonly 'notifications.unsupportedDismissOption': string; + readonly 'create.title': string; + readonly 'create.templates.errorFetching': string; + readonly 'create.templates.sectionTitle': string; + readonly 'create.templates.allTemplates': string; + readonly 'create.templates.noTemplatesAvailable': string; + readonly 'create.registerComponent.title': string; + readonly 'create.registerComponent.subtitle': string; + readonly 'starred.title': string; + readonly 'starred.removeTooltip': string; + readonly 'starred.noItemsTitle': string; + readonly 'starred.noItemsSubtitle': string; + readonly 'applicationLauncher.tooltip': string; + readonly 'applicationLauncher.developerHub': string; + readonly 'applicationLauncher.noLinksTitle': string; + readonly 'applicationLauncher.noLinksSubtitle': string; + readonly 'applicationLauncher.rhdhLocal': string; + readonly 'applicationLauncher.sections.documentation': string; + readonly 'applicationLauncher.sections.developerTools': string; + } +>; + +// @public +export const globalHeaderTranslations: TranslationResource<'plugin.global-header'>; + +// @public +export const globalHeaderTranslationsModule: FrontendModule; + // @public export const learningPathsModule: FrontendModule; diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/ApplicationLauncherDropdown.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/ApplicationLauncherDropdown.tsx new file mode 100644 index 00000000000..39f2b0d7d0e --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/ApplicationLauncherDropdown.tsx @@ -0,0 +1,52 @@ +/* + * 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 AppsOutlinedIcon from '@mui/icons-material/AppsOutlined'; +import AppRegistrationIcon from '@mui/icons-material/AppRegistration'; + +import { useTranslation } from '../hooks/useTranslation'; +import { HEADER_TOOLBAR_ICON_SIZE } from '../icons/headerToolbarIcon'; +import { DropdownEmptyState } from './HeaderDropdownComponent/DropdownEmptyState'; +import { GlobalHeaderDropdown } from './GlobalHeaderDropdown'; + +/** + * Application Launcher dropdown. Collects menu items from the `'app-launcher'` + * target. + * + * @internal + */ +export const ApplicationLauncherDropdown = () => { + const { t } = useTranslation(); + return ( + } + emptyState={ + + } + /> + } + /> + ); +}; diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/CompanyLogo.test.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/CompanyLogo.test.tsx new file mode 100644 index 00000000000..f310ccb2506 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/CompanyLogo.test.tsx @@ -0,0 +1,119 @@ +/* + * 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 type { ReactElement, ReactNode } from 'react'; +import { screen } from '@testing-library/react'; +import { appThemeApiRef, configApiRef } from '@backstage/core-plugin-api'; +import { + mockApis, + renderInTestApp, + TestApiProvider, +} from '@backstage/test-utils'; + +import { CompanyLogo } from './CompanyLogo'; + +const customLogo = 'data:image/png;base64,custom-logo'; + +const createMockThemeApi = ( + variant: 'light' | 'dark' = 'light', + themeId = variant, +) => ({ + getActiveThemeId: () => themeId, + getInstalledThemes: () => [ + { + id: themeId, + title: themeId, + variant, + Provider: ({ children }: { children: ReactNode }) => children, + }, + ], + activeThemeId$: () => ({ + subscribe: () => ({ unsubscribe: () => undefined }), + }), + setActiveThemeId: () => undefined, +}); + +const configWithFullLogo = mockApis.config({ + data: { + app: { + branding: { + fullLogo: customLogo, + }, + }, + }, +}); + +const renderCompanyLogo = ( + ui: ReactElement, + apis: Parameters[0]['apis'], +) => renderInTestApp({ui}); + +describe('CompanyLogo', () => { + it('renders the built-in default logo when no branding is configured', async () => { + await renderCompanyLogo(, [ + [configApiRef, mockApis.config({})], + [appThemeApiRef, createMockThemeApi('light')], + ]); + + expect( + screen.getByTestId('global-header-company-logo').querySelector('svg'), + ).toBeInTheDocument(); + expect(screen.queryByTestId('home-logo')).not.toBeInTheDocument(); + }); + + it('renders app.branding.fullLogo when no logo prop is provided', async () => { + await renderCompanyLogo(, [ + [configApiRef, configWithFullLogo], + [appThemeApiRef, createMockThemeApi('light')], + ]); + + const logo = screen.getByTestId('home-logo'); + expect(logo).toHaveAttribute('src', customLogo); + }); + + it('renders themed app.branding.fullLogo object for the active theme variant', async () => { + const lightLogo = 'data:image/png;base64,light-logo'; + const darkLogo = 'data:image/png;base64,dark-logo'; + const configWithThemedFullLogo = mockApis.config({ + data: { + app: { + branding: { + fullLogo: { light: lightLogo, dark: darkLogo }, + }, + }, + }, + }); + + await renderCompanyLogo(, [ + [configApiRef, configWithThemedFullLogo], + [appThemeApiRef, createMockThemeApi('light')], + ]); + + expect(screen.getByTestId('home-logo')).toHaveAttribute('src', lightLogo); + }); + + it('prefers the logo prop over app.branding.fullLogo', async () => { + const propLogo = 'data:image/png;base64,prop-logo'; + + await renderCompanyLogo(, [ + [configApiRef, configWithFullLogo], + [appThemeApiRef, createMockThemeApi('light')], + ]); + + const logo = screen.getByTestId('home-logo'); + expect(logo).toHaveAttribute('src', propLogo); + }); +}); diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/CompanyLogo.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/CompanyLogo.tsx new file mode 100644 index 00000000000..34b733bd26d --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/CompanyLogo.tsx @@ -0,0 +1,130 @@ +/* + * 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 { Link } from '@backstage/core-components'; +import { + appThemeApiRef, + configApiRef, + useApi, +} from '@backstage/frontend-plugin-api'; +import Box from '@mui/material/Box'; +import RedHatDeveloperHubLogo from './RedHatDeveloperHubLogo'; + +/** + * An interface representing the URLs for light and dark variants of a logo. + * @public + */ +export type LogoURLs = Record | string; + +/** + * Props for the global-header company logo (`GlobalHeaderCompanyLogo`). + * + * @public + */ +export interface CompanyLogoProps { + /** An object containing the logo URLs */ + logo?: LogoURLs; + /** The route to link the logo to */ + to?: string; + /** + * The width of the logo in pixels (defaults to 150px). This prop fixes an + * issue where encoded SVGs without an explicit width would not render. + * You likely do not need to set this prop, but we recommend setting it + * to a value under 200px. + */ + width?: string | number; + /** + * The maximum height of the logo in pixels (defaults to 40px). + * Note that changing this value may result in changes in the height of the global header. + **/ + height?: string | number; +} + +/** + * Company logo for the global header app bar. + * + * Publicly exported as `GlobalHeaderCompanyLogo` from the + * `/global-header-components` package entry so it is not confused with the + * sidebar `CompanyLogo` on the package root (different props: header uses + * `logo`, sidebar uses `fullLogo` / `iconLogo`). + * + * @public + */ +export const CompanyLogo = (props: CompanyLogoProps) => { + const configApi = useApi(configApiRef); + const themeApi = useApi(appThemeApiRef); + + const themeId = themeApi.getActiveThemeId(); + const themeVariant = themeApi + .getInstalledThemes() + .find(theme => theme.id === themeId)?.variant; + const logoURLs = + props.logo ?? configApi.getOptional('app.branding.fullLogo'); + const logoURI = + (typeof logoURLs === 'string' ? logoURLs : null) ?? + (typeof logoURLs === 'object' + ? logoURLs?.[themeId!] ?? logoURLs?.[themeVariant!] + : null); + + const to = props.to ?? '/'; + const width = + props.width ?? + configApi.getOptional('app.branding.fullLogoWidth') ?? + 150; + const height = props.height ?? 40; + + return ( + + + {logoURI ? ( + Home logo + ) : ( + + )} + + + ); +}; diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/RedHatDeveloperHubLogo.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/RedHatDeveloperHubLogo.tsx new file mode 100644 index 00000000000..e3a2cf4e615 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/CompanyLogo/RedHatDeveloperHubLogo.tsx @@ -0,0 +1,99 @@ +/* + * 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. + */ + +export default function RedHatDeveloperHubLogo({ + textFill, +}: { + textFill: string; +}) { + return ( + + + + + + + + + ); +} diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Divider/Divider.test.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Divider/Divider.test.tsx new file mode 100644 index 00000000000..2777edc0a86 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Divider/Divider.test.tsx @@ -0,0 +1,27 @@ +/* + * 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 { render } from '@testing-library/react'; + +import { Divider } from './Divider'; + +describe('Divider', () => { + it('render some default styles', () => { + const { debug, container } = render(); + debug(); + expect(container.firstElementChild?.nodeName).toEqual('HR'); + }); +}); diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Divider/Divider.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Divider/Divider.tsx new file mode 100644 index 00000000000..4db12a6c58e --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/Divider/Divider.tsx @@ -0,0 +1,38 @@ +/* + * 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 type { CSSProperties } from 'react'; +import MUIDivider from '@mui/material/Divider'; + +/** + * @public + */ +export interface DividerProps { + layout?: CSSProperties; +} + +/** + * @public + */ +export const Divider = ({ layout }: DividerProps) => { + return ( + + ); +}; diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeader.test.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeader.test.tsx new file mode 100644 index 00000000000..13b2dabeb2a --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeader.test.tsx @@ -0,0 +1,99 @@ +/* + * 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 { render, screen } from '@testing-library/react'; +import { GlobalHeaderProvider } from '@red-hat-developer-hub/backstage-plugin-app-react'; +import { GlobalHeader } from './GlobalHeader'; +import type { GlobalHeaderComponentData } from '@red-hat-developer-hub/backstage-plugin-app-react'; + +jest.mock('@backstage/core-components', () => ({ + ErrorBoundary: ({ children }: { children: React.ReactNode }) => ( + <>{children} + ), +})); + +describe('GlobalHeader', () => { + it('renders all components from context', () => { + const components: GlobalHeaderComponentData[] = [ + { + id: 'gh-component:global-header/company-logo', + component: () => Logo, + priority: 200, + }, + { + id: 'gh-component:global-header/search', + component: () => Search, + priority: 100, + }, + ]; + + render( + + + , + ); + + expect(screen.getByText('Logo')).toBeInTheDocument(); + expect(screen.getByText('Search')).toBeInTheDocument(); + }); + + it('renders an empty toolbar when no components are provided', () => { + render( + + + , + ); + + const nav = screen.getByRole('navigation'); + expect(nav).toBeInTheDocument(); + expect(nav.firstElementChild).toBeEmptyDOMElement(); + }); + + it('renders the nav element with id="global-header"', () => { + render( + + + , + ); + + expect(document.getElementById('global-header')).toBeInTheDocument(); + }); + + it('uses auto width so a docked drawer can shrink the bar', () => { + render( + + + , + ); + + expect(document.getElementById('global-header')).toHaveStyle({ + width: 'auto', + marginRight: 'var(--docked-drawer-width, 0px)', + }); + }); + + it('injects BUI dialog overlay offset styles', () => { + render( + + + , + ); + + expect( + document.querySelector('style[data-rhdh-global-header-dialog-offset]'), + ).toBeInTheDocument(); + }); +}); diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeader.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeader.tsx new file mode 100644 index 00000000000..f41934063ef --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeader.tsx @@ -0,0 +1,123 @@ +/* + * 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 { useEffect } from 'react'; +import { ErrorBoundary } from '@backstage/core-components'; + +import AppBar from '@mui/material/AppBar'; +import Box from '@mui/material/Box'; +import Toolbar from '@mui/material/Toolbar'; + +import '../configureMuiClassName'; +import { useGlobalHeaderComponents } from '@red-hat-developer-hub/backstage-plugin-app-react'; +import { GLOBAL_HEADER_DIALOG_OFFSET_CSS } from './globalHeaderDialogOffset'; + +const GLOBAL_HEADER_HEIGHT_VAR = '--rhdh-global-header-height'; + +/** + * Global header / masthead. Reads toolbar items from GlobalHeaderContext + * and renders them in a sticky AppBar. + * + * Spans the viewport (PatternFly masthead / OFS Root behavior) and shrinks + * when an application drawer docks from the right via + * `--docked-drawer-width`. Company logo is shown by default; app shells + * should not hide it in favor of a sidebar mark. Injected layout CSS + * publishes `--rhdh-global-header-height` and offsets the fixed Backstage + * sidebar drawer (and BUI dialogs) below this bar. A ResizeObserver keeps + * the CSS variable in sync with the real masthead height. + * + * @public + */ +export const GlobalHeader = () => { + const components = useGlobalHeaderComponents(); + + useEffect(() => { + const header = document.getElementById('global-header'); + if (!header) { + return undefined; + } + + const publishHeight = () => { + const height = Math.round(header.getBoundingClientRect().height); + document.documentElement.style.setProperty( + GLOBAL_HEADER_HEIGHT_VAR, + `${height}px`, + ); + }; + + publishHeight(); + + if (typeof ResizeObserver === 'undefined') { + return () => { + document.documentElement.style.removeProperty(GLOBAL_HEADER_HEIGHT_VAR); + }; + } + + const observer = new ResizeObserver(publishHeight); + observer.observe(header); + return () => { + observer.disconnect(); + document.documentElement.style.removeProperty(GLOBAL_HEADER_HEIGHT_VAR); + }; + }, []); + + return ( + <> + + + + (theme as any).rhdh?.general?.appBarForegroundColor ?? + theme.palette.text.primary, + }} + > + {components.map((item, index) => { + const Component = item.component; + if (!Component) { + return null; + } + return ( + + + + + + ); + })} + + + + ); +}; diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdown.test.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdown.test.tsx new file mode 100644 index 00000000000..637b4d6d2ce --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdown.test.tsx @@ -0,0 +1,474 @@ +/* + * 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 { + useEffect, + useState, + type ComponentProps, + type ComponentType, +} from 'react'; +import { act, fireEvent, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import MenuItem from '@mui/material/MenuItem'; +import { renderInTestApp } from '@backstage/test-utils'; + +import { GlobalHeaderProvider } from '@red-hat-developer-hub/backstage-plugin-app-react'; +import type { GlobalHeaderMenuItemData } from '@red-hat-developer-hub/backstage-plugin-app-react'; +import { GlobalHeaderDropdown } from './GlobalHeaderDropdown'; + +jest.mock('../hooks/useTranslation', () => { + const { mockUseTranslation } = require('../test-utils/mockTranslations'); + return { useTranslation: mockUseTranslation }; +}); + +jest.mock('../components/Trans', () => { + const { MockTrans } = require('../test-utils/mockTranslations'); + return { Trans: MockTrans }; +}); + +const emptyState =
No items
; + +const renderDropdown = ( + menuItems: GlobalHeaderMenuItemData[], + props: Partial> = {}, +) => + renderInTestApp( + + Help} + emptyState={emptyState} + {...props} + /> + , + ); + +/** Flush React.lazy() of dropdown content under fake timers. */ +const flushLazyMenu = async () => { + await act(async () => { + await Promise.resolve(); + }); +}; + +const openMenu = async () => { + fireEvent.click(screen.getByRole('button', { name: /help/i })); + await flushLazyMenu(); +}; + +describe('GlobalHeaderDropdown', () => { + beforeEach(() => { + jest.useRealTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + jest.clearAllMocks(); + }); + + it('returns null when there are no menu items and no emptyState', async () => { + const { container } = await renderInTestApp( + + Help} /> + , + ); + + expect(container).toBeEmptyDOMElement(); + }); + + it('renders the trigger when emptyState is provided with no menu items', async () => { + await renderDropdown([]); + + expect(screen.getByRole('button', { name: /help/i })).toBeInTheDocument(); + }); + + it('shows emptyState immediately when there are no contributions', async () => { + await renderDropdown([]); + await openMenu(); + + expect(await screen.findByTestId('empty-state')).toBeInTheDocument(); + }); + + it('renders data-driven menu items', async () => { + const menuItems: GlobalHeaderMenuItemData[] = [ + { + target: 'help', + type: 'data', + title: 'Documentation', + link: '/docs', + priority: 10, + }, + ]; + + await renderDropdown(menuItems); + await openMenu(); + + expect( + await screen.findByRole('menuitem', { name: /documentation/i }), + ).toBeInTheDocument(); + expect(screen.queryByTestId('empty-state')).not.toBeInTheDocument(); + }, 15000); + + it('renders component-type menu items', async () => { + const SupportItem: ComponentType<{ handleClose?: () => void }> = () => ( + Support + ); + + const menuItems: GlobalHeaderMenuItemData[] = [ + { + target: 'help', + type: 'component', + component: SupportItem, + priority: 10, + }, + ]; + + await renderDropdown(menuItems); + await openMenu(); + + expect( + await screen.findByRole('menuitem', { name: /support/i }), + ).toBeInTheDocument(); + }); + + it('ignores menu items for other targets', async () => { + const menuItems: GlobalHeaderMenuItemData[] = [ + { + target: 'create', + type: 'data', + title: 'Create template', + link: '/create', + priority: 10, + }, + ]; + + await renderDropdown(menuItems); + await openMenu(); + + expect(await screen.findByTestId('empty-state')).toBeInTheDocument(); + expect( + screen.queryByRole('menuitem', { name: /create template/i }), + ).not.toBeInTheDocument(); + }); + + describe('trackValidity', () => { + it('shows emptyState after settle timeout when contributed items render nothing', async () => { + jest.useFakeTimers(); + const user = userEvent.setup({ + advanceTimers: jest.advanceTimersByTime, + }); + + const NullItem: ComponentType = () => null; + const menuItems: GlobalHeaderMenuItemData[] = [ + { + target: 'help', + type: 'component', + component: NullItem, + priority: 10, + }, + ]; + + await renderDropdown(menuItems, { trackValidity: true }); + await user.click(screen.getByRole('button', { name: /help/i })); + await flushLazyMenu(); + + expect(screen.queryByTestId('empty-state')).not.toBeInTheDocument(); + + await act(async () => { + jest.advanceTimersByTime(500); + }); + + expect(await screen.findByTestId('empty-state')).toBeInTheDocument(); + }); + + it('keeps showing menu content when a menuitem is present synchronously', async () => { + jest.useFakeTimers(); + const user = userEvent.setup({ + advanceTimers: jest.advanceTimersByTime, + }); + + const SupportItem: ComponentType = () => Support; + const menuItems: GlobalHeaderMenuItemData[] = [ + { + target: 'help', + type: 'component', + component: SupportItem, + priority: 10, + }, + ]; + + await renderDropdown(menuItems, { trackValidity: true }); + await user.click(screen.getByRole('button', { name: /help/i })); + await flushLazyMenu(); + + expect( + await screen.findByRole('menuitem', { name: /support/i }), + ).toBeInTheDocument(); + + await act(async () => { + jest.advanceTimersByTime(1500); + }); + + expect(screen.queryByTestId('empty-state')).not.toBeInTheDocument(); + expect( + screen.getByRole('menuitem', { name: /support/i }), + ).toBeInTheDocument(); + }); + + it('does not show emptyState when a lazy item appears before settle timeout', async () => { + jest.useFakeTimers(); + const user = userEvent.setup({ + advanceTimers: jest.advanceTimersByTime, + }); + + const LazySupport: ComponentType = () => { + const [ready, setReady] = useState(false); + useEffect(() => { + const id = window.setTimeout(() => setReady(true), 100); + return () => window.clearTimeout(id); + }, []); + if (!ready) return null; + return Support; + }; + + const menuItems: GlobalHeaderMenuItemData[] = [ + { + target: 'help', + type: 'component', + component: LazySupport, + priority: 10, + }, + ]; + + await renderDropdown(menuItems, { trackValidity: true }); + await user.click(screen.getByRole('button', { name: /help/i })); + await flushLazyMenu(); + + await act(async () => { + jest.advanceTimersByTime(100); + }); + + expect( + await screen.findByRole('menuitem', { name: /support/i }), + ).toBeInTheDocument(); + + await act(async () => { + jest.advanceTimersByTime(1500); + }); + + expect(screen.queryByTestId('empty-state')).not.toBeInTheDocument(); + }); + + it('recovers from emptyState when a lazy item appears after settle timeout', async () => { + jest.useFakeTimers(); + const user = userEvent.setup({ + advanceTimers: jest.advanceTimersByTime, + }); + + const VeryLazySupport: ComponentType = () => { + const [ready, setReady] = useState(false); + useEffect(() => { + const id = window.setTimeout(() => setReady(true), 800); + return () => window.clearTimeout(id); + }, []); + if (!ready) return null; + return Support; + }; + + const menuItems: GlobalHeaderMenuItemData[] = [ + { + target: 'help', + type: 'component', + component: VeryLazySupport, + priority: 10, + }, + ]; + + await renderDropdown(menuItems, { trackValidity: true }); + await user.click(screen.getByRole('button', { name: /help/i })); + await flushLazyMenu(); + + await act(async () => { + jest.advanceTimersByTime(500); + }); + + expect(await screen.findByTestId('empty-state')).toBeInTheDocument(); + + await act(async () => { + jest.advanceTimersByTime(300); + }); + + await waitFor(() => { + expect(screen.queryByTestId('empty-state')).not.toBeInTheDocument(); + }); + await flushLazyMenu(); + expect( + await screen.findByRole('menuitem', { name: /support/i }), + ).toBeInTheDocument(); + }); + + it('hides contributed content while emptyState is shown, without unmounting it', async () => { + jest.useFakeTimers(); + const user = userEvent.setup({ + advanceTimers: jest.advanceTimersByTime, + }); + + let unmounted = false; + const PersistentNullItem: ComponentType = () => { + useEffect(() => { + return () => { + unmounted = true; + }; + }, []); + return
; + }; + + const menuItems: GlobalHeaderMenuItemData[] = [ + { + target: 'help', + type: 'component', + component: PersistentNullItem, + priority: 10, + }, + ]; + + await renderDropdown(menuItems, { trackValidity: true }); + await user.click(screen.getByRole('button', { name: /help/i })); + await flushLazyMenu(); + + await act(async () => { + jest.advanceTimersByTime(500); + }); + + expect(await screen.findByTestId('empty-state')).toBeInTheDocument(); + const probe = screen.getByTestId('validity-probe'); + expect(probe).toHaveAttribute('hidden'); + expect(probe).toContainElement( + screen.getByTestId('persistent-null-host'), + ); + expect(unmounted).toBe(false); + }); + }); + + describe('keyboard navigation', () => { + const twoItemMenu: GlobalHeaderMenuItemData[] = [ + { + target: 'help', + type: 'data', + title: 'First item', + link: '/first', + priority: 20, + }, + { + target: 'help', + type: 'data', + title: 'Second item', + link: '/second', + priority: 10, + }, + { + target: 'help', + type: 'data', + title: 'Third item', + link: '/third', + priority: 5, + }, + ]; + + const openTwoItemMenu = async () => { + await renderDropdown(twoItemMenu); + await openMenu(); + return { + first: await screen.findByRole('menuitem', { name: /first item/i }), + second: screen.getByRole('menuitem', { name: /second item/i }), + third: screen.getByRole('menuitem', { name: /third item/i }), + }; + }; + + it('moves focus with ArrowDown between menu items', async () => { + const { first, second } = await openTwoItemMenu(); + + first.focus(); + expect(first).toHaveFocus(); + + await userEvent.keyboard('{ArrowDown}'); + expect(second).toHaveFocus(); + }); + + it('wraps focus from last item to first with ArrowDown', async () => { + const { first, third } = await openTwoItemMenu(); + + third.focus(); + expect(third).toHaveFocus(); + + await userEvent.keyboard('{ArrowDown}'); + expect(first).toHaveFocus(); + }); + + it('wraps focus from first item to last with ArrowUp', async () => { + const { first, third } = await openTwoItemMenu(); + + first.focus(); + expect(first).toHaveFocus(); + + await userEvent.keyboard('{ArrowUp}'); + expect(third).toHaveFocus(); + }); + + it('moves focus to the first item with Home', async () => { + const { first, third } = await openTwoItemMenu(); + + third.focus(); + expect(third).toHaveFocus(); + + await userEvent.keyboard('{Home}'); + expect(first).toHaveFocus(); + }); + + it('moves focus to the last item with End', async () => { + const { first, third } = await openTwoItemMenu(); + + first.focus(); + expect(first).toHaveFocus(); + + await userEvent.keyboard('{End}'); + expect(third).toHaveFocus(); + }); + + it('keeps menu items as direct children of the menu list', async () => { + await openTwoItemMenu(); + + const menuList = screen.getByRole('menu'); + const menuItems = Array.from(menuList.children); + + expect(menuItems.length).toBe(3); + menuItems.forEach(child => { + expect(child).toHaveAttribute('role', 'menuitem'); + }); + }); + }); + + it('forwards tooltip and icon button props to the trigger', async () => { + await renderDropdown([], { + isIconButton: true, + tooltip: 'Help menu', + buttonContent: icon, + }); + + expect( + screen.getByRole('button', { name: 'Help menu' }), + ).toBeInTheDocument(); + }); +}); diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdown.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdown.tsx new file mode 100644 index 00000000000..2d0a2a6d921 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdown.tsx @@ -0,0 +1,221 @@ +/* + * 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 { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react'; +import type { ComponentProps, ReactNode } from 'react'; +import type Button from '@mui/material/Button'; + +import { useGlobalHeaderMenuItems } from '@red-hat-developer-hub/backstage-plugin-app-react'; +import { buildDropdownEntries } from '../utils/menuItemGrouping'; +import { useDropdownManager, useRetainMenuContent } from '../hooks'; +import { HeaderDropdownComponent } from './HeaderDropdownComponent/HeaderDropdownComponent'; +import { DropdownMenuLoading } from './HeaderDropdownComponent/DropdownMenuLoading'; + +const GlobalHeaderDropdownContent = lazy(() => + import('./GlobalHeaderDropdownContent').then(m => ({ + default: m.GlobalHeaderDropdownContent, + })), +); + +/** + * Settle delays for lazy menu items. + * Matches the old HelpDropdown validity tracking behaviour. + */ +const VALIDITY_CHECK_MS = [500, 1500] as const; + +type MenuValidity = 'pending' | 'valid' | 'empty'; + +/** + * Props for {@link GlobalHeaderDropdown}. + * + * @public + */ +export interface GlobalHeaderDropdownProps { + /** Extension target name that items are collected from (e.g. `'help'`, `'create'`). */ + target: string; + /** Content rendered inside the trigger button. */ + buttonContent: ReactNode; + /** MUI Button props forwarded to the trigger. */ + buttonProps?: ComponentProps; + /** Render an `IconButton` instead of a regular `Button`. */ + isIconButton?: boolean; + /** Tooltip shown on hover of the trigger button. */ + tooltip?: string; + /** Rendered when no menu items are contributed (or all render empty when `trackValidity` is on). */ + emptyState?: ReactNode; + /** + * When enabled, waits for lazy menu items to settle before deciding whether + * to display the empty state. + */ + trackValidity?: boolean; +} + +/** + * High-level dropdown building block for the global header. + * + * Collects menu items from a named extension `target`, groups them + * by section, sorts by priority, and renders them inside a + * `HeaderDropdownComponent`. + * + * @public + */ +export const GlobalHeaderDropdown = ({ + target, + buttonContent, + buttonProps, + isIconButton, + tooltip, + emptyState, + trackValidity = false, +}: GlobalHeaderDropdownProps) => { + const { anchorEl, handleOpen, handleClose } = useDropdownManager(); + const menuItems = useGlobalHeaderMenuItems(target); + const entries = useMemo(() => buildDropdownEntries(menuItems), [menuItems]); + + const validityProbeRef = useRef(null); + const [menuValidity, setMenuValidity] = useState('pending'); + + const isOpen = Boolean(anchorEl); + const { shouldRenderMenuContent, handleMenuTransitionExited } = + useRetainMenuContent(isOpen); + + const hasNoContributions = entries.length === 0; + + const showEmptyState = + hasNoContributions || (trackValidity && menuValidity === 'empty'); + + // While validity is tracked, keep contributed items in a hidden probe until + // they are confirmed valid so the menu list only contains focusable items. + const contentInValidityProbe = + trackValidity && + shouldRenderMenuContent && + !hasNoContributions && + menuValidity !== 'valid'; + + useEffect(() => { + if (!trackValidity) { + return; + } + + if (!isOpen) { + setMenuValidity('pending'); + return; + } + + if (menuValidity === 'valid') { + return; + } + + const list = validityProbeRef.current; + if (!list) { + return; + } + + const syncFromDom = () => { + if (list.querySelector('[role="menuitem"]')) { + setMenuValidity('valid'); + } + }; + + // Handle items that rendered synchronously. + syncFromDom(); + + const observer = new MutationObserver(syncFromDom); + + observer.observe(list, { + childList: true, + subtree: true, + }); + + const concludeEmpty = () => { + if (!list.querySelector('[role="menuitem"]')) { + setMenuValidity(prev => (prev === 'valid' ? prev : 'empty')); + } + }; + + const timers = VALIDITY_CHECK_MS.map(ms => + window.setTimeout(concludeEmpty, ms), + ); + + // eslint-disable-next-line consistent-return + return () => { + observer.disconnect(); + timers.forEach(id => window.clearTimeout(id)); + }; + }, [trackValidity, isOpen, menuValidity, shouldRenderMenuContent]); + + if (menuItems.length === 0 && !emptyState) { + return null; + } + + let menuBody: ReactNode = null; + if (shouldRenderMenuContent && hasNoContributions) { + menuBody = emptyState; + } else if ( + shouldRenderMenuContent && + contentInValidityProbe && + menuValidity === 'pending' + ) { + menuBody = ; + } else if (shouldRenderMenuContent && showEmptyState) { + menuBody = emptyState; + } else if (shouldRenderMenuContent && !contentInValidityProbe) { + menuBody = ( + }> + + + ); + } + + const dropdownContent = ( + + ); + + return ( + <> + + {menuBody} + + {contentInValidityProbe ? ( + + ) : null} + + ); +}; diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdownContent.test.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdownContent.test.tsx new file mode 100644 index 00000000000..429ba89f286 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdownContent.test.tsx @@ -0,0 +1,145 @@ +/* + * 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 { render, screen } from '@testing-library/react'; +import { GlobalHeaderDropdownContent } from './GlobalHeaderDropdownContent'; +import type { DropdownEntry } from '../utils/menuItemGrouping'; + +jest.mock('./HeaderDropdownComponent/MenuSection', () => ({ + MenuSection: ({ sectionLabel, hideDivider }: any) => ( +
+ {hideDivider ? 'no-divider' : 'has-divider'} +
+ ), +})); + +const MockComponent = ({ handleClose, hideDivider }: any) => ( +
+ + {hideDivider ? 'no-divider' : 'has-divider'} +
+); + +describe('GlobalHeaderDropdownContent', () => { + const handleClose = jest.fn(); + + it('renders standalone component entries', () => { + const entries: DropdownEntry[] = [ + { + type: 'component', + item: { target: 'test', component: MockComponent, type: 'component' }, + priority: 10, + }, + ]; + + render( + , + ); + + expect(screen.getByTestId('custom-component')).toBeInTheDocument(); + }); + + it('renders section group entries via MenuSection', () => { + const entries: DropdownEntry[] = [ + { + type: 'section', + group: { + sectionLabel: 'Resources', + items: [{ Component: () => null, label: 'Docs', link: '/docs' }], + priority: 10, + }, + priority: 10, + }, + ]; + + render( + , + ); + + expect(screen.getByTestId('menu-section')).toBeInTheDocument(); + expect(screen.getByTestId('menu-section')).toHaveAttribute( + 'data-label', + 'Resources', + ); + }); + + it('passes isLast=true to the last entry', () => { + const entries: DropdownEntry[] = [ + { + type: 'component', + item: { target: 'test', component: MockComponent, type: 'component' }, + priority: 20, + }, + { + type: 'component', + item: { target: 'test', component: MockComponent, type: 'component' }, + priority: 10, + }, + ]; + + render( + , + ); + + const components = screen.getAllByTestId('custom-component'); + expect(components[0]).toHaveTextContent('has-divider'); + expect(components[1]).toHaveTextContent('no-divider'); + }); + + it('returns null for component entries without a component', () => { + const entries: DropdownEntry[] = [ + { + type: 'component', + item: { target: 'test', type: 'component' }, + priority: 10, + }, + ]; + + const { container } = render( + , + ); + + expect(container.children).toHaveLength(0); + }); + + it('renders empty when given no entries', () => { + const { container } = render( + , + ); + + expect(container.children).toHaveLength(0); + }); +}); diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdownContent.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdownContent.tsx new file mode 100644 index 00000000000..1362fcbaacf --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderDropdownContent.tsx @@ -0,0 +1,82 @@ +/* + * 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 type { DropdownEntry } from '../utils/menuItemGrouping'; +import { MenuSection } from './HeaderDropdownComponent/MenuSection'; + +/** Renders a standalone component or a data-driven `MenuSection`. */ +const DropdownItem = ({ + entry, + isLast, + handleClose, +}: { + entry: DropdownEntry; + isLast: boolean; + handleClose: () => void; +}) => { + if (entry.type === 'component') { + const Comp = entry.item.component; + if (!Comp) return null; + return ( + + ); + } + + const { sectionLabel, sectionLink, sectionLinkLabel, items } = entry.group; + return ( + + ); +}; + +/** + * Renders the menu content for a {@link GlobalHeaderDropdown}. + * + * Maps each entry to either a standalone component or a `MenuSection`. + */ +export const GlobalHeaderDropdownContent = ({ + entries, + target, + handleClose, +}: { + entries: DropdownEntry[]; + target: string; + handleClose: () => void; +}) => ( + <> + {entries.map((entry, i) => ( + + ))} + +); diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderMenuItem.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderMenuItem.tsx new file mode 100644 index 00000000000..5b261c437b1 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/GlobalHeaderMenuItem.tsx @@ -0,0 +1,104 @@ +/* + * 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 { Link } from '@backstage/core-components'; + +import MenuItem from '@mui/material/MenuItem'; + +import { MenuItemLink } from './MenuItemLink/MenuItemLink'; + +/** + * Props for {@link GlobalHeaderMenuItem}. + * + * @public + */ +export interface GlobalHeaderMenuItemProps { + /** Navigation URL. When absent the item renders as a plain action button. */ + to?: string; + /** Display title. */ + title?: string; + /** Translation key for the title. */ + titleKey?: string; + /** Secondary text rendered below the title. */ + subTitle?: string; + /** Translation key for the secondary text. */ + subTitleKey?: string; + /** Icon identifier passed to `HeaderIcon`. */ + icon?: string; + /** Tooltip shown on hover. */ + tooltip?: string; + /** Called when the item is clicked (typically the dropdown's `handleClose`). */ + onClick?: () => void; +} + +/** + * A complete, self-contained menu item for use inside header dropdowns. + * + * Renders a MUI `MenuItem` with optional `Link` navigation and the + * standard `MenuItemLink` content (icon, title, subtitle, external + * link indicator). Consumers only need this one component — no manual + * `MenuItem` or `Link` wrapping required. + * + * @example + * ```tsx + * const MyHelpItem = ({ handleClose }) => ( + * + * ); + * ``` + * + * @public + */ +export const GlobalHeaderMenuItem = ({ + to, + title, + titleKey, + subTitle, + subTitleKey, + icon, + tooltip, + onClick, +}: GlobalHeaderMenuItemProps) => ( + + + +); diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderButton/HeaderButton.test.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderButton/HeaderButton.test.tsx new file mode 100644 index 00000000000..eb4f85a1be2 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderButton/HeaderButton.test.tsx @@ -0,0 +1,46 @@ +/* + * 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 { renderInTestApp } from '@backstage/test-utils'; + +import { HeaderButton } from './HeaderButton'; + +describe('HeaderButton', () => { + it('can render an internal link', async () => { + const { getByRole } = await renderInTestApp( + , + ); + expect(getByRole('button')).toBeInTheDocument(); + expect(getByRole('button')).toHaveTextContent('Internal link'); + expect(getByRole('button').getAttribute('href')).toEqual('/internal-link'); + expect(getByRole('button').getAttribute('target')).not.toEqual('_blank'); + }); + + it('can render an external link', async () => { + const { getByRole } = await renderInTestApp( + , + ); + expect(getByRole('button')).toBeInTheDocument(); + expect(getByRole('button')).toHaveTextContent('External link'); + expect(getByRole('button').getAttribute('href')).toEqual( + 'https://access.redhat.com/products/red-hat-developer-hub', + ); + expect(getByRole('button').getAttribute('target')).toEqual('_blank'); + }); +}); diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderButton/HeaderButton.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderButton/HeaderButton.tsx new file mode 100644 index 00000000000..3d836a30ee7 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderButton/HeaderButton.tsx @@ -0,0 +1,83 @@ +/* + * 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 type { CSSProperties } from 'react'; +import { LinkButton } from '@backstage/core-components'; + +import Box from '@mui/material/Box'; +import Tooltip from '@mui/material/Tooltip'; +import { HeaderIcon } from '../HeaderIcon/HeaderIcon'; + +/** + * @public + */ +export interface HeaderButtonProps { + title: string; + tooltip?: string; + color?: 'inherit' | 'primary' | 'secondary' | 'default'; + size?: 'small' | 'medium' | 'large'; + variant?: 'text' | 'outlined' | 'contained'; + ariaLabel?: string; + startIcon?: string; + endIcon?: string; + externalLinkIcon?: boolean; + to: string; + layout?: CSSProperties; +} + +/** + * @public + */ +export const HeaderButton = ({ + title, + tooltip, + color = 'inherit', + size = 'small', + variant, + ariaLabel, + startIcon, + endIcon, + externalLinkIcon = true, + to, + layout, +}: HeaderButtonProps) => { + const button = ( + : null} + endIcon={endIcon ? : null} + externalLinkIcon={externalLinkIcon} + to={to} + > + {title} + + ); + + if (tooltip) { + return ( + + +
{button}
+
+
+ ); + } + + return {button}; +}; diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/DropdownEmptyState.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/DropdownEmptyState.tsx new file mode 100644 index 00000000000..8eb0e6a4c83 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/DropdownEmptyState.tsx @@ -0,0 +1,71 @@ +/* + * 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 type { ReactNode, FC } from 'react'; +import Box from '@mui/material/Box'; +import Typography from '@mui/material/Typography'; +import { InfoCard } from '@backstage/core-components'; + +/** + * @public + * Props for dropdown empty state + */ +interface DropdownEmptyStateProps { + title: string; + subTitle: string; + icon: ReactNode; +} + +export const DropdownEmptyState: FC = ({ + title, + subTitle, + icon, +}) => { + return ( + theme.spacing(2.5), + overflow: 'hidden', + }} + > + + + {icon} + + {title} + + + {subTitle} + + + + + ); +}; diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/DropdownMenuLoading.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/DropdownMenuLoading.tsx new file mode 100644 index 00000000000..072b91271b9 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/DropdownMenuLoading.tsx @@ -0,0 +1,37 @@ +/* + * 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 { Progress } from '@backstage/core-components'; +import MenuItem from '@mui/material/MenuItem'; + +/** Horizontal progress bar shown while lazy dropdown menu content is loading. */ +export const DropdownMenuLoading = () => ( + + + +); diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/HeaderDropdownComponent.test.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/HeaderDropdownComponent.test.tsx new file mode 100644 index 00000000000..1920464e064 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/HeaderDropdownComponent.test.tsx @@ -0,0 +1,152 @@ +/* + * 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 { screen, fireEvent } from '@testing-library/react'; +import MenuItem from '@mui/material/MenuItem'; +import { HeaderDropdownComponent } from './HeaderDropdownComponent'; +import { renderInTestApp } from '@backstage/test-utils'; + +describe('HeaderDropdownComponent', () => { + const mockOnOpen = jest.fn(); + const mockOnClose = jest.fn(); + + beforeEach(() => { + jest.clearAllMocks(); + + jest.spyOn(console, 'warn').mockImplementation(message => { + if (message.includes('⚠️ React Router Future Flag Warning')) { + return; // Suppress React Router warning + } + // eslint-disable-next-line no-console + console.warn(message); // Log other warnings + }); + + jest.spyOn(console, 'error').mockImplementation(message => { + if ( + typeof message === 'string' && + message.includes('findDOMNode is deprecated') + ) { + return; // Suppress findDOMNode warning in tests + } + // eslint-disable-next-line no-console + console.error(message); // Allow other errors to be logged + }); + }); + + it('renders button with provided content', async () => { + await renderInTestApp( + Click Me} + onOpen={mockOnOpen} + onClose={mockOnClose} + anchorEl={null} + > +
Dropdown Content
+
, + ); + + expect(screen.getByText('Click Me')).toBeInTheDocument(); + }); + + it('opens dropdown when button is clicked', async () => { + await renderInTestApp( + Click Me} + onOpen={mockOnOpen} + onClose={mockOnClose} + anchorEl={null} + > +
Dropdown Content
+
, + ); + + fireEvent.click(screen.getByText('Click Me')); + expect(mockOnOpen).toHaveBeenCalled(); + }); + + it('renders as an icon button if isIconButton is true', async () => { + await renderInTestApp( + Icon} + onOpen={jest.fn()} + onClose={jest.fn()} + anchorEl={null} + isIconButton // Explicitly set to true + > +
Dropdown Content
+
, + ); + + // Check that an IconButton is rendered + const iconButton = screen.getByRole('button'); + expect(iconButton).toBeInTheDocument(); + expect(iconButton).toHaveClass('v5-MuiIconButton-root'); // Ensures it's an IconButton + }); + + it('displays tooltip when hovered', async () => { + await renderInTestApp( + Click Me} + onOpen={jest.fn()} + onClose={jest.fn()} + anchorEl={null} + tooltip="Test Tooltip" + > +
Dropdown Content
+
, + ); + + // Ensure the tooltip is not visible initially + expect(screen.queryByText('Test Tooltip')).not.toBeInTheDocument(); + + // Hover over the button to trigger the tooltip + fireEvent.mouseOver(screen.getByRole('button')); + + // The tooltip should now be visible + expect(await screen.findByText('Test Tooltip')).toBeInTheDocument(); + }); + + it('stretches mixed li/a menuitems to the full list width', async () => { + const anchorEl = document.createElement('button'); + document.body.appendChild(anchorEl); + + await renderInTestApp( + Click Me} + onOpen={mockOnOpen} + onClose={mockOnClose} + anchorEl={anchorEl} + > + Quick start + + Support with a longer label + + , + ); + + const menu = await screen.findByRole('menu'); + expect(menu).toHaveStyle({ + display: 'flex', + flexDirection: 'column', + alignItems: 'stretch', + }); + + const items = screen.getAllByRole('menuitem'); + expect(items).toHaveLength(2); + items.forEach(item => { + expect(item).toHaveStyle({ width: '100%' }); + }); + }); +}); diff --git a/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/HeaderDropdownComponent.tsx b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/HeaderDropdownComponent.tsx new file mode 100644 index 00000000000..e8dda8f0202 --- /dev/null +++ b/workspaces/app-defaults/plugins/app-defaults/src/global-header/components/HeaderDropdownComponent/HeaderDropdownComponent.tsx @@ -0,0 +1,166 @@ +/* + * 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 { useId } from 'react'; +import type { ReactNode, ComponentProps, MouseEvent, FC, Ref } from 'react'; +import Menu from '@mui/material/Menu'; +import Button from '@mui/material/Button'; +import { Theme } from '@mui/material/styles'; +import Box from '@mui/material/Box'; +import IconButton, { IconButtonProps } from '@mui/material/IconButton'; +import Tooltip from '@mui/material/Tooltip'; +import { MenuItemConfig, MenuSectionConfig } from './MenuSection'; + +interface HeaderDropdownProps { + buttonContent: ReactNode; + children: ReactNode; + menuSections?: MenuSectionConfig[]; + menuBottomItems?: MenuItemConfig[]; + buttonProps?: ComponentProps; + onOpen: (event: MouseEvent) => void; + onClose: () => void; + anchorEl: HTMLElement | null; + isIconButton?: boolean; + tooltip?: string; + size?: IconButtonProps['size']; + /** Ref forwarded to the underlying MUI MenuList (`