@elastic/eui
Version:
Elastic UI Component Library
395 lines (390 loc) • 19.7 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EuiMarkdownEditor = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _react = _interopRequireWildcard(require("react"));
var _unified = _interopRequireDefault(require("unified"));
var _classnames = _interopRequireDefault(require("classnames"));
var _services = require("../../services");
var _modal = require("../modal");
var _resize_observer = require("../observer/resize_observer");
var _markdown_actions = _interopRequireWildcard(require("./markdown_actions"));
var _markdown_editor_toolbar = require("./markdown_editor_toolbar");
var _markdown_editor_text_area = require("./markdown_editor_text_area");
var _markdown_format = require("./markdown_format");
var _markdown_editor_drop_zone = require("./markdown_editor_drop_zone");
var _markdown_modes = require("./markdown_modes");
var _markdown_context = require("./markdown_context");
var _markdown_default_plugins = require("./plugins/markdown_default_plugins");
var _markdown_editor = require("./markdown_editor.styles");
var _react2 = require("@emotion/react");
var _excluded = ["className", "editorId", "value", "onChange", "height", "maxHeight", "autoExpandPreview", "parsingPluginList", "processingPluginList", "uiPlugins", "onParse", "errors", "aria-label", "aria-labelledby", "aria-describedby", "initialViewMode", "dropHandlers", "markdownFormatProps", "placeholder", "readOnly", "toolbarProps", "showFooter"];
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
// TODO I wanted to use the useCombinedRefs
// but I can't because it's not allowed to use react hooks
// inside a callback.
var mergeRefs = function mergeRefs() {
for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
refs[_key] = arguments[_key];
}
var filteredRefs = refs.filter(Boolean);
if (!filteredRefs.length) return null;
if (filteredRefs.length === 0) return filteredRefs[0];
return function (inst) {
var _iterator = _createForOfIteratorHelper(filteredRefs),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var ref = _step.value;
if (typeof ref === 'function') {
ref(inst);
} else if (ref) {
ref.current = inst;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
};
};
function isNewLine(char) {
if (char == null) return true;
return !!char.match(/[\r\n]/);
}
function padWithNewlinesIfNeeded(textarea, text) {
var selectionStart = textarea.selectionStart;
var selectionEnd = textarea.selectionEnd;
// block parsing requires two leading new lines and none trailing, but we add an extra trailing line for readability
var isPrevNewLine = isNewLine(textarea.value[selectionStart - 1]);
var isPrevPrevNewLine = isNewLine(textarea.value[selectionStart - 2]);
var isNextNewLine = isNewLine(textarea.value[selectionEnd]);
// pad text with newlines as needed
text = "".concat(isPrevNewLine ? '' : '\n').concat(isPrevPrevNewLine ? '' : '\n').concat(text).concat(isNextNewLine ? '' : '\n');
return text;
}
var EuiMarkdownEditor = exports.EuiMarkdownEditor = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
var className = _ref.className,
_editorId = _ref.editorId,
value = _ref.value,
_onChange = _ref.onChange,
_ref$height = _ref.height,
height = _ref$height === void 0 ? 250 : _ref$height,
_ref$maxHeight = _ref.maxHeight,
maxHeight = _ref$maxHeight === void 0 ? 500 : _ref$maxHeight,
_ref$autoExpandPrevie = _ref.autoExpandPreview,
autoExpandPreview = _ref$autoExpandPrevie === void 0 ? true : _ref$autoExpandPrevie,
_ref$parsingPluginLis = _ref.parsingPluginList,
parsingPluginList = _ref$parsingPluginLis === void 0 ? _markdown_default_plugins.defaultParsingPlugins : _ref$parsingPluginLis,
_ref$processingPlugin = _ref.processingPluginList,
processingPluginList = _ref$processingPlugin === void 0 ? _markdown_default_plugins.defaultProcessingPlugins : _ref$processingPlugin,
_ref$uiPlugins = _ref.uiPlugins,
uiPlugins = _ref$uiPlugins === void 0 ? _markdown_default_plugins.defaultUiPlugins : _ref$uiPlugins,
onParse = _ref.onParse,
_ref$errors = _ref.errors,
errors = _ref$errors === void 0 ? [] : _ref$errors,
ariaLabel = _ref['aria-label'],
ariaLabelledBy = _ref['aria-labelledby'],
ariaDescribedBy = _ref['aria-describedby'],
_ref$initialViewMode = _ref.initialViewMode,
initialViewMode = _ref$initialViewMode === void 0 ? _markdown_modes.MODE_EDITING : _ref$initialViewMode,
_ref$dropHandlers = _ref.dropHandlers,
dropHandlers = _ref$dropHandlers === void 0 ? [] : _ref$dropHandlers,
markdownFormatProps = _ref.markdownFormatProps,
placeholder = _ref.placeholder,
readOnly = _ref.readOnly,
toolbarProps = _ref.toolbarProps,
_ref$showFooter = _ref.showFooter,
showFooter = _ref$showFooter === void 0 ? true : _ref$showFooter,
rest = (0, _objectWithoutProperties2.default)(_ref, _excluded);
var _useState = (0, _react.useState)(initialViewMode),
_useState2 = (0, _slicedToArray2.default)(_useState, 2),
viewMode = _useState2[0],
setViewMode = _useState2[1];
var editorId = (0, _services.useGeneratedHtmlId)({
conditionalId: _editorId
});
var _useState3 = (0, _react.useState)(undefined),
_useState4 = (0, _slicedToArray2.default)(_useState3, 2),
pluginEditorPlugin = _useState4[0],
setPluginEditorPlugin = _useState4[1];
var toolbarPlugins = (0, _toConsumableArray2.default)(uiPlugins);
var markdownActions = (0, _react.useMemo)(function () {
return new _markdown_actions.default(editorId, toolbarPlugins);
},
// toolbarPlugins _is_ accounted for
// eslint-disable-next-line react-hooks/exhaustive-deps
[editorId, toolbarPlugins.map(function (_ref2) {
var name = _ref2.name;
return name;
}).join(',')]);
var parser = (0, _react.useMemo)(function () {
var Compiler = function Compiler(tree) {
return tree;
};
function identityCompiler() {
this.Compiler = Compiler;
}
return (0, _unified.default)().use(parsingPluginList).use(identityCompiler);
}, [parsingPluginList]);
var _useMemo = (0, _react.useMemo)(function () {
try {
var _parsed = parser.processSync(value);
return [_parsed, null];
} catch (e) {
return [null, e];
}
}, [parser, value]),
_useMemo2 = (0, _slicedToArray2.default)(_useMemo, 2),
parsed = _useMemo2[0],
parseError = _useMemo2[1];
var isPreviewing = viewMode === _markdown_modes.MODE_VIEWING;
var isEditing = viewMode === _markdown_modes.MODE_EDITING;
var replaceNode = (0, _react.useCallback)(function (position, next) {
var leading = value.substring(0, position.start.offset);
var trailing = value.substring(position.end.offset);
_onChange("".concat(leading).concat(next).concat(trailing));
}, [value, _onChange]);
var contextValue = (0, _react.useMemo)(function () {
return {
openPluginEditor: readOnly ? function () {} : function (plugin) {
return setPluginEditorPlugin(function () {
return plugin;
});
},
replaceNode: readOnly ? function () {} : replaceNode,
readOnly: readOnly
};
}, [replaceNode, readOnly]);
var _useState5 = (0, _react.useState)(),
_useState6 = (0, _slicedToArray2.default)(_useState5, 2),
selectedNode = _useState6[0],
setSelectedNode = _useState6[1];
var textareaRef = (0, _react.useRef)(null);
(0, _react.useEffect)(function () {
if (textareaRef == null) return;
if (parsed == null) return;
var getCursorNode = function getCursorNode() {
var _parsed$result;
var _ref3 = textareaRef.current,
selectionStart = _ref3.selectionStart;
var node = (_parsed$result = parsed.result) !== null && _parsed$result !== void 0 ? _parsed$result : parsed.contents;
outer: while (true) {
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
var child = node.children[i];
if (child.position && child.position.start.offset < selectionStart && selectionStart < child.position.end.offset) {
if (child.type === 'text') break outer; // don't dive into `text` nodes
node = child;
continue outer;
}
}
}
break;
}
setSelectedNode(node);
};
// `parsed` changed, which means the node at the cursor may be different
// e.g. from clicking a toolbar button
getCursorNode();
var textarea = textareaRef.current;
textarea.addEventListener('keyup', getCursorNode);
textarea.addEventListener('mouseup', getCursorNode);
return function () {
textarea.removeEventListener('keyup', getCursorNode);
textarea.removeEventListener('mouseup', getCursorNode);
};
}, [parsed]);
(0, _react.useEffect)(function () {
if (onParse) {
var _parsed$result2;
var messages = parsed ? parsed.messages : [];
var ast = parsed ? (_parsed$result2 = parsed.result) !== null && _parsed$result2 !== void 0 ? _parsed$result2 : parsed.contents : null;
onParse(parseError, {
messages: messages,
ast: ast
});
}
}, [onParse, parsed, parseError]);
(0, _react.useImperativeHandle)(ref, function () {
return {
textarea: textareaRef.current,
replaceNode: replaceNode
};
}, [replaceNode]);
var textarea = textareaRef.current;
var previewRef = (0, _react.useRef)(null);
var editorToolbarRef = (0, _react.useRef)(null);
var _React$useState = _react.default.useState(false),
_React$useState2 = (0, _slicedToArray2.default)(_React$useState, 2),
hasUnacceptedItems = _React$useState2[0],
setHasUnacceptedItems = _React$useState2[1];
var _useState7 = (0, _react.useState)(height),
_useState8 = (0, _slicedToArray2.default)(_useState7, 2),
currentHeight = _useState8[0],
setCurrentHeight = _useState8[1];
var _useState9 = (0, _react.useState)(0),
_useState10 = (0, _slicedToArray2.default)(_useState9, 2),
editorFooterHeight = _useState10[0],
setEditorFooterHeight = _useState10[1];
var _useState11 = (0, _react.useState)(0),
_useState12 = (0, _slicedToArray2.default)(_useState11, 2),
editorToolbarHeight = _useState12[0],
setEditorToolbarHeight = _useState12[1];
var styles = (0, _services.useEuiMemoizedStyles)(_markdown_editor.euiMarkdownEditorStyles);
var cssStyles = [styles.euiMarkdownEditor, height === 'full' && styles.fullHeight];
var classes = (0, _classnames.default)('euiMarkdownEditor', {
'euiMarkdownEditor-isPreviewing': isPreviewing
}, className);
var classesPreview = (0, _classnames.default)('euiMarkdownEditorPreview', {
'euiMarkdownEditorPreview-isReadOnly': readOnly
});
var onResize = function onResize() {
if (textarea && isEditing && height !== 'full') {
var resizedTextareaHeight = textarea.offsetHeight + editorFooterHeight;
setCurrentHeight(resizedTextareaHeight);
}
};
(0, _react.useEffect)(function () {
setEditorToolbarHeight(editorToolbarRef.current.offsetHeight);
}, [setEditorToolbarHeight]);
(0, _react.useEffect)(function () {
if (height === 'full' || currentHeight === 'full') return;
if (isPreviewing && autoExpandPreview && previewRef.current.scrollHeight > currentHeight) {
// scrollHeight does not include the border or margin
// so we ask for the computed value for those,
// which is always in pixels because getComputedValue
// returns the resolved values
var elementComputedStyle = window.getComputedStyle(previewRef.current);
var borderWidth = parseFloat(elementComputedStyle.borderTopWidth) + parseFloat(elementComputedStyle.borderBottomWidth);
var marginWidth = parseFloat(elementComputedStyle.marginTop) + parseFloat(elementComputedStyle.marginBottom);
// then add an extra pixel for safety and because the scrollHeight value is rounded
var extraHeight = borderWidth + marginWidth + 1;
setCurrentHeight(previewRef.current.scrollHeight + extraHeight);
}
}, [currentHeight, isPreviewing, height, autoExpandPreview]);
var previewHeight = height === 'full' ? "calc(100% - ".concat(editorFooterHeight, "px)") : currentHeight;
var textAreaHeight = height === 'full' ? '100%' : "calc(".concat(height - editorFooterHeight, "px)");
var textAreaMaxHeight = height !== 'full' ? "".concat(maxHeight - editorFooterHeight, "px") : '';
// safari needs this calc when the height is set to full
var editorToggleContainerHeight = "calc(100% - ".concat(editorToolbarHeight, "px)");
return (0, _react2.jsx)(_markdown_context.EuiMarkdownContext.Provider, {
value: contextValue
}, (0, _react2.jsx)("div", (0, _extends2.default)({
className: classes,
css: cssStyles
}, rest), (0, _react2.jsx)(_markdown_editor_toolbar.EuiMarkdownEditorToolbar, (0, _extends2.default)({
ref: editorToolbarRef,
selectedNode: selectedNode,
markdownActions: markdownActions,
onClickPreview: function onClickPreview() {
return setViewMode(isPreviewing ? _markdown_modes.MODE_EDITING : _markdown_modes.MODE_VIEWING);
},
viewMode: viewMode,
uiPlugins: toolbarPlugins
}, toolbarProps)), isPreviewing && (0, _react2.jsx)("div", {
ref: previewRef,
className: classesPreview,
css: styles.euiMarkdownEditorPreview,
style: {
height: previewHeight
}
}, (0, _react2.jsx)(_markdown_format.EuiMarkdownFormat, (0, _extends2.default)({
parsingPluginList: parsingPluginList,
processingPluginList: processingPluginList
}, markdownFormatProps), value)), (0, _react2.jsx)("div", {
className: "euiMarkdownEditor__toggleContainer",
style: {
height: editorToggleContainerHeight,
display: isPreviewing ? 'none' : undefined
}
}, (0, _react2.jsx)(_markdown_editor_drop_zone.EuiMarkdownEditorDropZone, {
setEditorFooterHeight: setEditorFooterHeight,
isEditing: isEditing,
dropHandlers: dropHandlers,
insertText: function insertText(text, config) {
if (config.block) {
text = padWithNewlinesIfNeeded(textareaRef.current, text);
}
var originalSelectionStart = textareaRef.current.selectionStart;
var newSelectionPoint = originalSelectionStart + text.length;
(0, _markdown_actions.insertText)(textareaRef.current, {
text: text,
selectionStart: newSelectionPoint,
selectionEnd: newSelectionPoint
});
},
showFooter: showFooter,
uiPlugins: toolbarPlugins,
errors: errors,
hasUnacceptedItems: hasUnacceptedItems,
setHasUnacceptedItems: setHasUnacceptedItems
}, (0, _react2.jsx)(_resize_observer.EuiResizeObserver, {
onResize: onResize
}, function (resizeRef) {
return (0, _react2.jsx)(_markdown_editor_text_area.EuiMarkdownEditorTextArea, {
height: textAreaHeight,
maxHeight: textAreaMaxHeight,
ref: mergeRefs(textareaRef, resizeRef),
id: editorId,
onChange: function onChange(e) {
return _onChange(e.target.value);
},
value: value,
onFocus: function onFocus() {
return setHasUnacceptedItems(false);
},
placeholder: placeholder,
readOnly: readOnly,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
'aria-describedby': ariaDescribedBy
});
})), pluginEditorPlugin && (0, _react2.jsx)(_modal.EuiModal, {
onClose: function onClose() {
return setPluginEditorPlugin(undefined);
}
}, /*#__PURE__*/(0, _react.createElement)(pluginEditorPlugin.editor, {
node: selectedNode && selectedNode.type === pluginEditorPlugin.name ? selectedNode : null,
onCancel: function onCancel() {
return setPluginEditorPlugin(undefined);
},
onSave: function onSave(markdown, config) {
if (selectedNode && selectedNode.type === pluginEditorPlugin.name && selectedNode.position) {
// modifying an existing node
textareaRef.current.setSelectionRange(selectedNode.position.start.offset, selectedNode.position.end.offset);
} else {
// creating a new node
if (config.block) {
// inject newlines if needed
markdown = padWithNewlinesIfNeeded(textareaRef.current, markdown);
}
}
(0, _markdown_actions.insertText)(textareaRef.current, {
text: markdown,
selectionStart: undefined,
selectionEnd: undefined
});
setPluginEditorPlugin(undefined);
}
})))));
});
EuiMarkdownEditor.displayName = 'EuiMarkdownEditor';