UNPKG

wix-storybook-utils

Version:

Utilities for automated component documentation within Storybook

76 lines 2.88 kB
import React from 'react'; import debounce from 'lodash/debounce'; import { UnControlled as ReactCodeMirror } from 'react-codemirror2'; import 'codemirror/mode/jsx/jsx'; import 'codemirror/addon/edit/closetag'; import 'codemirror/addon/edit/closebrackets'; import 'codemirror/addon/hint/show-hint'; import 'codemirror/addon/hint/xml-hint'; import { formatCode } from './doctor-code'; import { completeAfter, completeIfInTag, completeIfInTagNewAttribute, handleIndentation, } from './autocomplete-utils'; import './styles.global.scss'; var autoCompleteHotkeysMap = { "'<'": completeAfter, 'Cmd-I': completeIfInTag, 'Ctrl-I': completeIfInTag, "'='": completeIfInTag, Space: completeIfInTagNewAttribute, Enter: completeIfInTagNewAttribute, Tab: handleIndentation, }; var Editor = function (_a) { var initialFormattedCode = _a.initialFormattedCode, hints = _a.hints, editorCodeUpdater = _a.editorCodeUpdater, onChange = _a.onChange; var editorDidMount = function (editor) { editor.setValue(initialFormattedCode); editorCodeUpdater(function (code) { return editor.setValue(code); }); }; var onCodeChange = function (_editor, _data, newCode) { onChange(newCode); }; var debouncedOnCodeChange = debounce(onCodeChange, 100, { trailing: true, }); var prettifyCode = function (editor) { try { var formattedValue = formatCode(editor.getValue()); editor.setValue(formattedValue); onChange(formattedValue); } catch (e) { console.error('Unable to prettify code', e); } }; var liveEditorOnKeyDown = function (editor, e) { var shouldPrettify = [ /* windows & unix: ctrl + s */ e.ctrlKey && e.key === 's', /* osx: command + s */ e.metaKey && e.key === 's', ].some(Boolean); if (shouldPrettify) { e.stopPropagation(); e.preventDefault(); var _a = editor.getCursor(), ch = _a.ch, line = _a.line; prettifyCode(editor); editor.setCursor({ ch: ch, line: line }); } }; return (React.createElement(ReactCodeMirror, { onChange: debouncedOnCodeChange, editorDidMount: editorDidMount, onKeyDown: liveEditorOnKeyDown, options: { mode: 'jsx', autoCloseTags: true, autoCloseBrackets: true, theme: 'wsr', viewportMargin: 50, lineNumbers: true, /** * Need to cast the type here, because xml-hint * plugin enhances hintOptions parameter with additional properties */ hintOptions: { schemaInfo: hints, }, extraKeys: autoCompleteHotkeysMap, } })); }; export default Editor; //# sourceMappingURL=Editor.js.map