import*as Platform from"../platform/platform.js";import{createTokenizer}from"./FormatterWorker.js";export class CSSFormatter{constructor(t){this._builder=t,this._toOffset,this._fromOffset,this._lineEndings,this._lastLine=-1,this._state={eatWhitespace:void 0,seenProperty:void 0,inPropertyValue:void 0,afterClosingBrace:void 0}}format(t,e,i,s){this._lineEndings=e,this._fromOffset=i,this._toOffset=s,this._state={eatWhitespace:void 0,seenProperty:void 0,inPropertyValue:void 0,afterClosingBrace:void 0},this._lastLine=-1;const r=createTokenizer("text/css"),a=this._builder.setEnforceSpaceBetweenWords(!1);r(t.substring(this._fromOffset,this._toOffset),this._tokenCallback.bind(this)),this._builder.setEnforceSpaceBetweenWords(a)}_tokenCallback(t,e,i){i+=this._fromOffset;const s=Platform.ArrayUtilities.lowerBound(this._lineEndings,i,Platform.ArrayUtilities.DEFAULT_COMPARATOR);s!==this._lastLine&&(this._state.eatWhitespace=!0),e&&(/^(css-)?property/.test(e)||/^(css-)?variable-2/.test(e))&&!this._state.inPropertyValue&&(this._state.seenProperty=!0),this._lastLine=s;if(/^\s+$/.test(t))this._state.eatWhitespace||this._builder.addSoftSpace();else if(this._state.eatWhitespace=!1,"\n"!==t){if("}"!==t&&(this._state.afterClosingBrace&&this._builder.addNewLine(!0),this._state.afterClosingBrace=!1),"}"===t)this._state.inPropertyValue&&this._builder.addNewLine(),this._builder.decreaseNestingLevel(),this._state.afterClosingBrace=!0,this._state.inPropertyValue=!1;else{if(":"===t&&!this._state.inPropertyValue&&this._state.seenProperty)return this._builder.addToken(t,i),this._builder.addSoftSpace(),this._state.eatWhitespace=!0,this._state.inPropertyValue=!0,void(this._state.seenProperty=!1);if("{"===t)return this._builder.addSoftSpace(),this._builder.addToken(t,i),this._builder.addNewLine(),void this._builder.increaseNestingLevel()}this._builder.addToken(t,i),"comment"!==e||this._state.inPropertyValue||this._state.seenProperty||this._builder.addNewLine(),";"===t&&this._state.inPropertyValue?(this._state.inPropertyValue=!1,this._builder.addNewLine()):"}"===t&&this._builder.addNewLine()}}}