@@ -31,13 +31,14 @@ let uniqueDefinitions: CssClassDefinition[] = [];
3131const completionTriggerChars = [ '"' , "'" , " " , "." ] ;
3232
3333let caching = false ;
34+ let cacheRequested = false ;
3435
3536const htmlDisposables : Disposable [ ] = [ ] ;
3637const cssDisposables : Disposable [ ] = [ ] ;
3738const javaScriptDisposables : Disposable [ ] = [ ] ;
3839const emmetDisposables : Disposable [ ] = [ ] ;
3940
40- async function cache ( ) : Promise < void > {
41+ async function performCache ( ) : Promise < void > {
4142 try {
4243 notifier . notify ( "eye" , "Looking for CSS classes in the workspace..." ) ;
4344
@@ -93,6 +94,33 @@ async function cache(): Promise<void> {
9394 }
9495}
9596
97+ async function cache ( ) {
98+ if ( caching ) {
99+ // Let the running cache function redo.
100+ cacheRequested = true ;
101+ return ;
102+ }
103+
104+ while ( true ) {
105+ caching = true ;
106+ try {
107+ await performCache ( ) ;
108+ } finally {
109+ caching = false ;
110+ }
111+
112+ // If the function itself was called while performing the process above,
113+ // the result might be invalidated. Redo the process to refresh it.
114+ // This trick reduces works and prevents parallel execution.
115+ if ( cacheRequested ) {
116+ cacheRequested = false ;
117+ continue ;
118+ } else {
119+ return ;
120+ }
121+ }
122+ }
123+
96124const registerCompletionProvider = (
97125 languageSelector : string ,
98126 classMatchRegex : RegExp ,
@@ -225,19 +253,18 @@ export async function activate(context: ExtensionContext): Promise<void> {
225253 context . subscriptions . push ( ...disposables ) ;
226254
227255 context . subscriptions . push ( commands . registerCommand ( Command . Cache , async ( ) => {
228- if ( caching ) {
229- return ;
230- }
231-
232- caching = true ;
233256 try {
234257 await cache ( ) ;
235258 } catch ( err ) {
236259 const newErr = new VError ( err as any , "Failed to cache the CSS classes in the workspace" ) ;
237260 console . error ( newErr ) ;
238261 window . showErrorMessage ( newErr . message ) ;
239- } finally {
240- caching = false ;
262+ }
263+ } ) ) ;
264+
265+ context . subscriptions . push ( workspace . onDidSaveTextDocument ( textDocument => {
266+ if ( textDocument . languageId === "css" ) {
267+ commands . executeCommand ( Command . Cache ) ;
241268 }
242269 } ) ) ;
243270
@@ -249,15 +276,12 @@ export async function activate(context: ExtensionContext): Promise<void> {
249276 registerCSSProviders ( cssDisposables ) ;
250277 registerJavaScriptProviders ( javaScriptDisposables ) ;
251278
252- caching = true ;
253279 try {
254280 await cache ( ) ;
255281 } catch ( err ) {
256282 const newErr = new VError ( err as any , "Failed to cache the CSS classes in the workspace for the first time" ) ;
257283 console . error ( newErr ) ;
258284 window . showErrorMessage ( newErr . message ) ;
259- } finally {
260- caching = false ;
261285 }
262286}
263287
0 commit comments