UNPKG

@patternfly/react-code-editor

Version:

This package provides a PatternFly wrapper for the Monaco code editor

273 lines • 19.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CodeEditor = exports.Language = void 0; const tslib_1 = require("tslib"); const jsx_runtime_1 = require("react/jsx-runtime"); const react_1 = require("react"); const react_styles_1 = require("@patternfly/react-styles"); const code_editor_1 = tslib_1.__importDefault(require("@patternfly/react-styles/css/components/CodeEditor/code-editor")); const file_upload_1 = tslib_1.__importDefault(require("@patternfly/react-styles/css/components/FileUpload/file-upload")); const t_global_font_family_mono_1 = tslib_1.__importDefault(require('@patternfly/react-tokens/dist/js/t_global_font_family_mono')); const Button_1 = require('@patternfly/react-core/dist/js/components/Button'); const EmptyState_1 = require('@patternfly/react-core/dist/js/components/EmptyState'); const Popover_1 = require('@patternfly/react-core/dist/js/components/Popover'); const resizeObserver_1 = require('@patternfly/react-core/dist/js/helpers/resizeObserver'); const react_2 = tslib_1.__importDefault(require("@monaco-editor/react")); const copy_icon_1 = tslib_1.__importDefault(require('@patternfly/react-icons/dist/js/icons/copy-icon')); const upload_icon_1 = tslib_1.__importDefault(require('@patternfly/react-icons/dist/js/icons/upload-icon')); const download_icon_1 = tslib_1.__importDefault(require('@patternfly/react-icons/dist/js/icons/download-icon')); const code_icon_1 = tslib_1.__importDefault(require('@patternfly/react-icons/dist/js/icons/code-icon')); const help_icon_1 = tslib_1.__importDefault(require('@patternfly/react-icons/dist/js/icons/help-icon')); const react_dropzone_1 = tslib_1.__importDefault(require("react-dropzone")); const CodeEditorUtils_1 = require("./CodeEditorUtils"); const CodeEditorControl_1 = require("./CodeEditorControl"); const CodeEditorTheme_1 = require("./CodeEditorTheme"); var Language; (function (Language) { Language["abap"] = "abap"; Language["aes"] = "aes"; Language["apex"] = "apex"; Language["azcli"] = "azcli"; Language["bat"] = "bat"; Language["bicep"] = "bicep"; Language["c"] = "c"; Language["cameligo"] = "cameligo"; Language["clojure"] = "clojure"; Language["coffeescript"] = "coffeescript"; Language["cpp"] = "cpp"; Language["csharp"] = "csharp"; Language["csp"] = "csp"; Language["css"] = "css"; Language["dart"] = "dart"; Language["dockerfile"] = "dockerfile"; Language["ecl"] = "ecl"; Language["elixir"] = "elixir"; Language["fsharp"] = "fsharp"; Language["go"] = "go"; Language["graphql"] = "graphql"; Language["handlebars"] = "handlebars"; Language["hcl"] = "hcl"; Language["html"] = "html"; Language["ini"] = "ini"; Language["java"] = "java"; Language["javascript"] = "javascript"; Language["json"] = "json"; Language["julia"] = "julia"; Language["kotlin"] = "kotlin"; Language["less"] = "less"; Language["lexon"] = "lexon"; Language["liquid"] = "liquid"; Language["lua"] = "lua"; Language["m3"] = "m3"; Language["markdown"] = "markdown"; Language["mips"] = "mips"; Language["msdax"] = "msdax"; Language["mysql"] = "mysql"; Language["objective-c"] = "objective-c"; Language["pascal"] = "pascal"; Language["pascaligo"] = "pascaligo"; Language["perl"] = "perl"; Language["pgsql"] = "pgsql"; Language["php"] = "php"; Language["plaintext"] = "plaintext"; Language["postiats"] = "postiats"; Language["powerquery"] = "powerquery"; Language["powershell"] = "powershell"; Language["pug"] = "pug"; Language["python"] = "python"; Language["r"] = "r"; Language["razor"] = "razor"; Language["redis"] = "redis"; Language["redshift"] = "redshift"; Language["restructuredtext"] = "restructuredtext"; Language["ruby"] = "ruby"; Language["rust"] = "rust"; Language["sb"] = "sb"; Language["scala"] = "scala"; Language["scheme"] = "scheme"; Language["scss"] = "scss"; Language["shell"] = "shell"; Language["sol"] = "sol"; Language["sql"] = "sql"; Language["st"] = "st"; Language["swift"] = "swift"; Language["systemverilog"] = "systemverilog"; Language["tcl"] = "tcl"; Language["twig"] = "twig"; Language["typescript"] = "typescript"; Language["vb"] = "vb"; Language["verilog"] = "verilog"; Language["xml"] = "xml"; Language["yaml"] = "yaml"; })(Language || (exports.Language = Language = {})); const getExtensionFromLanguage = (language) => { switch (language) { case Language.shell: return 'sh'; case Language.ruby: return 'rb'; case Language.perl: return 'pl'; case Language.python: return 'py'; case Language.mysql: return 'sql'; case Language.javascript: return 'js'; case Language.typescript: return 'ts'; case Language.markdown: return 'md'; case Language.plaintext: return 'txt'; default: return language.toString(); } }; /** * Downloads a file to a users device given its string content and a full file name. */ const defaultOnDownload = (value, fileName) => { const link = document.createElement('a'); link.href = URL.createObjectURL(new Blob([value], { type: 'text' })); link.download = fileName; link.click(); }; const CodeEditor = ({ className = '', code = '', copyButtonAriaLabel = 'Copy code to clipboard', copyButtonSuccessTooltipText = 'Content added to clipboard', copyButtonToolTipText = 'Copy to clipboard', customControls = null, downloadButtonAriaLabel = 'Download code', downloadButtonToolTipText = 'Download', downloadFileName = Date.now().toString(), editorProps, emptyState = '', emptyStateBody = 'Drag and drop a file or upload one.', emptyStateButton = 'Browse', emptyStateLink = 'Start from scratch', emptyStateTitle = 'Start editing', headerMainContent = '', height, isCopyEnabled = false, isDarkTheme = false, isDownloadEnabled = false, isFullHeight = false, isHeaderPlain = false, isLanguageLabelVisible = false, isLineNumbersVisible = true, isMinimapVisible = false, isReadOnly = false, isUploadEnabled = false, language = Language.plaintext, loading = '', onChange = () => { }, onCodeChange = () => { }, onDownload = defaultOnDownload, onEditorDidMount = () => { }, options = {}, overrideServices = {}, shortcutsPopoverButtonText = 'View Shortcuts', shortcutsPopoverProps = { bodyContent: '', 'aria-label': 'Keyboard Shortcuts' }, showEditor = true, toolTipCopyExitDelay = 1600, toolTipDelay = 300, toolTipMaxWidth = '100px', toolTipPosition = 'top', uploadButtonAriaLabel = 'Upload code', uploadButtonToolTipText = 'Upload', width = '' }) => { const [value, setValue] = (0, react_1.useState)(code); const [isLoading, setIsLoading] = (0, react_1.useState)(false); const [showEmptyState, setShowEmptyState] = (0, react_1.useState)(true); const [copied, setCopied] = (0, react_1.useState)(false); const editorRef = (0, react_1.useRef)(null); const wrapperRef = (0, react_1.useRef)(null); const ref = (0, react_1.useRef)(null); const observer = (0, react_1.useRef)(() => { }); const setHeightToFitContent = () => { var _a, _b, _c; const contentHeight = (_a = editorRef.current) === null || _a === void 0 ? void 0 : _a.getContentHeight(); const layoutInfo = (_b = editorRef.current) === null || _b === void 0 ? void 0 : _b.getLayoutInfo(); (_c = editorRef.current) === null || _c === void 0 ? void 0 : _c.layout({ width: layoutInfo.width, height: contentHeight }); }; const onModelChange = (value, event) => { if (height === 'sizeToFit') { setHeightToFitContent(); } if (onChange) { onChange(value, event); } setValue(value); onCodeChange(value); }; const handleResize = () => { if (editorRef.current) { editorRef.current.layout({ width: 0, height: 0 }); // ensures the editor won't take up more space than it needs editorRef.current.layout(); } }; const handleGlobalKeys = (event) => { var _a; if (wrapperRef.current === document.activeElement && (event.key === 'ArrowDown' || event.key === ' ')) { (_a = editorRef.current) === null || _a === void 0 ? void 0 : _a.focus(); event.preventDefault(); } }; // if the code changes due to the prop changing // set the value to the code prop (0, react_1.useEffect)(() => setValue(code), [code]); (0, react_1.useEffect)(() => { document.addEventListener('keydown', handleGlobalKeys); observer.current = (0, resizeObserver_1.getResizeObserver)(ref.current, handleResize, true); handleResize(); return () => { document.removeEventListener('keydown', handleGlobalKeys); observer.current(); }; }, []); const editorBeforeMount = (monaco) => { var _a; (0, CodeEditorTheme_1.defineThemes)(monaco.editor); (_a = editorProps === null || editorProps === void 0 ? void 0 : editorProps.beforeMount) === null || _a === void 0 ? void 0 : _a.call(editorProps, monaco); }; const editorDidMount = (editor, monaco) => { // eslint-disable-next-line no-bitwise editor.addCommand(monaco.KeyMod.Shift | monaco.KeyCode.Tab, () => wrapperRef.current.focus()); Array.from(document.getElementsByClassName('monaco-editor')).forEach((editorElement) => editorElement.removeAttribute('role')); onEditorDidMount(editor, monaco); editorRef.current = editor; if (height === 'sizeToFit') { setHeightToFitContent(); } }; const handleFileChange = (value) => { setValue(value); onCodeChange(value); }; const handleFileReadStarted = () => setIsLoading(true); const handleFileReadFinished = () => setIsLoading(false); const readFile = (fileHandle) => new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = () => reject(reader.error); reader.readAsText(fileHandle); }); const onDropAccepted = (acceptedFiles) => { if (acceptedFiles.length > 0) { const fileHandle = acceptedFiles[0]; handleFileChange(''); // Show the filename while reading handleFileReadStarted(); readFile(fileHandle) .then((data) => { handleFileReadFinished(); setShowEmptyState(false); handleFileChange(data); }) .catch((error) => { // eslint-disable-next-line no-console console.error('error', error); handleFileReadFinished(); handleFileChange(''); }); } }; const onDropRejected = (rejectedFiles) => { if (rejectedFiles.length > 0) { // eslint-disable-next-line no-console console.error('There was an error accepting that dropped file'); // TODO } }; const copyCode = () => { navigator.clipboard.writeText(value); setCopied(true); }; const editorOptions = Object.assign({ fontFamily: t_global_font_family_mono_1.default.var, scrollBeyondLastLine: height !== 'sizeToFit', readOnly: isReadOnly, cursorStyle: 'line', lineNumbers: isLineNumbersVisible ? 'on' : 'off', tabIndex: -1, minimap: { enabled: isMinimapVisible } }, options); const tooltipProps = { position: toolTipPosition, exitDelay: toolTipDelay, entryDelay: toolTipDelay, maxWidth: toolTipMaxWidth, trigger: 'mouseenter focus' }; const hasEditorHeaderContent = ((isCopyEnabled || isDownloadEnabled) && (!showEmptyState || !!value)) || isUploadEnabled || customControls || headerMainContent || !!shortcutsPopoverProps.bodyContent; return ((0, jsx_runtime_1.jsx)(react_dropzone_1.default, { multiple: false, onDropAccepted: onDropAccepted, onDropRejected: onDropRejected, children: ({ getRootProps, getInputProps, isDragActive, open }) => { const hiddenFileInput = (0, jsx_runtime_1.jsx)("input", Object.assign({}, getInputProps(), { hidden: true })); const editorEmptyState = emptyState || (isUploadEnabled ? ((0, jsx_runtime_1.jsxs)(EmptyState_1.EmptyState, { variant: EmptyState_1.EmptyStateVariant.sm, titleText: emptyStateTitle, icon: code_icon_1.default, headingLevel: "h4", children: [(0, jsx_runtime_1.jsx)(EmptyState_1.EmptyStateBody, { children: emptyStateBody }), !isReadOnly && ((0, jsx_runtime_1.jsxs)(EmptyState_1.EmptyStateFooter, { children: [(0, jsx_runtime_1.jsx)(EmptyState_1.EmptyStateActions, { children: (0, jsx_runtime_1.jsx)(Button_1.Button, { variant: "primary", onClick: open, children: emptyStateButton }) }), (0, jsx_runtime_1.jsx)(EmptyState_1.EmptyStateActions, { children: (0, jsx_runtime_1.jsx)(Button_1.Button, { variant: "link", onClick: () => setShowEmptyState(false), children: emptyStateLink }) })] }))] })) : ((0, jsx_runtime_1.jsx)(EmptyState_1.EmptyState, { variant: EmptyState_1.EmptyStateVariant.sm, titleText: emptyStateTitle, icon: code_icon_1.default, headingLevel: "h4", children: !isReadOnly && ((0, jsx_runtime_1.jsx)(EmptyState_1.EmptyStateFooter, { children: (0, jsx_runtime_1.jsx)(EmptyState_1.EmptyStateActions, { children: (0, jsx_runtime_1.jsx)(Button_1.Button, { variant: "primary", onClick: () => setShowEmptyState(false), children: emptyStateLink }) }) })) }))); const editorHeaderContent = ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("div", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorControls), children: (0, jsx_runtime_1.jsxs)(CodeEditorUtils_1.CodeEditorContext.Provider, { value: { code: value }, children: [isCopyEnabled && (!showEmptyState || !!value) && ((0, jsx_runtime_1.jsx)(CodeEditorControl_1.CodeEditorControl, { icon: (0, jsx_runtime_1.jsx)(copy_icon_1.default, {}), "aria-label": copyButtonAriaLabel, tooltipProps: Object.assign(Object.assign({}, tooltipProps), { 'aria-live': 'polite', content: (0, jsx_runtime_1.jsx)("div", { children: copied ? copyButtonSuccessTooltipText : copyButtonToolTipText }), exitDelay: copied ? toolTipCopyExitDelay : toolTipDelay, onTooltipHidden: () => setCopied(false) }), onClick: copyCode })), isUploadEnabled && ((0, jsx_runtime_1.jsx)(CodeEditorControl_1.CodeEditorControl, { icon: (0, jsx_runtime_1.jsx)(upload_icon_1.default, {}), "aria-label": uploadButtonAriaLabel, tooltipProps: Object.assign({ content: (0, jsx_runtime_1.jsx)("div", { children: uploadButtonToolTipText }) }, tooltipProps), onClick: open })), isDownloadEnabled && (!showEmptyState || !!value) && ((0, jsx_runtime_1.jsx)(CodeEditorControl_1.CodeEditorControl, { icon: (0, jsx_runtime_1.jsx)(download_icon_1.default, {}), "aria-label": downloadButtonAriaLabel, tooltipProps: Object.assign({ content: (0, jsx_runtime_1.jsx)("div", { children: downloadButtonToolTipText }) }, tooltipProps), onClick: () => { onDownload(value, `${downloadFileName}.${getExtensionFromLanguage(language)}`); } })), customControls && customControls] }) }), headerMainContent && (0, jsx_runtime_1.jsx)("div", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorHeaderMain), children: headerMainContent }), !!shortcutsPopoverProps.bodyContent && ((0, jsx_runtime_1.jsx)("div", { className: `${code_editor_1.default.codeEditor}__keyboard-shortcuts`, children: (0, jsx_runtime_1.jsx)(Popover_1.Popover, Object.assign({}, shortcutsPopoverProps, { children: (0, jsx_runtime_1.jsx)(Button_1.Button, { variant: Button_1.ButtonVariant.link, icon: (0, jsx_runtime_1.jsx)(help_icon_1.default, {}), children: shortcutsPopoverButtonText }) })) }))] })); const editorHeader = ((0, jsx_runtime_1.jsxs)("div", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorHeader, isHeaderPlain && code_editor_1.default.modifiers.plain), children: [hasEditorHeaderContent && (0, jsx_runtime_1.jsx)("div", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorHeaderContent), children: editorHeaderContent }), isLanguageLabelVisible && ((0, jsx_runtime_1.jsxs)("div", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorTab), children: [(0, jsx_runtime_1.jsx)("span", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorTabIcon), children: (0, jsx_runtime_1.jsx)(code_icon_1.default, {}) }), (0, jsx_runtime_1.jsx)("span", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorTabText), children: language.toUpperCase() })] }))] })); const editor = ((0, jsx_runtime_1.jsx)("div", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorCode), ref: wrapperRef, tabIndex: 0, dir: "ltr", children: (0, jsx_runtime_1.jsx)(react_2.default, Object.assign({ height: height === '100%' ? undefined : height, width: width, language: language, value: value, options: editorOptions, overrideServices: overrideServices, onChange: onModelChange, onMount: editorDidMount, loading: loading, theme: isDarkTheme ? 'pf-v6-theme-dark' : 'pf-v6-theme-light' }, editorProps, { beforeMount: editorBeforeMount })) })); return ((0, jsx_runtime_1.jsx)("div", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditor, isReadOnly && code_editor_1.default.modifiers.readOnly, (height === '100%' ? true : isFullHeight) && code_editor_1.default.modifiers.fullHeight, className), ref: ref, children: isUploadEnabled || emptyState ? ((0, jsx_runtime_1.jsxs)("div", Object.assign({}, getRootProps({ onClick: (event) => event.stopPropagation() // Prevents clicking TextArea from opening file dialog }), { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorContainer, isLoading && file_upload_1.default.modifiers.loading), children: [editorHeader, (0, jsx_runtime_1.jsx)("div", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorMain, isDragActive && code_editor_1.default.modifiers.dragHover), children: (showEmptyState || emptyState) && !value ? ((0, jsx_runtime_1.jsxs)("div", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorUpload), children: [hiddenFileInput, editorEmptyState] })) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [hiddenFileInput, editor] })) })] }))) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [editorHeader, showEditor && ((0, jsx_runtime_1.jsxs)("div", { className: (0, react_styles_1.css)(code_editor_1.default.codeEditorMain), children: [hiddenFileInput, editor] }))] })) })); } })); }; exports.CodeEditor = CodeEditor; exports.CodeEditor.displayName = 'CodeEditor'; //# sourceMappingURL=CodeEditor.js.map