@atlaskit/editor-plugin-quick-insert
Version:
Quick insert plugin for @atlaskit/editor-core
370 lines (369 loc) • 17.6 kB
JavaScript
/* RegistryElementBrowser.tsx generated by @compiled/babel-plugin v3.0.2 */
import "./RegistryElementBrowser.compiled.css";
import { ax, ix } from "@compiled/react/runtime";
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useIntl } from 'react-intl';
import IconButton from '@atlaskit/button/icon/button';
// eslint-disable-next-line @atlaskit/platform/no-barrel-entry-imports
import { messages } from '@atlaskit/editor-common/quick-insert';
import { MENU, RECOMMENDED_SECTION } from '@atlaskit/editor-common/quick-insert/keys';
import { createRegisteredMenuSurfaceContext } from '@atlaskit/editor-common/registered-menu/surface-context';
import { getMenuFooterSectionKey } from '@atlaskit/editor-common/type-ahead-get-menu-footer-section-key';
import { getSectionOverflowItemKey } from '@atlaskit/editor-common/type-ahead-get-section-overflow-item-key';
import CrossIcon from '@atlaskit/icon/core/cross';
import ModalBody from '@atlaskit/modal-dialog/modal-body';
import Modal from '@atlaskit/modal-dialog/modal-dialog';
import ModalFooter from '@atlaskit/modal-dialog/modal-footer';
import ModalHeader from '@atlaskit/modal-dialog/modal-header';
import ModalTitle from '@atlaskit/modal-dialog/modal-title';
import ModalTransition from '@atlaskit/modal-dialog/modal-transition';
import Textfield from '@atlaskit/textfield/text-field';
import { useQuickInsertSearchAnalytics } from '../registered-menu/useQuickInsertSearchAnalytics';
import { getArrowKeyTargetIndex, RETURN_TO_SEARCH } from './getArrowKeyTargetIndex';
import { createRegistryElementBrowserModel, getInitialRegistryElementBrowserSection, getRegistryElementBrowserItems } from './model';
import { getFirstEnabledOption, isOptionDisabled } from './options';
import { RegistryElementBrowserCategories } from './RegistryElementBrowserCategories';
import { RegistryElementBrowserFooter } from './RegistryElementBrowserFooter';
import { RegistryElementBrowserSearchResults } from './RegistryElementBrowserSearchResults';
const browserGridTemplateColumns = '182px minmax(0, 1fr)';
const categoryColumnGap = `calc(${"var(--ds-space-200, 16px)"} + ${"var(--ds-space-150, 12px)"})`;
const browserLayoutStyles = null;
// The modal header keeps its 24px inline padding, so a narrower gap lines the search field up
// with the results below (16px body padding + 182px + 28px gap).
const headerContentStyles = null;
const headerSearchStyles = null;
const EMPTY_ITEMS = [];
const resultsId = 'registry-element-browser-results';
const modalTestId = 'registry-element-browser-modal';
const arrowKeys = new Set(['ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowUp']);
const isArrowKey = key => arrowKeys.has(key);
const toArrowKeyOption = option => ({
getRect: () => option.getBoundingClientRect(),
isDisabled: isOptionDisabled(option)
});
export const RegistryElementBrowser = ({
components,
emptyStateHandler,
fireAnalyticsEvent,
defaultSection,
getRecommendedItems,
helpUrl,
editorView,
isLoading = false,
isOffline,
isOpen,
onClearSelection,
onClose,
onCloseComplete,
onConfirmInsert,
onSelect
}) => {
var _model$fallbackItems, _model$fallbackItems$, _model$fallbackItems2;
const {
formatMessage
} = useIntl();
const [session, setSession] = useState(() => ({
isOpen,
menuOpenId: Symbol('element-browser')
}));
if (session.isOpen !== isOpen) {
setSession({
isOpen,
menuOpenId: isOpen ? Symbol('element-browser') : session.menuOpenId
});
}
const surfaceContext = useMemo(() => createRegisteredMenuSurfaceContext({
menuOpenId: session.menuOpenId,
surface: 'element-browser'
}), [session.menuOpenId]);
const [browserState, setBrowserState] = useState({
query: '',
section: defaultSection
});
const {
query,
section,
selectedRegistration
} = browserState;
const selectedRegistrationRef = useRef(undefined);
// Recommendations depend only on the registry, so typing a query does not re-run the resolver.
const recommendedRegistrations = useMemo(() => getRecommendedItems === null || getRecommendedItems === void 0 ? void 0 : getRecommendedItems({
components,
surfaceContext
}), [components, getRecommendedItems, surfaceContext]);
const browserModel = useMemo(() => {
const model = createRegistryElementBrowserModel(components, {
footerKey: getMenuFooterSectionKey(MENU.key),
surfaceContext,
overflowKeys: new Set(components.filter(component => component.type === 'menu-section').map(component => getSectionOverflowItemKey(component.key))),
recommendedRegistrations,
recommendedSectionKey: RECOMMENDED_SECTION.key,
rootKey: MENU.key
});
const effectiveSection = section && model.sections.some(({
key
}) => key === section) ? section : undefined;
return {
model,
effectiveSection,
...getRegistryElementBrowserItems({
formatMessage,
model,
query,
section: effectiveSection
})
};
}, [components, formatMessage, query, recommendedRegistrations, section, surfaceContext]);
const {
model,
effectiveSection,
items,
recommendedItems
} = browserModel;
const resultItems = useMemo(() => [...recommendedItems, ...items], [items, recommendedItems]);
const visibleItems = resultItems.length === 0 && !isLoading && query.trim().length > 0 ? (_model$fallbackItems = model.fallbackItems) !== null && _model$fallbackItems !== void 0 ? _model$fallbackItems : EMPTY_ITEMS : resultItems;
const isSelectedRegistrationCurrent = Boolean(selectedRegistration && browserState.selectionIsOffline === isOffline && visibleItems.some(({
registration
}) => registration === selectedRegistration));
const selectedKey = isSelectedRegistrationCurrent ? selectedRegistration === null || selectedRegistration === void 0 ? void 0 : selectedRegistration.key : undefined;
const invalidSection = Boolean(section && section !== effectiveSection);
const invalidSelection = Boolean(selectedRegistration && !isSelectedRegistrationCurrent);
if (isOpen && (invalidSection || invalidSelection)) {
setBrowserState({
...browserState,
section: effectiveSection,
selectedRegistration: undefined,
selectionIsOffline: undefined,
invalidation: {
section: invalidSection ? section : undefined,
selection: invalidSelection
}
});
}
const searchInputRef = useRef(null);
const selectedCategoryRef = useRef(null);
const focusedCategoryRef = useRef();
const handledInvalidationRef = useRef(browserState.invalidation);
const wasOpen = useRef(false);
useEffect(() => {
if (isOpen && !wasOpen.current) {
selectedRegistrationRef.current = undefined;
setBrowserState({
query: '',
section: getInitialRegistryElementBrowserSection(model, defaultSection),
selectedRegistration: undefined
});
onClearSelection();
}
wasOpen.current = isOpen;
}, [defaultSection, isOpen, model, onClearSelection]);
useEffect(() => {
var _searchInputRef$curre;
const invalidation = browserState.invalidation;
if (!isOpen || !invalidation || handledInvalidationRef.current === invalidation) {
return;
}
handledInvalidationRef.current = invalidation;
selectedRegistrationRef.current = undefined;
onClearSelection();
const ownerDocument = (_searchInputRef$curre = searchInputRef.current) === null || _searchInputRef$curre === void 0 ? void 0 : _searchInputRef$curre.ownerDocument;
const activeElement = ownerDocument === null || ownerDocument === void 0 ? void 0 : ownerDocument.activeElement;
if (invalidation.section && focusedCategoryRef.current === invalidation.section && activeElement === (ownerDocument === null || ownerDocument === void 0 ? void 0 : ownerDocument.body)) {
var _selectedCategoryRef$;
(_selectedCategoryRef$ = selectedCategoryRef.current) === null || _selectedCategoryRef$ === void 0 ? void 0 : _selectedCategoryRef$.focus();
} else if (invalidation.selection && (activeElement === (ownerDocument === null || ownerDocument === void 0 ? void 0 : ownerDocument.body) || activeElement !== null && activeElement !== void 0 && activeElement.closest('[role="option"]'))) {
var _searchInputRef$curre2;
(_searchInputRef$curre2 = searchInputRef.current) === null || _searchInputRef$curre2 === void 0 ? void 0 : _searchInputRef$curre2.focus();
}
}, [browserState.invalidation, isOpen, onClearSelection]);
const resultCount = resultItems.length || (!isLoading && query.trim() ? (_model$fallbackItems$ = (_model$fallbackItems2 = model.fallbackItems) === null || _model$fallbackItems2 === void 0 ? void 0 : _model$fallbackItems2.length) !== null && _model$fallbackItems$ !== void 0 ? _model$fallbackItems$ : 0 : 0);
const flushSearchAnalytics = useQuickInsertSearchAnalytics({
query,
resultCount: resultItems.length,
surface: 'element-browser',
category: effectiveSection !== null && effectiveSection !== void 0 ? effectiveSection : 'all',
isOpen: isOpen && !isLoading,
fireAnalyticsEvent
});
const closeBrowser = useCallback(() => {
flushSearchAnalytics();
onClose();
}, [flushSearchAnalytics, onClose]);
const onSearchFocus = useCallback(() => {
focusedCategoryRef.current = undefined;
}, []);
const onBrowserFocusCapture = useCallback(event => {
var _category$dataset$sec;
const categories = event.currentTarget.querySelector('[data-testid="registry-element-browser-categories"]');
const category = event.target instanceof HTMLElement && categories !== null && categories !== void 0 && categories.contains(event.target) ? event.target.closest('[data-section]') : null;
focusedCategoryRef.current = category ? (_category$dataset$sec = category.dataset.section) !== null && _category$dataset$sec !== void 0 ? _category$dataset$sec : '' : undefined;
}, []);
const onSearchChange = useCallback(event => {
const nextQuery = event.currentTarget.value;
selectedRegistrationRef.current = undefined;
setBrowserState(current => ({
...current,
query: nextQuery,
selectedRegistration: undefined
}));
onClearSelection();
}, [onClearSelection]);
const onSectionClick = useCallback(event => {
const nextSection = event.currentTarget.dataset.section || undefined;
selectedRegistrationRef.current = undefined;
setBrowserState({
query: '',
section: nextSection,
selectedRegistration: undefined
});
onClearSelection();
}, [onClearSelection]);
const onRegistrySelect = useCallback((key, handler) => {
var _model$items$find;
const registration = (_model$items$find = model.items.find(({
registration
}) => registration.key === key)) === null || _model$items$find === void 0 ? void 0 : _model$items$find.registration;
selectedRegistrationRef.current = registration;
setBrowserState(current => ({
...current,
selectedRegistration: registration,
selectionIsOffline: isOffline
}));
onSelect(handler);
}, [isOffline, model.items, onSelect]);
const confirmInsert = useCallback(() => {
const selectedRegistration = selectedRegistrationRef.current;
if (!selectedRegistration || !visibleItems.some(({
registration
}) => registration === selectedRegistration)) {
return;
}
onConfirmInsert();
}, [onConfirmInsert, visibleItems]);
const onModalOpenComplete = useCallback(node => {
node.style.borderRadius = "var(--ds-radius-large, 8px)";
const footer = node.querySelector(`[data-testid="${modalTestId}--footer"]`);
footer === null || footer === void 0 ? void 0 : footer.style.setProperty('box-sizing', 'border-box');
footer === null || footer === void 0 ? void 0 : footer.style.setProperty('height', '64px');
footer === null || footer === void 0 ? void 0 : footer.style.setProperty('padding-block', "var(--ds-space-200, 16px)");
const scrollableBody = node.querySelector(`[data-testid="${modalTestId}--scrollable"]`);
scrollableBody === null || scrollableBody === void 0 ? void 0 : scrollableBody.style.setProperty('border-block-start', 'none');
scrollableBody === null || scrollableBody === void 0 ? void 0 : scrollableBody.style.setProperty('border-block-end', 'none');
}, []);
const onKeyDown = useCallback(event => {
if (event.key === 'Tab' && event.shiftKey && event.target instanceof HTMLElement && event.target.getAttribute('role') === 'option') {
var _selectedCategoryRef$2;
event.preventDefault();
(_selectedCategoryRef$2 = selectedCategoryRef.current) === null || _selectedCategoryRef$2 === void 0 ? void 0 : _selectedCategoryRef$2.focus();
return;
}
if (isArrowKey(event.key)) {
var _resultCollection$que;
if (event.currentTarget === searchInputRef.current && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
return;
}
const resultCollection = event.currentTarget.ownerDocument.getElementById(resultsId);
const options = Array.from((_resultCollection$que = resultCollection === null || resultCollection === void 0 ? void 0 : resultCollection.querySelectorAll('[role="option"]')) !== null && _resultCollection$que !== void 0 ? _resultCollection$que : []);
const currentIndex = options.findIndex(option => option === event.currentTarget.ownerDocument.activeElement);
const targetIndex = getArrowKeyTargetIndex(options.map(toArrowKeyOption), currentIndex, event.key);
const nextOption = targetIndex === undefined ? undefined : options[targetIndex];
if (nextOption) {
event.preventDefault();
nextOption.focus();
nextOption.click();
} else if (targetIndex === RETURN_TO_SEARCH) {
var _searchInputRef$curre3;
event.preventDefault();
(_searchInputRef$curre3 = searchInputRef.current) === null || _searchInputRef$curre3 === void 0 ? void 0 : _searchInputRef$curre3.focus();
}
return;
}
if (event.key === 'Escape') {
event.preventDefault();
closeBrowser();
return;
}
if (event.key === 'Enter') {
const focusedOption = event.target instanceof HTMLElement ? event.target.closest('[role="option"]') : null;
const firstOption = getFirstEnabledOption(event.currentTarget.ownerDocument.getElementById(resultsId));
const optionToActivate = focusedOption !== null && focusedOption !== void 0 ? focusedOption : firstOption;
if (isSelectedRegistrationCurrent || optionToActivate) {
event.preventDefault();
if (!isSelectedRegistrationCurrent) {
optionToActivate === null || optionToActivate === void 0 ? void 0 : optionToActivate.click();
}
confirmInsert();
}
}
}, [closeBrowser, confirmInsert, isSelectedRegistrationCurrent]);
return /*#__PURE__*/React.createElement(ModalTransition, null, isOpen && /*#__PURE__*/React.createElement(Modal, {
label: formatMessage({
defaultMessage: 'Insert elements',
id: 'editor.quick-insert.title'
}),
height: "804px",
onClose: closeBrowser,
onCloseComplete: onCloseComplete,
onOpenComplete: onModalOpenComplete,
testId: modalTestId,
width: "min(1072px, calc(100vw - 32px))"
}, /*#__PURE__*/React.createElement(ModalHeader, null, /*#__PURE__*/React.createElement("div", {
className: ax(["_zulpv47k _1e0c11p5 _yv0e1xuv _1bsb1osq _1ikai47z"])
}, /*#__PURE__*/React.createElement(ModalTitle, null, formatMessage({
defaultMessage: 'Insert elements',
id: 'editor.quick-insert.title'
})), /*#__PURE__*/React.createElement("div", {
className: ax(["_zulp1ejb _4cvr1h6o _1e0c11p5 _yv0ehpfy _1bsb1osq"])
}, /*#__PURE__*/React.createElement(Textfield, {
autoFocus: true,
"aria-controls": resultsId,
"aria-label": formatMessage({
defaultMessage: 'Search elements',
id: 'editor.quick-insert.search'
}),
isCompact: true,
name: "registry-element-browser-search",
onFocus: onSearchFocus,
onChange: onSearchChange,
onKeyDown: onKeyDown,
ref: searchInputRef,
value: query
}), /*#__PURE__*/React.createElement(IconButton, {
appearance: "subtle",
icon: CrossIcon,
label: formatMessage(messages.close),
onClick: closeBrowser,
spacing: "compact"
})))), /*#__PURE__*/React.createElement(ModalBody, {
hasInlinePadding: false
}, /*#__PURE__*/React.createElement("div", {
onFocusCapture: onBrowserFocusCapture,
className: ax(["_zulp1fka _18zrpxbi _1e0c11p5 _yv0e1xuv _1q511b66 _1ikai47z _uzjvutpp"])
}, /*#__PURE__*/React.createElement(RegistryElementBrowserCategories, {
section: effectiveSection,
sections: model.sections,
onSectionClick: onSectionClick,
selectedButtonRef: selectedCategoryRef
}), /*#__PURE__*/React.createElement(RegistryElementBrowserSearchResults, {
editorView: editorView,
emptyStateHandler: emptyStateHandler,
isLoading: isLoading,
isOffline: isOffline,
items: items,
fallbackItems: model.fallbackItems,
query: query,
recommendedItems: recommendedItems,
resultsId: resultsId,
surfaceContext: surfaceContext,
section: effectiveSection,
selectedKey: selectedKey,
onKeyDown: onKeyDown,
onSelect: onRegistrySelect
}))), /*#__PURE__*/React.createElement(ModalFooter, null, /*#__PURE__*/React.createElement(RegistryElementBrowserFooter, {
helpUrl: helpUrl,
isInsertEnabled: isSelectedRegistrationCurrent,
onClose: closeBrowser,
onConfirmInsert: confirmInsert,
resultCount: resultCount
}))));
};