"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CssGridItem = exports.CssGridContainer = exports.CssGrid = void 0;
var _path2 = _interopRequireDefault(require("ramda/src/path"));
var _styledComponents = _interopRequireWildcard(require("styled-components"));
var _react = _interopRequireWildcard(require("react"));
var _utils = require("../../common/utils");
var _utils2 = require("./utils");
var _excluded = ["theme", "children"];
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var formatAreas = function formatAreas(areas) {
  var _areas$map;
  return areas === null || areas === void 0 || (_areas$map = areas.map(function (areaRow) {
    return areaRow.join(' ');
  })) === null || _areas$map === void 0 ? void 0 : _areas$map.map(function (area) {
    return "\"".concat(area, "\"");
  }).join(' ');
};
var isNumber = function isNumber(x) {
  return x === parseInt(x, 10);
};
var isArrayOfStrings = function isArrayOfStrings(xs) {
  return xs.every(function (x) {
    return typeof x === 'string';
  });
};
var getGutterStyles = function getGutterStyles(props) {
  var gutter = props.gutter,
    theme = props.theme;
  var equalGaps = function equalGaps(value) {
    return "grid-gap: ".concat(theme.spacing.unit(value), "px;");
  };
  if (isNumber(gutter)) {
    return equalGaps(gutter);
  }
  var col = gutter.col,
    row = gutter.row;
  if (col && row && col === row) {
    return equalGaps(gutter.col);
  }
  return "\n    column-gap: ".concat(theme.spacing.unit(col), "px;\n    row-gap: ").concat(theme.spacing.unit(row), "px;\n  ");
};
var getTemplateColumns = function getTemplateColumns(props) {
  var templateColumns = props.templateColumns;
  var oneColSize = 100 / 12;
  if ((0, _utils.isUndefined)(templateColumns)) {
    return '';
  }
  if (isArrayOfStrings(templateColumns)) {
    return "grid-template-columns: ".concat(templateColumns.join(' '), ";");
  }
  return "grid-template-columns: ".concat(templateColumns === null || templateColumns === void 0 ? void 0 : templateColumns.map(function (x) {
    return "".concat(x * oneColSize, "fr");
  }).join(' '), ";");
};
var getTemplateRows = function getTemplateRows(props) {
  var templateRows = props.templateRows;
  if ((0, _utils.isUndefined)(templateRows)) {
    return '';
  }
  return "grid-template-rows: ".concat(templateRows.join(' '), ";");
};
var generateMSGridStyles = function generateMSGridStyles(_ref) {
  var gutter = _ref.gutter,
    columns = _ref.columns,
    rows = _ref.rows,
    areas = _ref.areas,
    templateColumnStyles = _ref.templateColumnStyles,
    templateRowsStyles = _ref.templateRowsStyles,
    theme = _ref.theme;
  var styles = ["display: -ms-grid;"];
  var columnsInAreas = (0, _path2.default)([0, 'length'], areas);
  var rowsInAreas = (0, _path2.default)(['length'], areas);
  var isGutterPresented = !(0, _utils.isUndefined)(gutter);
  var isColumnsPresented = !(0, _utils.isUndefined)(columns);
  var isRowsPresented = !(0, _utils.isUndefined)(rows);
  if (!isGutterPresented) {
    if (!isColumnsPresented && !isRowsPresented) {
      return styles.join('\n');
    }
    if (isColumnsPresented) {
      styles.push("-ms-grid-columns: ".concat(templateColumnStyles, ";"));
    }
    if (isRowsPresented) {
      styles.push("-ms-grid-rows: ".concat(templateRowsStyles, ";"));
    }
    return styles.join('\n');
  }
  if (isGutterPresented) {
    var rowGutter = isNumber(gutter) ? "".concat(theme.spacing.unit(gutter), "px") : isNumber(gutter.row) ? "".concat(theme.spacing.unit(gutter.row), "px") : gutter.row;
    var colGutter = isNumber(gutter) ? "".concat(theme.spacing.unit(gutter), "px") : isNumber(gutter.col) ? "".concat(theme.spacing.unit(gutter.col), "px") : gutter.col;
    if (isRowsPresented) {
      var rawTemplateRowsStyles = templateRowsStyles.replace('grid-template-rows: ', '').replace(';', '');
      var msGridRowsStyles = (0, _utils2.getMsRawTemplateColumnOrRowStyles)(rawTemplateRowsStyles, rowGutter);
      var msGridRows = "-ms-grid-rows: ".concat(msGridRowsStyles, ";");
      styles.push(msGridRows);
    } else {
      var _msGridRowsStyles = new Array(rowsInAreas).fill('1fr').join(" ".concat(rowGutter, " "));
      var _msGridRows = "-ms-grid-rows: ".concat(_msGridRowsStyles, ";");
      styles.push(_msGridRows);
    }
    if (isColumnsPresented) {
      var rawTemplateColumnStyles = templateColumnStyles.replace('grid-template-columns: ', '').replace(';', '');
      var msGridColumnsStyles = (0, _utils2.getMsRawTemplateColumnOrRowStyles)(rawTemplateColumnStyles, colGutter);
      var msGridColumns = "-ms-grid-columns: ".concat(msGridColumnsStyles, ";");
      styles.push(msGridColumns);
    } else {
      var _msGridColumnsStyles = new Array(columnsInAreas).fill('1fr').join(" ".concat(rowGutter, " "));
      var _msGridColumns = "-ms-grid-columns: ".concat(_msGridColumnsStyles, ";");
      styles.push(_msGridColumns);
    }
    return styles.join('\n');
  }
  return styles.join('\n');
};
var StyledDiv = _styledComponents.default.div.withConfig({
  displayName: "CssGrid__StyledDiv",
  componentId: "sc-bu5cxy-0"
})(["display:grid;box-sizing:border-box;", ""], function (props) {
  var _Object$entries$filte;
  var sm = props.sm,
    md = props.md,
    lg = props.lg,
    xl = props.xl;
  var createStyles = function createStyles(innerProps, size) {
    var height = innerProps.height,
      areas = innerProps.areas,
      templateRows = innerProps.templateRows,
      templateColumns = innerProps.templateColumns;
    var gutter = (0, _utils.isUndefined)(innerProps.gutter) ? props.theme.spacing.gutter : innerProps.gutter;
    var templateColumnStyles = getTemplateColumns(_objectSpread(_objectSpread({}, innerProps), {}, {
      templateColumns: templateColumns,
      size: size
    })) || '';
    var templateRowsStyles = getTemplateRows(_objectSpread(_objectSpread({}, innerProps), {}, {
      templateRows: templateRows,
      size: size
    })) || '';
    var baseStyles = "\n          ".concat(height ? "height: ".concat(height, ";") : '', "\n          ").concat(areas ? "grid-template-areas: ".concat(formatAreas(areas), ";") : '', "\n          ").concat(templateRowsStyles, "\n          ").concat(templateColumnStyles, "\n          ").concat(getGutterStyles(_objectSpread(_objectSpread({}, innerProps), {}, {
      gutter: gutter,
      theme: props.theme
    })) || '', "\n          ").concat(generateMSGridStyles({
      gutter: gutter,
      columns: templateColumns,
      rows: templateRows,
      areas: areas,
      templateColumnStyles: templateColumnStyles,
      templateRowsStyles: templateRowsStyles,
      theme: props.theme
    }), "\n        ");
    return size ? "\n            ".concat(props.theme.media.greaterThan(props.theme.breakpoints[size]), " {\n              ").concat(baseStyles, "\n            }\n          ") : "\n            ".concat(baseStyles, "\n          ");
  };
  var styles = (_Object$entries$filte = Object.entries({
    sm: sm,
    md: md,
    lg: lg,
    xl: xl
  }).filter(function (_ref2) {
    var _ref3 = _slicedToArray(_ref2, 2),
      _ = _ref3[0],
      sizeProps = _ref3[1];
    return sizeProps !== undefined;
  })) === null || _Object$entries$filte === void 0 ? void 0 : _Object$entries$filte.map(function (_ref4) {
    var _ref5 = _slicedToArray(_ref4, 2),
      size = _ref5[0],
      sizeProps = _ref5[1];
    return createStyles(sizeProps, size);
  });
  styles.unshift(createStyles(props, undefined));
  return styles.join('\n');
});
var getMsJustifySelfStyles = function getMsJustifySelfStyles(justify) {
  return "-ms-grid-column-align: ".concat(justify, ";");
};
var getMsAlignSelfStyles = function getMsAlignSelfStyles(align) {
  return "-ms-grid-row-align: ".concat(align, ";");
};
var getJustifySelfStyles = function getJustifySelfStyles(justify) {
  return justify ? "\n  justify-self: ".concat(justify, ";\n  ").concat(getMsJustifySelfStyles(justify), "\n") : '';
};
var getAlignSelfStyles = function getAlignSelfStyles(align) {
  return align ? "\n  align-self: ".concat(align, ";\n  ").concat(getMsAlignSelfStyles(align), "\n") : '';
};
var getPlaceSelfStyles = function getPlaceSelfStyles(place) {
  var styles = [];
  if (typeof place === 'string' && place) {
    var _ref6 = place.split(' '),
      _ref7 = _slicedToArray(_ref6, 2),
      alignOrBoth = _ref7[0],
      justify = _ref7[1];
    styles.push("place-self: ".concat(place, ";"));
    styles.push(getMsAlignSelfStyles(alignOrBoth));
    styles.push(getMsJustifySelfStyles(justify || alignOrBoth));
  }
  return styles.join('\n');
};
var getCssGridItemStylesFromProps = function getCssGridItemStylesFromProps(_ref8) {
  var justify = _ref8.justify,
    align = _ref8.align,
    place = _ref8.place;
  return "\n  ".concat(getJustifySelfStyles(justify), "\n  ").concat(getAlignSelfStyles(align), "\n  ").concat(getPlaceSelfStyles(place), "\n");
};
var RawCssGridItem = _styledComponents.default.div.withConfig({
  displayName: "CssGrid__RawCssGridItem",
  componentId: "sc-bu5cxy-1"
})(["box-sizing:border-box;min-width:0;", " ", ""], function (p) {
  return getCssGridItemStylesFromProps(p);
}, function (p) {
  var _Object$keys$filter;
  return (_Object$keys$filter = Object.keys(p.theme.breakpoints).filter(function (breakpoint) {
    return p[breakpoint];
  })) === null || _Object$keys$filter === void 0 ? void 0 : _Object$keys$filter.map(function (breakpoint) {
    return "".concat(p.theme.media.greaterThan(p.theme.breakpoints[breakpoint]), " {\n          ").concat(getCssGridItemStylesFromProps(p[breakpoint]), "\n        }");
  }).join('\n');
});
var _StyledRawCssGridItem = (0, _styledComponents.default)(RawCssGridItem).withConfig({
  displayName: "CssGrid___StyledRawCssGridItem",
  componentId: "sc-bu5cxy-2"
})(["", ""], function (p) {
  return p.$_css;
});
var CssGridItem = exports.CssGridItem = function CssGridItem(_ref9) {
  var align = _ref9.align,
    area = _ref9.area,
    children = _ref9.children,
    justify = _ref9.justify,
    place = _ref9.place,
    sm = _ref9.sm,
    md = _ref9.md,
    lg = _ref9.lg,
    xl = _ref9.xl;
  return _react.default.createElement(RawCssGridItem, {
    align: align,
    area: area,
    children: children,
    justify: justify,
    place: place,
    sm: sm,
    md: md,
    lg: lg,
    xl: xl
  });
};
CssGridItem.displayName = 'CssGrid.Item';
var generateChildStyles = function generateChildStyles(areasInfo, size, theme) {
  return function (areaName) {
    var styles = [];
    if (!areasInfo[areaName]) {
      styles.push('display: none; grid-area: none;');
    } else {
      var info = areasInfo[areaName];
      styles.push("-ms-grid-row: ".concat(info.rowStart, ";"), "-ms-grid-column: ".concat(info.colStart, ";"));
      styles.push("-ms-grid-column-span: ".concat(info.colSpan, ";"));
      styles.push("-ms-grid-row-span: ".concat(info.rowSpan, ";"));
      styles.push("display: block; grid-area: ".concat(areaName, ";"));
    }
    return size ? "\n    ".concat(theme.media.greaterThan(theme.breakpoints[size]), " {\n      ").concat(styles.join('\n'), "\n    }\n    ") : styles.join('\n');
  };
};
var RawCSSGridContainer = function RawCSSGridContainer(_ref10) {
  var _React$Children;
  var theme = _ref10.theme,
    children = _ref10.children,
    props = _objectWithoutProperties(_ref10, _excluded);
  var sm = props.sm,
    md = props.md,
    lg = props.lg,
    xl = props.xl;
  var stylesFnsForChild = (0, _react.useMemo)(function () {
    var _filter;
    return (_filter = [[undefined, {
      areas: props.areas
    }], ['sm', sm], ['md', md], ['lg', lg], ['xl', xl]].filter(function (_ref11) {
      var _ref12 = _slicedToArray(_ref11, 2),
        _ = _ref12[0],
        sizeProps = _ref12[1];
      return sizeProps !== undefined;
    })) === null || _filter === void 0 ? void 0 : _filter.map(function (_ref13, currentSizeIdx, allSizes) {
      var _ref14 = _slicedToArray(_ref13, 1),
        size = _ref14[0];
      var currentAreas = allSizes.slice(0, currentSizeIdx + 1).reverse().find(function (_ref15) {
        var _ref16 = _slicedToArray(_ref15, 2),
          _ = _ref16[0],
          sizeProps = _ref16[1];
        return !(0, _utils.isUndefined)(sizeProps.areas);
      });
      return generateChildStyles((0, _utils2.getAreasInfo)(currentAreas[1].areas, {
        col: true,
        row: true
      }), size, theme);
    });
  }, [sm, md, lg, xl, props.areas, theme]);
  var stylesFnForChild = function stylesFnForChild(areaName) {
    return stylesFnsForChild === null || stylesFnsForChild === void 0 ? void 0 : stylesFnsForChild.map(function (f) {
      return f(areaName);
    }).join('\n');
  };
  var renderedChildren = (_React$Children = _react.default.Children) === null || _React$Children === void 0 ? void 0 : _React$Children.map(children, function (child, childIndex) {
    if (!child) {
      (0, _utils.assert)(false, "CssGrid: It seems like you have null-ish children[".concat(childIndex, "]. \nIf you wanted to do a conditional rendering, do so with areas prop on CssGrid.Container"), {
        level: 'warn'
      });
      return null;
    }
    return _react.default.createElement(_StyledRawCssGridItem, _extends({}, child.props, {
      $_css: (0, _styledComponents.css)(["", ""], stylesFnForChild(child.props.area))
    }));
  });
  return _react.default.createElement(StyledDiv, props, renderedChildren);
};
var CssGridContainer = exports.CssGridContainer = (0, _styledComponents.withTheme)(RawCSSGridContainer);
CssGridContainer.displayName = 'CssGrid.Container';
var CssGrid = exports.CssGrid = {
  Container: CssGridContainer,
  Item: CssGridItem
};