Skip to content

Commit

Permalink
chore: refactor Expander to dynamically wrap to height if content is …
Browse files Browse the repository at this point in the history
…shorter than threshold
  • Loading branch information
jamiehenson committed Apr 26, 2024
1 parent 0f51cfe commit 2944826
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 27 deletions.
23 changes: 16 additions & 7 deletions src/core/Expander.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,40 @@
import React, { PropsWithChildren, useEffect, useRef, useState } from "react";

type ExpanderProps = {
height?: number;
heightThreshold?: number;
className?: string;
fadeClassName?: string;
};

const Expander = ({
height = 200,
heightThreshold = 200,
className,
fadeClassName,
children,
}: PropsWithChildren<ExpanderProps>) => {
const innerRef = useRef<HTMLDivElement>(null);
const [contentHeight, setContentHeight] = useState(height);
const [showControls, setShowControls] = useState(false);
const [height, setHeight] = useState<number | "auto">(heightThreshold);
const [expanded, setExpanded] = useState(false);

useEffect(() => {
setContentHeight(innerRef.current?.clientHeight ?? height);
}, [height, expanded]);
const contentHeight = innerRef.current?.clientHeight ?? heightThreshold;

const showControls = height > 0 && contentHeight > height;
if (contentHeight < heightThreshold) {
setHeight("auto");
} else if (expanded) {
setHeight(contentHeight);
} else {
setHeight(heightThreshold);
}

setShowControls(contentHeight >= heightThreshold);
}, [heightThreshold, expanded]);

return (
<>
<div
style={{ ...(height && { height: expanded ? contentHeight : height }) }}
style={{ height }}
className={`overflow-hidden transition-all relative ${className ?? ""}`}
>
{showControls && !expanded && (
Expand Down
20 changes: 0 additions & 20 deletions src/core/Expander/Expander.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,23 +130,3 @@ export const OverriddenStyles = {
},
},
};

export const Bypassed = {
render: () => (
<Expander
className="bg-neutral-400 p-16 rounded-lg"
fadeClassName="from-neutral-800"
height={0}
>
{longContentInner}
</Expander>
),
parameters: {
docs: {
description: {
story:
"A set height of 0, which means that no expansion behaviour is applied.",
},
},
},
};

0 comments on commit 2944826

Please sign in to comment.