"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useBreakPoint = useBreakPoint;
exports._xlQuery = exports._lgQuery = exports._mdQuery = void 0;

var _react = require("react");

var _breakpoints = require("../../breakpoints");

// The `useBreakPoint` hook returns a string with the browser's current break point
// value ('sm', 'md', 'lg', or 'xl') and triggers a rerender when it changes.
// These are basically javascript versions of css media queries.
// They let us attach listeners to them so we can respond whenever
// one of the queries change (window resizing).
// https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries
var mdQuery = window.matchMedia("(min-width: ".concat(_breakpoints.bpMedium, ")"));
exports._mdQuery = mdQuery;
var lgQuery = window.matchMedia("(min-width: ".concat(_breakpoints.bpLarge, ")"));
exports._lgQuery = lgQuery;
var xlQuery = window.matchMedia("(min-width: ".concat(_breakpoints.bpXLarge, ")")); // Store break point value as a global singleton for easy and efficient access.

exports._xlQuery = xlQuery;
var breakPoint = 'sm'; // Function for setting/updating the breakPoint value.

function updateBreakPoint() {
  if (xlQuery.matches) breakPoint = 'xl';else if (lgQuery.matches) breakPoint = 'lg';else if (mdQuery.matches) breakPoint = 'md';else breakPoint = 'sm';
} // Initialize breakPoint value for the first time.


updateBreakPoint(); // Store all active setStates in a Set so that we can call them when
// breakPoint changes, and efficiently add and remove setters.

var stateSetters = new Set(); // Handler for break point changes on window resizing.
// Updates breakPoint value and calls registered setters with new value.

function queryChangeHandler() {
  updateBreakPoint();
  stateSetters.forEach(function (setter) {
    return setter(breakPoint);
  });
} // Register handler with all of the media queries.


mdQuery.addListener(queryChangeHandler);
lgQuery.addListener(queryChangeHandler);
xlQuery.addListener(queryChangeHandler);

function useBreakPoint() {
  var setBreakPoint = (0, _react.useState)(breakPoint)[1];
  (0, _react.useEffect)(function () {
    stateSetters.add(setBreakPoint);
    return function () {
      stateSetters["delete"](setBreakPoint);
    };
  }, [setBreakPoint]);
  return breakPoint;
} // For testing