/* * GNU AGPL-3.0 License * * Copyright (c) 2021 - present core.ai . All rights reserved. * Original work Copyright (c) 2012 - 2021 Adobe Systems Incorporated. All rights reserved. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://opensource.org/licenses/AGPL-3.0. * */ // @INCLUDE_IN_API_DOCS define(function (require, exports, module) { var CodeMirror = require("thirdparty/CodeMirror/lib/codemirror"), TokenUtils = require("utils/TokenUtils"); // Constants /** * Key representing tag name * @type {string} */ const TAG_NAME = "tagName"; /** * Key representing closing tag * @type {string} */ const CLOSING_TAG = "closingTag"; /** * Key representing attribute name * @type {string} */ const ATTR_NAME = "attr.name"; /** * Key representing attribute value * @type {string} */ const ATTR_VALUE = "attr.value"; // Regular expression for token types with "tag" prefixed var tagPrefixedRegExp = /^tag/; /** * @private * Ensures that the attribute value retrieved is valid, especially when quotes * are unbalanced and extra 'non-attribute value' text might be included in the token. * * @param {{editor: CodeMirror, pos: {ch: number, line: number}, token: object}} context - * The context containing the editor instance, the cursor position, and token information. * @return {{val: string, offset: number}} - An object containing the valid attribute value * and the associated offset. */ function _extractAttrVal(ctx) { var attrValue = ctx.token.string, startChar = attrValue.charAt(0), endChar = attrValue.charAt(attrValue.length - 1), offset = TokenUtils.offsetInToken(ctx), foundEqualSign = false; //If this is a fully quoted value, return the whole //thing regardless of position if (attrValue.length > 1 && (startChar === "'" || startChar === '"') && endChar === startChar) { // Find an equal sign before the end quote. If found, // then the user may be entering an attribute value right before // another attribute and we're getting a false balanced string. // An example of this case is where the // cursor is right after the first double quote. foundEqualSign = (attrValue.match(/\=\s*['"]$/) !== null); if (!foundEqualSign) { //strip the quotes and return; attrValue = attrValue.substring(1, attrValue.length - 1); offset = offset - 1 > attrValue.length ? attrValue.length : offset - 1; return { val: attrValue, offset: offset, quoteChar: startChar, hasEndQuote: true }; } } if (foundEqualSign) { var spaceIndex = attrValue.indexOf(" "), bracketIndex = attrValue.indexOf(">"), upToIndex = (spaceIndex !== -1 && spaceIndex < bracketIndex) ? spaceIndex : bracketIndex; attrValue = attrValue.substring(0, (upToIndex > offset) ? upToIndex : offset); } else if (offset > 0 && (startChar === "'" || startChar === '"')) { //The att value is getting edit in progress. There is possible extra //stuff in this token state since the quote isn't closed, so we assume //the stuff from the quote to the current pos is definitely in the attribute //value. attrValue = attrValue.substring(0, offset); } //If the attrValue start with a quote, trim that now startChar = attrValue.charAt(0); if (startChar === "'" || startChar === '"') { attrValue = attrValue.substring(1); offset--; } else { startChar = ""; // Make attr value empty and set offset to zero if it has the ">" // which is the closing of the tag. if (endChar === ">") { attrValue = ""; offset = 0; } } return { val: attrValue, offset: offset, quoteChar: startChar, hasEndQuote: false }; } /** * @private * Retrieves the tag name based on the current state of the editor. * * @param {{editor: CodeMirror, pos: {ch: number, line: number}, token: object}} context - * The context containing the editor instance, the cursor position, and token information. * @return {string} - The tag name at the current cursor position. */ function _extractTagName(ctx) { var mode = ctx.editor.getMode(), innerModeData = CodeMirror.innerMode(mode, ctx.token.state); if (ctx.token.type === "tag bracket") { return innerModeData.state.tagName; } // If the ctx is inside the tag name of an end tag, innerModeData.state.tagName is // undefined. So return token string as the tag name. return innerModeData.state.tagName || ctx.token.string; } /** * Compiles a list of used attributes for a given tag. * * @param {CodeMirror} editor - An instance of a CodeMirror editor. * @param {{ch: number, line: number}} pos - The position in the CodeMirror editor, * specified by character and line numbers. * @return {Array.} - A list of the used attributes within the current tag. */ function getTagAttributes(editor, pos) { var attrs = [], backwardCtx = TokenUtils.getInitialContext(editor._codeMirror, pos), forwardCtx = $.extend({}, backwardCtx); if (editor.getModeForSelection() === "html") { if (backwardCtx.token && !tagPrefixedRegExp.test(backwardCtx.token.type)) { while (TokenUtils.movePrevToken(backwardCtx) && !tagPrefixedRegExp.test(backwardCtx.token.type)) { if (backwardCtx.token.type === "error" && backwardCtx.token.string.indexOf("<") === 0) { break; } if (backwardCtx.token.type === "attribute") { attrs.push(backwardCtx.token.string); } } while (TokenUtils.moveNextToken(forwardCtx) && !tagPrefixedRegExp.test(forwardCtx.token.type)) { if (forwardCtx.token.type === "attribute") { // If the current tag is not closed, codemirror may return the next opening // tag as an attribute. Stop the search loop in that case. if (forwardCtx.token.string.indexOf("<") === 0) { break; } attrs.push(forwardCtx.token.string); } else if (forwardCtx.token.type === "error") { if (forwardCtx.token.string.indexOf("<") === 0 || forwardCtx.token.string.indexOf(">") === 0) { break; } // If we type the first letter of the next attribute, it comes as an error // token. We need to double check for possible invalidated attributes. if (/\S/.test(forwardCtx.token.string) && forwardCtx.token.string.indexOf("\"") === -1 && forwardCtx.token.string.indexOf("'") === -1 && forwardCtx.token.string.indexOf("=") === -1) { attrs.push(forwardCtx.token.string); } } } } } return attrs; } /** * Creates a tagInfo object and assures all the values are entered or are empty strings * @param {string=} tokenType what is getting edited and should be hinted * @param {number=} offset where the cursor is for the part getting hinted * @param {string=} tagName The name of the tag * @param {string=} attrName The name of the attribute * @param {string=} attrValue The value of the attribute * @return {{tagName:string, * attr:{name:string, value:string, valueAssigned:boolean, quoteChar:string, hasEndQuote:boolean}, * position:{tokenType:string, offset:number} * }} * A tagInfo object with some context about the current tag hint. */ function createTagInfo(tokenType, offset, tagName, attrName, attrValue, valueAssigned, quoteChar, hasEndQuote) { return { tagName: tagName || "", attr: { name: attrName || "", value: attrValue || "", valueAssigned: valueAssigned || false, quoteChar: quoteChar || "", hasEndQuote: hasEndQuote || false }, position: { tokenType: tokenType || "", offset: offset || 0 } }; } /** * @private * Gets the tag information starting from the attribute value and moving backwards. * * @param {{editor: CodeMirror, pos: {ch: number, line: number}, token: object}} context - * The context containing the editor instance, the cursor position, and token information. * @return {string} - The tag information obtained from the context. */ function _getTagInfoStartingFromAttrValue(ctx) { // Assume we in the attr value // and validate that by going backwards var attrInfo = _extractAttrVal(ctx), attrVal = attrInfo.val, offset = attrInfo.offset, quoteChar = attrInfo.quoteChar, hasEndQuote = attrInfo.hasEndQuote, strLength = ctx.token.string.length; if ((ctx.token.type === "string" || ctx.token.type === "error") && ctx.pos.ch === ctx.token.end && strLength > 1) { var firstChar = ctx.token.string[0], lastChar = ctx.token.string[strLength - 1]; // We get here only when the cursor is immediately on the right of the end quote // of an attribute value. So we want to return an empty tag info so that the caller // can dismiss the code hint popup if it is still open. if (firstChar === lastChar && (firstChar === "'" || firstChar === "\"")) { return createTagInfo(); } } //Skip all the 'string' tokens backwards. Required to reach to the first line //of multiline HTML attribute value. while (TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctx)) { if (ctx.token.type !== "string") { break; } } //As we have skipped all the string tokens, make a forward navigation to move to the //first 'string token so that in next backward navigation we can find '='. TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctx); //Move to the prev token, and check if it's "=" if (!TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctx) || ctx.token.string !== "=") { return createTagInfo(); } //Move to the prev token, and check if it's an attribute if (!TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctx) || ctx.token.type !== "attribute") { return createTagInfo(); } var attrName = ctx.token.string; var tagName = _extractTagName(ctx); //We're good. return createTagInfo(ATTR_VALUE, offset, tagName, attrName, attrVal, true, quoteChar, hasEndQuote); } /** * @private * Gets the tag information starting from the attribute name and moving forwards. * * @param {{editor: CodeMirror, pos: {ch: number, line: number}, token: object}} context - * The context containing the editor instance, the cursor position, and token information. * @param {boolean} isPriorAttr - Indicates whether we're getting information for a prior attribute. * @return {string} - The tag information obtained from the context. */ function _getTagInfoStartingFromAttrName(ctx, isPriorAttr) { //Verify We're in the attribute name, move forward and try to extract the rest of //the info. If the user it typing the attr the rest might not be here if (isPriorAttr === false && ctx.token.type !== "attribute") { return createTagInfo(); } var tagName = _extractTagName(ctx); var attrName = ctx.token.string; var offset = TokenUtils.offsetInToken(ctx); if (!TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctx) || ctx.token.string !== "=") { // If we're checking for a prior attribute and the next token we get is a tag or an html comment or // an undefined token class, then we've already scanned past our original cursor location. // So just return an empty tag info. if (isPriorAttr && (!ctx.token.type || (ctx.token.type && ctx.token.type !== "attribute" && ctx.token.type.indexOf("error") === -1 && ctx.token.string.indexOf("<") !== -1))) { return createTagInfo(); } return createTagInfo(ATTR_NAME, offset, tagName, attrName); } if (!TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctx)) { return createTagInfo(ATTR_NAME, offset, tagName, attrName); } //this should be the attrvalue var attrInfo = _extractAttrVal(ctx), attrVal = attrInfo.val, quoteChar = attrInfo.quoteChar, hasEndQuote = attrInfo.hasEndQuote; return createTagInfo(ATTR_NAME, offset, tagName, attrName, attrVal, true, quoteChar, hasEndQuote); } /** * Figure out if we're in a tag, and if we are return info about it * An example token stream for this tag is * ```js * : * className:tag string:"" * ``` * @param {Editor} editor An instance of a Brackets editor * @param {{ch: number, line: number}} constPos A CM pos (likely from editor.getCursorPos()) * @param {isHtmlMode:boolean} let the module know we are in html mode * @return {{tagName:string, * attr:{name:string, value:string, valueAssigned:boolean, quoteChar:string, hasEndQuote:boolean}, * position:{tokenType:string, offset:number} * }} * A tagInfo object with some context about the current tag hint. */ function getTagInfo(editor, constPos, isHtmlMode) { // We're going to be changing pos a lot, but we don't want to mess up // the pos the caller passed in so we use extend to make a safe copy of it. var pos = $.extend({}, constPos), ctx = TokenUtils.getInitialContext(editor._codeMirror, pos), offset = TokenUtils.offsetInToken(ctx), tagInfo, tokenType; // Check if this is not known to be in html mode and inside a style block. if (!isHtmlMode && editor.getModeForSelection() !== "html") { return createTagInfo(); } // Check and see where we are in the tag if (ctx.token.string.length > 0 && !/\S/.test(ctx.token.string)) { // token at (i.e. before) pos is whitespace, so test token at next pos // // note: getTokenAt() does range checking for ch. If it detects that ch is past // EOL, it uses EOL, same token is returned, and the following condition fails, // so we don't need to worry about testPos being valid. var testPos = { ch: ctx.pos.ch + 1, line: ctx.pos.line }, testToken = editor._codeMirror.getTokenAt(testPos, true); if (testToken.string.length > 0 && /\S/.test(testToken.string) && testToken.string.charAt(0) !== ">") { // pos has whitespace before it and non-whitespace after it, so use token after ctx.token = testToken; // Check whether the token type is one of the types prefixed with "tag" // (e.g. "tag", "tag error", "tag brackets") if (tagPrefixedRegExp.test(ctx.token.type)) { // Check to see if the cursor is just before a "<" but not in any tag. if (ctx.token.string.charAt(0) === "<") { return createTagInfo(); } } else if (ctx.token.type === "attribute") { // Check to see if the user is going to add a new attr before an existing one return _getTagInfoStartingFromAttrName(ctx, false); } else if (ctx.token.string === "=") { // We're between a whitespace and "=", so return an empty tag info. return createTagInfo(); } } else { // We get here if ">" or white spaces after testPos. // Check if there is an equal sign after testPos by creating a new ctx // with the original pos. We can't use the current ctx since we need to // use it to scan backwards if we don't find an equal sign here. // Comment out this block to fix issue #1510. // if (testToken.string.length > 0 && testToken.string.charAt(0) !== ">") { // tempCtx = TokenUtils.getInitialContext(editor._codeMirror, pos); // if (TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, tempCtx) && tempCtx.token.string === "=") { // // Return an empty tag info since we're between an atribute name and the equal sign. // return createTagInfo(); // } // } // next, see what's before pos if (!TokenUtils.movePrevToken(ctx)) { return createTagInfo(); } if (ctx.token.type === "comment") { return createTagInfo(); } else if (!tagPrefixedRegExp.test(ctx.token.type) && ctx.token.string !== "=") { // If it wasn't the tag name, assume it was an attr value // Also we don't handle the "=" here. tagInfo = _getTagInfoStartingFromAttrValue(ctx); // Check to see if this is the closing of a tag (either the start or end) // or a comment tag. if (ctx.token.type === "comment" || (tagPrefixedRegExp.test(ctx.token.type) && (ctx.token.string === ">" || ctx.token.string === "/>" || ctx.token.string === "" || ctx.token.string === "/>") { return createTagInfo(); } // Make sure the cursor is not after an equal sign or a quote before we report the context as a tag. if (ctx.token.string !== "=" && ctx.token.string.match(/^["']/) === null) { if (!tokenType) { tokenType = TAG_NAME; if (ctx.token.type === "tag bracket") { // Check to see if this is a closing tag if (ctx.token.string === "