forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
1 lines (1 loc) · 13.8 KB
/
main.js
File metadata and controls
1 lines (1 loc) · 13.8 KB
1
define(function(require,exports,module){var AppInit=brackets.getModule("utils/AppInit"),CodeHintManager=brackets.getModule("editor/CodeHintManager"),EditorManager=brackets.getModule("editor/EditorManager"),CSSUtils=brackets.getModule("language/CSSUtils"),PreferencesManager=brackets.getModule("preferences/PreferencesManager"),TokenUtils=brackets.getModule("utils/TokenUtils"),StringMatch=brackets.getModule("utils/StringMatch"),ColorUtils=brackets.getModule("utils/ColorUtils"),Strings=brackets.getModule("strings"),KeyEvent=brackets.getModule("utils/KeyEvent"),LiveDevelopment=brackets.getModule("LiveDevelopment/main"),Metrics=brackets.getModule("utils/Metrics"),CSSProperties=require("text!CSSProperties.json"),properties=JSON.parse(CSSProperties);const expandAbbr=Phoenix.libs.Emmet.expand;let enabled=!0;require("./css-lint");const BOOSTED_PROPERTIES=["display","position","margin","margin-bottom","margin-left","margin-right","margin-top","padding","padding-bottom","padding-left","padding-right","padding-top","width","height","background-color","background","color","font-size","font-family","text-align","line-height","border","border-radius","box-shadow","transition","animation","transform","overflow","cursor","z-index","flex","grid"],MAX_CSS_HINTS=50,cssWideKeywords=["initial","inherit","unset","var()","calc()"];let computedProperties,computedPropertyKeys;const mdnPropertiesUrls={};var lastContext;function CssPropHints(){this.primaryTriggerKeys="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-()",this.secondaryTriggerKeys=":",this.exclusion=null}function isAlphanumeric(char){return/^[a-z0-9-@$]$/i.test(char)}function isValidColor(text,colorMatch){const colorIndex=colorMatch.index,previousChar=0===colorIndex?"":text.charAt(colorIndex-1),endIndex=colorIndex+colorMatch[0].length,nextChar=endIndex===text.length?"":text.charAt(endIndex);return!isAlphanumeric(previousChar)&&!isAlphanumeric(nextChar)}function updateColorList(colorList,color,lineNumber){const existingColor=colorList.find(item=>item.color===color);existingColor?(existingColor.count++,existingColor.lines.includes(lineNumber)||existingColor.lines.push(lineNumber)):colorList.push({color:color,lines:[lineNumber],count:1})}function getAllColorsInFile(){const editor=EditorManager.getActiveEditor(),nLen=editor.lineCount(),colorList=[];for(let i=0;i<nLen;i++){const lineText=editor.getLine(i);if(!lineText||lineText.length>1e3)continue;const matches=[...lineText.matchAll(ColorUtils.COLOR_REGEX)];for(const match of matches)if(isValidColor(lineText,match)){const token=editor.getToken({line:i,ch:match.index});!token||token.state&&token.state.htmlState&&"style"!==token.state.htmlState.context.tagName||"comment"===token.type||updateColorList(colorList,match[0],i)}}return colorList}function vendorPrefixesAndGenericToEnd(hints){const nonDashHints=[],dashHints=[];return hints.forEach(hint=>{hint.label.startsWith("-")||cssWideKeywords.includes(hint.label)?dashHints.push(hint):nonDashHints.push(hint)}),nonDashHints.concat(dashHints)}function formatHints(hints,isColorSwatch){return(hints=vendorPrefixesAndGenericToEnd(hints)).length>MAX_CSS_HINTS&&(hints=hints.splice(0,MAX_CSS_HINTS)),hints.map(function(token){var $hintObj=$(`<span data-val='${token.label||token.value||token.text}'></span>`).addClass("brackets-css-hints brackets-hints");if(token.stringRanges?token.stringRanges.forEach(function(item){item.matched?$hintObj.append($("<span>").text(item.text).addClass("matched-hint")):$hintObj.append(item.text)}):$hintObj.text(token.label||token.value),isColorSwatch&&($hintObj=ColorUtils.formatColorHint($hintObj,token.color||token.label||token.value)),token.MDN_URL){const $mdn=$(`<a class="css-code-hint-info" style="text-decoration: none;"\n href="${token.MDN_URL}" title="${Strings.DOCS_MORE_LINK_MDN_TITLE}">\n <i class="fa-solid fa-circle-info"></i></a>`);$hintObj=$(`<span data-val='${token.label||token.value}'></span>`).append($hintObj).append($mdn)}return $hintObj.attr("data-val",token.value),$hintObj})}function uniqueMerge(arr1,arr2){return arr2.forEach(item=>{arr1.includes(item)||arr1.push(item)}),arr1}function _computeProperties(){const blacklistedValues={none:!0,auto:!0};computedProperties={};for(let propertyKey of Object.keys(properties)){const property=properties[propertyKey];if("color"!==property.type&&property.values&&property.values.length&&"font-family"!==propertyKey){computedProperties[propertyKey]=propertyKey;for(let value of property.values)blacklistedValues[value]||(computedProperties[`${propertyKey}: ${value};`]=propertyKey)}else computedProperties[propertyKey]=propertyKey}computedPropertyKeys=Object.keys(computedProperties)}function _isEmmetExpandable(needle,expandedAbbr){return needle+": ;"!==expandedAbbr}function _isEmmetAbbrNumeric(expandedAbbr){return null!==expandedAbbr.match(/\d/)&&!expandedAbbr.includes("#")&&!expandedAbbr.includes(",")}PreferencesManager.definePreference("codehint.CssPropHints","boolean",!0,{description:Strings.DESCRIPTION_CSS_PROP_HINTS}),CssPropHints.prototype.updateExclusion=function(propNameOnly){var textAfterCursor;this.exclusion&&this.info&&(this.info.context===CSSUtils.PROP_NAME?textAfterCursor=this.info.name.substr(this.info.offset):propNameOnly||this.info.context!==CSSUtils.PROP_VALUE||(textAfterCursor=this.info.value.substr(this.info.offset)),CodeHintManager.hasValidExclusion(this.exclusion,textAfterCursor)||(this.exclusion=null))},CssPropHints.prototype.hasHints=function(editor,implicitChar){this.editor=editor;var cursor=this.editor.getCursorPos();return lastContext=null,this.info=CSSUtils.getInfoAtPos(editor,cursor),(this.info.context===CSSUtils.PROP_NAME||this.info.context===CSSUtils.PROP_VALUE)&&(implicitChar?(this.updateExclusion(!1),this.info.context===CSSUtils.PROP_NAME&&(this.exclusion||1!==this.info.offset||implicitChar!==this.info.name[0]||(this.exclusion=this.info.name.substr(this.info.offset))),-1!==this.primaryTriggerKeys.indexOf(implicitChar)||-1!==this.secondaryTriggerKeys.indexOf(implicitChar)):(this.info.context===CSSUtils.PROP_NAME&&(0===this.info.offset?this.exclusion=this.info.name:this.updateExclusion(!0)),!0))},CssPropHints.prototype.getHints=function(implicitChar){this.cursor=this.editor.getCursorPos(),this.info=CSSUtils.getInfoAtPos(this.editor,this.cursor);let needle=this.info.name,valueNeedle="",context=this.info.context,valueArray,type,result,selectInitial=!1,previouslyUsedColors=[];if(this.updateExclusion(!0),context===CSSUtils.PROP_VALUE){if(selectInitial=!0,"("===implicitChar)return!0;if(lastContext===CSSUtils.PROP_NAME)return!0;if(lastContext=CSSUtils.PROP_VALUE,!properties[needle])return null;this.info.isNewItem||-1===this.info.index||(valueNeedle=(valueNeedle=this.info.values[this.info.index].trim()).substr(0,this.info.offset)),properties[needle].injectedCSSDefaults||(uniqueMerge(properties[needle].values,cssWideKeywords),properties[needle].injectedCSSDefaults=!0),valueArray=properties[needle].values;let isColorSwatch=!1;if("color"===(type=properties[needle].type)){isColorSwatch=!0;const colorList=getAllColorsInFile();(valueArray=(previouslyUsedColors=colorList.sort((a,b)=>b.count-a.count).map(item=>item.color)).concat(ColorUtils.COLOR_NAMES.map(function(color){return{text:color,color:color}}))).push("transparent","currentColor")}return valueArray=$.map(valueArray,function(pvalue){return pvalue.text||pvalue}),{hints:formatHints(result=StringMatch.codeHintsSort(valueNeedle,valueArray,{limit:MAX_CSS_HINTS,boostPrefixList:previouslyUsedColors,onlyContiguous:isColorSwatch}),isColorSwatch),match:null,selectInitial:selectInitial}}if(context===CSSUtils.PROP_NAME){if(-1===this.primaryTriggerKeys.indexOf(implicitChar)&&""===needle||(selectInitial=!0),lastContext===CSSUtils.PROP_VALUE)return null;lastContext=CSSUtils.PROP_NAME,needle=needle.substr(0,this.info.offset),computedProperties||_computeProperties(),result=StringMatch.codeHintsSort(needle,computedPropertyKeys,{limit:MAX_CSS_HINTS,boostPrefixList:BOOSTED_PROPERTIES});for(let resultItem of result){const propertyKey=computedPropertyKeys[resultItem.sourceIndex];properties[propertyKey]&&properties[propertyKey].MDN_URL&&(resultItem.MDN_URL=properties[propertyKey].MDN_URL,mdnPropertiesUrls[propertyKey]=resultItem.MDN_URL)}let pushedHints=formatHints(result);if(enabled&&needle&&!needle.includes("-"))try{let expandedAbbr=expandAbbr(needle,{syntax:"css",type:"stylesheet",maxRepeat:400});if(expandedAbbr&&_isEmmetExpandable(needle,expandedAbbr)){_isEmmetAbbrNumeric(expandedAbbr)||(expandedAbbr=expandedAbbr.split(":")[0]);const[token]=StringMatch.codeHintsSort(needle,[expandedAbbr]);let $icon=$('<a class="emmet-css-code-hint" style="text-decoration: none">Emmet</a>');mdnPropertiesUrls[expandedAbbr]&&($icon.attr("href",mdnPropertiesUrls[expandedAbbr]),$icon.attr("title",Strings.DOCS_MORE_LINK_MDN_TITLE));const $emmetHintObj=$("<span>").addClass("brackets-css-hints brackets-hints").attr("data-val",expandedAbbr).attr("data-isEmmet",!0).css("margin-right","48px");if(token.stringRanges?token.stringRanges.forEach(function(range){range.matched?$emmetHintObj.append($("<span>").text(range.text).addClass("matched-hint")):$emmetHintObj.append(range.text)}):$emmetHintObj.text(expandedAbbr),$emmetHintObj.append($icon),pushedHints){for(let i=0;i<pushedHints.length;i++)if(pushedHints[i][0].getAttribute("data-val")===expandedAbbr){pushedHints.splice(i,1);break}pushedHints.unshift($emmetHintObj)}else pushedHints=$emmetHintObj}}catch(e){}return{hints:pushedHints,match:null,selectInitial:selectInitial,handleWideResults:!1}}return null};const HISTORY_PREFIX="Live_hint_";let hintSessionId=0,isInLiveHighlightSession=!1;function preferenceChanged(){enabled=PreferencesManager.get("emmet")}CssPropHints.prototype.onClose=function(){isInLiveHighlightSession&&(this.editor.restoreHistoryPoint(`Live_hint_${hintSessionId}`),isInLiveHighlightSession=!1),hintSessionId++},CssPropHints.prototype.onHighlight=function($highlightedEl,_$descriptionElem,reason){if(!reason)return console.error("OnHighlight called without reason, should never happen!"),void hintSessionId++;const currentLivePreviewDetails=LiveDevelopment.getLivePreviewDetails();if(!currentLivePreviewDetails||!currentLivePreviewDetails.liveDocument)return;const currentlyEditedFile=this.editor.document.file.fullPath,livePreviewedFile=currentLivePreviewDetails.liveDocument.doc.file.fullPath;if(currentlyEditedFile!==livePreviewedFile){const isRelatedFile=currentLivePreviewDetails.liveDocument.isRelated&¤tLivePreviewDetails.liveDocument.isRelated(currentlyEditedFile);if(!isRelatedFile)return}if(reason.source===CodeHintManager.SELECTION_REASON.SESSION_START)return hintSessionId++,void this.editor.createHistoryRestorePoint(`Live_hint_${hintSessionId}`);if(reason.source!==CodeHintManager.SELECTION_REASON.KEYBOARD_NAV)return;const event=reason.event;if(event.keyCode!==KeyEvent.DOM_VK_UP&&event.keyCode!==KeyEvent.DOM_VK_DOWN&&event.keyCode!==KeyEvent.DOM_VK_PAGE_UP&&event.keyCode!==KeyEvent.DOM_VK_PAGE_DOWN)return;Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW,"cssHint","preview");const $hintItem=$highlightedEl.find(".brackets-css-hints"),highligtedValue=$highlightedEl.find(".brackets-css-hints").data("val");highligtedValue&&$hintItem.is(":visible")&&(isInLiveHighlightSession=!0,this.editor._dontDismissPopupOnScroll(),this.editor.restoreHistoryPoint(`Live_hint_${hintSessionId}`),this.insertHint($highlightedEl.find(".brackets-css-hints"),!0))},CssPropHints.prototype.insertHint=function(hint,isLiveHighlight){var offset=this.info.offset,cursor=this.editor.getCursorPos(),start={line:-1,ch:-1},end={line:-1,ch:-1},keepHints=!1,adjustCursor=!1,newCursor,ctx;if(hint.jquery&&(hint.data("isEmmet")&&Metrics.countEvent(Metrics.EVENT_TYPE.CODE_HINTS,"emmet","cssInsert"),hint=hint.data("val")+""),this.info.context!==CSSUtils.PROP_NAME&&this.info.context!==CSSUtils.PROP_VALUE)return!1;if(start.line=end.line=cursor.line,start.ch=cursor.ch-offset,this.info.context===CSSUtils.PROP_NAME){keepHints=!0;var textAfterCursor=this.info.name.substr(this.info.offset);0===this.info.name.length||CodeHintManager.hasValidExclusion(this.exclusion,textAfterCursor)?(hint+=": ",end.ch=start.ch,end.ch+=offset,this.exclusion&&(hint+=" ",adjustCursor=!0,newCursor={line:cursor.line,ch:start.ch+hint.length-1},this.exclusion=null)):(end.ch=start.ch+this.info.name.length,(ctx=TokenUtils.getInitialContext(this.editor._codeMirror,cursor)).token.string.length>0&&!/\S/.test(ctx.token.string)&&TokenUtils.moveNextToken(ctx),TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken,ctx)&&":"===ctx.token.string?(adjustCursor=!0,newCursor={line:cursor.line,ch:cursor.ch+(hint.length-this.info.name.length)},TokenUtils.moveNextToken(ctx)&&ctx.token.string.length>0&&!/\S/.test(ctx.token.string)&&(newCursor.ch+=ctx.token.string.length)):hint.endsWith(";")||(hint+=": "))}else{this.info.isNewItem||-1===this.info.index?end.ch=start.ch:end.ch=start.ch+this.info.values[this.info.index].length;var parenMatch=hint.match(/\(.*?\)/);parenMatch&&(hint.startsWith("rgb")||hint.startsWith("rgba")||hint.startsWith("hsl")||hint.startsWith("hsla")||(adjustCursor=!0,newCursor={line:cursor.line,ch:start.ch+parenMatch.index+1},keepHints=!0))}if(isLiveHighlight)return this.info.context===CSSUtils.PROP_VALUE||hint.endsWith(";")?(this.editor.hasSelection()||this.editor.setSelection(start,end),this.editor.replaceSelection(hint,"around","liveHints"),keepHints):keepHints;if(isInLiveHighlightSession&&(isInLiveHighlightSession=!1,hintSessionId++),this.editor.hasSelection())return this.editor.replaceSelection(hint,"end"),keepHints;this.editor._codeMirror.replaceRange(hint,start,end),adjustCursor&&this.editor.setCursorPos(newCursor);const cursorPos=this.editor.getCursorPos();return";"===this.editor.getCharacterAtPosition({line:cursorPos.line,ch:cursorPos.ch-1})&&(keepHints=!1),keepHints},AppInit.appReady(function(){var cssPropHints=new CssPropHints;CodeHintManager.registerHintProvider(cssPropHints,["css","scss","less"],1),PreferencesManager.on("change","emmet",preferenceChanged),preferenceChanged(),exports.cssPropHintProvider=cssPropHints})});