'use client';
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var table = require('@react-stately/table');
var React = require('react');
var focus = require('@react-aria/focus');
var interactions = require('@react-aria/interactions');
var table$1 = require('@react-aria/table');
var utils$1 = require('@react-aria/utils');
var checkbox = require('@keystar/ui/checkbox');
var typography = require('@keystar/ui/typography');
var utils = require('@keystar/ui/utils');
var arrowUpIcon = require('@keystar/ui/icon/icons/arrowUpIcon');
var icon = require('@keystar/ui/icon');
var style = require('@keystar/ui/style');
var jsxRuntime = require('react/jsx-runtime');

// ============================================================================
// UTILS
// ============================================================================

function getStyleFromColumn(props) {
  const {
    maxWidth,
    minWidth,
    width
  } = props;
  if (width) {
    return {
      flex: '0 0 auto',
      width,
      maxWidth,
      minWidth
    };
  }
  return {
    maxWidth,
    minWidth
  };
}

// ============================================================================
// COMPONENTS
// ============================================================================

const SortIndicator = () => {
  // fix alignment: reduce the space the icon takes up, w/o affecting the icon layout itself
  let labelHeight = style.tokenSchema.typography.text.regular.capheight;
  return /*#__PURE__*/jsxRuntime.jsx("span", {
    "aria-hidden": "true",
    className: style.css({
      alignItems: 'center',
      display: 'flex',
      flexShrink: 0,
      height: labelHeight,
      justifyContent: 'center',
      marginInline: style.tokenSchema.size.space.small,
      opacity: 0,
      position: 'relative',
      transition: style.transition(['opacity', 'transform'], {
        easing: 'easeOut'
      }),
      width: labelHeight,
      svg: {
        position: 'absolute'
      },
      ['[aria-sort="ascending"] &, [aria-sort="descending"] &']: {
        opacity: 1
      },
      ['[aria-sort="descending"] &']: {
        transform: 'rotate(180deg)'
      }
    }),
    children: /*#__PURE__*/jsxRuntime.jsx(icon.Icon, {
      src: arrowUpIcon.arrowUpIcon
    })
  });
};

// ============================================================================
// HOOKS
// ============================================================================

// Table root
// ----------------------------------------------------------------------------

function useTableStyleProps(props) {
  let styleProps = style.useStyleProps(props);
  return {
    ...utils.toDataAttributes(props, new Set(['density', 'overflowMode', 'prominence'])),
    className: style.classNames(styleProps.className, 'ksv-table-view', style.css({
      display: 'flex',
      flexDirection: 'column',
      minHeight: 0,
      minWidth: 0
    })),
    style: styleProps.style
  };
}

// Row group (head/body/foot)
// ----------------------------------------------------------------------------

function useHeadStyleProps() {
  return {
    className: style.css({
      display: 'flex',
      flexDirection: 'column',
      '.ksv-table-view[data-prominence="low"] &': {
        borderBottom: `${style.tokenSchema.size.border.regular} solid ${style.tokenSchema.color.border.muted}`
      }
    })
  };
}
function useBodyStyleProps() {
  return {
    className: style.css({
      display: 'flex',
      flexDirection: 'column',
      overflow: 'auto',
      '.ksv-table-view:not([data-prominence="low"]) &': {
        backgroundColor: style.tokenSchema.color.background.canvas,
        border: `${style.tokenSchema.size.border.regular} solid ${style.tokenSchema.color.border.muted}`,
        borderRadius: style.tokenSchema.size.radius.medium
      }
    })
  };
}

// Cell common
// ----------------------------------------------------------------------------

