import { TocItem } from "../toc";
import * as React from "react";
import manageJss, { DesignSystemProvider } from "@microsoft/fast-jss-manager-react";
import { glyphGlobalnavbutton, glyphTransparency } from "@microsoft/fast-glyphs-msft";
import { uniqueId } from "lodash-es";
import devSiteDesignSystemDefaults from "../design-system";
import Shell, { ShellHeader, ShellInfoBar, ShellSlot } from "../shell";
import { BrowserRouter, Redirect, Route, Switch } from "react-router-dom";
import { ellipsis, localizeSpacing, toPx } from "@microsoft/fast-jss-utilities";
import ComponentWrapper from "./component-wrapper";
import SiteTitle from "./title";
import SiteTitleBrand from "./title-brand";
import SiteMenu from "./menu";
import SiteMenuItem from "./menu-item";
import SiteCategory, { Status } from "./category";
import SiteCategoryDocumentation from "./category-documentation";
import SiteCategoryIcon from "./category-icon";
import SiteCategoryItem from "./category-item";
import ActionBar from "./action-bar";
import DevTools from "./dev-tools";
import ConfigurationPanel from "./configuration-panel";
import NotFound from "./not-found";
import ComponentView, { ComponentViewTypes } from "./component-view";
import { Canvas, Pane, PaneResizeDirection, Row, RowResizeDirection } from "@microsoft/fast-layouts-react";
import { Direction, isRTL } from "@microsoft/fast-application-utilities";
export var ComponentViewSlot;
(function (ComponentViewSlot) {
    ComponentViewSlot["example"] = "canvas-example-view";
    ComponentViewSlot["detailExample"] = "canvas-detail-view-example";
    ComponentViewSlot["detailDocumentation"] = "canvas-detail-view-documentation";
})(ComponentViewSlot || (ComponentViewSlot = {}));
export var SiteSlot;
(function (SiteSlot) {
    SiteSlot["category"] = "category";
    SiteSlot["categoryIcon"] = "category-icon";
})(SiteSlot || (SiteSlot = {}));
const styles = {
    "@global": {
        "body, html": {
            fontFamily: "Segoe UI, SegoeUI, Helvetica Neue, Helvetica, Arial, sans-serif",
            fontSize: toPx(14),
            padding: toPx(0),
            margin: toPx(0)
        }
    },
    site_canvasContent: {
        height: `calc(100% - ${toPx(40)})`,
        display: "flex",
        flexDirection: "column"
    },
    site_headerTitle: {
        fontSize: toPx(15),
        marginLeft: toPx(8),
        cursor: "default"
    },
    site_infoBarConfiguration: {
        display: "flex",
        alignItems: "center",
        padding: toPx(4),
    },
    site_infoBarConfiguration_base: {
        position: "relative",
        "&::before, &::after": {
            content: "''",
            position: "absolute",
            top: toPx(11),
            zIndex: "1",
            borderRadius: toPx(2),
            width: toPx(1),
            height: toPx(10),
            background: "#000000"
        },
        "&::before": {
            right: toPx(15),
            transform: "rotate(45deg)"
        },
        "&::after": {
            right: toPx(22),
            transform: "rotate(-45deg)"
        }
    },
    site_infoBarConfiguration_theme: {
        marginRight: toPx(4)
    },
    site_infoBarConfiguration_input: {
        lineHeight: toPx(16),
        fontSize: toPx(14),
        backgroundColor: "rgba(0, 0, 0, 0.04)",
        borderRadius: toPx(2),
        boxShadow: `inset 0 0 ${toPx(4)} 0 rgba(0, 0, 0, 0.08)`,
        appearance: "none",
        padding: localizeSpacing(Direction.ltr)(`${toPx(8)} ${toPx(36)} ${toPx(8)} ${toPx(10)}`),
        border: "none",
        outline: "none",
        "&:-ms-expand": {
            display: "none"
        },
        "&:hover": {
            boxShadow: `inset 0 0 ${toPx(2)} 0 rgba(0,0,0, .3)`
        },
        "&:focus": {
            boxShadow: (config) => {
                return `inset 0 0 0 1 ${config.brandColor}`;
            }
        }
    },
    site_paneForm: {
        padding: toPx(12)
    },
    site_paneToc: {
        padding: "0"
    },
    site_paneTocRow: {
        display: "flex",
        flexWrap: "nowrap",
        alignItems: "center",
    },
    site_paneTocTitle: {
        fontWeight: "bold",
        marginLeft: toPx(-8),
        textOverflow: ellipsis().textOverflow,
        whiteSpace: "nowrap",
        overflow: "hidden",
        cursor: "default"
    },
    site_paneToggleButton: {
        border: "none",
        background: "none",
        padding: toPx(12),
        outline: "0"
    },
    site_paneToggleButtonIcon: {
        height: toPx(16),
        width: toPx(16),
        justifyContent: "center",
        fontSize: toPx(16),
        paddingTop: toPx(2),
        display: "inline-block"
    },
    site_paneToggleButtonIconLayout: {
        height: toPx(40),
        width: toPx(40),
        display: "flex",
        alignItems: "center",
        justifyContent: "center"
    },
    site_transparencyToggleButton: {
        border: "none",
        borderRadius: toPx(2),
        background: "none",
        height: toPx(32),
        width: toPx(32),
        cursor: "pointer",
        outline: "0",
        marginRight: toPx(4),
        opacity: ".85",
        paddingTop: toPx(4),
        "&:hover": {
            opacity: "1"
        },
        "&[aria-pressed=\"true\"]": {
            background: "#FFFFFF",
            opacity: "1"
        }
    },
    site_transparencyToggleButtonIcon: {
        position: "relative",
        top: toPx(1)
    },
    site_statusBar: {
        display: "flex",
        alignItems: "center",
        lineHeight: "1",
        textAlign: "left",
        flex: "1"
    },
    site_statusComponentName: {
        marginLeft: toPx(12),
        marginRight: toPx(15),
    },
    site_statusIndicator: {
        borderRadius: "50%",
        height: toPx(16),
        width: toPx(16),
        marginRight: toPx(4),
        boxSizing: "border-box",
        border: `${toPx(1)} solid #FFFFFF`,
    },
    site_statusReleased: {
        backgroundColor: "#3EC28F",
    },
    site_statusAlpha: {
        backgroundColor: "#824ED2",
    },
    site_statusBeta: {
        backgroundColor: "#950811",
    }
};
class Site extends React.Component {
    constructor(props) {
        super(props);
        this.getComponentName = (currentPath) => {
            const matchedPath = currentPath
                ? currentPath.match(/([a-z\d\-]+)(\/*)$/i)
                : this.getCurrentPath().match(/([a-z\d\-]+)(\/*)$/i);
            let componentName = matchedPath !== null && matchedPath[1] ? matchedPath[1] : "";
            componentName = componentName.charAt(0).toUpperCase() + componentName.slice(1, componentName.length);
            componentName = componentName.replace(/-([a-z])/g, (match) => {
                return match[1].toUpperCase();
            });
            return componentName;
        };
        /**
         * Renders a route based on the active component
         */
        this.renderComponentRoute = (route) => {
            const path = route.route;
            return (React.createElement(Route, { key: path, path: `${path}(|examples)`, exact: true }, this.renderShellRow(route)));
        };
        this.handleComponentDataChange = (data) => {
            const currentPath = this.getCurrentPath();
            if (this.state.componentView === ComponentViewTypes.examples) {
                const componentData = Object.assign({}, this.state.componentData);
                componentData[currentPath][this.state.activeComponentIndex] = data;
                this.setState({
                    componentData,
                    currentPath
                });
            }
            else if (this.state.componentView === ComponentViewTypes.detail) {
                const detailViewComponentData = Object.assign({}, this.state.detailViewComponentData);
                detailViewComponentData[currentPath] = data;
                this.setState({
                    detailViewComponentData,
                    currentPath
                });
            }
        };
        this.handleToggleDevToolsView = () => {
            this.setState({
                devToolsView: !this.state.devToolsView
            });
        };
        this.getInitialPath = () => {
            return Object.keys(this.getComponentData())[0];
        };
        this.getCurrentPath = () => {
            return this.getComponentViewTypesByLocation() === ComponentViewTypes.detail
                ? window.location.pathname
                : window.location.pathname.slice(0, window.location.pathname.length - 9);
        };
        this.handleComponentClick = (activeIndex) => {
            this.setState({
                activeComponentIndex: activeIndex
            });
        };
        this.onComponentViewChange = (type) => {
            this.setState({
                componentView: type
            });
        };
        this.onFormToggle = () => {
            this.setState({
                formView: !this.state.formView
            });
        };
        this.onDevToolsToggle = () => {
            this.setState({
                devToolsView: !this.state.devToolsView
            });
        };
        this.handleLocaleUpdate = (e) => {
            if (this.props.onUpdateDirection) {
                this.props.onUpdateDirection(isRTL(e.target.value) ? Direction.rtl : Direction.ltr);
            }
            this.setState({
                locale: e.target.value
            });
        };
        this.handleThemeUpdate = (e) => {
            if (this.props.onUpdateTheme) {
                this.props.onUpdateTheme(e.target.value);
            }
            if (!this.props.activeTheme) {
                const selectedTheme = this.props.themes.find((item) => {
                    return item.id === e.target.value;
                });
                this.setState({
                    theme: selectedTheme
                });
            }
        };
        this.handlePaneCollapse = () => {
            this.setState({
                tableOfContentsCollapsed: !this.state.tableOfContentsCollapsed
            });
        };
        this.handleTransparencyToggleClick = (e) => {
            this.setState({
                componentBackgroundTransparent: !this.state.componentBackgroundTransparent
            });
        };
        this.initialPath = this.getInitialPath();
        this.state = {
            currentPath: this.initialPath,
            activeComponentIndex: 0,
            tableOfContentsCollapsed: this.props.collapsed || false,
            componentBackgroundTransparent: this.props.componentBackgroundTransparent || false,
            componentView: ComponentViewTypes.examples,
            componentName: this.getComponentName(this.initialPath),
            componentData: this.getComponentData(),
            componentStatus: this.getComponentStatus(this.initialPath),
            detailViewComponentData: this.getDetailViewComponentData(),
            formView: true,
            devToolsView: false,
            locale: "en",
            theme: this.props.activeTheme || this.getInitialTheme()
        };
    }
    static getDerivedStateFromProps(props, state) {
        const updatedTheme = props.activeTheme
            ? props.activeTheme
            : props.themes
                ? props.themes.find((theme) => theme.id === state.theme.id)
                : null;
        return updatedTheme === null ? null : { theme: updatedTheme };
    }
    render() {
        return (React.createElement(DesignSystemProvider, { designSystem: devSiteDesignSystemDefaults },
            React.createElement(BrowserRouter, null,
                React.createElement(Shell, null,
                    this.renderShellHeader(),
                    React.createElement(Switch, null,
                        React.createElement(Route, { exact: true, path: "/" },
                            React.createElement(Redirect, { to: this.initialPath })),
                        this.renderRoutes(),
                        React.createElement(Route, { path: "*", component: NotFound })),
                    this.renderShellInfoBar()))));
    }
    componentDidMount() {
        // If the path we load the site in doesn't match component view, update state
        // to match the path
        if (this.getComponentViewTypesByLocation() !== this.state.componentView) {
            this.setState({
                componentView: this.getComponentViewTypesByLocation()
            });
        }
    }
    componentDidUpdate(prevProps) {
        if (prevProps !== this.props) {
            this.setState({
                componentData: this.getComponentData(),
                detailViewComponentData: this.getDetailViewComponentData()
            });
        }
    }
    getInitialTheme() {
        if (Array.isArray(this.props.themes) && this.props.themes.length) {
            return this.props.themes[0];
        }
    }
    /**
     * Gets the component data for each of the routes
     */
    getComponentData() {
        const componentData = {};
        this.getRoutes(this.props.children, "/", SiteSlot.category).forEach((route) => {
            componentData[route.route] = [];
            route.exampleView.forEach((routeChild, index) => {
                componentData[route.route][index] = routeChild.props.data;
            });
        });
        return componentData;
    }
    getComponentStatus(currentPath) {
        let componentStatus = Status.beta;
        this.getRoutes(this.props.children, "/", SiteSlot.category).forEach((route) => {
            if ((currentPath && route.route === currentPath || !currentPath && route.route === this.state.currentPath) && route.status) {
                componentStatus = route.status;
            }
        });
        return componentStatus;
    }
    getDetailViewComponentData() {
        const componentData = {};
        this.getRoutes(this.props.children, "/", SiteSlot.category).forEach((route) => {
            componentData[route.route] = [];
            route.detailView.forEach((routeChild, index) => {
                if (routeChild && routeChild.props && routeChild.props.slot === ComponentViewSlot.detailExample) {
                    componentData[route.route] = routeChild.props.data;
                }
            });
        });
        return componentData;
    }
    /**
     * Determine if the view is to the examples or detail of a component
     */
    getComponentViewTypesByLocation() {
        return window
            && window.location
            && new RegExp(`${ComponentViewTypes[ComponentViewTypes.examples]}/?$`).test(window.location.pathname)
            ? ComponentViewTypes.examples
            : ComponentViewTypes.detail;
    }
    renderRoutes() {
        return this.getRoutes(this.props.children, "/", SiteSlot.category)
            .map(this.renderComponentRoute);
    }
    renderShellHeader() {
        return (React.createElement(ShellHeader, null,
            this.renderChildrenBySlot(this, ShellSlot.header),
            this.renderTitle()));
    }
    renderShellRow(route) {
        const paneStyleSheet = {
            pane: {
                backgroundColor: (config) => {
                    return config.lightGray;
                }
            }
        };
        return (React.createElement(Row, { fill: true },
            React.createElement(Pane, { collapsed: this.state.tableOfContentsCollapsed, resizable: true, resizeFrom: PaneResizeDirection.east, jssStyleSheet: paneStyleSheet, minWidth: 200 },
                React.createElement("div", null,
                    this.renderPaneCollapseToggle(),
                    this.renderChildrenBySlot(this, ShellSlot.pane),
                    React.createElement("ul", { className: this.props.managedClasses.site_paneToc }, this.renderRootToc(this.props.children, SiteSlot.category, route.route, "/")))),
            React.createElement(Canvas, null,
                React.createElement(Row, null,
                    React.createElement(ActionBar, { onComponentViewChange: this.onComponentViewChange, onFormToggle: this.onFormToggle, onDevToolsToggle: this.onDevToolsToggle, componentView: this.state.componentView, formView: this.state.formView, devToolsView: this.state.devToolsView })),
                React.createElement("div", { className: this.props.managedClasses.site_canvasContent },
                    React.createElement(ComponentView, Object.assign({}, { viewType: this.state.componentView }),
                        this.renderChildrenBySlot(this, ShellSlot.canvas),
                        this.renderComponentByRoute(route)),
                    React.createElement(Row, { resizable: true, hidden: !this.state.devToolsView, resizeFrom: RowResizeDirection.north, minHeight: 180 }, this.renderDevTools(route.schema)))),
            React.createElement(Pane, { hidden: !this.state.formView, resizable: true, resizeFrom: PaneResizeDirection.west, jssStyleSheet: paneStyleSheet, minWidth: 324 }, this.generateForm(route.exampleView, route.schema, route.route))));
    }
    renderDevTools(schema) {
        if (this.state.devToolsView) {
            return (React.createElement(DevTools, { activeFramework: this.props.activeFramework, activeSchema: schema, activeComponentName: this.state.componentName, activeFormData: this.getCurrentComponentData(), childOptions: this.props.formChildOptions, frameworks: Array.isArray(this.props.frameworks) ? this.props.frameworks : [this.props.frameworks], onToggleView: this.handleToggleDevToolsView }));
        }
    }
    renderTitle() {
        const children = Array.isArray(this.props.children) ? this.props.children : [this.props.children];
        let title = null;
        children.forEach((child) => {
            if (child && child.props && child.props.slot === "title") {
                title = (React.createElement("span", { className: this.props.managedClasses.site_headerTitle }, child));
            }
        });
        return title;
    }
    getCurrentComponentData() {
        if (this.state.componentView === ComponentViewTypes.examples) {
            return this.state.componentData[this.state.currentPath][this.state.activeComponentIndex];
        }
        else if (this.state.componentView === ComponentViewTypes.detail) {
            return this.state.detailViewComponentData[this.state.currentPath];
        }
    }
    generateForm(component, schema, route) {
        if (component && schema) {
            const componentData = this.state.componentView === ComponentViewTypes.examples
                ? Object.assign({}, this.state.componentData[route][this.state.activeComponentIndex])
                : Object.assign({}, this.state.detailViewComponentData[route]);
            return (React.createElement(ConfigurationPanel, { schema: schema, data: componentData, onChange: this.handleComponentDataChange.bind(route), formChildOptions: this.props.formChildOptions }));
        }
    }
    generateComponentWrapperBackground() {
        return this.state.theme && this.state.theme.background ? this.state.theme.background : null;
    }
    renderComponentByRoute(route) {
        if (route.exampleView && this.state.componentView === ComponentViewTypes.examples) {
            return route.exampleView.map((componentItem, index) => {
                if (route.componentMapping && componentItem.props && componentItem.props.slot === ComponentViewSlot.example) {
                    return (React.createElement(ComponentWrapper, { key: index, onClick: this.handleComponentClick, index: index, background: this.generateComponentWrapperBackground(), dir: isRTL(this.state.locale) ? Direction.rtl : Direction.ltr, transparentBackground: this.state.componentBackgroundTransparent, designSystem: componentItem.props.designSystem, active: index === this.state.activeComponentIndex, view: this.state.componentView },
                        React.createElement(route.componentMapping, Object.assign({}, this.state.componentData[route.route][index]))));
                }
            });
        }
        else if (route.detailView && this.state.componentView === ComponentViewTypes.detail) {
            return route.detailView.map((componentItem, index) => {
                if (route.componentMapping) {
                    return (React.createElement(React.Fragment, { key: index },
                        this.renderDetailViewComponent(componentItem, index, route),
                        this.renderDetailViewDocumentation(componentItem)));
                }
            });
        }
    }
    renderDetailViewComponent(component, index, route) {
        if (component && component.props && component.props.slot === ComponentViewSlot.detailExample) {
            return (React.createElement(ComponentWrapper, { key: index, index: index, background: this.generateComponentWrapperBackground(), dir: isRTL(this.state.locale) ? Direction.rtl : Direction.ltr, transparentBackground: this.state.componentBackgroundTransparent, designSystem: component.props.designSystem, active: true, view: this.state.componentView },
                React.createElement(route.componentMapping, Object.assign({}, this.state.detailViewComponentData[route.route]))));
        }
        return null;
    }
    renderDetailViewDocumentation(component) {
        if (component && component.props && component.props.slot === ComponentViewSlot.detailDocumentation) {
            return component;
        }
        return null;
    }
    renderShellInfoBar() {
        return (React.createElement(ShellInfoBar, null,
            this.renderStatusBar(),
            this.renderChildrenBySlot(this, ShellSlot.infoBar),
            this.renderInfoBarConfiguration()));
    }
    renderInfoBarConfiguration() {
        return (React.createElement("div", { className: this.props.managedClasses.site_infoBarConfiguration },
            this.renderTransparencyToggle(),
            this.renderThemeSelect(),
            React.createElement("span", { className: this.props.managedClasses.site_infoBarConfiguration_base },
                React.createElement("select", { className: this.props.managedClasses.site_infoBarConfiguration_input, onChange: this.handleLocaleUpdate, value: this.state.locale }, this.renderLocales()))));
    }
    renderStatusBar() {
        return (React.createElement("div", { className: this.props.managedClasses.site_statusBar },
            React.createElement("span", { className: this.props.managedClasses.site_statusComponentName },
                "Component: ",
                this.state.componentName),
            this.renderStatus()));
    }
    renderTransparencyToggle() {
        if (this.props.showTransparencyToggle) {
            return (React.createElement("button", { "aria-pressed": this.state.componentBackgroundTransparent, onClick: this.handleTransparencyToggleClick, className: this.props.managedClasses.site_transparencyToggleButton },
                React.createElement("span", { dangerouslySetInnerHTML: { __html: glyphTransparency } })));
        }
    }
    renderStatus() {
        if (this.props.showComponentStatus) {
            return (React.createElement(React.Fragment, null,
                React.createElement("span", { className: this.getClassNames() }),
                this.state.componentStatus));
        }
    }
    renderThemeSelect() {
        /* tslint:disable-next-line */
        const className = `${this.props.managedClasses.site_infoBarConfiguration_base} ${this.props.managedClasses.site_infoBarConfiguration_theme}`;
        if (Array.isArray(this.props.themes) && this.props.themes.length > 0) {
            return (React.createElement("span", { className: className },
                React.createElement("select", { className: this.props.managedClasses.site_infoBarConfiguration_input, onChange: this.handleThemeUpdate, value: this.state.theme.displayName }, this.renderThemes())));
        }
    }
    getClassNames() {
        const classNames = this.props.managedClasses.site_statusIndicator;
        switch (this.state.componentStatus) {
            case Status.released:
                return `${classNames} ${this.props.managedClasses.site_statusReleased}`;
            case Status.alpha:
                return `${classNames} ${this.props.managedClasses.site_statusAlpha}`;
            default:
                return `${classNames} ${this.props.managedClasses.site_statusBeta}`;
        }
    }
    renderLocales() {
        return this.props.locales.map((locale, index) => {
            return (React.createElement("option", { key: index }, locale));
        });
    }
    renderThemes() {
        return this.props.themes.map((theme, index) => {
            return (React.createElement("option", { key: theme.id, value: theme.id }, theme.displayName));
        });
    }
    /**
     * Gets all of the potential routes as strings to be used to build the shell
     */
    getRoutes(items, baseRoute, slot, routes) {
        let currentRoutes = routes;
        const childItems = Array.isArray(items) ? items : [items];
        childItems.forEach((item) => {
            if (item && item.props && item.props.slot === slot) {
                currentRoutes = this.getCurrentRoute(item, slot, baseRoute, currentRoutes || []);
            }
        });
        return currentRoutes;
    }
    getCurrentRoute(item, slot, baseRoute, currentRoutes) {
        const currentRoute = currentRoutes;
        const itemRoute = `${baseRoute}${item.props.name}/`;
        const detailDocumentationSlotItems = this.renderChildrenBySlot(item, ComponentViewSlot.detailDocumentation);
        const detailExampleSlotItems = this.renderChildrenBySlot(item, ComponentViewSlot.detailExample);
        const detailSlotItems = detailExampleSlotItems.concat(detailDocumentationSlotItems);
        const exampleSlotItems = this.renderChildrenBySlot(item, ComponentViewSlot.example);
        if (exampleSlotItems && exampleSlotItems.length > 0) {
            currentRoute.push({
                route: this.convertToHyphenated(itemRoute),
                exampleView: exampleSlotItems,
                detailView: detailSlotItems,
                schema: item.props.schema,
                componentMapping: item.props.component,
                status: item.props.status
            });
        }
        if (item.props.children) {
            return this.getRoutes(item.props.children, itemRoute, slot, currentRoute);
        }
        return currentRoute;
    }
    renderChildrenBySlot(component, slot) {
        if (component && component.props) {
            return React.Children.map(component.props.children, (child, index) => {
                if (child && child.props && child.props.slot === slot) {
                    return child;
                }
            });
        }
    }
    renderPaneCollapseToggle() {
        return (React.createElement("button", { onClick: this.handlePaneCollapse, className: this.props.managedClasses.site_paneToggleButton },
            React.createElement("span", { className: this.props.managedClasses.site_paneToggleButtonIcon, dangerouslySetInnerHTML: { __html: glyphGlobalnavbutton } })));
    }
    renderRootToc(items, slot, currentPath, itemsPath) {
        if (this.props && this.props.children) {
            return this.getToc(items, slot, currentPath, itemsPath, this.state.tableOfContentsCollapsed);
        }
    }
    getToc(items, slot, currentPath, itemsPath, collapsed) {
        const categoryItems = [];
        const rootTocItems = [];
        const tocItems = Array.isArray(items) ? items : [items];
        tocItems.forEach((item) => {
            const isInSlot = item && item.props && item.props.slot === slot;
            if (isInSlot && ((collapsed && this.renderTocItemCategoryIcon(item)) || !collapsed)) {
                categoryItems.push(item);
            }
        });
        categoryItems.forEach((categoryItem, index) => {
            rootTocItems.push(this.renderTocItem(index, itemsPath, categoryItem, categoryItem, currentPath, slot));
        });
        return rootTocItems;
    }
    /**
     * Adjust URL of TocItem based on the current component-view
     */
    formatTocItemPathWithComponentViewTypes(path) {
        return this.state.componentView === ComponentViewTypes.examples
            ? `${path}${ComponentViewTypes[ComponentViewTypes.examples]}/`
            : path;
    }
    renderTocItem(index, itemsPath, items, child, currentPath, slot) {
        const tocItemPath = this.convertToHyphenated(`${itemsPath}${items.props.name}/`);
        const contentId = uniqueId(this.convertToHyphenated(items.props.name));
        const active = currentPath.match(tocItemPath) !== null;
        const attributes = {
            key: index,
            active,
            heading: child && child.props ? !Boolean(child.props.children) : false,
            to: void (0),
            controls: contentId,
            onClick: (e) => {
                this.setState({
                    activeComponentIndex: 0,
                    componentName: this.getComponentName(tocItemPath),
                    componentStatus: this.getComponentStatus(tocItemPath),
                    currentPath: tocItemPath
                });
            }
        };
        if (this.hasCanvasContent(items)) {
            attributes.to = this.formatTocItemPathWithComponentViewTypes(tocItemPath);
        }
        if (child && child.props && child.props.name) {
            return (React.createElement(TocItem, Object.assign({}, attributes),
                this.renderTocItemCategory(child.props.name, this.renderTocItemCategoryIcon(child)),
                this.renderTocItemMenu(child, slot, currentPath, tocItemPath)));
        }
        return null;
    }
    renderTocItemMenu(item, slot, currentPath, tocItemPath) {
        if (item.props.children &&
            (!item.props.children.props || (item.props.children.props && item.props.children.props.slot !== SiteSlot.categoryIcon))) {
            return this.getToc(item.props.children, slot, currentPath, tocItemPath);
        }
        return null;
    }
    renderTocItemCategory(name, icon) {
        const renderLayout = icon
            ? (React.createElement("div", { className: this.props.managedClasses.site_paneToggleButtonIconLayout },
                React.createElement("span", { className: this.props.managedClasses.site_paneToggleButtonIcon }, icon)))
            : null;
        if (this.state.tableOfContentsCollapsed) {
            return renderLayout;
        }
        return (React.createElement("span", { className: this.props.managedClasses.site_paneTocRow },
            renderLayout,
            icon ? React.createElement("span", { className: this.props.managedClasses.site_paneTocTitle }, name) : name));
    }
    renderTocItemCategoryIcon(item) {
        if (Array.isArray(item.props.children)) {
            item.props.children.forEach((childElement) => {
                if (childElement && childElement.props && childElement.props.slot === SiteSlot.categoryIcon) {
                    return childElement;
                }
            });
        }
        else {
            if (item.props.children.props && item.props.children.props.slot === SiteSlot.categoryIcon) {
                return item;
            }
        }
        return null;
    }
    hasCanvasContent(item) {
        let hasCanvasContent = false;
        const exampleSlot = ComponentViewSlot.example;
        const detailExampleSlot = ComponentViewSlot.detailExample;
        const detailDocumentationSlot = ComponentViewSlot.detailDocumentation;
        if (item.props.children) {
            const itemChildren = Array.isArray(item.props.children) ? item.props.children : [item.props.children];
            itemChildren.forEach((child) => {
                hasCanvasContent = child && child.props
                    ? child.props.slot === exampleSlot
                        || child.props.slot === detailExampleSlot
                        || child.props.slot === detailDocumentationSlot
                    : false;
            });
        }
        return hasCanvasContent;
    }
    convertToHyphenated(name) {
        return name.toLowerCase().replace(/\s/g, "-");
    }
}
Site.defaultProps = {
    locales: ["en", "en-rtl"],
    showComponentStatus: true,
    showTransparencyToggle: true
};
export default manageJss(styles)(Site);
export { SiteTitle, SiteTitleBrand, SiteMenu, SiteMenuItem, SiteCategory, SiteCategoryDocumentation, SiteCategoryIcon, SiteCategoryItem };
//# sourceMappingURL=index.js.map