Skip to content

Commit 21ca03c

Browse files
authored
feat: format editor content on blur (#197)
1 parent 63c2940 commit 21ca03c

File tree

3 files changed

+35
-11
lines changed

3 files changed

+35
-11
lines changed

src/components/Editor.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { queries } from '@testing-library/dom';
1111

1212
import CodeMirror from 'codemirror';
1313
import debounce from 'lodash/debounce';
14+
import beautifier from '../lib/beautify';
1415

1516
const baseOptions = {
1617
autoCloseBrackets: true,
@@ -200,6 +201,17 @@ function Editor({ onLoad, onChange, mode, initialValue }) {
200201
}
201202
});
202203

204+
editor.current.on('blur', () => {
205+
let formattedText = editor.current.getValue();
206+
if (mode === 'htmlmixed') {
207+
formattedText = beautifier.beautifyHtml(editor.current.getValue());
208+
} else if (mode === 'javascript') {
209+
formattedText = beautifier.beautifyJs(editor.current.getValue());
210+
}
211+
editor.current.setValue(formattedText);
212+
onChange(formattedText);
213+
});
214+
203215
onLoad(editor.current);
204216
}, [editor.current, onChange]);
205217

src/lib/beautify.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import beautify from 'js-beautify';
2+
3+
const beautifyOptions = {
4+
indent_size: 2,
5+
wrap_line_length: 72,
6+
wrap_attributes: 'force-expand-multiline',
7+
};
8+
9+
function beautifyHtml(html) {
10+
return beautify.html(html, beautifyOptions);
11+
}
12+
13+
function beautifyJs(js) {
14+
return beautify.js(js, beautifyOptions);
15+
}
16+
17+
export default {
18+
beautifyHtml,
19+
beautifyJs,
20+
};

src/lib/state.js

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import {
44
} from 'lz-string';
55
import queryString from 'query-string';
66

7-
import beautify from 'js-beautify';
7+
import beautifier from '../lib/beautify';
88

99
function unindent(string) {
1010
return (string || '').replace(/[ \t]*[\n][ \t]*/g, '\n');
@@ -21,13 +21,11 @@ export function compress({ markup, query }) {
2121

2222
export function decompress({ markup, query }) {
2323
const result = {
24-
markup: beautify.html(
24+
markup: beautifier.beautifyHtml(
2525
decompressFromEncodedURIComponent(markup || ''),
26-
beautifyOptions,
2726
),
28-
query: beautify.js(
27+
query: beautifier.beautifyJs(
2928
decompressFromEncodedURIComponent(query || ''),
30-
beautifyOptions,
3129
),
3230
};
3331

@@ -46,12 +44,6 @@ function save({ markup, query }) {
4644
history.replaceState(null, '', window.location.pathname + '?' + search);
4745
}
4846

49-
const beautifyOptions = {
50-
indent_size: 2,
51-
wrap_line_length: 72,
52-
wrap_attributes: 'force-expand-multiline',
53-
};
54-
5547
function load() {
5648
const { hash, search } = window.location;
5749

0 commit comments

Comments
 (0)