@atlaskit/editor-plugin-code-block
Version:
Code block plugin for @atlaskit/editor-core
288 lines (286 loc) • 15.5 kB
JavaScript
import React from 'react';
import { areCodeBlockLineNumbersVisible, isCodeBlockWordWrapEnabled } from '@atlaskit/editor-common/code-block';
import commonMessages, { codeBlockButtonMessages } from '@atlaskit/editor-common/messages';
import { areToolbarFlagsEnabled } from '@atlaskit/editor-common/toolbar-flag-check';
import { findDomRefAtPos } from '@atlaskit/editor-prosemirror/utils';
import AngleBracketsIcon from '@atlaskit/icon/core/angle-brackets';
import CopyIcon from '@atlaskit/icon/core/copy';
import DeleteIcon from '@atlaskit/icon/core/delete';
import ListNumberedIcon from '@atlaskit/icon/core/list-numbered';
import TextWrapIcon from '@atlaskit/icon/core/text-wrap';
import { fg } from '@atlaskit/platform-feature-flags';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { expValEqualsNoExposure } from '@atlaskit/tmp-editor-statsig/exp-val-equals-no-exposure';
import { changeLanguage, copyContentToClipboardWithAnalytics, createFormatCodeOnClick, removeCodeBlockWithAnalytics, resetCopiedState, toggleLineNumbersForCodeBlockNode, toggleWordWrapStateForCodeBlockNode } from '../editor-commands';
import { CodeBlockLanguagePicker } from '../ui/CodeBlockLanguagePicker';
import { WrapIcon } from '../ui/icons/WrapIcon';
import { DETECT_LANGUAGE_VALUE, NONE_LANGUAGE_VALUE, PLAIN_TEXT_LANGUAGE_VALUE } from '../ui/language-picker-options';
import { preloadFormatterOnIntent } from '../utils/format-code/formatter';
import { autoDetectPluginKey } from './auto-detect-state';
import { provideVisualFeedbackForCopyButton, removeVisualFeedbackForCopyButton } from './codeBlockCopySelectionPlugin';
import { createLanguageList, DEFAULT_LANGUAGES, getLanguageIdentifier } from './language-list';
import { pluginKey } from './plugin-key';
const getDetectLanguageOption = formatMessage => ({
alias: [],
label: formatMessage(codeBlockButtonMessages.detectLanguage),
value: DETECT_LANGUAGE_VALUE
});
const getNoneDetectedOption = formatMessage => ({
alias: [],
label: formatMessage(codeBlockButtonMessages.noneDetected),
value: NONE_LANGUAGE_VALUE
});
const getDefaultLanguagePickerValue = (language, languagePickerOptions) => language ? languagePickerOptions.find(option => language === NONE_LANGUAGE_VALUE ? option.value === PLAIN_TEXT_LANGUAGE_VALUE : option.value === language || option.alias.includes(language)) : undefined;
const getAutoDetectPickerValue = ({
autoDetectEntry,
formatMessage,
language,
languagePickerOptions
}) => {
const defaultPickerValue = getDefaultLanguagePickerValue(language, languagePickerOptions);
// A weak re-detection records noneDetected but can leave a previously auto-detected
// language on the node. Keep showing "(detected)" only while that preserved language
// still matches the node language, so manual language changes do not inherit the label.
const shouldShowDetectedLabel = Boolean(defaultPickerValue) && (autoDetectEntry === null || autoDetectEntry === void 0 ? void 0 : autoDetectEntry.autoDetectedLanguage) === language && Boolean(autoDetectEntry === null || autoDetectEntry === void 0 ? void 0 : autoDetectEntry.detectionResult);
if (shouldShowDetectedLabel && defaultPickerValue) {
return {
...defaultPickerValue,
label: formatMessage(codeBlockButtonMessages.detectedLanguage, {
language: defaultPickerValue.label
})
};
}
if (language || !autoDetectEntry) {
return defaultPickerValue;
}
if (autoDetectEntry.detectionResult === 'noneDetected') {
return getNoneDetectedOption(formatMessage);
}
if (!autoDetectEntry.detectionResult) {
return getDetectLanguageOption(formatMessage);
}
return undefined;
};
export const getToolbarConfig = (allowCopyToClipboard = false, api, overrideLanguageName = undefined, formatCodeProvider = undefined) => {
const languageList = createLanguageList(overrideLanguageName ? DEFAULT_LANGUAGES.map(languageOption => ({
...languageOption,
name: overrideLanguageName(languageOption.name)
})) : DEFAULT_LANGUAGES);
const languagePickerOptions = languageList.map(lang => ({
label: lang.name,
value: getLanguageIdentifier(lang),
alias: lang.alias
}));
return (state, {
formatMessage
}) => {
var _api$editorViewMode, _api$editorViewMode$s, _api$decorations$acti, _api$decorations, _api$analytics, _codeBlockState$pos, _node$attrs, _node$attrs2, _languagePicker;
const isViewMode = (api === null || api === void 0 ? void 0 : (_api$editorViewMode = api.editorViewMode) === null || _api$editorViewMode === void 0 ? void 0 : (_api$editorViewMode$s = _api$editorViewMode.sharedState.currentState()) === null || _api$editorViewMode$s === void 0 ? void 0 : _api$editorViewMode$s.mode) === 'view';
const {
hoverDecoration
} = (_api$decorations$acti = api === null || api === void 0 ? void 0 : (_api$decorations = api.decorations) === null || _api$decorations === void 0 ? void 0 : _api$decorations.actions) !== null && _api$decorations$acti !== void 0 ? _api$decorations$acti : {};
const editorAnalyticsAPI = api === null || api === void 0 ? void 0 : (_api$analytics = api.analytics) === null || _api$analytics === void 0 ? void 0 : _api$analytics.actions;
const codeBlockState = pluginKey.getState(state);
const pos = (_codeBlockState$pos = codeBlockState === null || codeBlockState === void 0 ? void 0 : codeBlockState.pos) !== null && _codeBlockState$pos !== void 0 ? _codeBlockState$pos : null;
if (!codeBlockState || pos === null) {
return;
}
const node = state.doc.nodeAt(pos);
const nodeType = state.schema.nodes.codeBlock;
if ((node === null || node === void 0 ? void 0 : node.type) !== nodeType) {
return;
}
const isWrapped = isCodeBlockWordWrapEnabled(node);
const areLineNumbersVisible = areCodeBlockLineNumbersVisible(node);
const language = node === null || node === void 0 ? void 0 : (_node$attrs = node.attrs) === null || _node$attrs === void 0 ? void 0 : _node$attrs.language;
const localId = node === null || node === void 0 ? void 0 : (_node$attrs2 = node.attrs) === null || _node$attrs2 === void 0 ? void 0 : _node$attrs2.localId;
const autoDetectState = autoDetectPluginKey.getState(state);
const isFormatCodePending = typeof localId === 'string' && Boolean(codeBlockState.pendingFormats[localId]);
// Keep fresh option objects for the legacy toolbar select so reopening it
// continues to start from the top rather than preserving the previously
// focused option by reference.
const languageSelectOptions = languagePickerOptions.map(option => ({
...option
}));
const defaultValue = language ? languageSelectOptions.find(option => option.value === language) || languageSelectOptions.find(option => option.alias.includes(language)) : null;
const languageSelect = {
id: 'editor.codeBlock.languageOptions',
type: 'select',
selectType: 'list',
onChange: option => changeLanguage(editorAnalyticsAPI)(option.value),
defaultValue,
placeholder: formatMessage(codeBlockButtonMessages.selectLanguage),
options: languageSelectOptions,
filterOption: languageListFilter
};
const areAnyNewToolbarFlagsEnabled = areToolbarFlagsEnabled(Boolean(api === null || api === void 0 ? void 0 : api.toolbar));
let languagePicker;
if (expValEquals('platform_editor_code_block_q4_lovability', 'isEnabled', true) && fg('platform_editor_code_block_add_line_number_button')) {
const autoDetectEntry = typeof localId === 'string' && fg('platform_editor_code_block_language_detection_flow') ? autoDetectState === null || autoDetectState === void 0 ? void 0 : autoDetectState.languageDetectionMap[localId] : undefined;
const autoDetectPickerValue = getAutoDetectPickerValue({
autoDetectEntry,
formatMessage,
language,
languagePickerOptions
});
languagePicker = {
type: 'custom',
fallback: [],
render: view => {
if (!view) {
return null;
}
return /*#__PURE__*/React.createElement(CodeBlockLanguagePicker, {
api: api,
defaultValue: autoDetectPickerValue,
editorView: view,
filterOption: languageListFilter,
formatMessage: formatMessage,
languagePickerOptions: languagePickerOptions,
triggerSpacing: !areAnyNewToolbarFlagsEnabled && fg('platform_editor_code_block_dogfooding_patch') ? 'compact' : 'default'
});
}
};
}
const separator = {
type: 'separator'
};
const copyToClipboardItems = !allowCopyToClipboard ? [] : [{
id: 'editor.codeBlock.copy',
type: 'button',
supportsViewMode: true,
appearance: 'subtle',
icon: CopyIcon,
// note: copyContentToClipboardWithAnalytics contains logic that also removes the
// visual feedback for the copy button
onClick: copyContentToClipboardWithAnalytics(editorAnalyticsAPI),
title: formatMessage(codeBlockState.contentCopied ? codeBlockButtonMessages.copiedCodeToClipboard : codeBlockButtonMessages.copyCodeToClipboard),
onMouseEnter: provideVisualFeedbackForCopyButton,
// note: resetCopiedState contains logic that also removes the
// visual feedback for the copy button
onMouseLeave: resetCopiedState,
onFocus: provideVisualFeedbackForCopyButton,
onBlur: removeVisualFeedbackForCopyButton,
hideTooltipOnClick: false,
disabled: codeBlockState.isNodeSelected,
tabIndex: null
}, separator];
let copyAndDeleteButtonMenuItems = [];
if (areAnyNewToolbarFlagsEnabled) {
const overflowMenuOptions = [{
title: formatMessage(commonMessages.delete),
icon: DeleteIcon({
label: ''
}),
onMouseEnter: hoverDecoration === null || hoverDecoration === void 0 ? void 0 : hoverDecoration(nodeType, true),
onMouseLeave: hoverDecoration === null || hoverDecoration === void 0 ? void 0 : hoverDecoration(nodeType, false),
onFocus: hoverDecoration === null || hoverDecoration === void 0 ? void 0 : hoverDecoration(nodeType, true),
onBlur: hoverDecoration === null || hoverDecoration === void 0 ? void 0 : hoverDecoration(nodeType, false),
onClick: removeCodeBlockWithAnalytics(editorAnalyticsAPI)
}];
if (allowCopyToClipboard) {
overflowMenuOptions.unshift({
title: formatMessage(commonMessages.copyToClipboard),
onClick: copyContentToClipboardWithAnalytics(editorAnalyticsAPI),
icon: CopyIcon({
label: ''
}),
onMouseEnter: provideVisualFeedbackForCopyButton,
onMouseLeave: resetCopiedState,
onFocus: provideVisualFeedbackForCopyButton,
onBlur: removeVisualFeedbackForCopyButton,
disabled: codeBlockState.isNodeSelected
});
}
copyAndDeleteButtonMenuItems = isViewMode ? [...copyToClipboardItems] : [{
type: 'separator',
fullHeight: true
}, {
type: 'overflow-dropdown',
testId: 'code-block-overflow-dropdown-trigger',
options: overflowMenuOptions
}];
} else {
const deleteButton = {
id: 'editor.codeBlock.delete',
type: 'button',
appearance: 'danger',
icon: DeleteIcon,
iconFallback: DeleteIcon,
onMouseEnter: hoverDecoration === null || hoverDecoration === void 0 ? void 0 : hoverDecoration(nodeType, true),
onMouseLeave: hoverDecoration === null || hoverDecoration === void 0 ? void 0 : hoverDecoration(nodeType, false),
onFocus: hoverDecoration === null || hoverDecoration === void 0 ? void 0 : hoverDecoration(nodeType, true),
onBlur: hoverDecoration === null || hoverDecoration === void 0 ? void 0 : hoverDecoration(nodeType, false),
onClick: removeCodeBlockWithAnalytics(editorAnalyticsAPI),
title: formatMessage(commonMessages.remove),
tabIndex: null
};
copyAndDeleteButtonMenuItems = [separator, ...copyToClipboardItems, deleteButton];
}
const codeBlockWrapButtonTitle = expValEqualsNoExposure('platform_editor_code_block_q4_lovability', 'isEnabled', true) ? formatMessage(isWrapped ? codeBlockButtonMessages.unwrapCodeLabel : codeBlockButtonMessages.wrapCodeLabel) : formatMessage(codeBlockButtonMessages.wrapCode);
const codeBlockWrapButton = {
id: 'editor.codeBlock.wrap',
type: 'button',
// Toggling button now writes to ADF, hence it should be available in view mode
supportsViewMode: !expValEqualsNoExposure('platform_editor_code_block_q4_lovability', 'isEnabled', true),
icon: TextWrapIcon,
iconFallback: WrapIcon,
onClick: toggleWordWrapStateForCodeBlockNode(editorAnalyticsAPI),
title: codeBlockWrapButtonTitle,
tabIndex: null,
selected: isWrapped
};
const codeBlockLineNumbersButton = {
id: 'editor.codeBlock.lineNumbers',
type: 'button',
supportsViewMode: false,
icon: ListNumberedIcon,
onClick: toggleLineNumbersForCodeBlockNode(editorAnalyticsAPI),
title: formatMessage(areLineNumbersVisible ? codeBlockButtonMessages.hideLineNumbersLabel : codeBlockButtonMessages.showLineNumbersLabel),
tabIndex: null,
selected: areLineNumbersVisible
};
const formatLanguage = formatCodeProvider !== null && formatCodeProvider !== void 0 && formatCodeProvider.isSupportedLanguage(language) ? language : undefined;
const canFormatCode = node.textContent.length > 0 && Boolean(formatLanguage);
const formatCodeButton = {
id: 'editor.codeBlock.formatCode',
type: 'button',
supportsViewMode: false,
disabled: !canFormatCode || isFormatCodePending,
icon: AngleBracketsIcon,
onClick: createFormatCodeOnClick({
api,
editorAnalyticsAPI,
formatCodeProvider
}),
onFocus: preloadFormatterOnIntent(formatCodeProvider, formatLanguage),
onMouseEnter: preloadFormatterOnIntent(formatCodeProvider, formatLanguage),
title: formatMessage(canFormatCode ? codeBlockButtonMessages.formatCode : codeBlockButtonMessages.formatCodeUnavailable)
};
return {
title: 'CodeBlock floating controls',
// Ignored via go/ees005
// eslint-disable-next-line @atlaskit/editor/no-as-casting
getDomRef: view => findDomRefAtPos(pos, view.domAtPos.bind(view)),
nodeType,
items: [(_languagePicker = languagePicker) !== null && _languagePicker !== void 0 ? _languagePicker : languageSelect, ...(areAnyNewToolbarFlagsEnabled ? [] : [separator]), codeBlockWrapButton, ...(expValEquals('platform_editor_code_block_q4_lovability', 'isEnabled', true) && fg('platform_editor_code_block_add_line_number_button') ? [codeBlockLineNumbersButton, ...(formatCodeProvider ? [formatCodeButton] : [])] : []), ...copyAndDeleteButtonMenuItems],
scrollable: true
};
};
};
/**
* Filters language list based on both name and alias properties.
* @param option
* @param rawInput
* @example
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const languageListFilter = (option, rawInput) => {
// Ignored via go/ees005
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const {
data
} = option;
const searchString = rawInput.toLowerCase();
return data.label.toLowerCase().includes(searchString) || data.alias.some(alias => alias.toLowerCase() === searchString);
};