@atlaskit/editor-common
Version:
A package that contains common classes and components for editor and renderer
625 lines (618 loc) • 22 kB
JavaScript
import _extends from "@babel/runtime/helpers/extends";
/* eslint-disable @atlaskit/ui-styling-standard/use-compiled -- Pre-existing lint debt surfaced by this mechanical type-import-only PR. */
/**
* @jsxRuntime classic
* @jsx jsx
*/
import React, { Fragment, memo, useCallback, useEffect, useMemo, useState } from 'react';
// eslint-disable-next-line @atlaskit/ui-styling-standard/use-compiled, @typescript-eslint/consistent-type-imports -- Ignored via go/DSP-18766; jsx required at runtime for @jsxRuntime classic
import { css, jsx } from '@emotion/react';
import { Grid, List } from 'react-virtualized';
import { AutoSizer } from 'react-virtualized/dist/commonjs/AutoSizer';
import { CellMeasurer, CellMeasurerCache } from 'react-virtualized/dist/commonjs/CellMeasurer';
import withAnalyticsContext from '@atlaskit/analytics-next/withAnalyticsContext';
import { relativeFontSizeToBase16 } from '@atlaskit/editor-shared-styles';
import { shortcutStyle } from '@atlaskit/editor-shared-styles/shortcut';
import { ButtonItem } from '@atlaskit/menu';
import { fg } from '@atlaskit/platform-feature-flags';
import { Flex, Stack, Text } from '@atlaskit/primitives/compiled';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { editorExperiment } from '@atlaskit/tmp-editor-statsig/experiments';
import Tooltip from '@atlaskit/tooltip';
import { ACTION, ACTION_SUBJECT, EVENT_TYPE, fireAnalyticsEvent } from '../../../analytics';
import { IconFallback } from '../../../quick-insert';
import { ELEMENT_ITEM_HEIGHT, ELEMENT_ITEM_PADDING, ELEMENT_LIST_PADDING, SCROLLBAR_WIDTH } from '../../constants';
import useContainerWidth from '../../hooks/use-container-width';
import useFocus from '../../hooks/use-focus';
import { Modes } from '../../types';
import EmptyState from './EmptyState';
import { getColumnCount, getScrollbarWidth } from './utils';
export const ICON_HEIGHT = 40;
export const ICON_WIDTH = 40;
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-exported-styles -- Ignored via go/DSP-18766
export const itemIcon = css({
width: `${ICON_WIDTH}px`,
height: `${ICON_HEIGHT}px`,
overflow: 'hidden',
border: `${"var(--ds-border-width, 1px)"} solid ${"var(--ds-border, #0B120E24)"}`,
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
borderRadius: "var(--ds-radius-small, 3px)",
boxSizing: 'border-box',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-nested-selectors -- Ignored via go/DSP-18766
div: {
width: `${ICON_WIDTH}px`,
height: `${ICON_HEIGHT}px`
}
});
function ElementList({
items,
mode,
selectedItemIndex,
focusedItemIndex,
focusOnEmptyStateButton,
columnCount,
setColumnCount,
createAnalyticsEvent,
emptyStateHandler,
selectedCategory,
selectedCategoryIndex,
searchTerm,
setFocusedCategoryIndex,
setFocusedItemIndex,
cache,
onInsertItem,
hasTabListContext = false
}) {
const {
containerWidth,
ContainerWidthMonitor
} = useContainerWidth();
const [scrollbarWidth, setScrollbarWidth] = useState(SCROLLBAR_WIDTH);
const fullMode = mode === Modes.full;
useEffect(() => {
/**
* More of an optimization condition.
* Initially the containerWidths are reported 0 twice.
**/
if (fullMode && containerWidth > 0) {
setColumnCount(getColumnCount(containerWidth));
const updatedScrollbarWidth = getScrollbarWidth();
if (updatedScrollbarWidth > 0) {
// eslint-disable-next-line @atlassian/perf-linting/no-chain-state-updates -- Ignored via go/ees017 (to be fixed)
setScrollbarWidth(updatedScrollbarWidth);
}
}
}, [fullMode, containerWidth, setColumnCount, scrollbarWidth]);
const onExternalLinkClick = useCallback(() => {
fireAnalyticsEvent(createAnalyticsEvent)({
payload: {
action: ACTION.VISITED,
actionSubject: ACTION_SUBJECT.SMART_LINK,
eventType: EVENT_TYPE.TRACK
}
});
}, [createAnalyticsEvent]);
const listCache = useMemo(() => {
return cache !== null && cache !== void 0 ? cache : new CellMeasurerCache({
fixedWidth: true,
defaultHeight: ELEMENT_ITEM_HEIGHT,
minHeight: ELEMENT_ITEM_HEIGHT
});
}, [cache]);
useEffect(() => {
// need to recalculate values if we have the same items, but they're reordered
listCache.clearAll();
}, [listCache, searchTerm]);
const rowHeight = ({
index
}) => {
return listCache.rowHeight({
index
});
};
return jsx(Fragment, null, jsx(ContainerWidthMonitor, null), jsx("div", {
css: elementItemsWrapper,
"data-testid": "element-items",
id: selectedCategory ? `browse-category-${selectedCategory}-tab` : 'browse-category-tab',
"aria-labelledby": !hasTabListContext && fg('platform_editor_ally_remove_role_tabpanel') ? undefined : selectedCategory ? `browse-category--${selectedCategory}-button` : 'browse-category-button',
role: !hasTabListContext && fg('platform_editor_ally_remove_role_tabpanel') ? undefined : 'tabpanel',
tabIndex: items.length === 0 ? 0 : undefined
}, !items.length ? emptyStateHandler ? emptyStateHandler({
mode,
selectedCategory,
searchTerm
}) : jsx(EmptyState, {
onExternalLinkClick: onExternalLinkClick,
focusOnEmptyStateButton: focusOnEmptyStateButton
}) : jsx(Fragment, null, containerWidth > 0 && jsx(AutoSizer, {
disableWidth: true
}, ({
height
}) => columnCount === 1 ? jsx(ElementListSingleColumn, {
cache: listCache,
setFocusedCategoryIndex: setFocusedCategoryIndex,
selectedCategoryIndex: selectedCategoryIndex,
items: items,
setFocusedItemIndex: setFocusedItemIndex,
fullMode: fullMode,
selectedItemIndex: selectedItemIndex,
focusedItemIndex: focusedItemIndex,
rowHeight: rowHeight,
containerWidth: containerWidth,
height: height,
onInsertItem: onInsertItem
}) : jsx(ElementListMultipleColumns, {
columnCount: columnCount,
cache: listCache,
setFocusedCategoryIndex: setFocusedCategoryIndex,
selectedCategoryIndex: selectedCategoryIndex,
items: items,
setFocusedItemIndex: setFocusedItemIndex,
fullMode: fullMode,
selectedItemIndex: selectedItemIndex,
focusedItemIndex: focusedItemIndex,
rowHeight: rowHeight,
containerWidth: containerWidth,
height: height,
onInsertItem: onInsertItem
})))));
}
const ElementListSingleColumn = props => {
const {
items,
fullMode,
setFocusedItemIndex,
rowHeight,
containerWidth,
height,
onInsertItem,
cache,
focusedItemIndex,
setFocusedCategoryIndex,
selectedCategoryIndex,
selectedItemIndex
} = props;
const rowRenderer = useMemo(() => ({
index,
key,
style,
parent
}) => {
return jsx(CellMeasurer, {
key: key,
cache: cache,
parent: parent,
columnIndex: 0,
rowIndex: index
}, jsx("div", {
// eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
style: style,
key: key
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766 -- Ignored via go/DSP-18766
,
className: "element-item-wrapper",
css: elementItemWrapperSingle,
role: expValEquals('editor_a11y__enghealth-46814_fy26', 'isEnabled', true) ? 'presentation' : undefined,
onKeyDown: e => {
if (e.key === 'Tab') {
if (e.shiftKey && index === 0) {
if (setFocusedCategoryIndex) {
if (!!selectedCategoryIndex) {
setFocusedCategoryIndex(selectedCategoryIndex);
} else {
setFocusedCategoryIndex(0);
}
e.preventDefault();
}
}
// before focus jumps from elements list we need to rerender react-virtualized grid.
// Otherwise on the next render 'scrollToCell' will have same cached value
// and grid will not be scrolled to top.
// So Tab press on category will not work anymore due to invisible 1-t element.
else if (index === items.length - 2) {
setFocusedItemIndex(items.length - 1);
}
}
}
}, jsx(MemoizedElementItem, {
inlineMode: !fullMode,
index: index,
item: items[index],
selected: selectedItemIndex === index,
focus: focusedItemIndex === index,
setFocusedItemIndex: setFocusedItemIndex,
onInsertItem: onInsertItem,
role: expValEquals('platform_editor_august_a11y', 'isEnabled', true) ? 'option' : undefined
})));
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[cache, items, fullMode, selectedItemIndex, focusedItemIndex, selectedCategoryIndex, setFocusedCategoryIndex, setFocusedItemIndex, props]);
return jsx(List, _extends({
rowRenderer: rowRenderer,
rowCount: items.length,
rowHeight: rowHeight,
width: containerWidth - ELEMENT_LIST_PADDING * 2,
height: height,
overscanRowCount: 3,
containerRole: "presentation",
role: "listbox"
// Ignored via go/ees005
// eslint-disable-next-line react/jsx-props-no-spreading
}, selectedItemIndex !== undefined && {
scrollToIndex: selectedItemIndex
}));
};
const ElementListMultipleColumns = props => {
const {
columnCount,
items,
fullMode,
setFocusedItemIndex,
rowHeight,
containerWidth,
height,
onInsertItem,
cache,
focusedItemIndex,
setFocusedCategoryIndex,
selectedCategoryIndex,
selectedItemIndex
} = props;
const columnWidth = (containerWidth - ELEMENT_ITEM_PADDING * 2) / columnCount;
const rowCount = Math.ceil(items.length / columnCount);
const cellRenderer = useMemo(() => ({
columnIndex,
key,
parent,
rowIndex,
style
}) => {
const index = rowIndex * columnCount + columnIndex;
if (items[index] == null) {
return;
}
return index > items.length - 1 ? null : jsx(CellMeasurer, {
cache: cache,
key: key,
rowIndex: rowIndex,
columnIndex: columnIndex,
parent: parent
}, jsx("div", {
// eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
style: style,
key: key
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766 -- Ignored via go/DSP-18766
,
className: "element-item-wrapper",
role: "gridcell",
tabIndex: 0,
css: elementItemWrapper,
onKeyDown: e => {
if (e.key === 'Tab') {
if (e.shiftKey && index === 0) {
if (setFocusedCategoryIndex) {
if (!!selectedCategoryIndex) {
setFocusedCategoryIndex(selectedCategoryIndex);
} else {
setFocusedCategoryIndex(0);
}
e.preventDefault();
}
}
// before focus jumps from elements list we need to rerender react-virtualized grid.
// Otherwise on the next render 'scrollToCell' will have same cached value
// and grid will not be scrolled to top.
// So Tab press on category will not work anymore due to invisible 1-t element.
else if (index === items.length - 2) {
setFocusedItemIndex(items.length - 1);
}
}
}
}, jsx(MemoizedElementItem, {
inlineMode: !fullMode,
index: index,
item: items[index],
selected: selectedItemIndex === index,
focus: focusedItemIndex === index,
setFocusedItemIndex: setFocusedItemIndex,
onInsertItem: onInsertItem
})));
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[cache, items, fullMode, selectedItemIndex, columnCount, focusedItemIndex, selectedCategoryIndex, setFocusedCategoryIndex, setFocusedItemIndex, props]);
return jsx(Grid, _extends({
containerRole: "row",
cellRenderer: cellRenderer,
height: height,
width: containerWidth - ELEMENT_LIST_PADDING * 2 // containerWidth - padding on Left/Right (for focus outline)
/**
* Refresh Grid on WidthObserver value change.
* Length of the items used to force re-render to solve Firefox bug with react-virtualized retaining
* scroll position after updating the data. If new data has different number of cells, a re-render
* is forced to prevent the scroll position render bug.
*/,
key: containerWidth + items.length,
rowHeight: rowHeight,
rowCount: rowCount,
columnCount: columnCount,
columnWidth: columnWidth,
deferredMeasurementCache: cache
// Ignored via go/ees005
// eslint-disable-next-line react/jsx-props-no-spreading
}, selectedItemIndex !== undefined && {
scrollToRow: Math.floor(selectedItemIndex / columnCount)
}));
};
const MemoizedElementItem = /*#__PURE__*/memo(ElementItem);
MemoizedElementItem.displayName = 'MemoizedElementItem';
export function ElementItem({
inlineMode,
selected,
item,
index,
onInsertItem,
focus,
setFocusedItemIndex,
role
}) {
const ref = useFocus(focus);
/**
* Note: props.onSelectItem(item) is not called here as the StatelessElementBrowser's
* useEffect would trigger it on selectedItemIndex change. (Line 106-110)
* This implementation was changed for keyboard/click selection to work with `onInsertItem`.
*/
const onClick = useCallback(e => {
e.preventDefault();
e.stopPropagation();
setFocusedItemIndex(index);
switch (e.nativeEvent.detail) {
case 0:
onInsertItem(item);
break;
case 1:
if (inlineMode) {
onInsertItem(item);
}
break;
case 2:
if (!inlineMode) {
onInsertItem(item);
}
break;
default:
return;
}
}, [index, inlineMode, item, onInsertItem, setFocusedItemIndex]);
const {
icon,
title,
description,
keyshortcut,
isDisabled,
lozenge
} = item;
return jsx(Tooltip, {
content: description,
testId: `element-item-tooltip-${index}`
}, jsx(ButtonItem, {
onClick: onClick,
iconBefore: jsx(ElementBefore, {
icon: icon,
title: title
}),
isSelected: selected,
"aria-describedby": expValEquals('platform_editor_august_a11y', 'isEnabled', true) ? undefined : title,
"aria-label": expValEquals('platform_editor_august_a11y', 'isEnabled', true) ? title : undefined,
ref: ref,
testId: `element-item-${index}`,
id: `searched-item-${index}`,
isDisabled: isDisabled,
role: role
}, jsx(ItemContent
// eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
, {
style: inlineMode ? null : itemStyleOverrides,
tabIndex: 0,
title: title,
description: description,
keyshortcut: keyshortcut,
isDisabled: isDisabled,
lozenge: lozenge
})));
}
/**
* Inline mode should use the existing Align-items:center value.
*/
const itemStyleOverrides = {
alignItems: 'flex-start'
};
const ElementBefore = /*#__PURE__*/memo(({
icon
}) => jsx("div", {
css: [itemIcon, itemIconStyle]
}, icon ? icon() : jsx(IconFallback, null)));
const ItemContent = /*#__PURE__*/memo(({
title,
description,
keyshortcut,
lozenge,
isDisabled
}) => {
if (fg('platform_editor_typography_ugc')) {
return (
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
jsx("div", {
css: itemBody,
className: "item-body"
}, jsx("div", {
css: itemText
}, jsx(Stack, {
space: "space.025"
}, jsx("div", {
css: itemTitleWrapper
}, editorExperiment('platform_synced_block', true) || lozenge ? jsx(Flex, {
alignItems: "center",
gap: "space.050"
}, jsx(Text, {
color: isDisabled ? 'color.text.disabled' : undefined,
maxLines: 1
}, title), lozenge) : jsx(Text, {
color: isDisabled ? 'color.text.disabled' : undefined,
maxLines: 1
}, title), jsx("div", {
css: itemAfter
}, keyshortcut && jsx("div", {
css: shortcutStyle
}, keyshortcut))), description && jsx(Text, {
color: isDisabled ? 'color.text.disabled' : 'color.text.subtle',
size: "small",
maxLines: 2
}, description))))
);
} else {
return (
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
jsx("div", {
css: itemBody,
className: "item-body"
}, jsx("div", {
css: itemText
}, jsx("div", {
css: itemTitleWrapper
}, jsx("p", {
css: isDisabled ? itemTitleDisabled : itemTitle
}, title), jsx("div", {
css: itemAfter
}, keyshortcut && jsx("div", {
css: shortcutStyle
}, keyshortcut))), description &&
// eslint-disable-next-line @atlaskit/design-system/use-primitives-text
jsx("p", {
css: isDisabled ? itemDescriptionDisabled : itemDescription
}, description)))
);
}
});
const elementItemsWrapper = css({
flex: 1,
flexFlow: 'row wrap',
alignItems: 'flex-start',
justifyContent: 'flex-start',
overflow: 'hidden',
padding: "var(--ds-space-025, 2px)",
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-nested-selectors -- Ignored via go/DSP-18766
'.ReactVirtualized__Grid': {
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/design-system/no-unsafe-design-token-usage -- Ignored via go/DSP-18766
borderRadius: "var(--ds-radius-small, 3px)",
outline: 'none',
'&:focus': {
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
boxShadow: `0 0 0 ${ELEMENT_LIST_PADDING}px ${"var(--ds-border-focused, #4688EC)"}`
}
},
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-nested-selectors -- Ignored via go/DSP-18766
'.ReactVirtualized__Grid__innerScrollContainer': {
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-nested-selectors, @atlaskit/ui-styling-standard/no-unsafe-selectors -- Ignored via go/DSP-18766
"div[class='element-item-wrapper']:last-child": {
paddingBottom: "var(--ds-space-050, 4px)"
}
}
});
const elementItemWrapperSingle = css({
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-nested-selectors -- Ignored via go/DSP-18766
div: {
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-nested-selectors -- Ignored via go/DSP-18766
button: {
minHeight: '60px',
alignItems: 'flex-start',
padding: `${"var(--ds-space-150, 12px)"} ${"var(--ds-space-150, 12px)"} 11px`
}
}
});
const elementItemWrapper = css({
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-nested-selectors -- Ignored via go/DSP-18766
div: {
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-nested-selectors -- Ignored via go/DSP-18766
button: {
minHeight: '75px',
alignItems: 'flex-start',
padding: `${"var(--ds-space-150, 12px)"} ${"var(--ds-space-150, 12px)"} 11px`
}
}
});
const itemBody = css({
display: 'flex',
flexDirection: 'row',
flexWrap: 'nowrap',
justifyContent: 'space-between',
// eslint-disable-next-line @atlaskit/design-system/use-tokens-typography
lineHeight: 1.4,
width: '100%',
marginTop: "var(--ds-space-negative-025, -2px)"
});
/*
* -webkit-line-clamp is also supported by firefox 🎉
* https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/68#CSS
*/
const multilineStyle = css({
display: '-webkit-box',
WebkitLineClamp: 2,
WebkitBoxOrient: 'vertical'
});
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
const itemDescription = css(multilineStyle, {
overflow: 'hidden',
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
fontSize: relativeFontSizeToBase16(11.67),
color: "var(--ds-text-subtle, #505258)",
marginTop: "var(--ds-space-025, 2px)"
});
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-unsafe-values, @atlaskit/design-system/consistent-css-prop-usage -- Ignored via go/DSP-18766
const itemDescriptionDisabled = css(multilineStyle, {
overflow: 'hidden',
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-imported-style-values, @atlaskit/ui-styling-standard/no-unsafe-values -- Ignored via go/DSP-18766
fontSize: relativeFontSizeToBase16(11.67),
color: "var(--ds-text-disabled, #080F214A)",
marginTop: "var(--ds-space-025, 2px)"
});
const itemText = css({
width: 'inherit',
whiteSpace: 'initial'
});
const itemTitleWrapper = css({
display: 'flex',
justifyContent: 'space-between'
});
const itemTitle = css({
width: '100%',
overflow: 'hidden',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis'
});
const itemTitleDisabled = css({
width: '100%',
overflow: 'hidden',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
color: "var(--ds-text-disabled, #080F214A)"
});
const itemAfter = css({
flex: '0 0 auto',
paddingTop: "var(--ds-space-025, 2px)",
marginBottom: "var(--ds-space-negative-025, -2px)"
});
const itemIconStyle = css({
// eslint-disable-next-line @atlaskit/ui-styling-standard/no-nested-selectors -- Ignored via go/DSP-18766
img: {
height: '40px',
width: '40px',
objectFit: 'cover'
}
});
const MemoizedElementListWithAnalytics = /*#__PURE__*/memo(withAnalyticsContext({
component: 'ElementList'
})(ElementList));
export default MemoizedElementListWithAnalytics;