UNPKG

@atlaskit/editor-plugin-block-controls

Version:

Block controls plugin for @atlaskit/editor-core

84 lines (83 loc) 3.16 kB
import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; import { EventEmitter } from 'events'; import { useCallback, useEffect, useState } from 'react'; import { editorExperiment } from '@atlaskit/tmp-editor-statsig/experiments'; export var ActiveAnchorTracker = /*#__PURE__*/function () { function ActiveAnchorTracker() { _classCallCheck(this, ActiveAnchorTracker); _defineProperty(this, "lastActiveAnchor", ''); this.emitter = new EventEmitter(); } return _createClass(ActiveAnchorTracker, [{ key: "getActiveAnchor", value: function getActiveAnchor() { return this.lastActiveAnchor; } }, { key: "subscribe", value: function subscribe(anchorName, callback) { if (this.emitter) { this.emitter.on(anchorName, callback); } } }, { key: "unsubscribe", value: function unsubscribe(anchorName, callback) { if (this.emitter) { this.emitter.removeListener(anchorName, callback); } } }, { key: "emit", value: function emit(anchorName) { if (this.lastActiveAnchor !== anchorName && this.emitter) { this.emitter.emit(this.lastActiveAnchor, false); this.emitter.emit(anchorName, true); this.lastActiveAnchor = anchorName; } } }, { key: "reset", value: function reset() { if (this.emitter) { // To prevent any potential memory leaks, // we set the event emitter to null and then create a new event emitter. this.emitter.removeAllListeners(); this.emitter = null; this.emitter = new EventEmitter(); } } }]); }(); // TODO: ED-26959 - We should use a scoped ActiveAnchorTracker rather than the global static object. // Move this into the plugin scope once the newApply functions becomes default apply. export var defaultActiveAnchorTracker = new ActiveAnchorTracker(); export var useActiveAnchorTracker = function useActiveAnchorTracker(anchorName) { var activeAnchorTracker = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultActiveAnchorTracker; var _useState = useState(false), _useState2 = _slicedToArray(_useState, 2), isActive = _useState2[0], setIsActive = _useState2[1]; var onActive = function onActive(eventIsActive) { setIsActive(eventIsActive); }; useEffect(function () { if (activeAnchorTracker && anchorName && editorExperiment('advanced_layouts', true)) { activeAnchorTracker.subscribe(anchorName, onActive); if (activeAnchorTracker.getActiveAnchor() === anchorName) { setIsActive(true); } var unsubscribe = function unsubscribe() { activeAnchorTracker.unsubscribe(anchorName, onActive); }; return unsubscribe; } }, [activeAnchorTracker, anchorName]); var setActive = useCallback(function () { activeAnchorTracker.emit(anchorName); }, [activeAnchorTracker, anchorName]); return [isActive, setActive]; };