All files / src/material-toolbox/elevation index.js

100% Statements 14/14
33.33% Branches 1/3
100% Functions 5/5
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                5x 83x   83x             5x       25x   25x   25x           25x   25x                   5x   58x 58x   58x                   5x      
// @flow strict
import React, { useMemo } from 'react';
import cx from 'classnames';
 
import type { Node, AbstractComponent } from 'react';
 
import { getDisplayName } from '../utils';
 
export const useElevation = (depth: number = 0, transition: boolean = false) =>
  useMemo(
    () =>
      cx({
        [`mdc-elevation--z${depth}`]: depth >= 0,
        'mdc-elevation-transition': transition,
      }),
    [depth, transition],
  );
 
export const withElevation = <Config: { className?: string }, Instance>(
  Component: AbstractComponent<Config, Instance>,
  { depth, transition }: { depth?: number, transition?: boolean } = {},
): AbstractComponent<Config, Instance> => {
  const Elevated = React.forwardRef<Config, Instance>(
    ({ className, ...rest }: Config, ref) => {
      const mtClassName = useElevation(depth, transition);
 
      return (
        <Component {...rest} ref={ref} className={cx(className, mtClassName)} />
      );
    },
  );
 
  Elevated.displayName = `WithElevation(${getDisplayName(Component)})`;
 
  return Elevated;
};
 
type Props = {
  children: Node,
  depth?: number,
  transition?: boolean,
  className?: string,
};
 
const Elevation = React.forwardRef<Props, _>(
  ({ children, className, transition, depth }: Props, ref) => {
    const child = React.Children.only(children);
    const mtClassName = useElevation(depth, transition);
 
    return (
      <child.type
        {...child.props}
        className={cx(mtClassName, className, child.props.className)}
        ref={ref}
      />
    );
  },
);
 
Elevation.displayName = 'Elevation';
 
export default Elevation;