getBreakpoint.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { getWindow } from 'ssr-window';
  2. export default function getBreakpoint(breakpoints, base = 'window', containerEl) {
  3. if (!breakpoints || base === 'container' && !containerEl) return undefined;
  4. let breakpoint = false;
  5. const window = getWindow();
  6. const currentHeight = base === 'window' ? window.innerHeight : containerEl.clientHeight;
  7. const points = Object.keys(breakpoints).map(point => {
  8. if (typeof point === 'string' && point.indexOf('@') === 0) {
  9. const minRatio = parseFloat(point.substr(1));
  10. const value = currentHeight * minRatio;
  11. return {
  12. value,
  13. point
  14. };
  15. }
  16. return {
  17. value: point,
  18. point
  19. };
  20. });
  21. points.sort((a, b) => parseInt(a.value, 10) - parseInt(b.value, 10));
  22. for (let i = 0; i < points.length; i += 1) {
  23. const {
  24. point,
  25. value
  26. } = points[i];
  27. if (base === 'window') {
  28. if (window.matchMedia(`(min-width: ${value}px)`).matches) {
  29. breakpoint = point;
  30. }
  31. } else if (value <= containerEl.clientWidth) {
  32. breakpoint = point;
  33. }
  34. }
  35. return breakpoint || 'max';
  36. }