Skip to content

Commit

Permalink
Playground Format Command Fixes (#128)
Browse files Browse the repository at this point in the history
- Removes debounce flag in favor of using the latest format result
- Adds `.catch()` clause to prevent syntax errors from breaking
formatting
  • Loading branch information
osyrisrblx authored Mar 19, 2024
1 parent ee23c26 commit c7287c3
Showing 1 changed file with 22 additions and 21 deletions.
43 changes: 22 additions & 21 deletions src/components/Playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -252,32 +252,33 @@ export default () => {
const modelContentChangedConn = editor.onDidChangeModelContent(() => setInput(editor.getValue()));

// alt+shift+f to format
let debounce = false;
editor.addCommand(monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyF, async () => {
if (!debounce) {
debounce = true;
const formatResult = await prettier.formatWithCursor(model.getValue(), {
let lastFormatId = 0;
editor.addCommand(monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyF, () => {
const formatId = ++lastFormatId;
prettier
.formatWithCursor(model.getValue(), {
...PRETTIER_OPTIONS,
printWidth: Math.min(PRETTIER_MAX_PRINT_WIDTH, editor.getLayoutInfo().viewportColumn),
cursorOffset: model.getOffsetAt(editor.getPosition() || new monaco.Position(0, 0)),
rangeStart: undefined,
rangeEnd: undefined,
});

editor.pushUndoStop();
editor.executeEdits(
"prettier",
[
{
range: model.getFullModelRange(),
text: formatResult.formatted,
},
],
() => [monaco.Selection.fromPositions(model.getPositionAt(formatResult.cursorOffset))],
);
editor.pushUndoStop();
debounce = false;
}
})
.then(formatResult => {
if (formatId !== lastFormatId) return;
editor.pushUndoStop();
editor.executeEdits(
"prettier",
[
{
range: model.getFullModelRange(),
text: formatResult.formatted,
},
],
() => [monaco.Selection.fromPositions(model.getPositionAt(formatResult.cursorOffset))],
);
editor.pushUndoStop();
})
.catch(reason => console.warn(`Prettier failed: ${reason}`));
});

setInputModel(model);
Expand Down

0 comments on commit c7287c3

Please sign in to comment.