Untitled

mail@pastecode.io avatar
unknown
jsx
2 years ago
2.3 kB
3
Indexable
Never
import { useContext, createContext, useState, useEffect } from "react";

// Components
import Image from "next/image";
import { Heading, SliderFilter } from "../../";

// Styles
import styles from "./accordion.module.scss";
import cn from "classnames";
import { useVariable } from "hooks/useVariable";

export const AccordionContext = createContext({});

const AccordionComponent = ({ children }) => {
  const { openFilters, setOpenFilters } = useVariable();
  const [openItems, setOpenItems] = useState(
    openFilters ? [...openFilters] : []
  );
  const [isReset, setIsReset] = useState(false);
  const toggle = (index) => {
    setOpenItems((currentOpen) => {
      if (!currentOpen?.includes(index)) {
        return [...openItems, index];
      }
      return currentOpen.filter((i) => i !== index);
    });
  };

  return (
    <AccordionContext.Provider
      value={{
        openItems,
        setOpenItems,
        toggle,
      }}
    >
      {children}
    </AccordionContext.Provider>
  );
};

const AccordionItem = ({ item, slider, children, ...rest }) => {
  const { openItems, toggle, isReset } = useContext(AccordionContext);
  const { id, parentName } = item;
  const isOpen = id && openItems?.includes(id);
  const headerClasses = cn(styles.heading, isOpen && styles.toggleOpen);
  const contentClasses = cn(styles.content, isOpen && styles.contentVisible);

  return (
    <div {...rest} className={styles.item}>
      <div
        className={headerClasses}
        onClick={(event) => {
          id && toggle(id);
        }}
      >
        <div className={styles.container}>
          <Heading level={6} className="span--accordionHeading">
            {parentName}
          </Heading>
        </div>

        {!!slider && (
          <div className={styles.slider}>
            <SliderFilter item={item} isReset={isReset} />
          </div>
        )}
        <div className={styles.toggle}>
          <Image
            src="/images/accordionToggle.svg"
            alt="toggle"
            width={13}
            height={10}
            className={isOpen ? styles.toggleIconOpen : styles.toggleIconClosed}
          />
        </div>
      </div>

      <div className={contentClasses}>{children}</div>
    </div>
  );
};

AccordionComponent.Item = AccordionItem;

export const Accordion = AccordionComponent;