UNPKG

@atlaskit/editor-plugin-media-insert

Version:

Media Insert plugin for @atlaskit/editor-core

62 lines (59 loc) 2.99 kB
"use strict"; var _typeof = require("@babel/runtime/helpers/typeof"); Object.defineProperty(exports, "__esModule", { value: true }); exports.useUnholyAutofocus = void 0; var _react = _interopRequireWildcard(require("react")); function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); } /** * Autofocuses the first interactive element in the first tab panel * when the media picker is opened. * * This is to mitigate the issue where the PopupWithListeners component * renders initially at the top of the editor and then repositioned. * * We want to autofocus after the repositioning to ensure we don't scroll * to the top of the editor when the media picker is opened. */ var useUnholyAutofocus = exports.useUnholyAutofocus = function useUnholyAutofocus() { var autofocusRef = _react.default.useRef(null); var positionRef = _react.default.useRef(null); var onPositionCalculated = _react.default.useCallback(function (position) { if (positionRef.current === null) { // Initial position is _always incorrect, so the first time this is set // we're going to ignore it. positionRef.current = position; } else if (positionRef.current !== position) { var _autofocusRef$current; // If it isn't the first position and it has changed, we're likely in // the actual position we want. We'll call focus and update the position. (_autofocusRef$current = autofocusRef.current) === null || _autofocusRef$current === void 0 || _autofocusRef$current.focus(); positionRef.current = position; } // Important to return this as the popup uses the returned position return position; }, [autofocusRef]); /** * If we don't clear the ref, then reopening the media picker will * not correctly focus the button. * * WARNING: If the component re-renders the ref will be cleared and * the button will be focused again. * * This is a trade-off, we prefer that the button is correctly focused * if the media picker is re-opened, rather than re-focusing the button * if the component re-renders/ the browser window is resized. * * This is a temporary solution until we can find a better way to do it. */ (0, _react.useEffect)(function () { return function () { positionRef.current = null; }; }); return { autofocusRef: autofocusRef, onPositionCalculated: onPositionCalculated }; };