|
| 1 | +import React, { useState, useEffect, ReactElement } from "react"; |
| 2 | +import { Toolbar, ToggleButton, ToggleButtonProps } from "@fluentui/react-components"; |
| 3 | +import eventBus from "../eventbus.js"; |
| 4 | + |
| 5 | +type PanelRightTogglesProps = { |
| 6 | + children: React.ReactNode; |
| 7 | +}; |
| 8 | + |
| 9 | +const PanelRightToggles: React.FC<PanelRightTogglesProps> = ({ children }) => { |
| 10 | + const [activePanel, setActivePanel] = useState<"first" | "second" | "third" | "fourth" | null>(null); |
| 11 | + |
| 12 | + const panelTypes = ["first", "second", "third", "fourth"] as const; |
| 13 | + |
| 14 | + useEffect(() => { |
| 15 | + const handlePanelToggle = (panel: "first" | "second" | "third" | "fourth" | null) => { |
| 16 | + setActivePanel(panel); |
| 17 | + }; |
| 18 | + |
| 19 | + const handlePanelInit = ({ panelType, isActive }: { panelType: string; isActive: boolean }) => { |
| 20 | + if (isActive) setActivePanel(panelType as any); |
| 21 | + }; |
| 22 | + |
| 23 | + eventBus.on("setActivePanel", handlePanelToggle); |
| 24 | + eventBus.on("panelInitState", handlePanelInit); |
| 25 | + |
| 26 | + return () => { |
| 27 | + eventBus.off("setActivePanel", handlePanelToggle); |
| 28 | + eventBus.off("panelInitState", handlePanelInit); |
| 29 | + }; |
| 30 | + }, []); |
| 31 | + |
| 32 | + const togglePanel = (panel: "first" | "second" | "third" | "fourth" | null) => { |
| 33 | + eventBus.emit("setActivePanel", activePanel === panel ? null : panel); |
| 34 | + }; |
| 35 | + |
| 36 | + const isToggleButton = (child: React.ReactNode): child is ReactElement<ToggleButtonProps> => { |
| 37 | + return React.isValidElement(child) && child.type === ToggleButton; |
| 38 | + }; |
| 39 | + |
| 40 | + return ( |
| 41 | + <Toolbar style={{ padding: "4px 0", display: "flex", flexDirection: "row-reverse" }}> |
| 42 | + {React.Children.map(children, (child, index) => { |
| 43 | + const panelType = panelTypes[index]; |
| 44 | + if (isToggleButton(child) && panelType) { |
| 45 | + return React.cloneElement(child, { |
| 46 | + onClick: () => togglePanel(panelType), |
| 47 | + checked: activePanel === panelType, |
| 48 | + }); |
| 49 | + } |
| 50 | + return child; |
| 51 | + })} |
| 52 | + </Toolbar> |
| 53 | + ); |
| 54 | +}; |
| 55 | + |
| 56 | +export default PanelRightToggles; |
0 commit comments