mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2026-09-20 18:52:58 +00:00
Merge branch 'master' of https://github.com/naturalcrit/homebrewery into add-settings-editor
This commit is contained in:
@@ -3,7 +3,60 @@ import { keymap } from '@codemirror/view';
|
||||
import { undo, redo, indentMore, indentLess, deleteLine } from '@codemirror/commands';
|
||||
import { EditorSelection } from '@codemirror/state';
|
||||
import { Prec } from '@codemirror/state';
|
||||
import * as prettier from 'prettier/standalone';
|
||||
import * as postcssPlugin from 'prettier/plugins/postcss';
|
||||
|
||||
export async function formatCSS(view) {
|
||||
try {
|
||||
const { from, to, empty } = view.state.selection.main;
|
||||
const fullDoc = view.state.doc.toString();
|
||||
const selection = view.state.doc.sliceString(from, to);
|
||||
const code = empty ? fullDoc : selection;
|
||||
|
||||
let formatted = await prettier.format(code, {
|
||||
parser: 'css',
|
||||
plugins: [postcssPlugin],
|
||||
|
||||
// formatting options
|
||||
tabWidth: 2,
|
||||
useTabs: false,
|
||||
printWidth: 100,
|
||||
singleQuote: false,
|
||||
trailingComma: 'all',
|
||||
bracketSpacing: true,
|
||||
endOfLine: 'lf'
|
||||
});
|
||||
|
||||
//format manually single declaration rules to span one line.
|
||||
//Prettier can't do it by default, this is crude but it works
|
||||
formatted = formatted.replace(
|
||||
/([^{]+)\{\s*\n\s*([^;\n]+:[^;\n]+;)\s*\n\s*\}(\s*)/g,
|
||||
(_, selector, decl, whitespace) =>
|
||||
`${selector} { ${decl.trim()} }${whitespace}`
|
||||
);
|
||||
if(formatted === code) return true;
|
||||
|
||||
const dom = view.dom;
|
||||
dom.classList.add('cm-flash');
|
||||
|
||||
setTimeout(()=>{
|
||||
dom.classList.remove('cm-flash');
|
||||
|
||||
view.dispatch({
|
||||
changes : {
|
||||
from : empty ? 0 : from,
|
||||
to : empty ? view.state.doc.length : to,
|
||||
insert : formatted
|
||||
}
|
||||
});
|
||||
|
||||
}, 500);
|
||||
} catch (err) {
|
||||
console.error('Error formatting css: ', err);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
const insertTab = (view)=>{
|
||||
// If any selection spans multiple lines, delegates to CodeMirror's indentMore
|
||||
// Otherwise inserts two spaces at each cursor/selection
|
||||
@@ -188,6 +241,11 @@ export const generalKeymap = Prec.high(keymap.of([
|
||||
{ key: 'Mod-d', run: deleteLine }, //annoyingly overrides "selectNextOccurrence" because users asked
|
||||
]));
|
||||
|
||||
export const cssKeymap = Prec.highest(keymap.of([
|
||||
{ key: 'Mod-Shift-f', run: formatCSS },
|
||||
{ key: 'Alt-Shift-f', run: formatCSS },
|
||||
]));
|
||||
|
||||
export const markdownKeymap = Prec.highest(keymap.of([
|
||||
|
||||
{ key: 'Mod-b', run: wrapSelection('**', '**') }, // makeBold
|
||||
|
||||
Reference in New Issue
Block a user