Skip to content
Snippets Groups Projects
createSidebar.tsx 6.27 KiB
Newer Older
Liliana Sanfilippo's avatar
Liliana Sanfilippo committed
import { useEffect, useState } from "react";
import { ScrollLink } from "../components/ScrollLink";
import { Highlight, NewHighlight } from "./Highlight-functions";

// Funktion zur Erstellung der Sidebar
export function createSidebar(tabs: Array<{ tab: string; subtabs?: Array<string> }>) {
    const { numsBig, numsSub } = deriveTabsData(tabs);
    console.log({ numsBig, numsSub })
Liliana Sanfilippo's avatar
Liliana Sanfilippo committed
    const [openTab, setOpenTab] = useState<string | null>(null);
    
           
    useEffect(() => {
      const handleScroll = () => {
        numsBig.forEach((item, ind) => {
          const element = document.getElementById(item);
          const subtitleElement = document.getElementById(`subtitle${ind}`);
          if (element && subtitleElement) {
            Highlight({ el: element }, { subtitle: subtitleElement });
          }
        });
  
        numsSub.forEach((item, ind) => {
          const element = document.getElementById(item);
          const subtitleElement = document.getElementById(`newsubtitle${ind}`);
          if (element && subtitleElement) {
            NewHighlight({ el: element }, { subtitle: subtitleElement });
          }
        });
      };
  
      window.addEventListener("scroll", handleScroll);
      return () => window.removeEventListener("scroll", handleScroll);
    }, [numsBig, numsSub, openTab]);

    const scrolling = (tab: string) => {
      const targetElement = document.getElementById(tab);
      if (targetElement) {
        //console.log(`Scrolling to element with ID: ${tab}`);
        
        // Get the position of the element relative to the document
        const elementRect = targetElement.getBoundingClientRect();
        const elementTop = elementRect.top + window.scrollY;
        
        // Calculate the middle of the viewport
        const viewportHeight = window.innerHeight;
        const scrollOffset = elementTop - (viewportHeight / 5 - targetElement.offsetHeight / 2);
       /*  
        console.log(`Element Top: ${elementTop}`);
        console.log(`Viewport Height: ${viewportHeight}`);
        console.log(`Scroll Offset: ${scrollOffset}`); */
        
        window.scrollTo({
            top: scrollOffset,
            behavior: "smooth"
        });
      } else {
          console.error(`Scroll target element not found for ID: ${tab}`);
      }
    }

    const toggleTab = (tab: string) => {
      setOpenTab(openTab === tab ? null : tab);
     // console.log(`Status of tab ${tab} is ${openTab}`)
     scrolling(tab)
Liliana Sanfilippo's avatar
Liliana Sanfilippo committed
    };

    let subtitlenumber = 0; 
    return (
      <>
        <br />
        <div className="sticky-top">
          <nav className="sidebar">
            {tabs.map((tab, index) => {
              const tabId = `tab-${tab.tab}`;
              const parentId = `parent-${tab.tab}`;
              const subtitleId = `subtitle${index}`;
              
              return (
                <div key={index}>
                  
                    <div id={subtitleId} className="detail-sideitem">
                      <div id={parentId} className="sideitem">
                      <a
                          onClick={() => {
                            // console.log(`Clicked on Tab ${tab.tab} with tab-name tab-${tab.tab} and parent parent-${tab.tab}`);
                            toggleTab(tab.tab);
                            // Close other tabs when a new tab is opened
                            tabs.forEach((t) => {
                              if (t.tab !== tab.tab) {
                                document.getElementById(`tab-${t.tab}`)!.style.display = "none";
                                document.getElementById(`parent-${t.tab}`)!.classList.remove("active-sideitem");
                              }
                            });
                            // Show or hide the selected tab
                            document.getElementById(tabId)!.style.display = openTab === tab.tab ? "block" : "none";
                            document.getElementById(parentId)!.classList.toggle("active-sideitem");
                          }}
                        >
                          <summary>{tab.tab}</summary>
                        </a>
                        {tab.subtabs && (
                          <span
                            id={tabId}
                            className="sidesubtab"
                            style={{ display: openTab === tab.tab ? "block" : "none" }}
                          >
                            <ul>
                              {tab.subtabs.map((subtab, subIndex) => {
                                const subTabId = `newsubtitle${subtitlenumber}`;
                               /*  console.log(`Old subtitlenumber is ${subtitlenumber}`) */
                                subtitlenumber = subtitlenumber + 1; 
                                // console.log(`New subtitlenumber is ${subtitlenumber}`)
                               // console.log(`Made subtab newsubtitle${subtitlenumber} that will link to ${tab.tab}${subIndex +1 }H`) 
Liliana Sanfilippo's avatar
Liliana Sanfilippo committed
                                return (
                                  <li key={subtitlenumber} id={subTabId}>
                                    <ScrollLink label={subtab} targetId={`${tab.tab}${subIndex +1 }H`} />
Liliana Sanfilippo's avatar
Liliana Sanfilippo committed
                                  </li>
                                );
                              })}
                            </ul>
                          </span>
                        )}
                      </div>
                    </div>
                  
  
                  
                </div>
              );
            })}
          </nav>
          <br />
          <div className="col" style={{ display: "flex", alignItems: "right" }}>
            <a href="#" className="backtotop">
              Back to Top &#8593;
            </a>
          </div>
        </div>
      </>
    );
  }


  function deriveTabsData(tabs: Array<{ tab: string; subtabs?: Array<string> }>) {
    const numsBig: string[] = [];
    const numsSub: string[] = [];

    tabs.forEach(tab => {
        let count = 1;  
        numsBig.push(`${tab.tab}H`); // z.B. RoleH, ChecksH
        if (tab.subtabs) {
            tab.subtabs.forEach((_index) => {
                // console.log(index)
                numsSub.push(`${tab.tab}${count}`); // z.B. Role1H, Role2H
                count += 1; 
            });
        }
    });

    return { numsBig, numsSub };
}