UNPKG

styled-media-helper

Version:
87 lines (70 loc) 3.03 kB
"use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var _require = require('./errors'), BreakpointNotFoundError = _require.BreakpointNotFoundError, NextBreakpointNotFoundError = _require.NextBreakpointNotFoundError; var Media = /*#__PURE__*/function () { function Media(sizes) { _classCallCheck(this, Media); this.sizes = sizes; } _createClass(Media, [{ key: "_isBreakpoint", value: function _isBreakpoint(breakpoint) { return Boolean(this.sizes[breakpoint]); } }, { key: "_next", value: function _next(breakpoint) { var keys = Object.keys(this.sizes); var index = keys.indexOf(breakpoint); return keys[index + 1]; } }, { key: "up", value: function up(breakpoint) { if (!this._isBreakpoint(breakpoint)) { throw new BreakpointNotFoundError(breakpoint); } return "@media (min-width: ".concat(this.sizes[breakpoint], "px)"); } // The max-width value is calculated as the next breakpoint less 0.02px. // See https://www.w3.org/TR/mediaqueries-4/#mq-min-max // Uses 0.02px rather than 0.01px to work around a current rounding bug // in Safari. See https://bugs.webkit.org/show_bug.cgi?id=178261 }, { key: "down", value: function down(breakpoint) { if (!this._isBreakpoint(breakpoint)) { throw new BreakpointNotFoundError(breakpoint); } var nextBreakpoint = this._next(breakpoint); if (!this._isBreakpoint(nextBreakpoint)) { throw new NextBreakpointNotFoundError(breakpoint); } return "@media (max-width: ".concat(this.sizes[nextBreakpoint] - 0.02, "px)"); } }, { key: "between", value: function between(min, max) { if (!this._isBreakpoint(min)) { throw new BreakpointNotFoundError(min); } if (!this._isBreakpoint(max)) { throw new BreakpointNotFoundError(max); } return "@media (min-width: ".concat(this.sizes[min], "px) and\n\t\t\t(max-width: ").concat(this.sizes[max] - 0.02, "px)"); } }, { key: "only", value: function only(breakpoint) { var nextBreakpoint = this._next(breakpoint); return this._isBreakpoint(nextBreakpoint) ? this.between(breakpoint, nextBreakpoint) : this.up(breakpoint); } }]); return Media; }(); module.exports = function (sizes) { return new Media(sizes); };