const commonCellStyles = {
  // borderBottom: `${tokenSchema.size.border.regular} solid ${tokenSchema.color.border.neutral}`,
  boxSizing: 'border-box',
  cursor: 'default',
  display: 'flex',
  flex: 1,
  justifyContent: 'flex-start',
  minWidth: 0,
  outline: 0,
  paddingInline: style.tokenSchema.size.space.medium,
  position: 'relative'
};
function useCellStyleProps(props, state) {
  const className = style.css([commonCellStyles, {
    // Alignment
    '&[data-align="end"]': {
      justifyContent: 'flex-end'
    },
    '&[data-align="center"]': {
      justifyContent: 'center'
    },
    // wrapping text shouldn't be centered
    alignItems: 'center',
    '.ksv-table-view[data-overflow-mode="wrap"] &': {
      alignItems: 'initial'
    },
    // Density
    paddingBlock: style.tokenSchema.size.space.medium,
    '.ksv-table-view[data-density="compact"] &': {
      paddingBlock: style.tokenSchema.size.space.regular
    },
    '.ksv-table-view[data-density="spacious"] &': {
      paddingBlock: style.tokenSchema.size.space.large
    },
    // focus ring
    '&[data-focus="visible"]::after': {
      borderRadius: style.tokenSchema.size.radius.small,
      boxShadow: `inset 0 0 0 ${style.tokenSchema.size.alias.focusRing} ${style.tokenSchema.color.alias.focusRing}`,
      content: '""',
      inset: 0,
      position: 'absolute',
      transition: style.transition(['box-shadow', 'margin'], {
        easing: 'easeOut'
      })
    },
    // HEADERS
    '&[role="columnheader"]': {
      color: style.tokenSchema.color.foreground.neutralSecondary,
      ['&[aria-sort]']: {
        cursor: 'default',
        '&:hover, &[data-focus="visible"]': {
          color: style.tokenSchema.color.foreground.neutralEmphasis
        }
      }
    }
  }]);
  return {
    ...utils.toDataAttributes({
      focus: state !== null && state !== void 0 && state.isFocusVisible ? 'visible' : undefined,
      align: props === null || props === void 0 ? void 0 : props.align
    }),
    className,
    style: getStyleFromColumn(props)
  };
}
function useSelectionCellStyleProps() {
  return {
    className: style.css(commonCellStyles, {
      alignItems: 'center',
      flex: '0 0 auto',
      paddingInlineStart: style.tokenSchema.size.space.medium,
      width: 'auto'
    })
  };
}

// Row body
// ----------------------------------------------------------------------------

function useRowStyleProps(state) {
  let calculatedRadius = `calc(${style.tokenSchema.size.radius.medium} - ${style.tokenSchema.size.border.regular})`;
  const className = style.css({
    boxSizing: 'border-box',
    display: 'flex',
    position: 'relative',
    outline: 0,
    '&:not(:last-child)': {
      borderBottom: `${style.tokenSchema.size.border.regular} solid ${style.tokenSchema.color.border.muted}`
    },
    // prominence
    '.ksv-table-view:not([data-prominence="low"]) &': {
      '&:first-child': {
        borderStartStartRadius: calculatedRadius,
        borderStartEndRadius: calculatedRadius
      },
      '&:last-child': {
        borderEndStartRadius: calculatedRadius,
        borderEndEndRadius: calculatedRadius
      }
    },
    // interactions
    '&[data-interaction="hover"]': {
      backgroundColor: style.tokenSchema.color.alias.backgroundIdle
    },
    '&[data-interaction="press"]': {
      backgroundColor: style.tokenSchema.color.alias.backgroundHovered
    },
    // focus indicator
    '&[data-focus="visible"]': {
      '&::before': {
        backgroundColor: style.tokenSchema.color.background.accentEmphasis,
        borderRadius: style.tokenSchema.size.space.small,
        content: '""',
        insetInlineStart: style.tokenSchema.size.space.xsmall,
        marginBlock: style.tokenSchema.size.space.xsmall,
        marginInlineEnd: `calc(${style.tokenSchema.size.space.small} * -1)`,
        position: 'sticky',
        width: style.tokenSchema.size.space.small
      }
    },
    // selected
    '&[aria-selected="true"]': {
      backgroundColor: style.tokenSchema.color.alias.backgroundSelected,
      // boxShadow: `0 0 0 ${tokenSchema.size.border.regular} ${tokenSchema.color.alias.focusRing}`,

      '&[data-interaction="hover"]': {
        backgroundColor: style.tokenSchema.color.alias.backgroundSelectedHovered
      }
    }
  });
  return {
    ...utils.toDataAttributes({
      focus: state.isFocusVisible ? 'visible' : state.isFocusWithin ? 'within' : undefined,
      interaction: state.isPressed ? 'press' : state.isHovered ? 'hover' : undefined
    }),
    className
  };
}

// Row header
// ----------------------------------------------------------------------------

