@@ -2,7 +2,10 @@ import PropTypes from 'prop-types';
2
2
import React from 'react' ;
3
3
import CodeMirror from 'codemirror' ;
4
4
import 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' ;
6
9
import { withTranslation } from 'react-i18next' ;
7
10
import 'codemirror/mode/css/css' ;
8
11
import 'codemirror/addon/selection/active-line' ;
@@ -59,14 +62,10 @@ import * as ConsoleActions from '../actions/console';
59
62
60
63
emmet ( CodeMirror ) ;
61
64
62
- const beautifyCSS = beautifyJS . css ;
63
- const beautifyHTML = beautifyJS . html ;
64
-
65
65
window . JSHINT = JSHINT ;
66
66
window . CSSLint = CSSLint ;
67
67
window . HTMLHint = HTMLHint ;
68
68
69
- const IS_TAB_INDENT = false ;
70
69
const INDENTATION_AMOUNT = 2 ;
71
70
72
71
class Editor extends React . Component {
@@ -335,31 +334,33 @@ class Editor extends React.Component {
335
334
this . _cm . execCommand ( 'replace' ) ;
336
335
}
337
336
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
+
338
355
tidyCode ( ) {
339
- const beautifyOptions = {
340
- indent_size : INDENTATION_AMOUNT ,
341
- indent_with_tabs : IS_TAB_INDENT
342
- } ;
343
356
const mode = this . _cm . getOption ( 'mode' ) ;
344
- const currentPosition = this . _cm . doc . getCursor ( ) ;
345
357
if ( mode === 'javascript' ) {
346
- this . _cm . doc . setValue (
347
- beautifyJS ( this . _cm . doc . getValue ( ) , beautifyOptions )
348
- ) ;
358
+ this . prettierFormatWithCursor ( 'babel' , [ babelParser ] ) ;
349
359
} else if ( mode === 'css' ) {
350
- this . _cm . doc . setValue (
351
- beautifyCSS ( this . _cm . doc . getValue ( ) , beautifyOptions )
352
- ) ;
360
+ this . prettierFormatWithCursor ( 'css' , [ cssParser ] ) ;
353
361
} else if ( mode === 'htmlmixed' ) {
354
- this . _cm . doc . setValue (
355
- beautifyHTML ( this . _cm . doc . getValue ( ) , beautifyOptions )
356
- ) ;
362
+ this . prettierFormatWithCursor ( 'html' , [ htmlParser ] ) ;
357
363
}
358
- this . _cm . focus ( ) ;
359
- this . _cm . doc . setCursor ( {
360
- line : currentPosition . line ,
361
- ch : currentPosition . ch + INDENTATION_AMOUNT
362
- } ) ;
363
364
}
364
365
365
366
initializeDocuments ( files ) {
0 commit comments