"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.Table = void 0;
var _compat = require("preact/compat");
var _Alert = _interopRequireDefault(require("../Alert/Alert"));
var _TableCaption = _interopRequireDefault(require("./TableCaption"));
var _TableContext = _interopRequireDefault(require("./TableContext"));
var _classnames = _interopRequireDefault(require("classnames"));
var _debounce = _interopRequireDefault(require("../utilities/debounce"));
var _useId = _interopRequireDefault(require("../utilities/useId"));
var _jsxRuntime = require("preact/compat/jsx-runtime");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
 * Determine if a ReactNode is a TableCaption
 */function isTableCaption(child) {
  if (!child || !(0, _compat.isValidElement)(child)) {
    return false;
  }

  // Check child.type first and as a fallback, check child.type.displayName follow by child.type.name
  const componentName = child.type?.displayName || child.type?.name;
  return child.type === _TableCaption.default || componentName === 'TableCaption';
}
/**
 * `Table` is a container component that contains `TableCaption`, `TableHead`
 * and `TableBody` as children, as well as `TableRow` and `TableCell` for the
 * table content. These components mostly follow ordinary HTML table semantics,
 * but also include some additional responsive features including horizontal
 * scrolling and vertically stacked rows.
 *
 * For information about how and when to use this component,
 * [refer to its full documentation page](https://design.cms.gov/components/table/).
 */
const Table = _ref => {
  let {
    borderless,
    className,
    compact,
    stackable,
    stackableBreakpoint,
    striped,
    scrollable,
    scrollableNotice,
    warningDisabled,
    children,
    id,
    ...tableProps
  } = _ref;
  const [scrollActive, setScrollActive] = (0, _compat.useState)(false);
  const captionId = (0, _useId.default)('table-caption--', id);
  if (process.env.NODE_ENV !== 'production') {
    if (scrollable && Array.isArray(children) && !children.some(child => isTableCaption(child))) {
      console.warn('The children prop in `Table` must include `TableCaption` component for scrollable tables.');
    }
  }
  const containerRef = (0, _compat.useRef)();
  (0, _compat.useEffect)(() => {
    if (!window || !scrollable) {
      return;
    }
    const handleResize = () => {
      if (containerRef.current) {
        const {
          scrollWidth,
          clientWidth
        } = containerRef.current;
        setScrollActive(scrollWidth > clientWidth);
      }
    };
    handleResize();
    const debounceHandleResize = (0, _debounce.default)(handleResize, 500);
    window.addEventListener('resize', debounceHandleResize);
    return () => {
      window.removeEventListener('resize', debounceHandleResize);
    };
  }, [setScrollActive, scrollable]);
  const classes = (0, _classnames.default)('ds-c-table', borderless ? 'ds-c-table--borderless' : null, compact ? 'ds-c-table--compact' : null, striped ? 'ds-c-table--striped' : null, stackable ? `ds-c-${stackableBreakpoint}-table--stacked` : null, className);

  /**
   * Makes table container focusable and displays the scrollable notice when table width exceeds viewport
   * by setting `tabIndex = 0` attribute.
   * This provides context for screen readers to the table's <caption> via aria-labelleby
   */
  const attributeScrollable = scrollable && {
    className: 'ds-c-table__wrapper',
    role: 'region',
    'aria-labelledby': captionId,
    tabIndex: scrollActive ? 0 : null
  };
  const contextValue = {
    stackable: !!stackable,
    warningDisabled: !!warningDisabled
  };
  const renderedChildren = _compat.Children.map(children, child => {
    if (isTableCaption(child)) {
      // Extend props on TableCaption before rendering.
      if (scrollable) {
        return (0, _compat.cloneElement)(child, {
          _id: captionId,
          _scrollActive: scrollActive,
          _scrollableNotice: scrollableNotice
        });
      }
    }
    return child;
  });
  const table = /*#__PURE__*/(0, _jsxRuntime.jsx)(_TableContext.default.Provider, {
    value: contextValue,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)("table", {
      className: classes,
      ...tableProps,
      children: renderedChildren
    })
  });
  return scrollable ? /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    ref: containerRef,
    "aria-live": "polite",
    "aria-relevant": "additions",
    ...attributeScrollable,
    children: table
  }) : table;
};
exports.Table = Table;
Table.defaultProps = {
  scrollableNotice: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Alert.default, {
    className: "ds-c-table__scroll-alert",
    role: "status",
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
      className: "ds-c-alert__text",
      children: "Scroll using arrow keys to see more"
    })
  }),
  stackableBreakpoint: 'sm'
};
var _default = Table;
exports.default = _default;