function useRowHeaderStyleProps() {
  const className = style.css({
    display: 'flex'
  });
  return {
    className
  };
}

function TableView(props) {
  let ref = React.useRef(null);
  // @ts-ignore FIXME: Resolve the disparity between the types of TableView and useTableState.
  let state = table.useTableState({
    ...props,
    showSelectionCheckboxes: props.selectionMode === 'multiple'
  });
  let {
    collection
  } = state;
  let {
    gridProps
  } = table$1.useTable(props, state, ref);
  let styleProps = useTableStyleProps(props);
  let rows = [...collection.body.childNodes];
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    ...gridProps,
    ...styleProps,
    ref: ref,
    children: [/*#__PURE__*/jsxRuntime.jsx(TableHead, {
      children: collection.headerRows.map(headerRow => /*#__PURE__*/jsxRuntime.jsx(TableHeaderRow, {
        item: headerRow,
        state: state,
        children: [...headerRow.childNodes].map(column => column.props.isSelectionCell ? /*#__PURE__*/jsxRuntime.jsx(TableSelectAllCell, {
          column: column,
          state: state
        }, column.key) : /*#__PURE__*/jsxRuntime.jsx(TableColumnHeader, {
          column: column,
          state: state
        }, column.key))
      }, headerRow.key))
    }), /*#__PURE__*/jsxRuntime.jsx(TableBody, {
      children: !rows.length && props.renderEmptyState ? /*#__PURE__*/jsxRuntime.jsx("div", {
        role: "row",
        "aria-rowindex": 2,
        children: /*#__PURE__*/jsxRuntime.jsx("div", {
          role: "rowheader",
          "aria-colspan": collection.columnCount,
          children: props.renderEmptyState()
        })
      }) : rows.map(row => /*#__PURE__*/jsxRuntime.jsx(TableRow, {
        item: row,
        state: state,
        hasAction: !!props.onRowAction,
        children: [...row.childNodes].map(cell => cell.props.isSelectionCell ? /*#__PURE__*/jsxRuntime.jsx(TableCheckboxCell, {
          cell: cell,
          state: state
        }, cell.key) : /*#__PURE__*/jsxRuntime.jsx(TableCell, {
          cell: cell,
          state: state,
          overflowMode: props.overflowMode
        }, cell.key))
      }, row.key))
    })]
  });
}

// Styled components
// ------------------------------

