@atlaskit/editor-common
Version:
A package that contains common classes and components for editor and renderer
61 lines • 2.4 kB
JavaScript
import _taggedTemplateLiteral from "@babel/runtime/helpers/taggedTemplateLiteral";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
var _templateObject;
/** @jsx jsx */
import React, { Fragment } from 'react';
import { css, jsx } from '@emotion/react';
import rafSchedule from 'raf-schd';
import { WidthObserver } from '@atlaskit/width-detector';
var SCROLLBAR_WIDTH = 30;
export function getBreakpoint() {
var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var MAX_S = 1266;
var MAX_M = 2146;
if (width >= MAX_S && width < MAX_M) {
return 'M';
} else if (width >= MAX_M) {
return 'L';
}
return 'S';
}
export function createWidthContext() {
var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return {
width: width,
breakpoint: getBreakpoint(width)
};
}
export var WidthContext = /*#__PURE__*/React.createContext(createWidthContext());
var Provider = WidthContext.Provider,
Consumer = WidthContext.Consumer;
export var WidthProvider = function WidthProvider(_ref) {
var className = _ref.className,
shouldCheckExistingValue = _ref.shouldCheckExistingValue,
children = _ref.children;
var existingContextValue = React.useContext(WidthContext);
var _React$useState = React.useState(typeof document !== 'undefined' ? document.body.offsetWidth : 0),
_React$useState2 = _slicedToArray(_React$useState, 2),
width = _React$useState2[0],
setWidth = _React$useState2[1];
var providerValue = React.useMemo(function () {
return createWidthContext(width);
}, [width]);
var updateWidth = rafSchedule(function (nextWidth) {
// Ignore changes that are less than SCROLLBAR_WIDTH, otherwise it can cause infinite re-scaling
if (Math.abs(width - nextWidth) < SCROLLBAR_WIDTH) {
return;
}
setWidth(nextWidth);
});
var skipWidthDetection = shouldCheckExistingValue && existingContextValue.width > 0;
return jsx("div", {
css: css(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n position: relative;\n width: 100%;\n "]))),
className: className
}, !skipWidthDetection && jsx(Fragment, null, jsx(WidthObserver, {
setWidth: updateWidth,
offscreen: true
}), jsx(Provider, {
value: providerValue
}, children)), skipWidthDetection && children);
};
export { Consumer as WidthConsumer };