Giter VIP home page Giter VIP logo

Comments (2)

yaldram avatar yaldram commented on May 25, 2024

Final hook code adapted to my use case -

export function useCollapse({
  isExpanded: configExpanded = false,
  onExpandStart = noop,
  onExpandEnd = noop,
  onCollapseStart = noop,
  onCollapseEnd = noop,
}: UseCollapseInput = {}) {
  const [isExpanded, setExpanded] = useState(configExpanded);

  const [styles, setStylesRaw] = useState<CSSProperties>(
    isExpanded ? {} : collapsedStyles
  );

  useEffect(() => {
    expandCollapse(configExpanded);
  }, [configExpanded]);

  const el = useRef<HTMLElement | null>(null);

  const setStyles = (newStyles: {} | ((oldStyles: {}) => {})) => {
    flushSync(() => {
      setStylesRaw(newStyles);
    });
  };

  const mergeStyles = (newStyles: {}) => {
    setStyles((oldStyles) => ({ ...oldStyles, ...newStyles }));
  };

  const handleTransitionEnd = (e: TransitionEvent): void => {
    if (e.target !== el.current || e.propertyName !== "height") {
      return;
    }
  
    if (isExpanded) {
      const height = getElementHeight(el);
    
      if (height === styles.height) {
        setStyles({});
      } else {
        mergeStyles({ height });
      }

      onExpandEnd();
    }

    onCollapseEnd();
  };

  function expandCollapse(nextState: boolean) {
    setExpanded(nextState);
    if (nextState) {
      requestAnimationFrame(() => {
        onExpandStart();
        mergeStyles({
          willChange: "height",
          display: "block",
          overflow: "hidden",
        });

        requestAnimationFrame(() => {
          const height = getElementHeight(el);
          mergeStyles({
            transition: `height ${duration}ms ${easing}`,
            height,
          });
        });
      });
    } else {
      requestAnimationFrame(() => {
        onCollapseStart();
        const height = getElementHeight(el);
        mergeStyles({
          transition: `height ${duration}ms ${easing}`,
          willChange: "height",
          height,
        });

        requestAnimationFrame(() => {
          mergeStyles({
            height: "0px",
            overflow: "hidden",
          });
        });
      });
    }
  }

  function getToggleProps({
    disabled = false,
    onClick = noop,
    ...rest
  }: GetTogglePropsInput = {}): GetTogglePropsOutput {
    return {
      type: "button",
      role: "button",
      id: `react-collapsed-toggle`,
      "aria-controls": `react-collapsed-panel`,
      "aria-expanded": isExpanded,
      tabIndex: 0,
      disabled,
      ...rest,
      onClick: disabled
        ? noop
        : callAll(onClick, () => {
            expandCollapse(!isExpanded);
          }),
    };
  }

  function getCollapseProps({
    style = {},
    onTransitionEnd = noop,
    refKey = "ref",
    ...rest
  }: GetCollapsePropsInput = {}): GetCollapsePropsOutput {
    const theirRef: any = rest[refKey];

    return {
      id: `react-collapsed-panel`,
      "aria-hidden": !isExpanded,
      [refKey]: mergeRefs(el, theirRef),
      ...rest,
      onTransitionEnd: callAll(handleTransitionEnd, onTransitionEnd),
      style: {
        boxSizing: "border-box",
        // additional styles passed, e.g. getCollapseProps({style: {}})
        ...style,
        // style overrides from state
        ...styles,
      },
    };
  }

  return {
    getToggleProps,
    getCollapseProps,
    isExpanded,
    setExpanded,
  };
}

from collapsed.

roginfarrer avatar roginfarrer commented on May 25, 2024

The problem with moving it to a click handler is that the expand state won't change when props change, only if the click handler is called with getToggleProps. This library is meant to be used without it.

This library was refactored to a vanilla JS core (will be soon pushed to latest), and that changes this whole set-up quite a bit.

from collapsed.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.