feat(ui): add support for default size in usePanel

This commit is contained in:
psychedelicious 2024-07-10 18:27:32 +10:00 committed by Kent Keirsey
parent 788f90a7d5
commit 2e7a95998c

View File

@ -16,6 +16,10 @@ export type UsePanelOptions =
* The minimum size of the panel as a percentage.
*/
minSize: number;
/**
* The default size of the panel as a percentage.
*/
defaultSize?: number;
/**
* The unit of the minSize
*/
@ -26,6 +30,10 @@ export type UsePanelOptions =
* The minimum size of the panel in pixels.
*/
minSize: number;
/**
* The default size of the panel in pixels.
*/
defaultSize?: number;
/**
* The unit of the minSize.
*/
@ -50,6 +58,10 @@ export type UsePanelReturn = {
* The dynamically calculated minimum size of the panel.
*/
minSize: number;
/**
* The dynamically calculated default size of the panel.
*/
defaultSize: number;
/**
* Whether the panel is collapsed.
*/
@ -94,6 +106,7 @@ export type UsePanelReturn = {
export const usePanel = (arg: UsePanelOptions): UsePanelReturn => {
const panelHandleRef = useRef<ImperativePanelHandle>(null);
const [_minSize, _setMinSize] = useState<number>(arg.unit === 'percentages' ? arg.minSize : 0);
const [_defaultSize, _setDefaultSize] = useState<number>(arg.defaultSize ?? arg.minSize);
// If the units are pixels, we need to calculate the min size as a percentage of the available space,
// then resize the panel if it is too small.
@ -115,6 +128,13 @@ export const usePanel = (arg: UsePanelOptions): UsePanelReturn => {
const minSizePct = getSizeAsPercentage(arg.minSize, arg.panelGroupRef, arg.panelGroupDirection);
_setMinSize(minSizePct);
const defaultSizePct = getSizeAsPercentage(
arg.defaultSize ?? arg.minSize,
arg.panelGroupRef,
arg.panelGroupDirection
);
_setDefaultSize(defaultSizePct);
if (!panelHandleRef.current.isCollapsed() && panelHandleRef.current.getSize() < minSizePct && minSizePct > 0) {
panelHandleRef.current.resize(minSizePct);
}
@ -124,8 +144,12 @@ export const usePanel = (arg: UsePanelOptions): UsePanelReturn => {
panelGroupHandleElements.forEach((el) => resizeObserver.observe(el));
// Resize the panel to the min size once on startup
const minSizePct = getSizeAsPercentage(arg.minSize, arg.panelGroupRef, arg.panelGroupDirection);
panelHandleRef.current?.resize(minSizePct);
const defaultSizePct = getSizeAsPercentage(
arg.defaultSize ?? arg.minSize,
arg.panelGroupRef,
arg.panelGroupDirection
);
panelHandleRef.current?.resize(defaultSizePct);
return () => {
resizeObserver.disconnect();
@ -185,8 +209,8 @@ export const usePanel = (arg: UsePanelOptions): UsePanelReturn => {
}
// Otherwise, resize to the min size
panelHandleRef.current?.resize(_minSize);
}, [_minSize, collapse]);
panelHandleRef.current?.resize(_defaultSize);
}, [_defaultSize, _minSize, collapse]);
return {
ref: panelHandleRef,
@ -200,6 +224,7 @@ export const usePanel = (arg: UsePanelOptions): UsePanelReturn => {
collapse,
resize,
onDoubleClickHandle,
defaultSize: _defaultSize,
};
};