UNPKG

@yuebai008/cli

Version:

Command line interface for rapid qg-minigame development

1 lines 45 kB
import*as Common from"../../core/common/common.js";import*as Host from"../../core/host/host.js";import*as i18n from"../../core/i18n/i18n.js";import*as Platform from"../../core/platform/platform.js";import{assertNotNullOrUndefined}from"../../core/platform/platform.js";import*as Root from"../../core/root/root.js";import*as SDK from"../../core/sdk/sdk.js";import*as Bindings from"../../models/bindings/bindings.js";import*as TextUtils from"../../models/text_utils/text_utils.js";import*as Workspace from"../../models/workspace/workspace.js";import*as WorkspaceDiff from"../../models/workspace_diff/workspace_diff.js";import{PanelUtils}from"../../panels/utils/utils.js";import*as DiffView from"../../ui/components/diff_view/diff_view.js";import*as IconButton from"../../ui/components/icon_button/icon_button.js";import*as InlineEditor from"../../ui/legacy/components/inline_editor/inline_editor.js";import*as Components from"../../ui/legacy/components/utils/utils.js";import*as UI from"../../ui/legacy/legacy.js";import*as ElementsComponents from"./components/components.js";import{ComputedStyleModel}from"./ComputedStyleModel.js";import{ElementsPanel}from"./ElementsPanel.js";import{ElementsSidebarPane}from"./ElementsSidebarPane.js";import{ImagePreviewPopover}from"./ImagePreviewPopover.js";import*as LayersWidget from"./LayersWidget.js";import{StyleEditorWidget}from"./StyleEditorWidget.js";import{BlankStylePropertiesSection,HighlightPseudoStylePropertiesSection,KeyframePropertiesSection,RegisteredPropertiesSection,StylePropertiesSection,TryRuleSection}from"./StylePropertiesSection.js";import{StylePropertyHighlighter}from"./StylePropertyHighlighter.js";import{activeHints}from"./StylePropertyTreeElement.js";import stylesSidebarPaneStyles from"./stylesSidebarPane.css.js";import{WebCustomData}from"./WebCustomData.js";const UIStrings={noMatchingSelectorOrStyle:"No matching selector or style",visibleSelectors:"{n, plural, =1 {# visible selector listed below} other {# visible selectors listed below}}",invalidPropertyValue:"Invalid property value",unknownPropertyName:"Unknown property name",filter:"Filter",filterStyles:"Filter Styles",pseudoSElement:"Pseudo ::{PH1} element",inheritedFroms:"Inherited from ",inheritedFromSPseudoOf:"Inherited from ::{PH1} pseudo of ",incrementdecrementWithMousewheelOne:"Increment/decrement with mousewheel or up/down keys. {PH1}: R ±1, Shift: G ±1, Alt: B ±1",incrementdecrementWithMousewheelHundred:"Increment/decrement with mousewheel or up/down keys. {PH1}: ±100, Shift: ±10, Alt: ±0.1",invalidString:"{PH1}, property name: {PH2}, property value: {PH3}",newStyleRule:"New Style Rule",cssPropertyName:"`CSS` property name: {PH1}",cssPropertyValue:"`CSS` property value: {PH1}",toggleRenderingEmulations:"Toggle common rendering emulations",automaticDarkMode:"Automatic dark mode",copyAllCSSChanges:"Copy CSS changes",copiedToClipboard:"Copied to clipboard",layer:"Layer",clickToRevealLayer:"Click to reveal layer in layer tree",specificity:"Specificity: {PH1}"},str_=i18n.i18n.registerUIStrings("panels/elements/StylesSidebarPane.ts",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_),FILTER_IDLE_PERIOD=500,MIN_FOLDED_SECTIONS_COUNT=5;export const REGISTERED_PROPERTY_SECTION_NAME="@property";const HIGHLIGHTABLE_PROPERTIES=[{mode:"padding",properties:["padding"]},{mode:"border",properties:["border"]},{mode:"margin",properties:["margin"]},{mode:"gap",properties:["gap","grid-gap"]},{mode:"column-gap",properties:["column-gap","grid-column-gap"]},{mode:"row-gap",properties:["row-gap","grid-row-gap"]},{mode:"grid-template-columns",properties:["grid-template-columns"]},{mode:"grid-template-rows",properties:["grid-template-rows"]},{mode:"grid-template-areas",properties:["grid-areas"]},{mode:"justify-content",properties:["justify-content"]},{mode:"align-content",properties:["align-content"]},{mode:"align-items",properties:["align-items"]},{mode:"flexibility",properties:["flex","flex-basis","flex-grow","flex-shrink"]}];let stylesSidebarPaneInstance;export class StylesSidebarPane extends(Common.ObjectWrapper.eventMixin(ElementsSidebarPane)){currentToolbarPane;animatedToolbarPane;pendingWidget;pendingWidgetToggle;toolbar;toolbarPaneElement;lastFilterChange;visibleSections;noMatchesElement;sectionsContainer;sectionByElement;swatchPopoverHelperInternal;linkifier;decorator;lastRevealedProperty;userOperation;isEditingStyle;filterRegexInternal;isActivePropertyHighlighted;initialUpdateCompleted;hasMatchedStyles;sectionBlocks;idleCallbackManager;needsForceUpdate;resizeThrottler;scrollerElement;boundOnScroll;imagePreviewPopover;#e;#t;#i;#n=new WeakMap;activeCSSAngle;#s=new Map;#o;#r;#a;static instance(e){return stylesSidebarPaneInstance&&!e?.forceNew||(stylesSidebarPaneInstance=new StylesSidebarPane),stylesSidebarPaneInstance}constructor(){super(!0),this.setMinimumSize(96,26),this.registerCSSFiles([stylesSidebarPaneStyles]),Common.Settings.Settings.instance().moduleSetting("colorFormat").addChangeListener(this.update.bind(this)),Common.Settings.Settings.instance().moduleSetting("textEditorIndent").addChangeListener(this.update.bind(this)),this.currentToolbarPane=null,this.animatedToolbarPane=null,this.pendingWidget=null,this.pendingWidgetToggle=null,this.toolbar=null,this.lastFilterChange=null,this.visibleSections=null,this.toolbarPaneElement=this.createStylesSidebarToolbar(),this.computedStyleModelInternal=new ComputedStyleModel,this.noMatchesElement=this.contentElement.createChild("div","gray-info-message hidden"),this.noMatchesElement.textContent=i18nString(UIStrings.noMatchingSelectorOrStyle),this.sectionsContainer=this.contentElement.createChild("div"),UI.ARIAUtils.markAsList(this.sectionsContainer),this.sectionsContainer.addEventListener("keydown",this.sectionsContainerKeyDown.bind(this),!1),this.sectionsContainer.addEventListener("focusin",this.sectionsContainerFocusChanged.bind(this),!1),this.sectionsContainer.addEventListener("focusout",this.sectionsContainerFocusChanged.bind(this),!1),this.sectionByElement=new WeakMap,this.swatchPopoverHelperInternal=new InlineEditor.SwatchPopoverHelper.SwatchPopoverHelper,this.swatchPopoverHelperInternal.addEventListener(InlineEditor.SwatchPopoverHelper.Events.WillShowPopover,this.hideAllPopovers,this),this.linkifier=new Components.Linkifier.Linkifier(MAX_LINK_LENGTH,!0),this.decorator=new StylePropertyHighlighter(this),this.lastRevealedProperty=null,this.userOperation=!1,this.isEditingStyle=!1,this.filterRegexInternal=null,this.isActivePropertyHighlighted=!1,this.initialUpdateCompleted=!1,this.hasMatchedStyles=!1,this.contentElement.classList.add("styles-pane"),this.sectionBlocks=[],this.idleCallbackManager=null,this.needsForceUpdate=!1,stylesSidebarPaneInstance=this,UI.Context.Context.instance().addFlavorChangeListener(SDK.DOMModel.DOMNode,this.forceUpdate,this),this.contentElement.addEventListener("copy",this.clipboardCopy.bind(this)),this.resizeThrottler=new Common.Throttler.Throttler(100),this.boundOnScroll=this.onScroll.bind(this),this.imagePreviewPopover=new ImagePreviewPopover(this.contentElement,(e=>{const t=e.composedPath()[0];return t instanceof Element?t:null}),(()=>this.node())),this.activeCSSAngle=null;const e=Common.Settings.Settings.instance().moduleSetting("showCSSPropertyDocumentationOnHover");e.addChangeListener((e=>{const t=Boolean(e.data)?1:2;Host.userMetrics.cssPropertyDocumentation(t)})),this.#t=new UI.PopoverHelper.PopoverHelper(this.contentElement,(t=>{const i=t.composedPath()[0],n=t.composedPath()[2];if(!(i&&i instanceof Element))return null;if(n instanceof Element&&n.matches(".hint")){const e=activeHints.get(n);if(e)return{box:i.boxInWindow(),show:async t=>{const i=new ElementsComponents.CSSHintDetailsView.CSSHintDetailsView(e);return t.contentElement.appendChild(i),!0}}}if(e.get()&&i.matches(".webkit-css-property")){this.#e||(this.#e=WebCustomData.create());const e=i.textContent,t=e&&this.#e.findCssProperty(e);if(t)return{box:i.boxInWindow(),show:async e=>{const i=new ElementsComponents.CSSPropertyDocsView.CSSPropertyDocsView(t);return e.contentElement.appendChild(i),Host.userMetrics.cssPropertyDocumentation(0),!0}}}if(i.matches(".simple-selector")){const e=StylePropertiesSection.getSpecificityStoredForNodeElement(i);return{box:i.boxInWindow(),show:async t=>{t.setIgnoreLeftMargin(!0);const i=document.createElement("span");return i.textContent=i18nString(UIStrings.specificity,{PH1:e?`(${e.a},${e.b},${e.c})`:"(?,?,?)"}),t.contentElement.appendChild(i),!0}}}return null})),this.#t.setDisableOnClick(!0),this.#t.setTimeout(300),this.#t.setHasPadding(!0),this.#i=new UI.PopoverHelper.PopoverHelper(this.contentElement,(e=>{for(let t=e.composedPath().length-1;t>=0;--t){const i=e.composedPath()[t],n=this.#n.get(i),s=n?n():void 0;if(s)return{box:i.boxInWindow(),show:async e=>(e.contentElement.appendChild(s),!0)}}return null})),this.#i.setDisableOnClick(!0),this.#i.setTimeout(500,200)}addPopover(e,t){this.#n.set(e,t)}onScroll(e){this.hideAllPopovers()}swatchPopoverHelper(){return this.swatchPopoverHelperInternal}setUserOperation(e){this.userOperation=e}createExclamationMark(e,t){const i=document.createElement("span",{is:"dt-icon-label"});let n;i.className="exclamation-mark",StylesSidebarPane.ignoreErrorsForProperty(e)||(i.data={iconName:"warning-filled",color:"var(--icon-warning)",width:"14px",height:"14px"}),"string"==typeof t?(UI.Tooltip.Tooltip.install(i,t),n=t):(n=SDK.CSSMetadata.cssMetadata().isCSSPropertyName(e.name)?i18nString(UIStrings.invalidPropertyValue):i18nString(UIStrings.unknownPropertyName),t?this.addPopover(i,(()=>t)):UI.Tooltip.Tooltip.install(i,n));const s=i18nString(UIStrings.invalidString,{PH1:n,PH2:e.name,PH3:e.value});return e.setDisplayedStringForInvalidProperty(s),i}static ignoreErrorsForProperty(e){function t(e){return!e.startsWith("-webkit-")&&/^[-_][\w\d]+-\w/.test(e)}const i=e.name.toLowerCase();if("_"===i.charAt(0))return!0;if("filter"===i)return!0;if(i.startsWith("scrollbar-"))return!0;if(t(i))return!0;const n=e.value.toLowerCase();return!!n.endsWith("\\9")||!!t(n)}static createPropertyFilterElement(e,t,i){const n=document.createElement("input");function s(){const e=n.value?new RegExp(Platform.StringUtilities.escapeForRegExp(n.value),"i"):null;i(e)}return n.type="search",n.classList.add("custom-search-input"),n.placeholder=e,n.addEventListener("input",s,!1),n.addEventListener("keydown",(function(e){const t=e;t.key===Platform.KeyboardUtilities.ESCAPE_KEY&&n.value&&(t.consume(!0),n.value="",s())}),!1),n}static formatLeadingProperties(e){const t=e.headerText(),i=Common.Settings.Settings.instance().moduleSetting("textEditorIndent").get(),n=e.style(),s=[];for(const e of n.leadingProperties())e.disabled?s.push(`${i}/* ${e.name}: ${e.value}; */`):s.push(`${i}${e.name}: ${e.value};`);const o=s.join("\n");return{allDeclarationText:o,ruleText:`${t} {\n${o}\n}`}}revealProperty(e){this.decorator.highlightProperty(e),this.lastRevealedProperty=e,this.update()}jumpToProperty(e,t,i){return this.decorator.findAndHighlightPropertyName(e,t,i)}jumpToSection(e,t){this.decorator.findAndHighlightSection(e,t)}jumpToSectionBlock(e){this.decorator.findAndHighlightSectionBlock(e)}forceUpdate(){this.needsForceUpdate=!0,this.swatchPopoverHelperInternal.hide(),this.#r?.abort(),this.resetCache(),this.update()}sectionsContainerKeyDown(e){const t=Platform.DOMUtilities.deepActiveElement(this.sectionsContainer.ownerDocument);if(!t)return;const i=this.sectionByElement.get(t);if(!i)return;let n=null,s=!1;switch(e.key){case"ArrowUp":case"ArrowLeft":n=i.previousSibling()||i.lastSibling(),s=!1;break;case"ArrowDown":case"ArrowRight":n=i.nextSibling()||i.firstSibling(),s=!0;break;case"Home":n=i.firstSibling(),s=!0;break;case"End":n=i.lastSibling(),s=!1}n&&this.filterRegexInternal&&(n=n.findCurrentOrNextVisible(s)),n&&(n.element.focus(),e.consume(!0))}sectionsContainerFocusChanged(){this.resetFocus()}resetFocus(){if(this.noMatchesElement.classList.contains("hidden")&&this.sectionBlocks[0]&&this.sectionBlocks[0].sections[0]){const e=this.sectionBlocks[0].sections[0].findCurrentOrNextVisible(!0);e&&(e.element.tabIndex=this.sectionsContainer.hasFocus()?-1:0)}}onAddButtonLongClick(e){const t=this.cssModel();if(!t)return;const i=t.styleSheetHeaders().filter((function(e){return!e.isViaInspector()&&!e.isInline&&Boolean(e.resourceURL())})),n=[];for(let e=0;e<i.length;++e){const t=i[e],s=this.createNewRuleInStyleSheet.bind(this,t);n.push({text:Bindings.ResourceUtils.displayNameForURL(t.resourceURL()),handler:s})}n.sort((function(e,t){return Platform.StringUtilities.naturalOrderComparator(e.text,t.text)}));const s=new UI.ContextMenu.ContextMenu(e);for(let e=0;e<n.length;++e){const t=n[e];s.defaultSection().appendItem(t.text,t.handler)}s.footerSection().appendItem("inspector-stylesheet",this.createNewRuleInViaInspectorStyleSheet.bind(this)),s.show()}onFilterChanged(e){this.lastFilterChange=Date.now(),this.filterRegexInternal=e,this.updateFilter(),this.resetFocus(),setTimeout((()=>{if(this.lastFilterChange){Date.now()-this.lastFilterChange<500||UI.ARIAUtils.alert(this.visibleSections?i18nString(UIStrings.visibleSelectors,{n:this.visibleSections}):i18nString(UIStrings.noMatchingSelectorOrStyle))}}),500)}refreshUpdate(e,t){if(t)for(const e of this.allSections())e instanceof BlankStylePropertiesSection&&e.isBlank||e.updateVarFunctions(t);if(this.isEditingStyle)return;const i=this.node();if(i){for(const t of this.allSections())t instanceof BlankStylePropertiesSection&&t.isBlank||t.update(t===e);this.filterRegexInternal&&this.updateFilter(),this.swatchPopoverHelper().reposition(),this.nodeStylesUpdatedForTest(i,!1)}}async doUpdate(){this.#r?.abort(),this.#r=new AbortController,await this.#l(this.#r.signal);const e=this?.contentElement?.enclosingNodeOrSelfWithClass("style-panes-wrapper")?.parentElement?.querySelectorAll(".style-panes-wrapper");if(e.length>0)for(const t of e)this.scrollerElement=t,this.scrollerElement.addEventListener("scroll",this.boundOnScroll,!1)}async#l(e){this.initialUpdateCompleted||window.setTimeout((()=>{e.aborted||this.initialUpdateCompleted||this.sectionsContainer.createChild("span","spinner")}),200);const t=await this.fetchMatchedCascade();if(e.aborted)return;const i=this.node()?.id,n=t?.getParentLayoutNodeId(),[s,o]=await Promise.all([this.fetchComputedStylesFor(i),this.fetchComputedStylesFor(n)]);e.aborted||(await this.innerRebuildUpdate(e,t,s,o),e.aborted||(this.initialUpdateCompleted||(this.initialUpdateCompleted=!0,this.appendToolbarItem(this.createRenderingShortcuts()),Root.Runtime.experiments.isEnabled(Root.Runtime.ExperimentName.STYLES_PANE_CSS_CHANGES)&&(this.#o=this.createCopyAllChangesButton(),this.appendToolbarItem(this.#o),this.#o.element.classList.add("hidden")),this.dispatchEventToListeners("InitialUpdateCompleted")),this.nodeStylesUpdatedForTest(this.node(),!0),this.dispatchEventToListeners("StylesUpdateCompleted",{hasMatchedStyles:this.hasMatchedStyles})))}async fetchComputedStylesFor(e){const t=this.node();return null===t||void 0===e?null:await t.domModel().cssModel().getComputedStyle(e)}onResize(){this.resizeThrottler.schedule(this.innerResize.bind(this))}innerResize(){const e=this.contentElement.getBoundingClientRect().width+"px";return this.allSections().forEach((t=>{t.propertiesTreeOutline.element.style.width=e})),this.hideAllPopovers(),Promise.resolve()}resetCache(){const e=this.cssModel();e&&e.discardCachedMatchedCascade()}fetchMatchedCascade(){const e=this.node();if(!e||!this.cssModel())return Promise.resolve(null);const t=this.cssModel();return t?t.cachedMatchedCascadeForNode(e).then(function(e){return e&&e.node()===this.node()?e:null}.bind(this)):Promise.resolve(null)}setEditingStyle(e,t){this.isEditingStyle!==e&&(this.contentElement.classList.toggle("is-editing-style",e),this.isEditingStyle=e,this.setActiveProperty(null))}setActiveProperty(e){if(this.isActivePropertyHighlighted&&SDK.OverlayModel.OverlayModel.hideDOMNodeHighlight(),this.isActivePropertyHighlighted=!1,!this.node())return;if(!e||e.overloaded()||e.inherited())return;const t=e.property.ownerStyle.parentRule,i=t instanceof SDK.CSSRule.CSSStyleRule?t.selectorText():void 0;for(const{properties:t,mode:n}of HIGHLIGHTABLE_PROPERTIES){if(!t.includes(e.name))continue;const s=this.node();if(s){s.domModel().overlayModel().highlightInOverlay({node:this.node(),selectorList:i},n),this.isActivePropertyHighlighted=!0;break}}}onCSSModelChanged(e){const t=e?.data&&"edit"in e.data?e.data.edit:null;if(t){for(const e of this.allSections())e.styleSheetEdited(t);this.refreshComputedStyles()}else this.userOperation||this.isEditingStyle?this.refreshComputedStyles():(this.resetCache(),this.update())}async refreshComputedStyles(){this.#a?.abort(),this.#r=new AbortController;const e=this.#r.signal,t=await this.fetchMatchedCascade(),i=this.node()?.id,n=t?.getParentLayoutNodeId(),[s,o]=await Promise.all([this.fetchComputedStylesFor(i),this.fetchComputedStylesFor(n)]);if(!e.aborted)for(const e of this.allSections())e.setComputedStyles(s),e.setParentsComputedStyles(o),e.updateAuthoringHint()}focusedSectionIndex(){let e=0;for(const t of this.sectionBlocks)for(const i of t.sections){if(i.element.hasFocus())return e;e++}return-1}continueEditingElement(e,t){const i=this.allSections()[e];if(i){const e=i.closestPropertyForEditing(t);if(!e)return void i.element.focus();e.startEditing()}}async innerRebuildUpdate(e,t,i,n){if(this.needsForceUpdate)this.needsForceUpdate=!1;else if(this.isEditingStyle||this.userOperation)return;const s=this.focusedSectionIndex();this.linkifier.reset();const o=this.sectionBlocks.map((e=>e.sections)).flat();this.sectionBlocks=[];const r=this.node();if(this.hasMatchedStyles=null!==t&&null!==r,!this.hasMatchedStyles)return this.sectionsContainer.removeChildren(),void this.noMatchesElement.classList.remove("hidden");const a=await this.rebuildSectionsForMatchedStyleRules(t,i,n);if(e.aborted)return;this.sectionBlocks=a;const l=this.sectionBlocks.map((e=>e.sections)).flat(),c=StyleEditorWidget.instance(),d=c.getSection();if(d){c.unbindContext();for(const[e,t]of o.entries())d===t&&e<l.length&&c.bindContext(this,l[e])}this.sectionsContainer.removeChildren();const h=document.createDocumentFragment();let p=0,u=null;for(const e of this.sectionBlocks){const t=e.titleElement();t&&h.appendChild(t);for(const t of e.sections)h.appendChild(t.element),p===s&&(u=t.element),p++}this.sectionsContainer.appendChild(h),u&&u.focus(),s>=p&&this.sectionBlocks[0].sections[0].element.focus(),this.sectionsContainerFocusChanged(),this.filterRegexInternal?this.updateFilter():this.noMatchesElement.classList.toggle("hidden",this.sectionBlocks.length>0),this.lastRevealedProperty&&(this.decorator.highlightProperty(this.lastRevealedProperty),this.lastRevealedProperty=null),this.swatchPopoverHelper().reposition(),Host.userMetrics.panelLoaded("elements","DevTools.Launch.Elements"),this.dispatchEventToListeners("StylesUpdateCompleted",{hasMatchedStyles:!1})}nodeStylesUpdatedForTest(e,t){}rebuildSectionsForMatchedStyleRulesForTest(e,t,i){return this.rebuildSectionsForMatchedStyleRules(e,t,i)}async rebuildSectionsForMatchedStyleRules(e,t,i){this.idleCallbackManager&&this.idleCallbackManager.discard(),this.idleCallbackManager=new IdleCallbackManager;const n=[new SectionBlock(null)];let s=0,o=null,r=null,a=!1;const l=e=>{const t=e.parentRule;if(t instanceof SDK.CSSRule.CSSStyleRule){const e=t.layers;if((e.length||r)&&r!==e){const i=SectionBlock.createLayerBlock(t);n.push(i),a=!0,r=e}}};LayersWidget.ButtonProvider.instance().item().setVisible(!1);const c=new Set;for(const r of e.nodeStyles()){if(Root.Runtime.experiments.isEnabled(Root.Runtime.ExperimentName.STYLES_PANE_CSS_CHANGES)&&r.parentRule){const e=r.parentRule.resourceURL();e&&!c.has(e)&&(await this.trackURLForChanges(e),c.add(e))}const a=e.isInherited(r)?e.nodeForStyle(r):null;if(a&&a!==o){o=a;const e=await SectionBlock.createInheritedNodeBlock(o);n.push(e)}l(r);const d=n[n.length-1];d&&this.idleCallbackManager.schedule((()=>{const n=new StylePropertiesSection(this,e,r,s,t,i);s++,d.sections.push(n)}))}const d=Array.from(e.customHighlightPseudoNames()).map((t=>({highlightName:t,pseudoType:"highlight",pseudoStyles:e.customHighlightPseudoStyles(t)}))),h=[...e.pseudoTypes()].map((t=>({highlightName:null,pseudoType:t,pseudoStyles:e.pseudoStyles(t)}))),p=d.concat(h).sort(((e,t)=>"before"===e.pseudoType&&"before"!==t.pseudoType?-1:"before"!==e.pseudoType&&"before"===t.pseudoType?1:e.pseudoType<t.pseudoType?-1:e.pseudoType>t.pseudoType?1:0));for(const a of p){o=null;for(let c=0;c<a.pseudoStyles.length;++c){const d=a.pseudoStyles[c],h=e.isInherited(d)?e.nodeForStyle(d):null;if(0===c||h!==o)if(r=null,h){const e=await SectionBlock.createInheritedPseudoTypeBlock(a.pseudoType,a.highlightName,h);n.push(e)}else{const e=SectionBlock.createPseudoTypeBlock(a.pseudoType,a.highlightName);n.push(e)}o=h,l(d);const p=n[n.length-1];this.idleCallbackManager.schedule((()=>{const n=new HighlightPseudoStylePropertiesSection(this,e,d,s,t,i);s++,p.sections.push(n)}))}}for(const t of e.keyframes()){const i=SectionBlock.createKeyframesBlock(t.name().text);for(const n of t.keyframes())this.idleCallbackManager.schedule((()=>{i.sections.push(new KeyframePropertiesSection(this,e,n.style,s)),s++}));n.push(i)}for(const o of e.positionFallbackRules()){const r=SectionBlock.createPositionFallbackBlock(o.name().text);for(const n of o.tryRules())this.idleCallbackManager.schedule((()=>{r.sections.push(new TryRuleSection(this,e,n.style,s,t,i)),s++}));n.push(r)}if(e.registeredProperties().length>0){const t=e.registeredProperties().length<=5,i=SectionBlock.createRegisteredPropertiesBlock(t);for(const n of e.registeredProperties())this.idleCallbackManager.schedule((()=>{i.sections.push(new RegisteredPropertiesSection(this,e,n.style(),s,n.propertyName(),t)),s++}));n.push(i)}return a?LayersWidget.ButtonProvider.instance().item().setVisible(!0):LayersWidget.LayersWidget.instance().isShowing()&&ElementsPanel.instance().showToolbarPane(null,LayersWidget.ButtonProvider.instance().item()),await this.idleCallbackManager.awaitDone(),n}async createNewRuleInViaInspectorStyleSheet(){const e=this.cssModel(),t=this.node();if(!e||!t)return;this.setUserOperation(!0);const i=await e.requestViaInspectorStylesheet(t);this.setUserOperation(!1),await this.createNewRuleInStyleSheet(i)}async createNewRuleInStyleSheet(e){if(!e)return;const t=((await e.requestContent()).content||"").split("\n"),i=TextUtils.TextRange.TextRange.createFromLocation(t.length-1,t[t.length-1].length);this.sectionBlocks&&this.sectionBlocks.length>0&&this.addBlankSection(this.sectionBlocks[0].sections[0],e.id,i)}addBlankSection(e,t,i){const n=this.node(),s=new BlankStylePropertiesSection(this,e.matchedStyles,n?n.simpleSelector():"",t,i,e.style(),0);this.sectionsContainer.insertBefore(s.element,e.element.nextSibling);for(const t of this.sectionBlocks){const i=t.sections.indexOf(e);-1!==i&&(t.sections.splice(i+1,0,s),s.startEditingSelector())}let o=0;for(const e of this.sectionBlocks)for(const t of e.sections)t.setSectionIdx(o),o++}removeSection(e){for(const t of this.sectionBlocks){const i=t.sections.indexOf(e);-1!==i&&(t.sections.splice(i,1),e.element.remove())}}filterRegex(){return this.filterRegexInternal}updateFilter(){let e=!1,t=0;for(const i of this.sectionBlocks)t+=i.updateFilter(),e=Boolean(t)||e;this.noMatchesElement.classList.toggle("hidden",Boolean(e)),this.visibleSections=t}willHide(){this.hideAllPopovers(),super.willHide()}hideAllPopovers(){this.swatchPopoverHelperInternal.hide(),this.imagePreviewPopover.hide(),this.activeCSSAngle&&(this.activeCSSAngle.minify(),this.activeCSSAngle=null),this.#t?.hidePopover(),this.#i?.hidePopover()}getSectionBlockByName(e){return this.sectionBlocks.find((t=>t.titleElement()?.textContent===e))}allSections(){let e=[];for(const t of this.sectionBlocks)e=e.concat(t.sections);return e}async trackURLForChanges(e){const t=this.#s.get(e);t&&WorkspaceDiff.WorkspaceDiff.workspaceDiff().unsubscribeFromDiffChange(t.uiSourceCode,t.diffChangeCallback);const i=Workspace.Workspace.WorkspaceImpl.instance().uiSourceCodeForURL(e);if(!i)return;const n=this.refreshChangedLines.bind(this,i);WorkspaceDiff.WorkspaceDiff.workspaceDiff().subscribeToDiffChange(i,n);const s={uiSourceCode:i,changedLines:new Set,diffChangeCallback:n};this.#s.set(e,s),await this.refreshChangedLines(s.uiSourceCode)}isPropertyChanged(e){const t=e.ownerStyle.parentRule?.resourceURL();if(!t)return!1;const i=this.#s.get(t);if(!i)return!1;const{changedLines:n,formattedCurrentMapping:s}=i,o=Bindings.CSSWorkspaceBinding.CSSWorkspaceBinding.instance().propertyUILocation(e,!0);if(!o)return!1;if(!s)return n.has(o.lineNumber+1);const r=s.originalToFormatted(o.lineNumber,o.columnNumber)[0];return n.has(r+1)}updateChangeStatus(){if(!this.#o)return;let e=!1;for(const t of this.#s.values())if(t.changedLines.size>0){e=!0;break}this.#o.element.classList.toggle("hidden",!e)}async refreshChangedLines(e){const t=this.#s.get(e.url());if(!t)return;const i=await WorkspaceDiff.WorkspaceDiff.workspaceDiff().requestDiff(e,{shouldFormatDiff:!0}),n=new Set;if(t.changedLines=n,!i)return;const{diff:s,formattedCurrentMapping:o}=i,{rows:r}=DiffView.DiffView.buildDiffRows(s);for(const e of r)"addition"===e.type&&n.add(e.currentLineNumber);t.formattedCurrentMapping=o}async getFormattedChanges(){let e="";for(const[t,{uiSourceCode:i}]of this.#s){const n=await WorkspaceDiff.WorkspaceDiff.workspaceDiff().requestDiff(i,{shouldFormatDiff:!0});if(!n||n?.diff.length<2)continue;const s=await PanelUtils.formatCSSChangesFromDiff(n.diff);s.length>0&&(e+=`/* ${escapeUrlAsCssComment(t)} */\n\n${s}\n\n`)}return e}clipboardCopy(e){Host.userMetrics.actionTaken(Host.UserMetrics.Action.StyleRuleCopied)}createStylesSidebarToolbar(){const e=this.contentElement.createChild("div","styles-sidebar-pane-toolbar-container"),t=e.createChild("div","hbox styles-sidebar-pane-toolbar"),i=t.createChild("div","styles-sidebar-pane-filter-box"),n=StylesSidebarPane.createPropertyFilterElement(i18nString(UIStrings.filter),t,this.onFilterChanged.bind(this));UI.ARIAUtils.setLabel(n,i18nString(UIStrings.filterStyles)),i.appendChild(n);const s=new UI.Toolbar.Toolbar("styles-pane-toolbar",t);s.makeToggledGray(),s.appendItemsAtLocation("styles-sidebarpane-toolbar"),this.toolbar=s;return e.createChild("div","styles-sidebar-toolbar-pane-container").createChild("div","styles-sidebar-toolbar-pane")}showToolbarPane(e,t){this.pendingWidgetToggle&&this.pendingWidgetToggle.setToggled(!1),this.pendingWidgetToggle=t,this.animatedToolbarPane?this.pendingWidget=e:this.startToolbarPaneAnimation(e),e&&t&&t.setToggled(!0)}appendToolbarItem(e){this.toolbar&&this.toolbar.appendToolbarItem(e)}startToolbarPaneAnimation(e){if(e===this.currentToolbarPane)return;if(e&&this.currentToolbarPane)return this.currentToolbarPane.detach(),e.show(this.toolbarPaneElement),this.currentToolbarPane=e,void this.currentToolbarPane.focus();this.animatedToolbarPane=e,this.currentToolbarPane?this.toolbarPaneElement.style.animationName="styles-element-state-pane-slideout":e&&(this.toolbarPaneElement.style.animationName="styles-element-state-pane-slidein"),e&&e.show(this.toolbarPaneElement);const t=function(){this.toolbarPaneElement.style.removeProperty("animation-name"),this.toolbarPaneElement.removeEventListener("animationend",t,!1),this.currentToolbarPane&&this.currentToolbarPane.detach();this.currentToolbarPane=this.animatedToolbarPane,this.currentToolbarPane&&this.currentToolbarPane.focus();this.animatedToolbarPane=null,this.pendingWidget&&(this.startToolbarPaneAnimation(this.pendingWidget),this.pendingWidget=null)}.bind(this);this.toolbarPaneElement.addEventListener("animationend",t,!1)}createRenderingShortcuts(){const e=Common.Settings.Settings.instance().moduleSetting("emulatedCSSMediaFeaturePrefersColorScheme"),t=Common.Settings.Settings.instance().moduleSetting("emulateAutoDarkMode"),i=(e,t)=>`${e?"✓ ":""}${t}`,n=new UI.Toolbar.ToolbarToggle(i18nString(UIStrings.toggleRenderingEmulations),"brush","brush-filled");return n.element.addEventListener("click",(s=>{const o=n.element.getBoundingClientRect(),r=new UI.ContextMenu.ContextMenu(s,{x:o.left,y:o.bottom}),a=e.get(),l="light"===a,c="dark"===a,d=t.get(),h=i(l,"prefers-color-scheme: light"),p=i(c,"prefers-color-scheme: dark"),u=i(d,i18nString(UIStrings.automaticDarkMode));r.defaultSection().appendItem(h,(()=>{t.set(!1),e.set(l?"":"light"),n.setToggled(Boolean(e.get()))})),r.defaultSection().appendItem(p,(()=>{t.set(!1),e.set(c?"":"dark"),n.setToggled(Boolean(e.get()))})),r.defaultSection().appendItem(u,(()=>{t.set(!d),n.setToggled(Boolean(e.get()))})),r.show(),s.stopPropagation()}),{capture:!0}),n}createCopyAllChangesButton(){const e=new UI.Toolbar.ToolbarButton(i18nString(UIStrings.copyAllCSSChanges),"copy");let t;return e.element.setAttribute("data-content",i18nString(UIStrings.copiedToClipboard)),e.addEventListener(UI.Toolbar.ToolbarButton.Events.Click,(async()=>{const i=await this.getFormattedChanges();Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(i),Host.userMetrics.styleTextCopied(Host.UserMetrics.StyleTextCopied.AllChangesViaStylesPane),t&&(clearTimeout(t),t=void 0),e.element.classList.add("copied-to-clipboard"),t=window.setTimeout((()=>{e.element.classList.remove("copied-to-clipboard"),t=void 0}),2e3)})),e}}const MAX_LINK_LENGTH=23;export class SectionBlock{titleElementInternal;sections;#c=!1;#d;constructor(e,t,i){this.titleElementInternal=e,this.sections=[],this.#c=i??!1,t&&e instanceof HTMLElement&&(this.#d=UI.Icon.Icon.create(this.#c?"triangle-down":"triangle-right","section-block-expand-icon"),e.classList.toggle("empty-section",!this.#c),UI.ARIAUtils.setExpanded(e,this.#c),e.appendChild(this.#d),e.tabIndex=-1,e.addEventListener("click",(()=>this.expand(!this.#c)),!1))}expand(e){this.titleElementInternal&&this.#d&&(this.titleElementInternal.classList.toggle("empty-section",!e),this.#d.setIconType(e?"triangle-down":"triangle-right"),UI.ARIAUtils.setExpanded(this.titleElementInternal,e),this.#c=e,this.sections.forEach((t=>t.element.classList.toggle("hidden",!e))))}static createPseudoTypeBlock(e,t){const i=document.createElement("div");i.className="sidebar-separator";const n=`${e}${t?`(${t})`:""}`;return i.textContent=i18nString(UIStrings.pseudoSElement,{PH1:n}),new SectionBlock(i)}static async createInheritedPseudoTypeBlock(e,t,i){const n=document.createElement("div");n.className="sidebar-separator";const s=`${e}${t?`(${t})`:""}`;UI.UIUtils.createTextChild(n,i18nString(UIStrings.inheritedFromSPseudoOf,{PH1:s}));const o=await Common.Linkifier.Linkifier.linkify(i,{preventKeyboardFocus:!0,tooltip:void 0});return n.appendChild(o),new SectionBlock(n)}static createRegisteredPropertiesBlock(e){const t=document.createElement("div"),i=new SectionBlock(t,!0,e);return t.className="sidebar-separator",t.appendChild(document.createTextNode("@property")),i}static createKeyframesBlock(e){const t=document.createElement("div");return t.className="sidebar-separator",t.textContent=`@keyframes ${e}`,new SectionBlock(t)}static createPositionFallbackBlock(e){const t=document.createElement("div");return t.className="sidebar-separator",t.textContent=`@position-fallback ${e}`,new SectionBlock(t)}static async createInheritedNodeBlock(e){const t=document.createElement("div");t.className="sidebar-separator",UI.UIUtils.createTextChild(t,i18nString(UIStrings.inheritedFroms));const i=await Common.Linkifier.Linkifier.linkify(e,{preventKeyboardFocus:!0,tooltip:void 0});return t.appendChild(i),new SectionBlock(t)}static createLayerBlock(e){const t=document.createElement("div");t.className="sidebar-separator layer-separator",UI.UIUtils.createTextChild(t.createChild("div"),i18nString(UIStrings.layer));const i=e.layers;if(!i.length&&"user-agent"===e.origin){const i="user-agent"===e.origin?" user agent stylesheet":" implicit outer layer";return UI.UIUtils.createTextChild(t.createChild("div"),i),new SectionBlock(t)}const n=t.createChild("button");n.className="link",n.title=i18nString(UIStrings.clickToRevealLayer);const s=i.map((e=>SDK.CSSModel.CSSModel.readableLayerName(e.text))).join(".");return n.textContent=s,n.onclick=()=>LayersWidget.LayersWidget.instance().revealLayer(s),new SectionBlock(t)}updateFilter(){let e=!1,t=0;for(const i of this.sections)t+=i.updateFilter()?1:0,e=i.updateFilter()||e;return this.titleElementInternal&&this.titleElementInternal.classList.toggle("hidden",!e),t}titleElement(){return this.titleElementInternal}}export class IdleCallbackManager{discarded;promises;queue;constructor(){this.discarded=!1,this.promises=[],this.queue=[]}discard(){this.discarded=!0}schedule(e){if(this.discarded)return;const t=new Promise(((t,i)=>{this.queue.push({fn:e,resolve:t,reject:i})}));this.promises.push(t),this.scheduleIdleCallback(100)}scheduleIdleCallback(e){window.requestIdleCallback((()=>{const e=this.queue.shift();assertNotNullOrUndefined(e);try{this.discarded||e.fn(),e.resolve()}catch(t){e.reject(t)}}),{timeout:e})}awaitDone(){return Promise.all(this.promises)}}export function quoteFamilyName(e){return`'${e.replaceAll("'","\\'")}'`}export class CSSPropertyPrompt extends UI.TextPrompt.TextPrompt{isColorAware;cssCompletions;selectedNodeComputedStyles;parentNodeComputedStyles;treeElement;isEditingName;cssVariables;constructor(e,t){super(),this.initialize(this.buildPropertyCompletions.bind(this),UI.UIUtils.StyleValueDelimiters);const i=SDK.CSSMetadata.cssMetadata();this.isColorAware=SDK.CSSMetadata.cssMetadata().isColorAwareProperty(e.property.name),this.cssCompletions=[];const n=e.node();if(t)this.cssCompletions=i.allProperties(),n&&!n.isSVGNode()&&(this.cssCompletions=this.cssCompletions.filter((e=>!i.isSVGProperty(e))));else if(this.cssCompletions=i.getPropertyValues(e.property.name),n&&i.isFontFamilyProperty(e.property.name)){const e=n.domModel().cssModel().fontFaces().map((e=>quoteFamilyName(e.getFontFamily())));this.cssCompletions.unshift(...e)}if(this.selectedNodeComputedStyles=null,this.parentNodeComputedStyles=null,this.treeElement=e,this.isEditingName=t,this.cssVariables=e.matchedStyles().availableCSSVariables(e.property.ownerStyle),this.cssVariables.length<1e3?this.cssVariables.sort(Platform.StringUtilities.naturalOrderComparator):this.cssVariables.sort(),!t&&(this.disableDefaultSuggestionForEmptyInput(),e&&e.valueElement)){const t=e.valueElement.textContent,i=Host.Platform.isMac()?"Cmd":"Ctrl";null!==t&&(t.match(/#[\da-f]{3,6}$/i)?this.setTitle(i18nString(UIStrings.incrementdecrementWithMousewheelOne,{PH1:i})):t.match(/\d+/)&&this.setTitle(i18nString(UIStrings.incrementdecrementWithMousewheelHundred,{PH1:i})))}}onKeyDown(e){const t=e;switch(t.key){case"ArrowUp":case"ArrowDown":case"PageUp":case"PageDown":if(!this.isSuggestBoxVisible()&&this.handleNameOrValueUpDown(t))return void t.preventDefault();break;case"Enter":if(t.shiftKey)return;return this.tabKeyPressed(),void t.preventDefault();case" ":if(this.isEditingName)return this.tabKeyPressed(),void t.preventDefault()}super.onKeyDown(t)}onMouseWheel(e){this.handleNameOrValueUpDown(e)?e.consume(!0):super.onMouseWheel(e)}tabKeyPressed(){return this.acceptAutoComplete(),!1}handleNameOrValueUpDown(e){return!(this.isEditingName||!this.treeElement.valueElement||!UI.UIUtils.handleElementValueModifications(e,this.treeElement.valueElement,function(e,t){this.treeElement.nameElement&&this.treeElement.valueElement&&this.treeElement.applyStyleText(this.treeElement.nameElement.textContent+": "+this.treeElement.valueElement.textContent,!1)}.bind(this),this.isValueSuggestion.bind(this),function(e,t,i){return 0===t||i.length||!SDK.CSSMetadata.cssMetadata().isLengthProperty(this.treeElement.property.name)||this.treeElement.property.value.toLowerCase().startsWith("calc(")||(i="px"),e+t+i}.bind(this)))}isValueSuggestion(e){return!!e&&(e=e.toLowerCase(),-1!==this.cssCompletions.indexOf(e)||e.startsWith("--"))}async buildPropertyCompletions(e,t,i){const n=t.toLowerCase(),s=!this.isEditingName&&e.trim().endsWith("var(");if(!t&&!i&&!s&&(this.isEditingName||e))return Promise.resolve([]);const o=[],r=[];s||(this.cssCompletions.forEach((e=>h.call(this,e,!1))),this.isEditingName&&SDK.CSSMetadata.cssMetadata().aliasesFor().forEach(((e,t)=>{if(0!==t.toLowerCase().indexOf(n))return;const i={text:t,priority:SDK.CSSMetadata.cssMetadata().propertyUsageWeight(t),isCSSVariableColor:!1},s={text:e,priority:SDK.CSSMetadata.cssMetadata().propertyUsageWeight(e),subtitle:`= ${t}`,isCSSVariableColor:!1};o.push(i,s)})));const a=this.treeElement.node();if(this.isEditingName&&a){SDK.CSSMetadata.cssMetadata().nameValuePresets(a.isSVGNode()).forEach((e=>h.call(this,e,!1,!0)))}(this.isEditingName||s)&&this.cssVariables.forEach((e=>h.call(this,e,!0)));const l=o.concat(r);!this.isEditingName&&!l.length&&t.length>1&&"!important".startsWith(n)&&l.push({text:"!important",title:void 0,subtitle:void 0,priority:void 0,isSecondary:void 0,subtitleRenderer:void 0,selectionRange:void 0,hideGhostText:void 0,iconElement:void 0});const c=t.replace("-","");if(c&&c===c.toUpperCase())for(let e=0;e<l.length;++e)l[e].text.startsWith("--")||(l[e].text=l[e].text.toUpperCase());for(const e of l){if(s){e.title=e.text,e.text+=")";continue}const t=SDK.CSSMetadata.cssMetadata().getValuePreset(this.treeElement.name,e.text);!this.isEditingName&&t&&(e.title=e.text,e.text=t.text,e.selectionRange={startColumn:t.startColumn,endColumn:t.endColumn})}const d=async()=>{if(!a||this.selectedNodeComputedStyles)return;this.selectedNodeComputedStyles=await a.domModel().cssModel().getComputedStyle(a.id);const e=a.parentNode;e&&(this.parentNodeComputedStyles=await e.domModel().cssModel().getComputedStyle(e.id))};for(const e of l){await d();const t=ElementsComponents.CSSPropertyIconResolver.findIcon(this.isEditingName?e.text:`${this.treeElement.property.name}: ${e.text}`,this.selectedNodeComputedStyles,this.parentNodeComputedStyles);if(!t)continue;const i=new IconButton.Icon.Icon,n="12.5px",s="12.5px";i.data={iconName:t.iconName,width:n,height:s,color:"black"},i.style.transform=`rotate(${t.rotate}deg) scale(${1.1*t.scaleX}, ${1.1*t.scaleY})`,i.style.maxHeight=s,i.style.maxWidth=n,e.iconElement=i}return this.isColorAware&&!this.isEditingName&&l.sort(((e,t)=>e.isCSSVariableColor&&t.isCSSVariableColor?0:e.isCSSVariableColor?-1:1)),Promise.resolve(l);function h(e,t,i){const s=e.toLowerCase().indexOf(n),a={text:e,title:void 0,subtitle:void 0,priority:void 0,isSecondary:void 0,subtitleRenderer:void 0,selectionRange:void 0,hideGhostText:void 0,iconElement:void 0,isCSSVariableColor:!1};if(t){const t=this.treeElement.matchedStyles().computeCSSVariable(this.treeElement.property.ownerStyle,e);if(t){const e=Common.Color.parse(t);e?(a.subtitleRenderer=p.bind(null,e),a.isCSSVariableColor=!0):a.subtitleRenderer=u.bind(null,t)}}i&&(a.hideGhostText=!0),0===s?(a.priority=this.isEditingName?SDK.CSSMetadata.cssMetadata().propertyUsageWeight(e):1,o.push(a)):s>-1&&r.push(a)}function p(e){const t=new InlineEditor.ColorSwatch.ColorSwatch;return t.renderColor(e),t.style.pointerEvents="none",t}function u(e){const t=document.createElement("span");return t.className="suggestion-subtitle",t.textContent=`${e}`,t.style.maxWidth="100px",t.title=`${e}`,t}}}export function unescapeCssString(e){return e.replace(/(?<!\\)\\(?:([a-fA-F0-9]{1,6})|(.))[\n\t\x20]?/gs,((e,t,i)=>{if(i)return i;const n=parseInt(t,16);return 55296<=n&&n<=57343||0===n||n>1114111?"�":String.fromCodePoint(n)}))}export function escapeUrlAsCssComment(e){const t=new URL(e);return t.search?`${t.origin}${t.pathname}${t.search.replaceAll("*/","*%2F")}${t.hash}`:t.toString()}export class StylesSidebarPropertyRenderer{rule;node;propertyName;propertyValue;colorHandler;colorMixHandler;bezierHandler;fontHandler;shadowHandler;gridHandler;varHandler;angleHandler;lengthHandler;animationNameHandler;animationHandler;positionFallbackHandler;constructor(e,t,i,n){this.rule=e,this.node=t,this.propertyName=i,this.propertyValue=n,this.colorHandler=null,this.colorMixHandler=null,this.bezierHandler=null,this.fontHandler=null,this.shadowHandler=null,this.gridHandler=null,this.varHandler=document.createTextNode.bind(document),this.animationNameHandler=null,this.angleHandler=null,this.lengthHandler=null,this.animationHandler=null,this.positionFallbackHandler=null}setColorHandler(e){this.colorHandler=e}setColorMixHandler(e){this.colorMixHandler=e}setBezierHandler(e){this.bezierHandler=e}setFontHandler(e){this.fontHandler=e}setShadowHandler(e){this.shadowHandler=e}setGridHandler(e){this.gridHandler=e}setVarHandler(e){this.varHandler=e}setAnimationNameHandler(e){this.animationNameHandler=e}setAnimationHandler(e){this.animationHandler=e}setAngleHandler(e){this.angleHandler=e}setLengthHandler(e){this.lengthHandler=e}setPositionFallbackHandler(e){this.positionFallbackHandler=e}renderName(){const e=document.createElement("span");return UI.ARIAUtils.setLabel(e,i18nString(UIStrings.cssPropertyName,{PH1:this.propertyName})),e.className="webkit-css-property",e.textContent=this.propertyName,e.normalize(),e}renderValue(){const e=document.createElement("span");if(UI.ARIAUtils.setLabel(e,i18nString(UIStrings.cssPropertyValue,{PH1:this.propertyValue})),e.className="value",!this.propertyValue)return e;const t=SDK.CSSMetadata.cssMetadata();if(this.shadowHandler&&t.isShadowProperty(this.propertyName)&&!SDK.CSSMetadata.VariableRegex.test(this.propertyValue))return e.appendChild(this.shadowHandler(this.propertyValue,this.propertyName)),e.normalize(),e;if(this.gridHandler&&t.isGridAreaDefiningProperty(this.propertyName))return e.appendChild(this.gridHandler(this.propertyValue,this.propertyName)),e.normalize(),e;if(this.animationHandler&&("animation"===this.propertyName||"-webkit-animation"===this.propertyName))return e.appendChild(this.animationHandler(this.propertyValue)),e.normalize(),e;t.isStringProperty(this.propertyName)&&UI.Tooltip.Tooltip.install(e,unescapeCssString(this.propertyValue));const i=[],n=[];this.colorMixHandler&&t.isColorAwareProperty(this.propertyName)&&(i.push(Common.Color.ColorMixRegex),n.push(this.colorMixHandler)),i.push(SDK.CSSMetadata.VariableRegex,SDK.CSSMetadata.URLRegex),n.push(this.varHandler,this.processURL.bind(this)),this.colorHandler&&t.isColorAwareProperty(this.propertyName)&&(i.push(Common.Color.Regex),n.push(this.colorHandler)),this.bezierHandler&&t.isBezierAwareProperty(this.propertyName)&&(i.push(UI.Geometry.CubicBezier.Regex),n.push(this.bezierHandler)),this.angleHandler&&t.isAngleAwareProperty(this.propertyName)&&(i.push(InlineEditor.CSSAngleUtils.CSSAngleRegex),n.push(this.angleHandler)),this.fontHandler&&t.isFontAwareProperty(this.propertyName)&&("font-family"===this.propertyName?i.push(InlineEditor.FontEditorUtils.FontFamilyRegex):i.push(InlineEditor.FontEditorUtils.FontPropertiesRegex),n.push(this.fontHandler)),Root.Runtime.experiments.isEnabled("cssTypeComponentLength")&&this.lengthHandler&&(i.push(InlineEditor.CSSLengthUtils.CSSLengthRegex),n.push(this.lengthHandler)),"animation-name"===this.propertyName&&(i.push(/^.*$/g),n.push(this.animationNameHandler)),this.positionFallbackHandler&&"position-fallback"===this.propertyName&&(i.push(/^.*$/g),n.push(this.positionFallbackHandler));const s=TextUtils.TextUtils.Utils.splitStringByRegexes(this.propertyValue,i);for(let t=0;t<s.length;t++){const i=s[t],o=-1===i.regexIndex?document.createTextNode.bind(document):n[i.regexIndex];o&&e.appendChild(o(i.value))}return e.normalize(),e}processURL(e){let t=e.substring(4,e.length-1).trim();(/^'.*'$/s.test(t)||/^".*"$/s.test(t))&&(t=Common.ParsedURL.ParsedURL.substring(t,1,t.length-1));const i=document.createDocumentFragment();UI.UIUtils.createTextChild(i,"url(");let n=null;this.rule&&this.rule.resourceURL()?n=Common.ParsedURL.ParsedURL.completeURL(this.rule.resourceURL(),t):this.node&&(n=this.node.resolveURL(t));const s=ImagePreviewPopover.setImageUrl(Components.Linkifier.Linkifier.linkifyURL(n||t,{text:t,preventClick:!1,bypassURLTrimming:!0,showColumnNumber:!1,inlineFrameIndex:0}),n||t);return i.appendChild(s),UI.UIUtils.createTextChild(i,")"),i}}let buttonProviderInstance;export class ButtonProvider{button;constructor(){this.button=new UI.Toolbar.ToolbarButton(i18nString(UIStrings.newStyleRule),"plus"),this.button.addEventListener(UI.Toolbar.ToolbarButton.Events.Click,this.clicked,this);const e=UI.Icon.Icon.create("triangle-bottom-right","long-click-glyph");function t(){let e=UI.Context.Context.instance().flavor(SDK.DOMModel.DOMNode);e=e?e.enclosingElementOrSelf():null,this.button.setEnabled(Boolean(e))}this.button.element.appendChild(e),new UI.UIUtils.LongClickController(this.button.element,this.longClicked.bind(this)),UI.Context.Context.instance().addFlavorChangeListener(SDK.DOMModel.DOMNode,t.bind(this)),t.call(this)}static instance(e={forceNew:null}){const{forceNew:t}=e;return buttonProviderInstance&&!t||(buttonProviderInstance=new ButtonProvider),buttonProviderInstance}clicked(){StylesSidebarPane.instance().createNewRuleInViaInspectorStyleSheet()}longClicked(e){StylesSidebarPane.instance().onAddButtonLongClick(e)}item(){return this.button}}