@@ -3,9 +3,10 @@ import { HTMLParser } from '../utils/parser';
33import { writeFileSync } from 'fs' ;
44import { dirname , join } from 'path' ;
55import { StyleSheet } from 'windicss/utils/style' ;
6+ import { workspace } from 'vscode' ;
67import type { ExtensionContext } from 'vscode' ;
78import type { Core } from '../interfaces' ;
8- import { sortClassNames , toggleConfig } from '../utils' ;
9+ import { getConfig , sortClassNames , toggleConfig } from '../utils' ;
910
1011export function registerCommands ( ctx : ExtensionContext , core : Core ) : void {
1112 ctx . subscriptions . push (
@@ -49,25 +50,27 @@ export function registerCommands(ctx: ExtensionContext, core: Core): void {
4950 commands . registerTextEditorCommand ( 'windicss.sort' , ( textEditor , textEdit ) => {
5051 const text = textEditor . document . getText ( ) ;
5152 const parser = new HTMLParser ( text ) ;
52- const outputHTML : string [ ] = [ ] ;
53-
54- let indexStart = 0 ;
5553
5654 const classes = parser . parseClasses ( ) ;
5755 const variants = Object . keys ( core . processor ?. resolveVariants ( ) ?? { } ) ;
5856 const variantsMap = Object . assign ( { } , ...variants . map ( ( value , index ) => ( { [ value ] : index + 1 } ) ) ) ;
5957
6058 for ( const p of classes ) {
61- outputHTML . push ( text . substring ( indexStart , p . start ) ) ;
62- outputHTML . push ( sortClassNames ( p . result , variantsMap ) ) ;
63- indexStart = p . end ;
59+ const sortedP = sortClassNames ( p . result , variantsMap ) ;
60+ textEdit . replace ( new Range ( textEditor . document . positionAt ( p . start ) , textEditor . document . positionAt ( p . end ) ) , sortedP ) ;
6461 }
65- outputHTML . push ( text . substring ( indexStart ) ) ;
66-
67- textEdit . replace ( new Range ( new Position ( 0 , 0 ) , textEditor . document . lineAt ( textEditor . document . lineCount - 1 ) . range . end ) , outputHTML . join ( '' ) ) ;
6862 } )
6963 ) ;
7064
65+ // if runOnSave is enabled in settings, trigger command on file save
66+ if ( getConfig ( 'windicss.runOnSave' ) ) {
67+ ctx . subscriptions . push (
68+ workspace . onWillSaveTextDocument ( ( _e ) => {
69+ commands . executeCommand ( 'windicss.sort' ) ;
70+ } )
71+ ) ;
72+ }
73+
7174 ctx . subscriptions . push (
7275 commands . registerCommand ( 'windicss.toggle-folding' , ( ) => toggleConfig ( 'windicss.enableCodeFolding' ) )
7376 ) ;
@@ -99,4 +102,4 @@ export function registerCommands(ctx: ExtensionContext, core: Core): void {
99102 commands . executeCommand ( 'workbench.action.reloadWindow' ) ;
100103 } )
101104 ) ;
102- }
105+ }
0 commit comments