@@ -2,7 +2,10 @@ import PropTypes from 'prop-types';
22import React from 'react' ;
33import CodeMirror from 'codemirror' ;
44import emmet from '@emmetio/codemirror-plugin' ;
5- import beautifyJS from 'js-beautify' ;
5+ import prettier from 'prettier' ;
6+ import babelParser from 'prettier/parser-babel' ;
7+ import htmlParser from 'prettier/parser-html' ;
8+ import cssParser from 'prettier/parser-postcss' ;
69import { withTranslation } from 'react-i18next' ;
710import 'codemirror/mode/css/css' ;
811import 'codemirror/addon/selection/active-line' ;
@@ -59,14 +62,10 @@ import * as ConsoleActions from '../actions/console';
5962
6063emmet ( CodeMirror ) ;
6164
62- const beautifyCSS = beautifyJS . css ;
63- const beautifyHTML = beautifyJS . html ;
64-
6565window . JSHINT = JSHINT ;
6666window . CSSLint = CSSLint ;
6767window . HTMLHint = HTMLHint ;
6868
69- const IS_TAB_INDENT = false ;
7069const INDENTATION_AMOUNT = 2 ;
7170
7271class Editor extends React . Component {
@@ -335,31 +334,33 @@ class Editor extends React.Component {
335334 this . _cm . execCommand ( 'replace' ) ;
336335 }
337336
337+ prettierFormatWithCursor ( parser , plugins ) {
338+ try {
339+ const { formatted, cursorOffset } = prettier . formatWithCursor (
340+ this . _cm . doc . getValue ( ) ,
341+ {
342+ cursorOffset : this . _cm . doc . indexFromPos ( this . _cm . doc . getCursor ( ) ) ,
343+ parser,
344+ plugins
345+ }
346+ ) ;
347+ this . _cm . doc . setValue ( formatted ) ;
348+ this . _cm . focus ( ) ;
349+ this . _cm . doc . setCursor ( this . _cm . doc . posFromIndex ( cursorOffset ) ) ;
350+ } catch ( error ) {
351+ console . error ( error ) ;
352+ }
353+ }
354+
338355 tidyCode ( ) {
339- const beautifyOptions = {
340- indent_size : INDENTATION_AMOUNT ,
341- indent_with_tabs : IS_TAB_INDENT
342- } ;
343356 const mode = this . _cm . getOption ( 'mode' ) ;
344- const currentPosition = this . _cm . doc . getCursor ( ) ;
345357 if ( mode === 'javascript' ) {
346- this . _cm . doc . setValue (
347- beautifyJS ( this . _cm . doc . getValue ( ) , beautifyOptions )
348- ) ;
358+ this . prettierFormatWithCursor ( 'babel' , [ babelParser ] ) ;
349359 } else if ( mode === 'css' ) {
350- this . _cm . doc . setValue (
351- beautifyCSS ( this . _cm . doc . getValue ( ) , beautifyOptions )
352- ) ;
360+ this . prettierFormatWithCursor ( 'css' , [ cssParser ] ) ;
353361 } else if ( mode === 'htmlmixed' ) {
354- this . _cm . doc . setValue (
355- beautifyHTML ( this . _cm . doc . getValue ( ) , beautifyOptions )
356- ) ;
362+ this . prettierFormatWithCursor ( 'html' , [ htmlParser ] ) ;
357363 }
358- this . _cm . focus ( ) ;
359- this . _cm . doc . setCursor ( {
360- line : currentPosition . line ,
361- ch : currentPosition . ch + INDENTATION_AMOUNT
362- } ) ;
363364 }
364365
365366 initializeDocuments ( files ) {
0 commit comments