UNPKG

@atlaskit/renderer

Version:
66 lines (65 loc) 2.99 kB
import { ACTION, ACTION_SUBJECT, EVENT_TYPE } from '@atlaskit/editor-common/analytics'; import React from 'react'; import AnalyticsContext from '../../analytics/analyticsContext'; import { ElementSelection } from './element-selection'; export var useSelectAllTrap = function useSelectAllTrap() { var _React$useContext = React.useContext(AnalyticsContext), fireAnalyticsEvent = _React$useContext.fireAnalyticsEvent; var ref = React.useRef(null); var clicked = React.useRef(false); var caught = React.useRef(); // Ignored via go/ees005 // eslint-disable-next-line require-unicode-regexp var mac = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false; var onKeyDown = React.useCallback(function (e) { var _e$target, _e$target$matches; var el = ref.current; if (!el) { return; } var modKey = mac ? e.metaKey : e.ctrlKey; if (!modKey || e.code !== 'KeyA' || e.shiftKey) { return; } var elementSelection = ElementSelection.fromWindow(); var isInput = (_e$target = e.target) === null || _e$target === void 0 || (_e$target$matches = _e$target.matches) === null || _e$target$matches === void 0 ? void 0 : _e$target$matches.call(_e$target, 'input'); if (elementSelection.eq(caught.current) || isInput) { fireAnalyticsEvent({ eventType: EVENT_TYPE.TRACK, action: ACTION.SELECT_ALL_ESCAPED, actionSubject: ACTION_SUBJECT.RENDERER }); return; } if (elementSelection.inside(el) || elementSelection.type === 'None' && clicked.current) { fireAnalyticsEvent({ eventType: EVENT_TYPE.TRACK, action: ACTION.SELECT_ALL_CAUGHT, actionSubject: ACTION_SUBJECT.RENDERER }); e.preventDefault(); caught.current = elementSelection.select(el); } }, [mac, ref, fireAnalyticsEvent, clicked, caught]); var onClick = React.useCallback(function (e) { var _ref$current$contains, _ref$current; clicked.current = (_ref$current$contains = (_ref$current = ref.current) === null || _ref$current === void 0 ? void 0 : _ref$current.contains(e.target)) !== null && _ref$current$contains !== void 0 ? _ref$current$contains : false; }, [ref, clicked]); React.useEffect(function () { // Ignored via go/ees005 // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners window.addEventListener('keydown', onKeyDown); // Ignored via go/ees005 // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners window.addEventListener('click', onClick); return function () { // Ignored via go/ees005 // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners window.removeEventListener('keydown', onKeyDown); // Ignored via go/ees005 // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners window.removeEventListener('click', onClick); }; }, [onKeyDown, onClick]); return ref; };