function TableHead(_ref) {
  let {
    children
  } = _ref;
  let {
    rowGroupProps
  } = table$1.useTableRowGroup();
  let styleProps = useHeadStyleProps();
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    ...rowGroupProps,
    ...styleProps,
    children: children
  });
}
function TableBody(_ref2) {
  let {
    children
  } = _ref2;
  let {
    rowGroupProps
  } = table$1.useTableRowGroup();
  let styleProps = useBodyStyleProps();
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    ...rowGroupProps,
    ...styleProps,
    children: children
  });
}
function TableHeaderRow(_ref3) {
  let {
    item,
    state,
    children
  } = _ref3;
  let ref = React.useRef(null);
  let {
    rowProps
  } = table$1.useTableHeaderRow({
    node: item
  }, state, ref);
  let styleProps = useRowHeaderStyleProps();
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    ...rowProps,
    ...styleProps,
    ref: ref,
    children: children
  });
}
function TableColumnHeader(_ref4) {
  let {
    column,
    state
  } = _ref4;
  let ref = React.useRef(null);
  let {
    columnHeaderProps
  } = table$1.useTableColumnHeader({
    node: column
  }, state, ref);
  let {
    isFocusVisible,
    focusProps
  } = focus.useFocusRing();
  let columnProps = column.props;
  let cellStyleProps = useCellStyleProps(columnProps, {
    isFocusVisible
  });
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    ...utils$1.mergeProps(columnHeaderProps, focusProps),
    ...cellStyleProps,
    ref: ref,
    children: [columnProps.allowsSorting && columnProps.align === 'end' && /*#__PURE__*/jsxRuntime.jsx(SortIndicator, {}), utils.isReactText(column.rendered) ? /*#__PURE__*/jsxRuntime.jsx(typography.Text, {
      color: "inherit",
      weight: "semibold",
      truncate: true,
      children: column.rendered
    }) : column.rendered, columnProps.allowsSorting && columnProps.align !== 'end' && /*#__PURE__*/jsxRuntime.jsx(SortIndicator, {})]
  });
}
function TableRow(_ref5) {
  let {
    item,
    children,
    state,
    hasAction
  } = _ref5;
  let ref = React.useRef(null);
  let allowsInteraction = state.selectionManager.selectionMode !== 'none' || hasAction;
  let isDisabled = !allowsInteraction || state.disabledKeys.has(item.key);
  let {
    rowProps,
    isPressed
  } = table$1.useTableRow({
    node: item
  }, state, ref);
  // The row should show the focus background style when any cell inside it is focused.
  // If the row itself is focused, then it should have a blue focus indicator on the left.
  let {
    isFocusVisible: isFocusWithin,
    focusProps: focusWithinProps
  } = focus.useFocusRing({
    within: true
  });
  let {
    isFocusVisible,
    focusProps
  } = focus.useFocusRing();
  let {
    hoverProps,
    isHovered
  } = interactions.useHover({
    isDisabled
  });
  let styleProps = useRowStyleProps({
    isFocusVisible,
    isFocusWithin,
    isHovered,
    isPressed
  });
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    ...utils$1.mergeProps(rowProps, focusWithinProps, focusProps, hoverProps),
    ...styleProps,
    ref: ref,
    children: children
  });
}
function TableCell(_ref6) {
  let {
    cell,
    overflowMode,
    state
  } = _ref6;
  let ref = React.useRef(null);
  let {
    gridCellProps
  } = table$1.useTableCell({
    node: cell
  }, state, ref);
  let {
    isFocusVisible,
    focusProps
  } = focus.useFocusRing();
  let styleProps = useCellStyleProps(cell.column.props, {
    isFocusVisible
  });
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    ...utils$1.mergeProps(gridCellProps, focusProps),
    ...styleProps,
    ref: ref,
    children: utils.isReactText(cell.rendered) ? /*#__PURE__*/jsxRuntime.jsx(typography.Text, {
      truncate: overflowMode === 'truncate',
      children: cell.rendered
    }) : cell.rendered
  });
}
function TableCheckboxCell(_ref7) {
  let {
    cell,
    state
  } = _ref7;
  let ref = React.useRef(null);
  let {
    gridCellProps
  } = table$1.useTableCell({
    node: cell
  }, state, ref);
  let {
    checkboxProps
  } = table$1.useTableSelectionCheckbox({
    key: cell.parentKey
  }, state);
  let styleProps = useSelectionCellStyleProps();
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    ...styleProps,
    ...gridCellProps,
    ref: ref,
    children: /*#__PURE__*/jsxRuntime.jsx(checkbox.Checkbox, {
      ...checkboxProps
    })
  });
}
function TableSelectAllCell(_ref8) {
  let {
    column,
    state
  } = _ref8;
  let ref = React.useRef(null);
  let {
    columnHeaderProps
  } = table$1.useTableColumnHeader({
    node: column
  }, state, ref);
  let {
    checkboxProps
  } = table$1.useTableSelectAllCheckbox(state);
  let styleProps = useSelectionCellStyleProps();
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    ...styleProps,
    ...columnHeaderProps,
    ref: ref,
    children: state.selectionManager.selectionMode === 'single' ? /*#__PURE__*/jsxRuntime.jsx(typography.Text, {
      visuallyHidden: true,
      children: checkboxProps['aria-label']
    }) : /*#__PURE__*/jsxRuntime.jsx(checkbox.Checkbox, {
      ...checkboxProps
    })
  });
}

// Override TS for Column to support Keystar UI specific props.
const VoussoirColumn = table.Column;

Object.defineProperty(exports, 'Cell', {
  enumerable: true,
  get: function () { return table.Cell; }
});
Object.defineProperty(exports, 'Row', {
  enumerable: true,
  get: function () { return table.Row; }
});
Object.defineProperty(exports, 'TableBody', {
  enumerable: true,
  get: function () { return table.TableBody; }
});
Object.defineProperty(exports, 'TableHeader', {
  enumerable: true,
  get: function () { return table.TableHeader; }
});
exports.Column = VoussoirColumn;
exports.TableView = TableView;
