UNPKG

@yuebai008/cli

Version:

Command line interface for rapid qg-minigame development

1 lines 15.7 kB
import*as TextUtils from"../../models/text_utils/text_utils.js";import*as Common from"../common/common.js";import*as Host from"../host/host.js";import*as Platform from"../platform/platform.js";import{CSSFontFace}from"./CSSFontFace.js";import{CSSMatchedStyles}from"./CSSMatchedStyles.js";import{CSSMedia}from"./CSSMedia.js";import{CSSStyleRule}from"./CSSRule.js";import{CSSStyleDeclaration,Type}from"./CSSStyleDeclaration.js";import{CSSStyleSheetHeader}from"./CSSStyleSheetHeader.js";import{DOMModel}from"./DOMModel.js";import{Events as ResourceTreeModelEvents,ResourceTreeModel}from"./ResourceTreeModel.js";import{SDKModel}from"./SDKModel.js";import{SourceMapManager}from"./SourceMapManager.js";import{Capability}from"./Target.js";export class CSSModel extends SDKModel{agent;#e;#t;#s;#r;#a;#o;#n;#i;#l;#d;#c;#h;#S;#u;#y;#g;constructor(e){super(e),this.#u=!1,this.#d=null,this.#c=null,this.#e=e.model(DOMModel),this.#a=new SourceMapManager(e),this.agent=e.cssAgent(),this.#o=new ComputedStyleLoader(this),this.#r=e.model(ResourceTreeModel),this.#r&&this.#r.addEventListener(ResourceTreeModelEvents.PrimaryPageChanged,this.onPrimaryPageChanged,this),e.registerCSSDispatcher(new CSSDispatcher(this)),e.suspended()||this.enable(),this.#l=new Map,this.#i=new Map,this.#s=new Map,this.#y=!1,this.#t=new Map,this.#h=null,this.#S=!1,this.#g=!1,this.#n=new Common.Throttler.Throttler(StylePollingInterval),this.#a.setEnabled(Common.Settings.Settings.instance().moduleSetting("cssSourceMapsEnabled").get()),Common.Settings.Settings.instance().moduleSetting("cssSourceMapsEnabled").addChangeListener((e=>this.#a.setEnabled(e.data)))}headersForSourceURL(e){const t=[];for(const s of this.getStyleSheetIdsForURL(e)){const e=this.styleSheetHeaderForId(s);e&&t.push(e)}return t}createRawLocationsByURL(e,t,s=0){const r=this.headersForSourceURL(e);r.sort((function(e,t){return e.startLine-t.startLine||e.startColumn-t.startColumn||e.id.localeCompare(t.id)}));const a=Platform.ArrayUtilities.upperBound(r,void 0,((e,r)=>t-r.startLine||s-r.startColumn));if(!a)return[];const o=[],n=r[a-1];for(let e=a-1;e>=0&&r[e].startLine===n.startLine&&r[e].startColumn===n.startColumn;--e)r[e].containsLocation(t,s)&&o.push(new CSSLocation(r[e],t,s));return o}sourceMapManager(){return this.#a}static readableLayerName(e){return e||"<anonymous>"}static trimSourceURL(e){let t=e.lastIndexOf("/*# sourceURL=");if(-1===t&&(t=e.lastIndexOf("/*@ sourceURL="),-1===t))return e;const s=e.lastIndexOf("\n",t);if(-1===s)return e;const r=e.substr(s+1).split("\n",1)[0];return-1===r.search(/[\040\t]*\/\*[#@] sourceURL=[\040\t]*([^\s]*)[\040\t]*\*\/[\040\t]*$/)?e:e.substr(0,s)+e.substr(s+r.length+1)}domModel(){return this.#e}async setStyleText(e,t,s,r){try{await this.ensureOriginalStyleSheetText(e);const{styles:a}=await this.agent.invoke_setStyleTexts({edits:[{styleSheetId:e,range:t.serializeToObject(),text:s}]});if(!a||1!==a.length)return!1;this.#e.markUndoableState(!r);const o=new Edit(e,t,s,a[0]);return this.fireStyleSheetChanged(e,o),!0}catch(e){return!1}}async setSelectorText(e,t,s){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{selectorList:r}=await this.agent.invoke_setRuleSelector({styleSheetId:e,range:t,selector:s});if(!r)return!1;this.#e.markUndoableState();const a=new Edit(e,t,s,r);return this.fireStyleSheetChanged(e,a),!0}catch(e){return!1}}async setKeyframeKey(e,t,s){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{keyText:r}=await this.agent.invoke_setKeyframeKey({styleSheetId:e,range:t,keyText:s});if(!r)return!1;this.#e.markUndoableState();const a=new Edit(e,t,s,r);return this.fireStyleSheetChanged(e,a),!0}catch(e){return!1}}startCoverage(){return this.#y=!0,this.agent.invoke_startRuleUsageTracking()}async takeCoverageDelta(){const e=await this.agent.invoke_takeCoverageDelta();return{timestamp:e&&e.timestamp||0,coverage:e&&e.coverage||[]}}setLocalFontsEnabled(e){return this.agent.invoke_setLocalFontsEnabled({enabled:e})}async stopCoverage(){this.#y=!1,await this.agent.invoke_stopRuleUsageTracking()}async getMediaQueries(){const{medias:e}=await this.agent.invoke_getMediaQueries();return e?CSSMedia.parseMediaArrayPayload(this,e):[]}async getRootLayer(e){const{rootLayer:t}=await this.agent.invoke_getLayersForNode({nodeId:e});return t}isEnabled(){return this.#u}async enable(){await this.agent.invoke_enable(),this.#u=!0,this.#y&&await this.startCoverage(),this.dispatchEventToListeners(Events.ModelWasEnabled)}async getMatchedStyles(e){const t=await this.agent.invoke_getMatchedStylesForNode({nodeId:e});if(t.getError())return null;const s=this.#e.nodeForId(e);return s?new CSSMatchedStyles({cssModel:this,node:s,inlinePayload:t.inlineStyle||null,attributesPayload:t.attributesStyle||null,matchedPayload:t.matchedCSSRules||[],pseudoPayload:t.pseudoElements||[],inheritedPayload:t.inherited||[],inheritedPseudoPayload:t.inheritedPseudoElements||[],animationsPayload:t.cssKeyframesRules||[],parentLayoutNodeId:t.parentLayoutNodeId,positionFallbackRules:t.cssPositionFallbackRules||[],propertyRules:t.cssPropertyRules??[],cssPropertyRegistrations:t.cssPropertyRegistrations??[]}):null}async getClassNames(e){const{classNames:t}=await this.agent.invoke_collectClassNames({styleSheetId:e});return t||[]}async getComputedStyle(e){return this.isEnabled()||await this.enable(),this.#o.computedStylePromise(e)}async getBackgroundColors(e){const t=await this.agent.invoke_getBackgroundColors({nodeId:e});return t.getError()?null:{backgroundColors:t.backgroundColors||null,computedFontSize:t.computedFontSize||"",computedFontWeight:t.computedFontWeight||""}}async getPlatformFonts(e){const{fonts:t}=await this.agent.invoke_getPlatformFontsForNode({nodeId:e});return t}allStyleSheets(){const e=[...this.#l.values()];return e.sort((function(e,t){return e.sourceURL<t.sourceURL?-1:e.sourceURL>t.sourceURL?1:e.startLine-t.startLine||e.startColumn-t.startColumn})),e}async getInlineStyles(e){const t=await this.agent.invoke_getInlineStylesForNode({nodeId:e});if(t.getError()||!t.inlineStyle)return null;const s=new CSSStyleDeclaration(this,null,t.inlineStyle,Type.Inline),r=t.attributesStyle?new CSSStyleDeclaration(this,null,t.attributesStyle,Type.Attributes):null;return new InlineStyleResult(s,r)}forcePseudoState(e,t,s){const r=e.marker(PseudoStateMarker)||[],a=r.includes(t);if(s){if(a)return!1;r.push(t),e.setMarker(PseudoStateMarker,r)}else{if(!a)return!1;Platform.ArrayUtilities.removeElement(r,t),r.length?e.setMarker(PseudoStateMarker,r):e.setMarker(PseudoStateMarker,null)}return void 0!==e.id&&(this.agent.invoke_forcePseudoState({nodeId:e.id,forcedPseudoClasses:r}),this.dispatchEventToListeners(Events.PseudoStateForced,{node:e,pseudoClass:t,enable:s}),!0)}pseudoState(e){return e.marker(PseudoStateMarker)||[]}async setMediaText(e,t,s){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{media:r}=await this.agent.invoke_setMediaText({styleSheetId:e,range:t,text:s});if(!r)return!1;this.#e.markUndoableState();const a=new Edit(e,t,s,r);return this.fireStyleSheetChanged(e,a),!0}catch(e){return!1}}async setContainerQueryText(e,t,s){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{containerQuery:r}=await this.agent.invoke_setContainerQueryText({styleSheetId:e,range:t,text:s});if(!r)return!1;this.#e.markUndoableState();const a=new Edit(e,t,s,r);return this.fireStyleSheetChanged(e,a),!0}catch(e){return!1}}async setSupportsText(e,t,s){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{supports:r}=await this.agent.invoke_setSupportsText({styleSheetId:e,range:t,text:s});if(!r)return!1;this.#e.markUndoableState();const a=new Edit(e,t,s,r);return this.fireStyleSheetChanged(e,a),!0}catch(e){return!1}}async setScopeText(e,t,s){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleEdited);try{await this.ensureOriginalStyleSheetText(e);const{scope:r}=await this.agent.invoke_setScopeText({styleSheetId:e,range:t,text:s});if(!r)return!1;this.#e.markUndoableState();const a=new Edit(e,t,s,r);return this.fireStyleSheetChanged(e,a),!0}catch(e){return console.error(e),!1}}async addRule(e,t,s){try{await this.ensureOriginalStyleSheetText(e);const{rule:r}=await this.agent.invoke_addRule({styleSheetId:e,ruleText:t,location:s});if(!r)return null;this.#e.markUndoableState();const a=new Edit(e,s,t,r);return this.fireStyleSheetChanged(e,a),new CSSStyleRule(this,r)}catch(e){return null}}async requestViaInspectorStylesheet(e){const t=e.frameId()||(this.#r&&this.#r.mainFrame?this.#r.mainFrame.id:null),s=[...this.#l.values()].find((e=>e.frameId===t&&e.isViaInspector()));if(s)return s;if(!t)return null;try{const{styleSheetId:e}=await this.agent.invoke_createStyleSheet({frameId:t});return e&&this.#l.get(e)||null}catch(e){return null}}mediaQueryResultChanged(){this.dispatchEventToListeners(Events.MediaQueryResultChanged)}fontsUpdated(e){e&&this.#t.set(e.src,new CSSFontFace(e)),this.dispatchEventToListeners(Events.FontsUpdated)}fontFaces(){return[...this.#t.values()]}fontFaceForSource(e){return this.#t.get(e)}styleSheetHeaderForId(e){return this.#l.get(e)||null}styleSheetHeaders(){return[...this.#l.values()]}fireStyleSheetChanged(e,t){this.dispatchEventToListeners(Events.StyleSheetChanged,{styleSheetId:e,edit:t})}ensureOriginalStyleSheetText(e){const t=this.styleSheetHeaderForId(e);if(!t)return Promise.resolve(null);let s=this.#s.get(t);return s||(s=this.getStyleSheetText(t.id),this.#s.set(t,s),this.originalContentRequestedForTest(t)),s}originalContentRequestedForTest(e){}originalStyleSheetText(e){return this.ensureOriginalStyleSheetText(e.id)}getAllStyleSheetHeaders(){return this.#l.values()}styleSheetAdded(e){console.assert(!this.#l.get(e.styleSheetId)),e.loadingFailed&&(e.hasSourceURL=!1,e.isConstructed=!0,e.isInline=!1,e.isMutable=!1,e.sourceURL="",e.sourceMapURL=void 0);const t=new CSSStyleSheetHeader(this,e);this.#l.set(e.styleSheetId,t);const s=t.resourceURL();let r=this.#i.get(s);if(r||(r=new Map,this.#i.set(s,r)),r){let e=r.get(t.frameId);e||(e=new Set,r.set(t.frameId,e)),e.add(t.id)}this.#a.attachSourceMap(t,t.sourceURL,t.sourceMapURL),this.dispatchEventToListeners(Events.StyleSheetAdded,t)}styleSheetRemoved(e){const t=this.#l.get(e);if(console.assert(Boolean(t)),!t)return;this.#l.delete(e);const s=t.resourceURL(),r=this.#i.get(s);if(console.assert(Boolean(r),"No frameId to styleSheetId map is available for given style sheet URL."),r){const a=r.get(t.frameId);a&&(a.delete(e),a.size||(r.delete(t.frameId),r.size||this.#i.delete(s)))}this.#s.delete(t),this.#a.detachSourceMap(t),this.dispatchEventToListeners(Events.StyleSheetRemoved,t)}getStyleSheetIdsForURL(e){const t=this.#i.get(e);if(!t)return[];const s=[];for(const e of t.values())s.push(...e);return s}async setStyleSheetText(e,t,s){const r=this.#l.get(e);if(!r)return"Unknown stylesheet in CSS.setStyleSheetText";t=CSSModel.trimSourceURL(t),r.hasSourceURL&&(t+="\n/*# sourceURL="+r.sourceURL+" */"),await this.ensureOriginalStyleSheetText(e);const a=(await this.agent.invoke_setStyleSheetText({styleSheetId:r.id,text:t})).sourceMapURL;return this.#a.detachSourceMap(r),r.setSourceMapURL(a),this.#a.attachSourceMap(r,r.sourceURL,r.sourceMapURL),null===a?"Error in CSS.setStyleSheetText":(this.#e.markUndoableState(!s),this.fireStyleSheetChanged(e),null)}async getStyleSheetText(e){try{const{text:t}=await this.agent.invoke_getStyleSheetText({styleSheetId:e});return t&&CSSModel.trimSourceURL(t)}catch(e){return null}}async onPrimaryPageChanged(e){e.data.frame.backForwardCacheDetails.restoredFromCache?(await this.suspendModel(),await this.resumeModel()):(this.resetStyleSheets(),this.resetFontFaces())}resetStyleSheets(){const e=[...this.#l.values()];this.#i.clear(),this.#l.clear();for(const t of e)this.#a.detachSourceMap(t),this.dispatchEventToListeners(Events.StyleSheetRemoved,t)}resetFontFaces(){this.#t.clear()}async suspendModel(){this.#u=!1,await this.agent.invoke_disable(),this.resetStyleSheets(),this.resetFontFaces()}async resumeModel(){return this.enable()}setEffectivePropertyValueForNode(e,t,s){this.agent.invoke_setEffectivePropertyValueForNode({nodeId:e,propertyName:t,value:s})}cachedMatchedCascadeForNode(e){if(this.#d!==e&&this.discardCachedMatchedCascade(),this.#d=e,!this.#c){if(!e.id)return Promise.resolve(null);this.#c=this.getMatchedStyles(e.id)}return this.#c}discardCachedMatchedCascade(){this.#d=null,this.#c=null}createCSSPropertyTracker(e){return new CSSPropertyTracker(this,e)}enableCSSPropertyTracker(e){const t=e.getTrackedProperties();0!==t.length&&(this.agent.invoke_trackComputedStyleUpdates({propertiesToTrack:t}),this.#S=!0,this.#h=e,this.pollComputedStyleUpdates())}disableCSSPropertyTracker(){this.#S=!1,this.#h=null,this.agent.invoke_trackComputedStyleUpdates({propertiesToTrack:[]})}async pollComputedStyleUpdates(){if(!this.#g){if(this.#S){this.#g=!0;const e=await this.agent.invoke_takeComputedStyleUpdates();if(this.#g=!1,e.getError()||!e.nodeIds||!this.#S)return;this.#h&&this.#h.dispatchEventToListeners(CSSPropertyTrackerEvents.TrackedCSSPropertiesUpdated,e.nodeIds.map((e=>this.#e.nodeForId(e))))}this.#S&&this.#n.schedule(this.pollComputedStyleUpdates.bind(this))}}dispose(){this.disableCSSPropertyTracker(),super.dispose(),this.#a.dispose()}getAgent(){return this.agent}}export var Events;!function(e){e.FontsUpdated="FontsUpdated",e.MediaQueryResultChanged="MediaQueryResultChanged",e.ModelWasEnabled="ModelWasEnabled",e.PseudoStateForced="PseudoStateForced",e.StyleSheetAdded="StyleSheetAdded",e.StyleSheetChanged="StyleSheetChanged",e.StyleSheetRemoved="StyleSheetRemoved"}(Events||(Events={}));const PseudoStateMarker="pseudo-state-marker";export class Edit{styleSheetId;oldRange;newRange;newText;payload;constructor(e,t,s,r){this.styleSheetId=e,this.oldRange=t,this.newRange=TextUtils.TextRange.TextRange.fromEdit(t,s),this.newText=s,this.payload=r}}export class CSSLocation{#p;styleSheetId;url;lineNumber;columnNumber;constructor(e,t,s){this.#p=e.cssModel(),this.styleSheetId=e.id,this.url=e.resourceURL(),this.lineNumber=t,this.columnNumber=s||0}cssModel(){return this.#p}header(){return this.#p.styleSheetHeaderForId(this.styleSheetId)}}class CSSDispatcher{#m;constructor(e){this.#m=e}mediaQueryResultChanged(){this.#m.mediaQueryResultChanged()}fontsUpdated({font:e}){this.#m.fontsUpdated(e)}styleSheetChanged({styleSheetId:e}){this.#m.fireStyleSheetChanged(e)}styleSheetAdded({header:e}){this.#m.styleSheetAdded(e)}styleSheetRemoved({styleSheetId:e}){this.#m.styleSheetRemoved(e)}}class ComputedStyleLoader{#m;#M;constructor(e){this.#m=e,this.#M=new Map}computedStylePromise(e){let t=this.#M.get(e);return t||(t=this.#m.getAgent().invoke_getComputedStyleForNode({nodeId:e}).then((({computedStyle:t})=>{if(this.#M.delete(e),!t||!t.length)return null;const s=new Map;for(const e of t)s.set(e.name,e.value);return s})),this.#M.set(e,t),t)}}export class InlineStyleResult{inlineStyle;attributesStyle;constructor(e,t){this.inlineStyle=e,this.attributesStyle=t}}export class CSSPropertyTracker extends Common.ObjectWrapper.ObjectWrapper{#m;#T;constructor(e,t){super(),this.#m=e,this.#T=t}start(){this.#m.enableCSSPropertyTracker(this)}stop(){this.#m.disableCSSPropertyTracker()}getTrackedProperties(){return this.#T}}const StylePollingInterval=1e3;export var CSSPropertyTrackerEvents;!function(e){e.TrackedCSSPropertiesUpdated="TrackedCSSPropertiesUpdated"}(CSSPropertyTrackerEvents||(CSSPropertyTrackerEvents={})),SDKModel.register(CSSModel,{capabilities:Capability.DOM,autostart:!0});