code
stringlengths 28
313k
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
74
| language
stringclasses 1
value | repo
stringlengths 5
60
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
function getParentTypeOfClassElement(node) {
var classSymbol = getSymbolOfNode(node.parent);
return node.flags & 64 /* Static */
? getTypeOfSymbol(classSymbol)
: getDeclaredTypeOfSymbol(classSymbol);
}
|
Gets either the static or instance type of a class element, based on
whether the element is declared as "static".
|
getParentTypeOfClassElement
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function comparePrecedenceToBinaryPlus(expression) {
// All binary expressions have lower precedence than '+' apart from '*', '/', and '%'
// which have greater precedence and '-' which has equal precedence.
// All unary operators have a higher precedence apart from yield.
// Arrow functions and conditionals have a lower precedence,
// although we convert the former into regular function expressions in ES5 mode,
// and in ES6 mode this function won't get called anyway.
//
// TODO (drosen): Note that we need to account for the upcoming 'yield' and
// spread ('...') unary operators that are anticipated for ES6.
switch (expression.kind) {
case 181 /* BinaryExpression */:
switch (expression.operatorToken.kind) {
case 37 /* AsteriskToken */:
case 39 /* SlashToken */:
case 40 /* PercentToken */:
return 1 /* GreaterThan */;
case 35 /* PlusToken */:
case 36 /* MinusToken */:
return 0 /* EqualTo */;
default:
return -1 /* LessThan */;
}
case 184 /* YieldExpression */:
case 182 /* ConditionalExpression */:
return -1 /* LessThan */;
default:
return 1 /* GreaterThan */;
}
}
|
Returns whether the expression has lesser, greater,
or equal precedence to the binary '+' operator
|
comparePrecedenceToBinaryPlus
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function emitSerializedTypeNode(node) {
if (node) {
switch (node.kind) {
case 103 /* VoidKeyword */:
write("void 0");
return;
case 160 /* ParenthesizedType */:
emitSerializedTypeNode(node.type);
return;
case 152 /* FunctionType */:
case 153 /* ConstructorType */:
write("Function");
return;
case 156 /* ArrayType */:
case 157 /* TupleType */:
write("Array");
return;
case 150 /* TypePredicate */:
case 120 /* BooleanKeyword */:
write("Boolean");
return;
case 130 /* StringKeyword */:
case 9 /* StringLiteral */:
write("String");
return;
case 128 /* NumberKeyword */:
write("Number");
return;
case 131 /* SymbolKeyword */:
write("Symbol");
return;
case 151 /* TypeReference */:
emitSerializedTypeReferenceNode(node);
return;
case 154 /* TypeQuery */:
case 155 /* TypeLiteral */:
case 158 /* UnionType */:
case 159 /* IntersectionType */:
case 117 /* AnyKeyword */:
break;
default:
ts.Debug.fail("Cannot serialize unexpected type node.");
break;
}
}
write("Object");
}
|
Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member.
|
emitSerializedTypeNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function emitSerializedTypeReferenceNode(node) {
var location = node.parent;
while (ts.isDeclaration(location) || ts.isTypeNode(location)) {
location = location.parent;
}
// Clone the type name and parent it to a location outside of the current declaration.
var typeName = ts.cloneEntityName(node.typeName);
typeName.parent = location;
var result = resolver.getTypeReferenceSerializationKind(typeName);
switch (result) {
case ts.TypeReferenceSerializationKind.Unknown:
var temp = createAndRecordTempVariable(0 /* Auto */);
write("(typeof (");
emitNodeWithoutSourceMap(temp);
write(" = ");
emitEntityNameAsExpression(typeName, /*useFallback*/ true);
write(") === 'function' && ");
emitNodeWithoutSourceMap(temp);
write(") || Object");
break;
case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
emitEntityNameAsExpression(typeName, /*useFallback*/ false);
break;
case ts.TypeReferenceSerializationKind.VoidType:
write("void 0");
break;
case ts.TypeReferenceSerializationKind.BooleanType:
write("Boolean");
break;
case ts.TypeReferenceSerializationKind.NumberLikeType:
write("Number");
break;
case ts.TypeReferenceSerializationKind.StringLikeType:
write("String");
break;
case ts.TypeReferenceSerializationKind.ArrayLikeType:
write("Array");
break;
case ts.TypeReferenceSerializationKind.ESSymbolType:
if (languageVersion < 2 /* ES6 */) {
write("typeof Symbol === 'function' ? Symbol : Object");
}
else {
write("Symbol");
}
break;
case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
write("Function");
break;
case ts.TypeReferenceSerializationKind.ObjectType:
write("Object");
break;
}
}
|
Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator.
|
emitSerializedTypeReferenceNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function emitSerializedParameterTypesOfNode(node) {
// serialization of parameter types uses the following rules:
//
// * If the declaration is a class, the parameters of the first constructor with a body are used.
// * If the declaration is function-like and has a body, the parameters of the function are used.
//
// For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`.
if (node) {
var valueDeclaration;
if (node.kind === 214 /* ClassDeclaration */) {
valueDeclaration = ts.getFirstConstructorWithBody(node);
}
else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) {
valueDeclaration = node;
}
if (valueDeclaration) {
var parameters = valueDeclaration.parameters;
var parameterCount = parameters.length;
if (parameterCount > 0) {
for (var i = 0; i < parameterCount; i++) {
if (i > 0) {
write(", ");
}
if (parameters[i].dotDotDotToken) {
var parameterType = parameters[i].type;
if (parameterType.kind === 156 /* ArrayType */) {
parameterType = parameterType.elementType;
}
else if (parameterType.kind === 151 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) {
parameterType = parameterType.typeArguments[0];
}
else {
parameterType = undefined;
}
emitSerializedTypeNode(parameterType);
}
else {
emitSerializedTypeOfNode(parameters[i]);
}
}
}
}
}
}
|
Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor.
|
emitSerializedParameterTypesOfNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function emitSerializedTypeMetadata(node, writeComma) {
// This method emits the serialized type metadata for a decorator target.
// The caller should have already tested whether the node has decorators.
var argumentsWritten = 0;
if (compilerOptions.emitDecoratorMetadata) {
if (shouldEmitTypeMetadata(node)) {
if (writeComma) {
write(", ");
}
writeLine();
write("__metadata('design:type', ");
emitSerializedTypeOfNode(node);
write(")");
argumentsWritten++;
}
if (shouldEmitParamTypesMetadata(node)) {
if (writeComma || argumentsWritten) {
write(", ");
}
writeLine();
write("__metadata('design:paramtypes', [");
emitSerializedParameterTypesOfNode(node);
write("])");
argumentsWritten++;
}
if (shouldEmitReturnTypeMetadata(node)) {
if (writeComma || argumentsWritten) {
write(", ");
}
writeLine();
write("__metadata('design:returntype', ");
emitSerializedReturnTypeOfNode(node);
write(")");
argumentsWritten++;
}
}
return argumentsWritten;
}
|
Serializes the return type of function. Used by the __metadata decorator for a method.
|
emitSerializedTypeMetadata
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function isTripleSlashComment(comment) {
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
if (currentText.charCodeAt(comment.pos + 1) === 47 /* slash */ &&
comment.pos + 2 < comment.end &&
currentText.charCodeAt(comment.pos + 2) === 47 /* slash */) {
var textSubStr = currentText.substring(comment.pos, comment.end);
return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ?
true : false;
}
return false;
}
|
Determine if the given comment is a triple-slash
@return true if the comment is a triple-slash comment else false
|
isTripleSlashComment
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function findConfigFile(searchPath) {
var fileName = "tsconfig.json";
while (true) {
if (ts.sys.fileExists(fileName)) {
return fileName;
}
var parentPath = ts.getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
fileName = "../" + fileName;
}
return undefined;
}
|
The version of the TypeScript compiler release
|
findConfigFile
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function parseConfigFileTextToJson(fileName, jsonText) {
try {
var jsonTextWithoutComments = removeComments(jsonText);
return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} };
}
catch (e) {
return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) };
}
}
|
Parse the text of the tsconfig.json file
@param fileName The path to the config file
@param jsonText The text of the config file
|
parseConfigFileTextToJson
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function removeComments(jsonText) {
var output = "";
var scanner = ts.createScanner(1 /* ES5 */, /* skipTrivia */ false, 0 /* Standard */, jsonText);
var token;
while ((token = scanner.scan()) !== 1 /* EndOfFileToken */) {
switch (token) {
case 2 /* SingleLineCommentTrivia */:
case 3 /* MultiLineCommentTrivia */:
// replace comments with whitespace to preserve original character positions
output += scanner.getTokenText().replace(/\S/g, " ");
break;
default:
output += scanner.getTokenText();
break;
}
}
return output;
}
|
Remove the comments from a json like text.
Comments can be single line comments (starting with # or //) or multiline comments using / * * /
This method replace comment content by whitespace rather than completely remove them to keep positions in json parsing error reporting accurate.
|
removeComments
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function parseJsonConfigFileContent(json, host, basePath) {
var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors;
return {
options: options,
fileNames: getFileNames(),
errors: errors
};
function getFileNames() {
var fileNames = [];
if (ts.hasProperty(json, "files")) {
if (json["files"] instanceof Array) {
fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); });
}
else {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"));
}
}
else {
var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined;
var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (var i = 0; i < sysFiles.length; i++) {
var name_31 = sysFiles[i];
if (ts.fileExtensionIs(name_31, ".d.ts")) {
var baseName = name_31.substr(0, name_31.length - ".d.ts".length);
if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) {
fileNames.push(name_31);
}
}
else if (ts.fileExtensionIs(name_31, ".ts")) {
if (!ts.contains(sysFiles, name_31 + "x")) {
fileNames.push(name_31);
}
}
else {
fileNames.push(name_31);
}
}
}
return fileNames;
}
}
|
Parse the contents of a config file (tsconfig.json).
@param json The contents of the config file to parse
@param host Instance of ParseConfigHost used to enumerate files in folder.
@param basePath A root directory to resolve relative path entries in the config
file to. e.g. outDir
|
parseJsonConfigFileContent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getInnermostModule(node) {
while (node.body.kind === 218 /* ModuleDeclaration */) {
node = node.body;
}
return node;
}
|
Like removeComputedProperties, but retains the properties with well known symbol names
|
getInnermostModule
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getArgumentIndex(argumentsList, node) {
// The list we got back can include commas. In the presence of errors it may
// also just have nodes without commas. For example "Foo(a b c)" will have 3
// args without commas. We want to find what index we're at. So we count
// forward until we hit ourselves, only incrementing the index if it isn't a
// comma.
//
// Note: the subtlety around trailing commas (in getArgumentCount) does not apply
// here. That's because we're only walking forward until we hit the node we're
// on. In that case, even if we're after the trailing comma, we'll still see
// that trailing comma in the list, and we'll have generated the appropriate
// arg index.
var argumentIndex = 0;
var listChildren = argumentsList.getChildren();
for (var _i = 0, listChildren_1 = listChildren; _i < listChildren_1.length; _i++) {
var child = listChildren_1[_i];
if (child === node) {
break;
}
if (child.kind !== 24 /* CommaToken */) {
argumentIndex++;
}
}
return argumentIndex;
}
|
Returns relevant information for the argument list and the current argument if we are
in the argument of an invocation; returns undefined otherwise.
|
getArgumentIndex
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function createSignatureHelpItems(candidates, bestSignature, argumentListInfo) {
var applicableSpan = argumentListInfo.argumentsSpan;
var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */;
var invocation = argumentListInfo.invocation;
var callTarget = ts.getInvokedExpression(invocation);
var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget);
var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined);
var items = ts.map(candidates, function (candidateSignature) {
var signatureHelpParameters;
var prefixDisplayParts = [];
var suffixDisplayParts = [];
if (callTargetDisplayParts) {
ts.addRange(prefixDisplayParts, callTargetDisplayParts);
}
if (isTypeParameterList) {
prefixDisplayParts.push(ts.punctuationPart(25 /* LessThanToken */));
var typeParameters = candidateSignature.typeParameters;
signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray;
suffixDisplayParts.push(ts.punctuationPart(27 /* GreaterThanToken */));
var parameterParts = ts.mapToDisplayParts(function (writer) {
return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.parameters, writer, invocation);
});
ts.addRange(suffixDisplayParts, parameterParts);
}
else {
var typeParameterParts = ts.mapToDisplayParts(function (writer) {
return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation);
});
ts.addRange(prefixDisplayParts, typeParameterParts);
prefixDisplayParts.push(ts.punctuationPart(17 /* OpenParenToken */));
var parameters = candidateSignature.parameters;
signatureHelpParameters = parameters.length > 0 ? ts.map(parameters, createSignatureHelpParameterForParameter) : emptyArray;
suffixDisplayParts.push(ts.punctuationPart(18 /* CloseParenToken */));
}
var returnTypeParts = ts.mapToDisplayParts(function (writer) {
return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation);
});
ts.addRange(suffixDisplayParts, returnTypeParts);
return {
isVariadic: candidateSignature.hasRestParameter,
prefixDisplayParts: prefixDisplayParts,
suffixDisplayParts: suffixDisplayParts,
separatorDisplayParts: [ts.punctuationPart(24 /* CommaToken */), ts.spacePart()],
parameters: signatureHelpParameters,
documentation: candidateSignature.getDocumentationComment()
};
});
var argumentIndex = argumentListInfo.argumentIndex;
// argumentCount is the *apparent* number of arguments.
var argumentCount = argumentListInfo.argumentCount;
var selectedItemIndex = candidates.indexOf(bestSignature);
if (selectedItemIndex < 0) {
selectedItemIndex = selectBestInvalidOverloadIndex(candidates, argumentCount);
}
ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex);
return {
items: items,
applicableSpan: applicableSpan,
selectedItemIndex: selectedItemIndex,
argumentIndex: argumentIndex,
argumentCount: argumentCount
};
function createSignatureHelpParameterForParameter(parameter) {
var displayParts = ts.mapToDisplayParts(function (writer) {
return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation);
});
return {
name: parameter.name,
documentation: parameter.getDocumentationComment(),
displayParts: displayParts,
isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration)
};
}
function createSignatureHelpParameterForTypeParameter(typeParameter) {
var displayParts = ts.mapToDisplayParts(function (writer) {
return typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation);
});
return {
name: typeParameter.symbol.name,
documentation: emptyArray,
displayParts: displayParts,
isOptional: false
};
}
}
|
The selectedItemIndex could be negative for several reasons.
1. There are too many arguments for all of the overloads
2. None of the overloads were type compatible
The solution here is to try to pick the best overload by picking
either the first one that has an appropriate number of parameters,
or the one with the most parameters.
|
createSignatureHelpItems
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getTouchingToken(sourceFile, position, includeItemAtEndPosition) {
return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition);
}
|
Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true
|
getTouchingToken
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getTokenAtPosition(sourceFile, position) {
return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined);
}
|
Returns a token if position is in [start-of-leading-trivia, end)
|
getTokenAtPosition
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function findNextToken(previousToken, parent) {
return find(parent);
function find(n) {
if (isToken(n) && n.pos === previousToken.end) {
// this is token that starts at the end of previous token - return it
return n;
}
var children = n.getChildren();
for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
var child = children_1[_i];
var shouldDiveInChildNode =
// previous token is enclosed somewhere in the child
(child.pos <= previousToken.pos && child.end > previousToken.end) ||
// previous token ends exactly at the beginning of child
(child.pos === previousToken.end);
if (shouldDiveInChildNode && nodeHasTokens(child)) {
return find(child);
}
}
return undefined;
}
}
|
The token on the left of the position is the token that strictly includes the position
or sits to the left of the cursor if it is on a boundary. For example
fo|o -> will return foo
foo <comment> |bar -> will return foo
|
findNextToken
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function isInCommentHelper(sourceFile, position, predicate) {
var token = getTokenAtPosition(sourceFile, position);
if (token && position <= token.getStart()) {
var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos);
// The end marker of a single-line comment does not include the newline character.
// In the following case, we are inside a comment (^ denotes the cursor position):
//
// // asdf ^\n
//
// But for multi-line comments, we don't want to be inside the comment in the following case:
//
// /* asdf */^
//
// Internally, we represent the end of the comment at the newline and closing '/', respectively.
return predicate ?
ts.forEach(commentRanges, function (c) { return c.pos < position &&
(c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) &&
predicate(c); }) :
ts.forEach(commentRanges, function (c) { return c.pos < position &&
(c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); });
}
return false;
}
|
Returns true if the cursor at position in sourceFile is within a comment that additionally
satisfies predicate, and false otherwise.
|
isInCommentHelper
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function nodeHasTokens(n) {
// If we have a token or node that has a non-zero width, it must have tokens.
// Note, that getWidth() does not take trivia into account.
return n.getWidth() !== 0;
}
|
Get the corresponding JSDocTag node if the position is in a jsDoc comment
|
nodeHasTokens
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getFormattingScanner(sourceFile, startPos, endPos) {
ts.Debug.assert(scanner === undefined);
scanner = sourceFile.languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner;
scanner.setText(sourceFile.text);
scanner.setTextPos(startPos);
var wasNewLine = true;
var leadingTrivia;
var trailingTrivia;
var savedPos;
var lastScanAction;
var lastTokenInfo;
return {
advance: advance,
readTokenInfo: readTokenInfo,
isOnToken: isOnToken,
lastTrailingTriviaWasNewLine: function () { return wasNewLine; },
close: function () {
ts.Debug.assert(scanner !== undefined);
lastTokenInfo = undefined;
scanner.setText(undefined);
scanner = undefined;
}
};
function advance() {
ts.Debug.assert(scanner !== undefined);
lastTokenInfo = undefined;
var isStarted = scanner.getStartPos() !== startPos;
if (isStarted) {
if (trailingTrivia) {
ts.Debug.assert(trailingTrivia.length !== 0);
wasNewLine = ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */;
}
else {
wasNewLine = false;
}
}
leadingTrivia = undefined;
trailingTrivia = undefined;
if (!isStarted) {
scanner.scan();
}
var t;
var pos = scanner.getStartPos();
// Read leading trivia and token
while (pos < endPos) {
var t_1 = scanner.getToken();
if (!ts.isTrivia(t_1)) {
break;
}
// consume leading trivia
scanner.scan();
var item = {
pos: pos,
end: scanner.getStartPos(),
kind: t_1
};
pos = scanner.getStartPos();
if (!leadingTrivia) {
leadingTrivia = [];
}
leadingTrivia.push(item);
}
savedPos = scanner.getStartPos();
}
function shouldRescanGreaterThanToken(node) {
if (node) {
switch (node.kind) {
case 29 /* GreaterThanEqualsToken */:
case 64 /* GreaterThanGreaterThanEqualsToken */:
case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
case 45 /* GreaterThanGreaterThanGreaterThanToken */:
case 44 /* GreaterThanGreaterThanToken */:
return true;
}
}
return false;
}
function shouldRescanJsxIdentifier(node) {
if (node.parent) {
switch (node.parent.kind) {
case 238 /* JsxAttribute */:
case 235 /* JsxOpeningElement */:
case 237 /* JsxClosingElement */:
case 234 /* JsxSelfClosingElement */:
return node.kind === 69 /* Identifier */;
}
}
return false;
}
function shouldRescanSlashToken(container) {
return container.kind === 10 /* RegularExpressionLiteral */;
}
function shouldRescanTemplateToken(container) {
return container.kind === 13 /* TemplateMiddle */ ||
container.kind === 14 /* TemplateTail */;
}
function startsWithSlashToken(t) {
return t === 39 /* SlashToken */ || t === 61 /* SlashEqualsToken */;
}
function readTokenInfo(n) {
ts.Debug.assert(scanner !== undefined);
if (!isOnToken()) {
// scanner is not on the token (either advance was not called yet or scanner is already past the end position)
return {
leadingTrivia: leadingTrivia,
trailingTrivia: undefined,
token: undefined
};
}
// normally scanner returns the smallest available token
// check the kind of context node to determine if scanner should have more greedy behavior and consume more text.
var expectedScanAction = shouldRescanGreaterThanToken(n)
? 1 /* RescanGreaterThanToken */
: shouldRescanSlashToken(n)
? 2 /* RescanSlashToken */
: shouldRescanTemplateToken(n)
? 3 /* RescanTemplateToken */
: shouldRescanJsxIdentifier(n)
? 4 /* RescanJsxIdentifier */
: 0 /* Scan */;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
// readTokenInfo was called before with the same expected scan action.
// No need to re-scan text, return existing 'lastTokenInfo'
// it is ok to call fixTokenKind here since it does not affect
// what portion of text is consumed. In opposize rescanning can change it,
// i.e. for '>=' when originally scanner eats just one character
// and rescanning forces it to consume more.
return fixTokenKind(lastTokenInfo, n);
}
if (scanner.getStartPos() !== savedPos) {
ts.Debug.assert(lastTokenInfo !== undefined);
// readTokenInfo was called before but scan action differs - rescan text
scanner.setTextPos(savedPos);
scanner.scan();
}
var currentToken = scanner.getToken();
if (expectedScanAction === 1 /* RescanGreaterThanToken */ && currentToken === 27 /* GreaterThanToken */) {
currentToken = scanner.reScanGreaterToken();
ts.Debug.assert(n.kind === currentToken);
lastScanAction = 1 /* RescanGreaterThanToken */;
}
else if (expectedScanAction === 2 /* RescanSlashToken */ && startsWithSlashToken(currentToken)) {
currentToken = scanner.reScanSlashToken();
ts.Debug.assert(n.kind === currentToken);
lastScanAction = 2 /* RescanSlashToken */;
}
else if (expectedScanAction === 3 /* RescanTemplateToken */ && currentToken === 16 /* CloseBraceToken */) {
currentToken = scanner.reScanTemplateToken();
lastScanAction = 3 /* RescanTemplateToken */;
}
else if (expectedScanAction === 4 /* RescanJsxIdentifier */ && currentToken === 69 /* Identifier */) {
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4 /* RescanJsxIdentifier */;
}
else {
lastScanAction = 0 /* Scan */;
}
var token = {
pos: scanner.getStartPos(),
end: scanner.getTextPos(),
kind: currentToken
};
// consume trailing trivia
if (trailingTrivia) {
trailingTrivia = undefined;
}
while (scanner.getStartPos() < endPos) {
currentToken = scanner.scan();
if (!ts.isTrivia(currentToken)) {
break;
}
var trivia = {
pos: scanner.getStartPos(),
end: scanner.getTextPos(),
kind: currentToken
};
if (!trailingTrivia) {
trailingTrivia = [];
}
trailingTrivia.push(trivia);
if (currentToken === 4 /* NewLineTrivia */) {
// move past new line
scanner.scan();
break;
}
}
lastTokenInfo = {
leadingTrivia: leadingTrivia,
trailingTrivia: trailingTrivia,
token: token
};
return fixTokenKind(lastTokenInfo, n);
}
function isOnToken() {
ts.Debug.assert(scanner !== undefined);
var current = (lastTokenInfo && lastTokenInfo.token.kind) || scanner.getToken();
var startPos = (lastTokenInfo && lastTokenInfo.token.pos) || scanner.getStartPos();
return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current);
}
// when containing node in the tree is token
// but its kind differs from the kind that was returned by the scanner,
// then kind needs to be fixed. This might happen in cases
// when parser interprets token differently, i.e keyword treated as identifier
function fixTokenKind(tokenInfo, container) {
if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) {
tokenInfo.token.kind = container.kind;
}
return tokenInfo;
}
}
|
Scanner that is currently used for formatting
|
getFormattingScanner
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function find(n) {
var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; });
if (candidate) {
var result = find(candidate);
if (result) {
return result;
}
}
return n;
}
|
find node that fully contains given text range
|
find
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function prepareRangeContainsErrorFunction(errors, originalRange) {
if (!errors.length) {
return rangeHasNoErrors;
}
// pick only errors that fall in range
var sorted = errors
.filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); })
.sort(function (e1, e2) { return e1.start - e2.start; });
if (!sorted.length) {
return rangeHasNoErrors;
}
var index = 0;
return function (r) {
// in current implementation sequence of arguments [r1, r2...] is monotonically increasing.
// 'index' tracks the index of the most recent error that was checked.
while (true) {
if (index >= sorted.length) {
// all errors in the range were already checked -> no error in specified range
return false;
}
var error = sorted[index];
if (r.end <= error.start) {
// specified range ends before the error refered by 'index' - no error in range
return false;
}
if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) {
// specified range overlaps with error range
return true;
}
index++;
}
};
function rangeHasNoErrors(r) {
return false;
}
}
|
formatting is not applied to ranges that contain parse errors.
This function will return a predicate that for a given text range will tell
if there are any parse errors that overlap with the range.
|
prepareRangeContainsErrorFunction
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getScanStartPosition(enclosingNode, originalRange, sourceFile) {
var start = enclosingNode.getStart(sourceFile);
if (start === originalRange.pos && enclosingNode.end === originalRange.end) {
return start;
}
var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile);
if (!precedingToken) {
// no preceding token found - start from the beginning of enclosing node
return enclosingNode.pos;
}
// preceding token ends after the start of original range (i.e when originaRange.pos falls in the middle of literal)
// start from the beginning of enclosingNode to handle the entire 'originalRange'
if (precedingToken.end >= originalRange.pos) {
return enclosingNode.pos;
}
return precedingToken.end;
}
|
Start of the original range might fall inside the comment - scanner will not yield appropriate results
This function will look for token that is located before the start of target range
and return its end as start position for the scanner.
|
getScanStartPosition
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) {
if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) {
if (inheritedIndentation !== -1 /* Unknown */) {
return inheritedIndentation;
}
}
else {
var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile);
var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options);
if (startLine !== parentStartLine || startPos === column) {
return column;
}
}
return -1 /* Unknown */;
}
|
Tries to compute the indentation for a list element.
If list element is not in range then
function will pick its actual indentation
so it can be pushed downstream as inherited indentation.
If list element is in the range - its indentation will be equal
to inherited indentation from its predecessors.
|
tryComputeIndentationForListItem
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function StringScriptSnapshot(text) {
this.text = text;
}
|
The version of the language service API
|
StringScriptSnapshot
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function tryConsumeDeclare() {
var token = scanner.getToken();
if (token === 122 /* DeclareKeyword */) {
// declare module "mod"
token = scanner.scan();
if (token === 125 /* ModuleKeyword */) {
token = scanner.scan();
if (token === 9 /* StringLiteral */) {
recordAmbientExternalModule();
}
}
return true;
}
return false;
}
|
Returns true if at least one token was consumed from the stream
|
tryConsumeDeclare
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function isLabeledBy(node, labelName) {
for (var owner = node.parent; owner.kind === 207 /* LabeledStatement */; owner = owner.parent) {
if (owner.label.text === labelName) {
return true;
}
}
return false;
}
|
Whether or not a 'node' is preceded by a label of the given string.
Note: 'node' cannot be a SourceFile.
|
isLabeledBy
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) {
if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) {
switch (node.parent.kind) {
case 141 /* PropertyDeclaration */:
case 140 /* PropertySignature */:
case 245 /* PropertyAssignment */:
case 247 /* EnumMember */:
case 143 /* MethodDeclaration */:
case 142 /* MethodSignature */:
case 145 /* GetAccessor */:
case 146 /* SetAccessor */:
case 218 /* ModuleDeclaration */:
return node.parent.name === node;
case 167 /* ElementAccessExpression */:
return node.parent.argumentExpression === node;
}
}
return false;
}
|
Returns true if node is a name of an object literal property, e.g. "a" in x = { "a": 1 }
|
isLiteralNameOfPropertyDeclarationOrIndexAccess
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function isInsideComment(sourceFile, token, position) {
// The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment
return position <= token.getStart(sourceFile) &&
(isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) ||
isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart())));
function isInsideCommentRange(comments) {
return ts.forEach(comments, function (comment) {
// either we are 1. completely inside the comment, or 2. at the end of the comment
if (comment.pos < position && position < comment.end) {
return true;
}
else if (position === comment.end) {
var text = sourceFile.text;
var width = comment.end - comment.pos;
// is single line comment or just /*
if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) {
return true;
}
else {
// is unterminated multi-line comment
return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ &&
text.charCodeAt(comment.end - 2) === 42 /* asterisk */);
}
}
return false;
});
}
}
|
Returns true if the position is within a comment
|
isInsideComment
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) {
var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location);
if (displayName) {
var firstCharCode = displayName.charCodeAt(0);
// First check of the displayName is not external module; if it is an external module, it is not valid entry
if ((symbol.flags & 1536 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) {
// If the symbol is external module, don't show it in the completion list
// (i.e declare module "http" { let x; } | // <= request completion here, "http" should not be there)
return undefined;
}
}
return getCompletionEntryDisplayName(displayName, target, performCharacterChecks);
}
|
Get the name to be display in completion from a given symbol.
@return undefined if the name is of external module otherwise a name with striped of any quote
|
getCompletionEntryDisplayNameForSymbol
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getCompletionData(fileName, position) {
var typeChecker = program.getTypeChecker();
var syntacticStart = new Date().getTime();
var sourceFile = getValidSourceFile(fileName);
var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile);
var isJsDocTagName = false;
var start = new Date().getTime();
var currentToken = ts.getTokenAtPosition(sourceFile, position);
log("getCompletionData: Get current token: " + (new Date().getTime() - start));
start = new Date().getTime();
// Completion not allowed inside comments, bail out if this is the case
var insideComment = isInsideComment(sourceFile, currentToken, position);
log("getCompletionData: Is inside comment: " + (new Date().getTime() - start));
if (insideComment) {
// The current position is next to the '@' sign, when no tag name being provided yet.
// Provide a full list of tag names
if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
isJsDocTagName = true;
}
// Completion should work inside certain JsDoc tags. For example:
// /** @type {number | string} */
// Completion should work in the brackets
var insideJsDocTagExpression = false;
var tag = ts.getJsDocTagAtPosition(sourceFile, position);
if (tag) {
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
isJsDocTagName = true;
}
switch (tag.kind) {
case 269 /* JSDocTypeTag */:
case 267 /* JSDocParameterTag */:
case 268 /* JSDocReturnTag */:
var tagWithExpression = tag;
if (tagWithExpression.typeExpression) {
insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end;
}
break;
}
}
if (isJsDocTagName) {
return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName };
}
if (!insideJsDocTagExpression) {
// Proceed if the current position is in jsDoc tag expression; otherwise it is a normal
// comment or the plain text part of a jsDoc comment, so no completion should be available
log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment.");
return undefined;
}
}
start = new Date().getTime();
var previousToken = ts.findPrecedingToken(position, sourceFile);
log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start));
// The decision to provide completion depends on the contextToken, which is determined through the previousToken.
// Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file
var contextToken = previousToken;
// Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS|
// Skip this partial identifier and adjust the contextToken to the token that precedes it.
if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) {
var start_3 = new Date().getTime();
contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile);
log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_3));
}
// Find the node where completion is requested on.
// Also determine whether we are trying to complete with members of that node
// or attributes of a JSX tag.
var node = currentToken;
var isRightOfDot = false;
var isRightOfOpenTag = false;
var isStartingCloseTag = false;
var location = ts.getTouchingPropertyName(sourceFile, position);
if (contextToken) {
// Bail out if this is a known invalid completion location
if (isCompletionListBlocker(contextToken)) {
log("Returning an empty list because completion was requested in an invalid position.");
return undefined;
}
var parent_9 = contextToken.parent, kind = contextToken.kind;
if (kind === 21 /* DotToken */) {
if (parent_9.kind === 166 /* PropertyAccessExpression */) {
node = contextToken.parent.expression;
isRightOfDot = true;
}
else if (parent_9.kind === 135 /* QualifiedName */) {
node = contextToken.parent.left;
isRightOfDot = true;
}
else {
// There is nothing that precedes the dot, so this likely just a stray character
// or leading into a '...' token. Just bail out instead.
return undefined;
}
}
else if (sourceFile.languageVariant === 1 /* JSX */) {
if (kind === 25 /* LessThanToken */) {
isRightOfOpenTag = true;
location = contextToken;
}
else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 237 /* JsxClosingElement */) {
isStartingCloseTag = true;
}
}
}
var semanticStart = new Date().getTime();
var isMemberCompletion;
var isNewIdentifierLocation;
var symbols = [];
if (isRightOfDot) {
getTypeScriptMemberSymbols();
}
else if (isRightOfOpenTag) {
var tagSymbols = typeChecker.getJsxIntrinsicTagNames();
if (tryGetGlobalSymbols()) {
symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & 107455 /* Value */); }));
}
else {
symbols = tagSymbols;
}
isMemberCompletion = true;
isNewIdentifierLocation = false;
}
else if (isStartingCloseTag) {
var tagName = contextToken.parent.parent.openingElement.tagName;
symbols = [typeChecker.getSymbolAtLocation(tagName)];
isMemberCompletion = true;
isNewIdentifierLocation = false;
}
else {
// For JavaScript or TypeScript, if we're not after a dot, then just try to get the
// global symbols in scope. These results should be valid for either language as
// the set of symbols that can be referenced from this location.
if (!tryGetGlobalSymbols()) {
return undefined;
}
}
log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart));
return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName };
function getTypeScriptMemberSymbols() {
// Right of dot member completion list
isMemberCompletion = true;
isNewIdentifierLocation = false;
if (node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */) {
var symbol = typeChecker.getSymbolAtLocation(node);
// This is an alias, follow what it aliases
if (symbol && symbol.flags & 8388608 /* Alias */) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
if (symbol && symbol.flags & 1952 /* HasExports */) {
// Extract module or enum members
var exportedSymbols = typeChecker.getExportsOfModule(symbol);
ts.forEach(exportedSymbols, function (symbol) {
if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) {
symbols.push(symbol);
}
});
}
}
var type = typeChecker.getTypeAtLocation(node);
addTypeProperties(type);
}
function addTypeProperties(type) {
if (type) {
// Filter private properties
for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) {
var symbol = _a[_i];
if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) {
symbols.push(symbol);
}
}
if (isJavaScriptFile && type.flags & 16384 /* Union */) {
// In javascript files, for union types, we don't just get the members that
// the individual types have in common, we also include all the members that
// each individual type has. This is because we're going to add all identifiers
// anyways. So we might as well elevate the members that were at least part
// of the individual types to a higher status since we know what they are.
var unionType = type;
for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) {
var elementType = _c[_b];
addTypeProperties(elementType);
}
}
}
}
function tryGetGlobalSymbols() {
var objectLikeContainer;
var namedImportsOrExports;
var jsxContainer;
if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) {
return tryGetObjectLikeCompletionSymbols(objectLikeContainer);
}
if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) {
// cursor is in an import clause
// try to show exported member for imported module
return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports);
}
if (jsxContainer = tryGetContainingJsxElement(contextToken)) {
var attrsType;
if ((jsxContainer.kind === 234 /* JsxSelfClosingElement */) || (jsxContainer.kind === 235 /* JsxOpeningElement */)) {
// Cursor is inside a JSX self-closing element or opening element
attrsType = typeChecker.getJsxElementAttributesType(jsxContainer);
if (attrsType) {
symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes);
isMemberCompletion = true;
isNewIdentifierLocation = false;
return true;
}
}
}
// Get all entities in the current scope.
isMemberCompletion = false;
isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
if (previousToken !== contextToken) {
ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
}
// We need to find the node that will give us an appropriate scope to begin
// aggregating completion candidates. This is achieved in 'getScopeNode'
// by finding the first node that encompasses a position, accounting for whether a node
// is "complete" to decide whether a position belongs to the node.
//
// However, at the end of an identifier, we are interested in the scope of the identifier
// itself, but fall outside of the identifier. For instance:
//
// xyz => x$
//
// the cursor is outside of both the 'x' and the arrow function 'xyz => x',
// so 'xyz' is not returned in our results.
//
// We define 'adjustedPosition' so that we may appropriately account for
// being at the end of an identifier. The intention is that if requesting completion
// at the end of an identifier, it should be effectively equivalent to requesting completion
// anywhere inside/at the beginning of the identifier. So in the previous case, the
// 'adjustedPosition' will work as if requesting completion in the following:
//
// xyz => $x
//
// If previousToken !== contextToken, then
// - 'contextToken' was adjusted to the token prior to 'previousToken'
// because we were at the end of an identifier.
// - 'previousToken' is defined.
var adjustedPosition = previousToken !== contextToken ?
previousToken.getStart() :
position;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
/// TODO filter meaning based on the current context
var symbolMeanings = 793056 /* Type */ | 107455 /* Value */ | 1536 /* Namespace */ | 8388608 /* Alias */;
symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings);
return true;
}
/**
* Finds the first node that "embraces" the position, so that one may
* accurately aggregate locals from the closest containing scope.
*/
function getScopeNode(initialToken, position, sourceFile) {
var scope = initialToken;
while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) {
scope = scope.parent;
}
return scope;
}
function isCompletionListBlocker(contextToken) {
var start = new Date().getTime();
var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) ||
isSolelyIdentifierDefinitionLocation(contextToken) ||
isDotOfNumericLiteral(contextToken) ||
isInJsxText(contextToken);
log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start));
return result;
}
function isInJsxText(contextToken) {
if (contextToken.kind === 236 /* JsxText */) {
return true;
}
if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) {
if (contextToken.parent.kind === 235 /* JsxOpeningElement */) {
return true;
}
if (contextToken.parent.kind === 237 /* JsxClosingElement */ || contextToken.parent.kind === 234 /* JsxSelfClosingElement */) {
return contextToken.parent.parent && contextToken.parent.parent.kind === 233 /* JsxElement */;
}
}
return false;
}
function isNewIdentifierDefinitionLocation(previousToken) {
if (previousToken) {
var containingNodeKind = previousToken.parent.kind;
switch (previousToken.kind) {
case 24 /* CommaToken */:
return containingNodeKind === 168 /* CallExpression */ // func( a, |
|| containingNodeKind === 144 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */
|| containingNodeKind === 169 /* NewExpression */ // new C(a, |
|| containingNodeKind === 164 /* ArrayLiteralExpression */ // [a, |
|| containingNodeKind === 181 /* BinaryExpression */ // let x = (a, |
|| containingNodeKind === 152 /* FunctionType */; // var x: (s: string, list|
case 17 /* OpenParenToken */:
return containingNodeKind === 168 /* CallExpression */ // func( |
|| containingNodeKind === 144 /* Constructor */ // constructor( |
|| containingNodeKind === 169 /* NewExpression */ // new C(a|
|| containingNodeKind === 172 /* ParenthesizedExpression */ // let x = (a|
|| containingNodeKind === 160 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */
case 19 /* OpenBracketToken */:
return containingNodeKind === 164 /* ArrayLiteralExpression */ // [ |
|| containingNodeKind === 149 /* IndexSignature */ // [ | : string ]
|| containingNodeKind === 136 /* ComputedPropertyName */; // [ | /* this can become an index signature */
case 125 /* ModuleKeyword */: // module |
case 126 /* NamespaceKeyword */:
return true;
case 21 /* DotToken */:
return containingNodeKind === 218 /* ModuleDeclaration */; // module A.|
case 15 /* OpenBraceToken */:
return containingNodeKind === 214 /* ClassDeclaration */; // class A{ |
case 56 /* EqualsToken */:
return containingNodeKind === 211 /* VariableDeclaration */ // let x = a|
|| containingNodeKind === 181 /* BinaryExpression */; // x = a|
case 12 /* TemplateHead */:
return containingNodeKind === 183 /* TemplateExpression */; // `aa ${|
case 13 /* TemplateMiddle */:
return containingNodeKind === 190 /* TemplateSpan */; // `aa ${10} dd ${|
case 112 /* PublicKeyword */:
case 110 /* PrivateKeyword */:
case 111 /* ProtectedKeyword */:
return containingNodeKind === 141 /* PropertyDeclaration */; // class A{ public |
}
// Previous token may have been a keyword that was converted to an identifier.
switch (previousToken.getText()) {
case "public":
case "protected":
case "private":
return true;
}
}
return false;
}
function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) {
if (contextToken.kind === 9 /* StringLiteral */
|| contextToken.kind === 10 /* RegularExpressionLiteral */
|| ts.isTemplateLiteralKind(contextToken.kind)) {
var start_4 = contextToken.getStart();
var end = contextToken.getEnd();
// To be "in" one of these literals, the position has to be:
// 1. entirely within the token text.
// 2. at the end position of an unterminated token.
// 3. at the end of a regular expression (due to trailing flags like '/foo/g').
if (start_4 < position && position < end) {
return true;
}
if (position === end) {
return !!contextToken.isUnterminated
|| contextToken.kind === 10 /* RegularExpressionLiteral */;
}
}
return false;
}
/**
* Aggregates relevant symbols for completion in object literals and object binding patterns.
* Relevant symbols are stored in the captured 'symbols' variable.
*
* @returns true if 'symbols' was successfully populated; false otherwise.
*/
function tryGetObjectLikeCompletionSymbols(objectLikeContainer) {
// We're looking up possible property names from contextual/inferred/declared type.
isMemberCompletion = true;
var typeForObject;
var existingMembers;
if (objectLikeContainer.kind === 165 /* ObjectLiteralExpression */) {
// We are completing on contextual types, but may also include properties
// other than those within the declared type.
isNewIdentifierLocation = true;
typeForObject = typeChecker.getContextualType(objectLikeContainer);
existingMembers = objectLikeContainer.properties;
}
else if (objectLikeContainer.kind === 161 /* ObjectBindingPattern */) {
// We are *only* completing on properties from the type being destructured.
isNewIdentifierLocation = false;
var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
if (ts.isVariableLike(rootDeclaration)) {
// We don't want to complete using the type acquired by the shape
// of the binding pattern; we are only interested in types acquired
// through type declaration or inference.
if (rootDeclaration.initializer || rootDeclaration.type) {
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = objectLikeContainer.elements;
}
}
else {
ts.Debug.fail("Root declaration is not variable-like.");
}
}
else {
ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind);
}
if (!typeForObject) {
return false;
}
var typeMembers = typeChecker.getPropertiesOfType(typeForObject);
if (typeMembers && typeMembers.length > 0) {
// Add filtered items to the completion list
symbols = filterObjectMembersList(typeMembers, existingMembers);
}
return true;
}
/**
* Aggregates relevant symbols for completion in import clauses and export clauses
* whose declarations have a module specifier; for instance, symbols will be aggregated for
*
* import { | } from "moduleName";
* export { a as foo, | } from "moduleName";
*
* but not for
*
* export { | };
*
* Relevant symbols are stored in the captured 'symbols' variable.
*
* @returns true if 'symbols' was successfully populated; false otherwise.
*/
function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) {
var declarationKind = namedImportsOrExports.kind === 225 /* NamedImports */ ?
222 /* ImportDeclaration */ :
228 /* ExportDeclaration */;
var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind);
var moduleSpecifier = importOrExportDeclaration.moduleSpecifier;
if (!moduleSpecifier) {
return false;
}
isMemberCompletion = true;
isNewIdentifierLocation = false;
var exports;
var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier);
if (moduleSpecifierSymbol) {
exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol);
}
symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray;
return true;
}
/**
* Returns the immediate owning object literal or binding pattern of a context token,
* on the condition that one exists and that the context implies completion should be given.
*/
function tryGetObjectLikeCompletionContainer(contextToken) {
if (contextToken) {
switch (contextToken.kind) {
case 15 /* OpenBraceToken */: // let x = { |
case 24 /* CommaToken */:
var parent_10 = contextToken.parent;
if (parent_10 && (parent_10.kind === 165 /* ObjectLiteralExpression */ || parent_10.kind === 161 /* ObjectBindingPattern */)) {
return parent_10;
}
break;
}
}
return undefined;
}
/**
* Returns the containing list of named imports or exports of a context token,
* on the condition that one exists and that the context implies completion should be given.
*/
function tryGetNamedImportsOrExportsForCompletion(contextToken) {
if (contextToken) {
switch (contextToken.kind) {
case 15 /* OpenBraceToken */: // import { |
case 24 /* CommaToken */:
switch (contextToken.parent.kind) {
case 225 /* NamedImports */:
case 229 /* NamedExports */:
return contextToken.parent;
}
}
}
return undefined;
}
function tryGetContainingJsxElement(contextToken) {
if (contextToken) {
var parent_11 = contextToken.parent;
switch (contextToken.kind) {
case 26 /* LessThanSlashToken */:
case 39 /* SlashToken */:
case 69 /* Identifier */:
case 238 /* JsxAttribute */:
case 239 /* JsxSpreadAttribute */:
if (parent_11 && (parent_11.kind === 234 /* JsxSelfClosingElement */ || parent_11.kind === 235 /* JsxOpeningElement */)) {
return parent_11;
}
else if (parent_11.kind === 238 /* JsxAttribute */) {
return parent_11.parent;
}
break;
// The context token is the closing } or " of an attribute, which means
// its parent is a JsxExpression, whose parent is a JsxAttribute,
// whose parent is a JsxOpeningLikeElement
case 9 /* StringLiteral */:
if (parent_11 && ((parent_11.kind === 238 /* JsxAttribute */) || (parent_11.kind === 239 /* JsxSpreadAttribute */))) {
return parent_11.parent;
}
break;
case 16 /* CloseBraceToken */:
if (parent_11 &&
parent_11.kind === 240 /* JsxExpression */ &&
parent_11.parent &&
(parent_11.parent.kind === 238 /* JsxAttribute */)) {
return parent_11.parent.parent;
}
if (parent_11 && parent_11.kind === 239 /* JsxSpreadAttribute */) {
return parent_11.parent;
}
break;
}
}
return undefined;
}
function isFunction(kind) {
switch (kind) {
case 173 /* FunctionExpression */:
case 174 /* ArrowFunction */:
case 213 /* FunctionDeclaration */:
case 143 /* MethodDeclaration */:
case 142 /* MethodSignature */:
case 145 /* GetAccessor */:
case 146 /* SetAccessor */:
case 147 /* CallSignature */:
case 148 /* ConstructSignature */:
case 149 /* IndexSignature */:
return true;
}
return false;
}
/**
* @returns true if we are certain that the currently edited location must define a new location; false otherwise.
*/
function isSolelyIdentifierDefinitionLocation(contextToken) {
var containingNodeKind = contextToken.parent.kind;
switch (contextToken.kind) {
case 24 /* CommaToken */:
return containingNodeKind === 211 /* VariableDeclaration */ ||
containingNodeKind === 212 /* VariableDeclarationList */ ||
containingNodeKind === 193 /* VariableStatement */ ||
containingNodeKind === 217 /* EnumDeclaration */ ||
isFunction(containingNodeKind) ||
containingNodeKind === 214 /* ClassDeclaration */ ||
containingNodeKind === 186 /* ClassExpression */ ||
containingNodeKind === 215 /* InterfaceDeclaration */ ||
containingNodeKind === 162 /* ArrayBindingPattern */ ||
containingNodeKind === 216 /* TypeAliasDeclaration */; // type Map, K, |
case 21 /* DotToken */:
return containingNodeKind === 162 /* ArrayBindingPattern */; // var [.|
case 54 /* ColonToken */:
return containingNodeKind === 163 /* BindingElement */; // var {x :html|
case 19 /* OpenBracketToken */:
return containingNodeKind === 162 /* ArrayBindingPattern */; // var [x|
case 17 /* OpenParenToken */:
return containingNodeKind === 244 /* CatchClause */ ||
isFunction(containingNodeKind);
case 15 /* OpenBraceToken */:
return containingNodeKind === 217 /* EnumDeclaration */ ||
containingNodeKind === 215 /* InterfaceDeclaration */ ||
containingNodeKind === 155 /* TypeLiteral */; // let x : { |
case 23 /* SemicolonToken */:
return containingNodeKind === 140 /* PropertySignature */ &&
contextToken.parent && contextToken.parent.parent &&
(contextToken.parent.parent.kind === 215 /* InterfaceDeclaration */ ||
contextToken.parent.parent.kind === 155 /* TypeLiteral */); // let x : { a; |
case 25 /* LessThanToken */:
return containingNodeKind === 214 /* ClassDeclaration */ ||
containingNodeKind === 186 /* ClassExpression */ ||
containingNodeKind === 215 /* InterfaceDeclaration */ ||
containingNodeKind === 216 /* TypeAliasDeclaration */ ||
isFunction(containingNodeKind);
case 113 /* StaticKeyword */:
return containingNodeKind === 141 /* PropertyDeclaration */;
case 22 /* DotDotDotToken */:
return containingNodeKind === 138 /* Parameter */ ||
(contextToken.parent && contextToken.parent.parent &&
contextToken.parent.parent.kind === 162 /* ArrayBindingPattern */); // var [...z|
case 112 /* PublicKeyword */:
case 110 /* PrivateKeyword */:
case 111 /* ProtectedKeyword */:
return containingNodeKind === 138 /* Parameter */;
case 116 /* AsKeyword */:
return containingNodeKind === 226 /* ImportSpecifier */ ||
containingNodeKind === 230 /* ExportSpecifier */ ||
containingNodeKind === 224 /* NamespaceImport */;
case 73 /* ClassKeyword */:
case 81 /* EnumKeyword */:
case 107 /* InterfaceKeyword */:
case 87 /* FunctionKeyword */:
case 102 /* VarKeyword */:
case 123 /* GetKeyword */:
case 129 /* SetKeyword */:
case 89 /* ImportKeyword */:
case 108 /* LetKeyword */:
case 74 /* ConstKeyword */:
case 114 /* YieldKeyword */:
case 132 /* TypeKeyword */:
return true;
}
// Previous token may have been a keyword that was converted to an identifier.
switch (contextToken.getText()) {
case "abstract":
case "async":
case "class":
case "const":
case "declare":
case "enum":
case "function":
case "interface":
case "let":
case "private":
case "protected":
case "public":
case "static":
case "var":
case "yield":
return true;
}
return false;
}
function isDotOfNumericLiteral(contextToken) {
if (contextToken.kind === 8 /* NumericLiteral */) {
var text = contextToken.getFullText();
return text.charAt(text.length - 1) === ".";
}
return false;
}
/**
* Filters out completion suggestions for named imports or exports.
*
* @param exportsOfModule The list of symbols which a module exposes.
* @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause.
*
* @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports
* do not occur at the current position and have not otherwise been typed.
*/
function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) {
var exisingImportsOrExports = {};
for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) {
var element = namedImportsOrExports_1[_i];
// If this is the current item we are editing right now, do not filter it out
if (element.getStart() <= position && position <= element.getEnd()) {
continue;
}
var name_35 = element.propertyName || element.name;
exisingImportsOrExports[name_35.text] = true;
}
if (ts.isEmpty(exisingImportsOrExports)) {
return exportsOfModule;
}
return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(exisingImportsOrExports, e.name); });
}
/**
* Filters out completion suggestions for named imports or exports.
*
* @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations
* do not occur at the current position and have not otherwise been typed.
*/
function filterObjectMembersList(contextualMemberSymbols, existingMembers) {
if (!existingMembers || existingMembers.length === 0) {
return contextualMemberSymbols;
}
var existingMemberNames = {};
for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) {
var m = existingMembers_1[_i];
// Ignore omitted expressions for missing members
if (m.kind !== 245 /* PropertyAssignment */ &&
m.kind !== 246 /* ShorthandPropertyAssignment */ &&
m.kind !== 163 /* BindingElement */) {
continue;
}
// If this is the current item we are editing right now, do not filter it out
if (m.getStart() <= position && position <= m.getEnd()) {
continue;
}
var existingName = void 0;
if (m.kind === 163 /* BindingElement */ && m.propertyName) {
// include only identifiers in completion list
if (m.propertyName.kind === 69 /* Identifier */) {
existingName = m.propertyName.text;
}
}
else {
// TODO(jfreeman): Account for computed property name
// NOTE: if one only performs this step when m.name is an identifier,
// things like '__proto__' are not filtered out.
existingName = m.name.text;
}
existingMemberNames[existingName] = true;
}
return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); });
}
/**
* Filters out completion suggestions from 'symbols' according to existing JSX attributes.
*
* @returns Symbols to be suggested in a JSX element, barring those whose attributes
* do not occur at the current position and have not otherwise been typed.
*/
function filterJsxAttributes(symbols, attributes) {
var seenNames = {};
for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {
var attr = attributes_1[_i];
// If this is the current item we are editing right now, do not filter it out
if (attr.getStart() <= position && position <= attr.getEnd()) {
continue;
}
if (attr.kind === 238 /* JsxAttribute */) {
seenNames[attr.name.text] = true;
}
}
return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); });
}
}
|
Get a displayName from a given for completion list, performing any necessary quotes stripping
and checking whether the name is valid identifier name.
|
getCompletionData
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function isCompletionListBlocker(contextToken) {
var start = new Date().getTime();
var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) ||
isSolelyIdentifierDefinitionLocation(contextToken) ||
isDotOfNumericLiteral(contextToken) ||
isInJsxText(contextToken);
log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start));
return result;
}
|
Finds the first node that "embraces" the position, so that one may
accurately aggregate locals from the closest containing scope.
|
isCompletionListBlocker
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function tryGetNamedImportsOrExportsForCompletion(contextToken) {
if (contextToken) {
switch (contextToken.kind) {
case 15 /* OpenBraceToken */: // import { |
case 24 /* CommaToken */:
switch (contextToken.parent.kind) {
case 225 /* NamedImports */:
case 229 /* NamedExports */:
return contextToken.parent;
}
}
}
return undefined;
}
|
Returns the containing list of named imports or exports of a context token,
on the condition that one exists and that the context implies completion should be given.
|
tryGetNamedImportsOrExportsForCompletion
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function isSolelyIdentifierDefinitionLocation(contextToken) {
var containingNodeKind = contextToken.parent.kind;
switch (contextToken.kind) {
case 24 /* CommaToken */:
return containingNodeKind === 211 /* VariableDeclaration */ ||
containingNodeKind === 212 /* VariableDeclarationList */ ||
containingNodeKind === 193 /* VariableStatement */ ||
containingNodeKind === 217 /* EnumDeclaration */ ||
isFunction(containingNodeKind) ||
containingNodeKind === 214 /* ClassDeclaration */ ||
containingNodeKind === 186 /* ClassExpression */ ||
containingNodeKind === 215 /* InterfaceDeclaration */ ||
containingNodeKind === 162 /* ArrayBindingPattern */ ||
containingNodeKind === 216 /* TypeAliasDeclaration */; // type Map, K, |
case 21 /* DotToken */:
return containingNodeKind === 162 /* ArrayBindingPattern */; // var [.|
case 54 /* ColonToken */:
return containingNodeKind === 163 /* BindingElement */; // var {x :html|
case 19 /* OpenBracketToken */:
return containingNodeKind === 162 /* ArrayBindingPattern */; // var [x|
case 17 /* OpenParenToken */:
return containingNodeKind === 244 /* CatchClause */ ||
isFunction(containingNodeKind);
case 15 /* OpenBraceToken */:
return containingNodeKind === 217 /* EnumDeclaration */ ||
containingNodeKind === 215 /* InterfaceDeclaration */ ||
containingNodeKind === 155 /* TypeLiteral */; // let x : { |
case 23 /* SemicolonToken */:
return containingNodeKind === 140 /* PropertySignature */ &&
contextToken.parent && contextToken.parent.parent &&
(contextToken.parent.parent.kind === 215 /* InterfaceDeclaration */ ||
contextToken.parent.parent.kind === 155 /* TypeLiteral */); // let x : { a; |
case 25 /* LessThanToken */:
return containingNodeKind === 214 /* ClassDeclaration */ ||
containingNodeKind === 186 /* ClassExpression */ ||
containingNodeKind === 215 /* InterfaceDeclaration */ ||
containingNodeKind === 216 /* TypeAliasDeclaration */ ||
isFunction(containingNodeKind);
case 113 /* StaticKeyword */:
return containingNodeKind === 141 /* PropertyDeclaration */;
case 22 /* DotDotDotToken */:
return containingNodeKind === 138 /* Parameter */ ||
(contextToken.parent && contextToken.parent.parent &&
contextToken.parent.parent.kind === 162 /* ArrayBindingPattern */); // var [...z|
case 112 /* PublicKeyword */:
case 110 /* PrivateKeyword */:
case 111 /* ProtectedKeyword */:
return containingNodeKind === 138 /* Parameter */;
case 116 /* AsKeyword */:
return containingNodeKind === 226 /* ImportSpecifier */ ||
containingNodeKind === 230 /* ExportSpecifier */ ||
containingNodeKind === 224 /* NamespaceImport */;
case 73 /* ClassKeyword */:
case 81 /* EnumKeyword */:
case 107 /* InterfaceKeyword */:
case 87 /* FunctionKeyword */:
case 102 /* VarKeyword */:
case 123 /* GetKeyword */:
case 129 /* SetKeyword */:
case 89 /* ImportKeyword */:
case 108 /* LetKeyword */:
case 74 /* ConstKeyword */:
case 114 /* YieldKeyword */:
case 132 /* TypeKeyword */:
return true;
}
// Previous token may have been a keyword that was converted to an identifier.
switch (contextToken.getText()) {
case "abstract":
case "async":
case "class":
case "const":
case "declare":
case "enum":
case "function":
case "interface":
case "let":
case "private":
case "protected":
case "public":
case "static":
case "var":
case "yield":
return true;
}
return false;
}
|
@returns true if we are certain that the currently edited location must define a new location; false otherwise.
|
isSolelyIdentifierDefinitionLocation
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) {
var exisingImportsOrExports = {};
for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) {
var element = namedImportsOrExports_1[_i];
// If this is the current item we are editing right now, do not filter it out
if (element.getStart() <= position && position <= element.getEnd()) {
continue;
}
var name_35 = element.propertyName || element.name;
exisingImportsOrExports[name_35.text] = true;
}
if (ts.isEmpty(exisingImportsOrExports)) {
return exportsOfModule;
}
return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(exisingImportsOrExports, e.name); });
}
|
Filters out completion suggestions for named imports or exports.
@param exportsOfModule The list of symbols which a module exposes.
@param namedImportsOrExports The list of existing import/export specifiers in the import/export clause.
@returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports
do not occur at the current position and have not otherwise been typed.
|
filterNamedImportOrExportCompletionItems
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function filterObjectMembersList(contextualMemberSymbols, existingMembers) {
if (!existingMembers || existingMembers.length === 0) {
return contextualMemberSymbols;
}
var existingMemberNames = {};
for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) {
var m = existingMembers_1[_i];
// Ignore omitted expressions for missing members
if (m.kind !== 245 /* PropertyAssignment */ &&
m.kind !== 246 /* ShorthandPropertyAssignment */ &&
m.kind !== 163 /* BindingElement */) {
continue;
}
// If this is the current item we are editing right now, do not filter it out
if (m.getStart() <= position && position <= m.getEnd()) {
continue;
}
var existingName = void 0;
if (m.kind === 163 /* BindingElement */ && m.propertyName) {
// include only identifiers in completion list
if (m.propertyName.kind === 69 /* Identifier */) {
existingName = m.propertyName.text;
}
}
else {
// TODO(jfreeman): Account for computed property name
// NOTE: if one only performs this step when m.name is an identifier,
// things like '__proto__' are not filtered out.
existingName = m.name.text;
}
existingMemberNames[existingName] = true;
}
return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); });
}
|
Filters out completion suggestions for named imports or exports.
@returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations
do not occur at the current position and have not otherwise been typed.
|
filterObjectMembersList
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function filterJsxAttributes(symbols, attributes) {
var seenNames = {};
for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {
var attr = attributes_1[_i];
// If this is the current item we are editing right now, do not filter it out
if (attr.getStart() <= position && position <= attr.getEnd()) {
continue;
}
if (attr.kind === 238 /* JsxAttribute */) {
seenNames[attr.name.text] = true;
}
}
return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); });
}
|
Filters out completion suggestions from 'symbols' according to existing JSX attributes.
@returns Symbols to be suggested in a JSX element, barring those whose attributes
do not occur at the current position and have not otherwise been typed.
|
filterJsxAttributes
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function aggregateOwnedThrowStatements(node) {
var statementAccumulator = [];
aggregate(node);
return statementAccumulator;
function aggregate(node) {
if (node.kind === 208 /* ThrowStatement */) {
statementAccumulator.push(node);
}
else if (node.kind === 209 /* TryStatement */) {
var tryStatement = node;
if (tryStatement.catchClause) {
aggregate(tryStatement.catchClause);
}
else {
// Exceptions thrown within a try block lacking a catch clause
// are "owned" in the current context.
aggregate(tryStatement.tryBlock);
}
if (tryStatement.finallyBlock) {
aggregate(tryStatement.finallyBlock);
}
}
else if (!ts.isFunctionLike(node)) {
ts.forEachChild(node, aggregate);
}
}
}
|
Aggregates all throw-statements within this node *without* crossing
into function boundaries and try-blocks with catch-clauses.
|
aggregateOwnedThrowStatements
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function aggregateAllBreakAndContinueStatements(node) {
var statementAccumulator = [];
aggregate(node);
return statementAccumulator;
function aggregate(node) {
if (node.kind === 203 /* BreakStatement */ || node.kind === 202 /* ContinueStatement */) {
statementAccumulator.push(node);
}
else if (!ts.isFunctionLike(node)) {
ts.forEachChild(node, aggregate);
}
}
}
|
For lack of a better name, this function takes a throw statement and returns the
nearest ancestor that is a try-block (whose try statement has a catch clause),
function-block, or source file.
|
aggregateAllBreakAndContinueStatements
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getSymbolScope(symbol) {
// If this is the symbol of a named function expression or named class expression,
// then named references are limited to its own scope.
var valueDeclaration = symbol.valueDeclaration;
if (valueDeclaration && (valueDeclaration.kind === 173 /* FunctionExpression */ || valueDeclaration.kind === 186 /* ClassExpression */)) {
return valueDeclaration;
}
// If this is private property or method, the scope is the containing class
if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) {
var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16 /* Private */) ? d : undefined; });
if (privateDeclaration) {
return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */);
}
}
// If the symbol is an import we would like to find it if we are looking for what it imports.
// So consider it visibile outside its declaration scope.
if (symbol.flags & 8388608 /* Alias */) {
return undefined;
}
// if this symbol is visible from its parent container, e.g. exported, then bail out
// if symbol correspond to the union property - bail out
if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) {
return undefined;
}
var scope = undefined;
var declarations = symbol.getDeclarations();
if (declarations) {
for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
var declaration = declarations_8[_i];
var container = getContainerNode(declaration);
if (!container) {
return undefined;
}
if (scope && scope !== container) {
// Different declarations have different containers, bail out
return undefined;
}
if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) {
// This is a global variable and not an external module, any declaration defined
// within this scope is visible outside the file
return undefined;
}
// The search scope is the container node
scope = container;
}
}
return scope;
}
|
Determines the smallest scope in which a symbol may have named references.
Note that not every construct has been accounted for. This function can
probably be improved.
@returns undefined if the scope cannot be determined, implying that
a reference to a symbol can occur anywhere.
|
getSymbolScope
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) {
var sourceFile = container.getSourceFile();
var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</;
var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, container.getStart(), container.getEnd());
if (possiblePositions.length) {
// Build the set of symbols to search for, initially it has only the current symbol
var searchSymbols = populateSearchSymbolSet(searchSymbol, searchLocation);
ts.forEach(possiblePositions, function (position) {
cancellationToken.throwIfCancellationRequested();
var referenceLocation = ts.getTouchingPropertyName(sourceFile, position);
if (!isValidReferencePosition(referenceLocation, searchText)) {
// This wasn't the start of a token. Check to see if it might be a
// match in a comment or string if that's what the caller is asking
// for.
if ((findInStrings && ts.isInString(sourceFile, position)) ||
(findInComments && isInNonReferenceComment(sourceFile, position))) {
// In the case where we're looking inside comments/strings, we don't have
// an actual definition. So just use 'undefined' here. Features like
// 'Rename' won't care (as they ignore the definitions), and features like
// 'FindReferences' will just filter out these results.
result.push({
definition: undefined,
references: [{
fileName: sourceFile.fileName,
textSpan: ts.createTextSpan(position, searchText.length),
isWriteAccess: false
}]
});
}
return;
}
if (!(getMeaningFromLocation(referenceLocation) & searchMeaning)) {
return;
}
var referenceSymbol = typeChecker.getSymbolAtLocation(referenceLocation);
if (referenceSymbol) {
var referenceSymbolDeclaration = referenceSymbol.valueDeclaration;
var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration);
var relatedSymbol = getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation);
if (relatedSymbol) {
var referencedSymbol = getReferencedSymbol(relatedSymbol);
referencedSymbol.references.push(getReferenceEntryFromNode(referenceLocation));
}
else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols.indexOf(shorthandValueSymbol) >= 0) {
var referencedSymbol = getReferencedSymbol(shorthandValueSymbol);
referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name));
}
}
});
}
return;
function getReferencedSymbol(symbol) {
var symbolId = ts.getSymbolId(symbol);
var index = symbolToIndex[symbolId];
if (index === undefined) {
index = result.length;
symbolToIndex[symbolId] = index;
result.push({
definition: getDefinition(symbol),
references: []
});
}
return result[index];
}
function isInNonReferenceComment(sourceFile, position) {
return ts.isInCommentHelper(sourceFile, position, isNonReferenceComment);
function isNonReferenceComment(c) {
var commentText = sourceFile.text.substring(c.pos, c.end);
return !tripleSlashDirectivePrefixRegex.test(commentText);
}
}
}
|
Search within node "container" for references for a search value, where the search value is defined as a
tuple of(searchSymbol, searchText, searchLocation, and searchMeaning).
searchLocation: a node where the search value
|
getReferencesInNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function containErrors(diagnostics) {
return ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
}
|
A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment
|
containErrors
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function processNode(node) {
// Only walk into nodes that intersect the requested span.
if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) {
var kind = node.kind;
checkForClassificationCancellation(kind);
if (kind === 69 /* Identifier */ && !ts.nodeIsMissing(node)) {
var identifier = node;
// Only bother calling into the typechecker if this is an identifier that
// could possibly resolve to a type name. This makes classification run
// in a third of the time it would normally take.
if (classifiableNames[identifier.text]) {
var symbol = typeChecker.getSymbolAtLocation(node);
if (symbol) {
var type = classifySymbol(symbol, getMeaningFromLocation(node));
if (type) {
pushClassification(node.getStart(), node.getWidth(), type);
}
}
}
}
ts.forEachChild(node, processNode);
}
}
|
Returns true if there exists a module that introduces entities on the value side.
|
processNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getDocCommentTemplateAtPosition(fileName, position) {
var start = new Date().getTime();
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
// Check if in a context where we don't want to perform any insertion
if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) {
return undefined;
}
var tokenAtPos = ts.getTokenAtPosition(sourceFile, position);
var tokenStart = tokenAtPos.getStart();
if (!tokenAtPos || tokenStart < position) {
return undefined;
}
// TODO: add support for:
// - enums/enum members
// - interfaces
// - property declarations
// - potentially property assignments
var commentOwner;
findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) {
switch (commentOwner.kind) {
case 213 /* FunctionDeclaration */:
case 143 /* MethodDeclaration */:
case 144 /* Constructor */:
case 214 /* ClassDeclaration */:
case 193 /* VariableStatement */:
break findOwner;
case 248 /* SourceFile */:
return undefined;
case 218 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
// then we must be somewhere within a dotted namespace name; however we don't
// want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'.
if (commentOwner.parent.kind === 218 /* ModuleDeclaration */) {
return undefined;
}
break findOwner;
}
}
if (!commentOwner || commentOwner.getStart() < position) {
return undefined;
}
var parameters = getParametersForJsDocOwningNode(commentOwner);
var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position);
var lineStart = sourceFile.getLineStarts()[posLineAndChar.line];
var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character);
// TODO: call a helper method instead once PR #4133 gets merged in.
var newLine = host.getNewLine ? host.getNewLine() : "\r\n";
var docParams = "";
for (var i = 0, numParams = parameters.length; i < numParams; i++) {
var currentName = parameters[i].name;
var paramName = currentName.kind === 69 /* Identifier */ ?
currentName.text :
"param" + i;
docParams += indentationStr + " * @param " + paramName + newLine;
}
// A doc comment consists of the following
// * The opening comment line
// * the first line (without a param) for the object's untagged info (this is also where the caret ends up)
// * the '@param'-tagged lines
// * TODO: other tags.
// * the closing comment line
// * if the caret was directly in front of the object, then we add an extra line and indentation.
var preamble = "/**" + newLine +
indentationStr + " * ";
var result = preamble + newLine +
docParams +
indentationStr + " */" +
(tokenStart === position ? newLine + indentationStr : "");
return { newText: result, caretOffset: preamble.length };
}
|
Checks if position points to a valid position to add JSDoc comments, and if so,
returns the appropriate template. Otherwise returns an empty string.
Valid positions are
- outside of comments, statements, and expressions, and
- preceding a:
- function/constructor/method declaration
- class declarations
- variable statements
- namespace declarations
Hosts should ideally check that:
- The line is all whitespace up to 'position' before performing the insertion.
- If the keystroke sequence "/\*\*" induced the call, we also check that the next
non-whitespace character is '*', which (approximately) indicates whether we added
the second '*' to complete an existing (JSDoc) comment.
@param fileName The file in which to perform the check.
@param position The (character-indexed) position in the file where the check should
be performed.
|
getDocCommentTemplateAtPosition
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getParametersForJsDocOwningNode(commentOwner) {
if (ts.isFunctionLike(commentOwner)) {
return commentOwner.parameters;
}
if (commentOwner.kind === 193 /* VariableStatement */) {
var varStatement = commentOwner;
var varDeclarations = varStatement.declarationList.declarations;
if (varDeclarations.length === 1 && varDeclarations[0].initializer) {
return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer);
}
}
return emptyArray;
}
|
" + newLine +
indentationStr + " * ";
var result = preamble + newLine +
docParams +
indentationStr + "
|
getParametersForJsDocOwningNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function getTodoComments(fileName, descriptors) {
// Note: while getting todo comments seems like a syntactic operation, we actually
// treat it as a semantic operation here. This is because we expect our host to call
// this on every single file. If we treat this syntactically, then that will cause
// us to populate and throw away the tree in our syntax tree cache for each file. By
// treating this as a semantic operation, we can access any tree without throwing
// anything away.
synchronizeHostData();
var sourceFile = getValidSourceFile(fileName);
cancellationToken.throwIfCancellationRequested();
var fileContents = sourceFile.text;
var result = [];
if (descriptors.length > 0) {
var regExp = getTodoCommentsRegExp();
var matchArray;
while (matchArray = regExp.exec(fileContents)) {
cancellationToken.throwIfCancellationRequested();
// If we got a match, here is what the match array will look like. Say the source text is:
//
// " // hack 1"
//
// The result array with the regexp: will be:
//
// ["// hack 1", "// ", "hack 1", undefined, "hack"]
//
// Here are the relevant capture groups:
// 0) The full match for the entire regexp.
// 1) The preamble to the message portion.
// 2) The message portion.
// 3...N) The descriptor that was matched - by index. 'undefined' for each
// descriptor that didn't match. an actual value if it did match.
//
// i.e. 'undefined' in position 3 above means TODO(jason) didn't match.
// "hack" in position 4 means HACK did match.
var firstDescriptorCaptureIndex = 3;
ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex);
var preamble = matchArray[1];
var matchPosition = matchArray.index + preamble.length;
// OK, we have found a match in the file. This is only an acceptable match if
// it is contained within a comment.
var token = ts.getTokenAtPosition(sourceFile, matchPosition);
if (!isInsideComment(sourceFile, token, matchPosition)) {
continue;
}
var descriptor = undefined;
for (var i = 0, n = descriptors.length; i < n; i++) {
if (matchArray[i + firstDescriptorCaptureIndex]) {
descriptor = descriptors[i];
}
}
ts.Debug.assert(descriptor !== undefined);
// We don't want to match something like 'TODOBY', so we make sure a non
// letter/digit follows the match.
if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) {
continue;
}
var message = matchArray[2];
result.push({
descriptor: descriptor,
message: message,
position: matchPosition
});
}
}
return result;
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function getTodoCommentsRegExp() {
// NOTE: ?: means 'non-capture group'. It allows us to have groups without having to
// filter them out later in the final result array.
// TODO comments can appear in one of the following forms:
//
// 1) // TODO or /////////// TODO
//
// 2) /* TODO or /********** TODO
//
// 3) /*
// * TODO
// */
//
// The following three regexps are used to match the start of the text up to the TODO
// comment portion.
var singleLineCommentStart = /(?:\/\/+\s*)/.source;
var multiLineCommentStart = /(?:\/\*+\s*)/.source;
var anyNumberOfSpacesAndAsterixesAtStartOfLine = /(?:^(?:\s|\*)*)/.source;
// Match any of the above three TODO comment start regexps.
// Note that the outermost group *is* a capture group. We want to capture the preamble
// so that we can determine the starting position of the TODO comment match.
var preamble = "(" + anyNumberOfSpacesAndAsterixesAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")";
// Takes the descriptors and forms a regexp that matches them as if they were literals.
// For example, if the descriptors are "TODO(jason)" and "HACK", then this will be:
//
// (?:(TODO\(jason\))|(HACK))
//
// Note that the outermost group is *not* a capture group, but the innermost groups
// *are* capture groups. By capturing the inner literals we can determine after
// matching which descriptor we are dealing with.
var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")";
// After matching a descriptor literal, the following regexp matches the rest of the
// text up to the end of the line (or */).
var endOfLineOrEndOfComment = /(?:$|\*\/)/.source;
var messageRemainder = /(?:.*?)/.source;
// This is the portion of the match we'll return as part of the TODO comment result. We
// match the literal portion up to the end of the line or end of comment.
var messagePortion = "(" + literals + messageRemainder + ")";
var regExpString = preamble + messagePortion + endOfLineOrEndOfComment;
// The final regexp will look like this:
// /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim
// The flags of the regexp are important here.
// 'g' is so that we are doing a global search and can find matches several times
// in the input.
//
// 'i' is for case insensitivity (We do this to match C# TODO comment code).
//
// 'm' is so we can find matches in a multi-line input.
return new RegExp(regExpString, "gim");
}
function isLetterOrDigit(char) {
return (char >= 97 /* a */ && char <= 122 /* z */) ||
(char >= 65 /* A */ && char <= 90 /* Z */) ||
(char >= 48 /* _0 */ && char <= 57 /* _9 */);
}
}
|
Digs into an an initializer or RHS operand of an assignment operation
to get the parameters of an apt signature corresponding to a
function expression or a class expression.
@param rightHandSide the expression which may contain an appropriate set of parameters
@returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
|
getTodoComments
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function canFollow(keyword1, keyword2) {
if (ts.isAccessibilityModifier(keyword1)) {
if (keyword2 === 123 /* GetKeyword */ ||
keyword2 === 129 /* SetKeyword */ ||
keyword2 === 121 /* ConstructorKeyword */ ||
keyword2 === 113 /* StaticKeyword */) {
// Allow things like "public get", "public constructor" and "public static".
// These are all legal.
return true;
}
// Any other keyword following "public" is actually an identifier an not a real
// keyword.
return false;
}
// Assume any other keyword combination is legal. This can be refined in the future
// if there are more cases we want the classifier to be better at.
return true;
}
|
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
|
canFollow
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function initializeServices() {
ts.objectAllocator = {
getNodeConstructor: function () { return NodeObject; },
getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
getSignatureConstructor: function () { return SignatureObject; }
};
}
|
Get the path of the default library files (lib.d.ts) as distributed with the typescript
node package.
The functionality is not supported if the ts module is consumed outside of a node module.
|
initializeServices
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function spanInSourceFileAtLocation(sourceFile, position) {
// Cannot set breakpoint in dts file
if (sourceFile.flags & 4096 /* DeclarationFile */) {
return undefined;
}
var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position);
var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) {
// Get previous token if the token is returned starts on new line
// eg: let x =10; |--- cursor is here
// let y = 10;
// token at position will return let keyword on second line as the token but we would like to use
// token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line
tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile);
// Its a blank line
if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) {
return undefined;
}
}
// Cannot set breakpoint in ambient declarations
if (ts.isInAmbientContext(tokenAtLocation)) {
return undefined;
}
// Get the span in the node based on its syntax
return spanInNode(tokenAtLocation);
function textSpan(startNode, endNode) {
return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd());
}
function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) {
return spanInNode(node);
}
return spanInNode(otherwiseOnNode);
}
function spanInPreviousNode(node) {
return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
}
function spanInNextNode(node) {
return spanInNode(ts.findNextToken(node, node.parent));
}
function spanInNode(node) {
if (node) {
if (ts.isExpression(node)) {
if (node.parent.kind === 197 /* DoStatement */) {
// Set span as if on while keyword
return spanInPreviousNode(node);
}
if (node.parent.kind === 199 /* ForStatement */) {
// For now lets set the span on this expression, fix it later
return textSpan(node);
}
if (node.parent.kind === 181 /* BinaryExpression */ && node.parent.operatorToken.kind === 24 /* CommaToken */) {
// if this is comma expression, the breakpoint is possible in this expression
return textSpan(node);
}
if (node.parent.kind === 174 /* ArrowFunction */ && node.parent.body === node) {
// If this is body of arrow function, it is allowed to have the breakpoint
return textSpan(node);
}
}
switch (node.kind) {
case 193 /* VariableStatement */:
// Span on first variable declaration
return spanInVariableDeclaration(node.declarationList.declarations[0]);
case 211 /* VariableDeclaration */:
case 141 /* PropertyDeclaration */:
case 140 /* PropertySignature */:
return spanInVariableDeclaration(node);
case 138 /* Parameter */:
return spanInParameterDeclaration(node);
case 213 /* FunctionDeclaration */:
case 143 /* MethodDeclaration */:
case 142 /* MethodSignature */:
case 145 /* GetAccessor */:
case 146 /* SetAccessor */:
case 144 /* Constructor */:
case 173 /* FunctionExpression */:
case 174 /* ArrowFunction */:
return spanInFunctionDeclaration(node);
case 192 /* Block */:
if (ts.isFunctionBlock(node)) {
return spanInFunctionBlock(node);
}
// Fall through
case 219 /* ModuleBlock */:
return spanInBlock(node);
case 244 /* CatchClause */:
return spanInBlock(node.block);
case 195 /* ExpressionStatement */:
// span on the expression
return textSpan(node.expression);
case 204 /* ReturnStatement */:
// span on return keyword and expression if present
return textSpan(node.getChildAt(0), node.expression);
case 198 /* WhileStatement */:
// Span on while(...)
return textSpan(node, ts.findNextToken(node.expression, node));
case 197 /* DoStatement */:
// span in statement of the do statement
return spanInNode(node.statement);
case 210 /* DebuggerStatement */:
// span on debugger keyword
return textSpan(node.getChildAt(0));
case 196 /* IfStatement */:
// set on if(..) span
return textSpan(node, ts.findNextToken(node.expression, node));
case 207 /* LabeledStatement */:
// span in statement
return spanInNode(node.statement);
case 203 /* BreakStatement */:
case 202 /* ContinueStatement */:
// On break or continue keyword and label if present
return textSpan(node.getChildAt(0), node.label);
case 199 /* ForStatement */:
return spanInForStatement(node);
case 200 /* ForInStatement */:
case 201 /* ForOfStatement */:
// span on for (a in ...)
return textSpan(node, ts.findNextToken(node.expression, node));
case 206 /* SwitchStatement */:
// span on switch(...)
return textSpan(node, ts.findNextToken(node.expression, node));
case 241 /* CaseClause */:
case 242 /* DefaultClause */:
// span in first statement of the clause
return spanInNode(node.statements[0]);
case 209 /* TryStatement */:
// span in try block
return spanInBlock(node.tryBlock);
case 208 /* ThrowStatement */:
// span in throw ...
return textSpan(node, node.expression);
case 227 /* ExportAssignment */:
// span on export = id
return textSpan(node, node.expression);
case 221 /* ImportEqualsDeclaration */:
// import statement without including semicolon
return textSpan(node, node.moduleReference);
case 222 /* ImportDeclaration */:
// import statement without including semicolon
return textSpan(node, node.moduleSpecifier);
case 228 /* ExportDeclaration */:
// import statement without including semicolon
return textSpan(node, node.moduleSpecifier);
case 218 /* ModuleDeclaration */:
// span on complete module if it is instantiated
if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
return undefined;
}
case 214 /* ClassDeclaration */:
case 217 /* EnumDeclaration */:
case 247 /* EnumMember */:
case 168 /* CallExpression */:
case 169 /* NewExpression */:
// span on complete node
return textSpan(node);
case 205 /* WithStatement */:
// span in statement
return spanInNode(node.statement);
// No breakpoint in interface, type alias
case 215 /* InterfaceDeclaration */:
case 216 /* TypeAliasDeclaration */:
return undefined;
// Tokens:
case 23 /* SemicolonToken */:
case 1 /* EndOfFileToken */:
return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile));
case 24 /* CommaToken */:
return spanInPreviousNode(node);
case 15 /* OpenBraceToken */:
return spanInOpenBraceToken(node);
case 16 /* CloseBraceToken */:
return spanInCloseBraceToken(node);
case 17 /* OpenParenToken */:
return spanInOpenParenToken(node);
case 18 /* CloseParenToken */:
return spanInCloseParenToken(node);
case 54 /* ColonToken */:
return spanInColonToken(node);
case 27 /* GreaterThanToken */:
case 25 /* LessThanToken */:
return spanInGreaterThanOrLessThanToken(node);
// Keywords:
case 104 /* WhileKeyword */:
return spanInWhileKeyword(node);
case 80 /* ElseKeyword */:
case 72 /* CatchKeyword */:
case 85 /* FinallyKeyword */:
return spanInNextNode(node);
default:
// If this is name of property assignment, set breakpoint in the initializer
if (node.parent.kind === 245 /* PropertyAssignment */ && node.parent.name === node) {
return spanInNode(node.parent.initializer);
}
// Breakpoint in type assertion goes to its operand
if (node.parent.kind === 171 /* TypeAssertionExpression */ && node.parent.type === node) {
return spanInNode(node.parent.expression);
}
// return type of function go to previous token
if (ts.isFunctionLike(node.parent) && node.parent.type === node) {
return spanInPreviousNode(node);
}
// Default go to parent to set the breakpoint
return spanInNode(node.parent);
}
}
function spanInVariableDeclaration(variableDeclaration) {
// If declaration of for in statement, just set the span in parent
if (variableDeclaration.parent.parent.kind === 200 /* ForInStatement */ ||
variableDeclaration.parent.parent.kind === 201 /* ForOfStatement */) {
return spanInNode(variableDeclaration.parent.parent);
}
var isParentVariableStatement = variableDeclaration.parent.parent.kind === 193 /* VariableStatement */;
var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 199 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration);
var declarations = isParentVariableStatement
? variableDeclaration.parent.parent.declarationList.declarations
: isDeclarationOfForStatement
? variableDeclaration.parent.parent.initializer.declarations
: undefined;
// Breakpoint is possible in variableDeclaration only if there is initialization
if (variableDeclaration.initializer || (variableDeclaration.flags & 2 /* Export */)) {
if (declarations && declarations[0] === variableDeclaration) {
if (isParentVariableStatement) {
// First declaration - include let keyword
return textSpan(variableDeclaration.parent, variableDeclaration);
}
else {
ts.Debug.assert(isDeclarationOfForStatement);
// Include let keyword from for statement declarations in the span
return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
}
}
else {
// Span only on this declaration
return textSpan(variableDeclaration);
}
}
else if (declarations && declarations[0] !== variableDeclaration) {
// If we cant set breakpoint on this declaration, set it on previous one
var indexOfCurrentDeclaration = ts.indexOf(declarations, variableDeclaration);
return spanInVariableDeclaration(declarations[indexOfCurrentDeclaration - 1]);
}
}
function canHaveSpanInParameterDeclaration(parameter) {
// Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier
return !!parameter.initializer || parameter.dotDotDotToken !== undefined ||
!!(parameter.flags & 8 /* Public */) || !!(parameter.flags & 16 /* Private */);
}
function spanInParameterDeclaration(parameter) {
if (canHaveSpanInParameterDeclaration(parameter)) {
return textSpan(parameter);
}
else {
var functionDeclaration = parameter.parent;
var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter);
if (indexOfParameter) {
// Not a first parameter, go to previous parameter
return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]);
}
else {
// Set breakpoint in the function declaration body
return spanInNode(functionDeclaration.body);
}
}
}
function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) {
return !!(functionDeclaration.flags & 2 /* Export */) ||
(functionDeclaration.parent.kind === 214 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */);
}
function spanInFunctionDeclaration(functionDeclaration) {
// No breakpoints in the function signature
if (!functionDeclaration.body) {
return undefined;
}
if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) {
// Set the span on whole function declaration
return textSpan(functionDeclaration);
}
// Set span in function body
return spanInNode(functionDeclaration.body);
}
function spanInFunctionBlock(block) {
var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
if (canFunctionHaveSpanInWholeDeclaration(block.parent)) {
return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
}
return spanInNode(nodeForSpanInBlock);
}
function spanInBlock(block) {
switch (block.parent.kind) {
case 218 /* ModuleDeclaration */:
if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) {
return undefined;
}
// Set on parent if on same line otherwise on first statement
case 198 /* WhileStatement */:
case 196 /* IfStatement */:
case 200 /* ForInStatement */:
case 201 /* ForOfStatement */:
return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);
// Set span on previous token if it starts on same line otherwise on the first statement of the block
case 199 /* ForStatement */:
return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
}
// Default action is to set on first statement
return spanInNode(block.statements[0]);
}
function spanInForStatement(forStatement) {
if (forStatement.initializer) {
if (forStatement.initializer.kind === 212 /* VariableDeclarationList */) {
var variableDeclarationList = forStatement.initializer;
if (variableDeclarationList.declarations.length > 0) {
return spanInNode(variableDeclarationList.declarations[0]);
}
}
else {
return spanInNode(forStatement.initializer);
}
}
if (forStatement.condition) {
return textSpan(forStatement.condition);
}
if (forStatement.incrementor) {
return textSpan(forStatement.incrementor);
}
}
// Tokens:
function spanInOpenBraceToken(node) {
switch (node.parent.kind) {
case 217 /* EnumDeclaration */:
var enumDeclaration = node.parent;
return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));
case 214 /* ClassDeclaration */:
var classDeclaration = node.parent;
return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));
case 220 /* CaseBlock */:
return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]);
}
// Default to parent node
return spanInNode(node.parent);
}
function spanInCloseBraceToken(node) {
switch (node.parent.kind) {
case 219 /* ModuleBlock */:
// If this is not instantiated module block no bp span
if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) {
return undefined;
}
case 217 /* EnumDeclaration */:
case 214 /* ClassDeclaration */:
// Span on close brace token
return textSpan(node);
case 192 /* Block */:
if (ts.isFunctionBlock(node.parent)) {
// Span on close brace token
return textSpan(node);
}
// fall through.
case 244 /* CatchClause */:
return spanInNode(ts.lastOrUndefined(node.parent.statements));
case 220 /* CaseBlock */:
// breakpoint in last statement of the last clause
var caseBlock = node.parent;
var lastClause = ts.lastOrUndefined(caseBlock.clauses);
if (lastClause) {
return spanInNode(ts.lastOrUndefined(lastClause.statements));
}
return undefined;
// Default to parent node
default:
return spanInNode(node.parent);
}
}
function spanInOpenParenToken(node) {
if (node.parent.kind === 197 /* DoStatement */) {
// Go to while keyword and do action instead
return spanInPreviousNode(node);
}
// Default to parent node
return spanInNode(node.parent);
}
function spanInCloseParenToken(node) {
// Is this close paren token of parameter list, set span in previous token
switch (node.parent.kind) {
case 173 /* FunctionExpression */:
case 213 /* FunctionDeclaration */:
case 174 /* ArrowFunction */:
case 143 /* MethodDeclaration */:
case 142 /* MethodSignature */:
case 145 /* GetAccessor */:
case 146 /* SetAccessor */:
case 144 /* Constructor */:
case 198 /* WhileStatement */:
case 197 /* DoStatement */:
case 199 /* ForStatement */:
return spanInPreviousNode(node);
// Default to parent node
default:
return spanInNode(node.parent);
}
}
function spanInColonToken(node) {
// Is this : specifying return annotation of the function declaration
if (ts.isFunctionLike(node.parent) || node.parent.kind === 245 /* PropertyAssignment */) {
return spanInPreviousNode(node);
}
return spanInNode(node.parent);
}
function spanInGreaterThanOrLessThanToken(node) {
if (node.parent.kind === 171 /* TypeAssertionExpression */) {
return spanInNode(node.parent.expression);
}
return spanInNode(node.parent);
}
function spanInWhileKeyword(node) {
if (node.parent.kind === 197 /* DoStatement */) {
// Set span on while expression
return textSpan(node, ts.findNextToken(node.parent.expression, node.parent));
}
// Default to parent node
return spanInNode(node.parent);
}
}
}
|
Get the breakpoint span in given sourceFile
|
spanInSourceFileAtLocation
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function ThrottledCancellationToken(hostCancellationToken) {
this.hostCancellationToken = hostCancellationToken;
// Store when we last tried to cancel. Checking cancellation can be expensive (as we have
// to marshall over to the host layer). So we only bother actually checking once enough
// time has passed.
this.lastCancellationCheckTime = 0;
}
|
A cancellation that throttles calls to the host
|
ThrottledCancellationToken
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
function convertClassifications(classifications) {
return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState };
}
|
Return a list of symbols that are interesting to navigate to
|
convertClassifications
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/typescriptServices.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/typescriptServices.js
|
MIT
|
fileParsedFunc = function (e, root, fullPath) {
importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
var importedEqualsRoot = fullPath === importManager.rootFilename;
if (importOptions.optional && e) {
callback(null, {rules:[]}, false, null);
}
else {
importManager.files[fullPath] = root;
if (e && !importManager.error) { importManager.error = e; }
callback(e, root, importedEqualsRoot, fullPath);
}
}
|
Add an import to be imported
@param path - the raw path
@param tryAppendLessExtension - whether to try appending the less extension (if the path has no extension)
@param currentFileInfo - the current file info (used for instance to work out relative paths)
@param importOptions - import options
@param callback - callback for when it is imported
|
fileParsedFunc
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/less/less/import-manager.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/less/less/import-manager.js
|
MIT
|
function extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = FallbackCompositionState.getPooled(topLevelTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
fallbackData = currentComposition.getData();
}
}
}
var event = SyntheticCompositionEvent.getPooled(eventType, topLevelTargetID, nativeEvent, nativeEventTarget);
if (fallbackData) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
|
@param {string} topLevelType Record from `EventConstants`.
@param {DOMEventTarget} topLevelTarget The listening component root node.
@param {string} topLevelTargetID ID of `topLevelTarget`.
@param {object} nativeEvent Native browser event.
@return {?object} A SyntheticCompositionEvent.
|
extractCompositionEvent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, topLevelTargetID, nativeEvent, nativeEventTarget);
event.data = chars;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
|
Extract a SyntheticInputEvent for `beforeInput`, based on either native
`textInput` or fallback behavior.
@param {string} topLevelType Record from `EventConstants`.
@param {DOMEventTarget} topLevelTarget The listening component root node.
@param {string} topLevelTargetID ID of `topLevelTarget`.
@param {object} nativeEvent Native browser event.
@return {?object} A SyntheticInputEvent.
|
extractBeforeInputEvent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function startWatchingForValueChange(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value');
// Not guarded in a canDefineProperty check: IE8 supports defineProperty only
// on DOM elements
Object.defineProperty(activeElement, 'value', newValueProp);
activeElement.attachEvent('onpropertychange', handlePropertyChange);
}
|
(For old IE.) Starts tracking propertychange events on the passed-in element
and override the value property so that we can distinguish user events from
value changes in JS.
|
startWatchingForValueChange
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
// delete restores the original property definition
delete activeElement.value;
activeElement.detachEvent('onpropertychange', handlePropertyChange);
activeElement = null;
activeElementID = null;
activeElementValue = null;
activeElementValueProp = null;
}
|
(For old IE.) Removes the event listeners from the currently-tracked element,
if any exists.
|
stopWatchingForValueChange
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
var value = nativeEvent.srcElement.value;
if (value === activeElementValue) {
return;
}
activeElementValue = value;
manualDispatchChangeEvent(nativeEvent);
}
|
(For old IE.) Handles a propertychange event, sending a `change` event if
the value of the active element has changed.
|
handlePropertyChange
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getNodeName(markup) {
return markup.substring(1, markup.indexOf(' '));
}
|
Extracts the `nodeName` from a string of markup.
NOTE: Extracting the `nodeName` does not require a regular expression match
because we make assumptions about React-generated markup (i.e. there are no
spaces surrounding the opening tag and there is at least one attribute).
@param {string} markup String of markup.
@return {string} Node name of the supplied markup.
@see http://jsperf.com/extract-nodename
|
getNodeName
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function validateInstanceHandle() {
var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave;
"development" !== 'production' ? warning(valid, 'InstanceHandle not injected before use!') : undefined;
}
|
- `InstanceHandle`: [required] Module that performs logical traversals of DOM
hierarchy given ids of the logical DOM elements involved.
|
validateInstanceHandle
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel;
}
|
- `Mount`: [required] Module that can convert between React dom IDs and
actual node references.
|
isEndish
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function executeDispatch(event, simulated, listener, domID) {
var type = event.type || 'unknown-event';
event.currentTarget = injection.Mount.getNode(domID);
if (simulated) {
ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event, domID);
} else {
ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID);
}
event.currentTarget = null;
}
|
Dispatch the event to the listener.
@param {SyntheticEvent} event SyntheticEvent to handle
@param {boolean} simulated If the event is simulated (changes exn behavior)
@param {function} listener Application-level callback
@param {string} domID DOM id to pass to the callback.
|
executeDispatch
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
addPoolingTo = function (CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
}
|
Augments `CopyConstructor` to be a poolable class, augmenting only the class
itself (statically) not adding any prototypical fields. Any CopyConstructor
you give this may have a `poolSize` property, and will look for a
prototypical `destructor` on instances (optional).
@param {Function} CopyConstructor Constructor that can be used to reset.
@param {Function} pooler Customizable pooler.
|
addPoolingTo
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
|
Iterates through children that are typically specified as `props.children`.
The provided forEachFunc(child, index) will be called for each
leaf child.
@param {?*} children Children tree container.
@param {function(*, int)} forEachFunc
@param {*} forEachContext Context for forEachContext.
|
forEachChildren
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, func, context);
return result;
}
|
Maps children that are typically specified as `props.children`.
The provided mapFunction(child, key, index) will be called for each
leaf child.
@param {?*} children Children tree container.
@param {function(*, int)} func The map function.
@param {*} context Context for mapFunction.
@return {object} Object containing the ordered map of results.
|
mapChildren
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
|
Count the number of children that are typically specified as
`props.children`.
@param {?*} children Children tree container.
@return {number} The number of children.
|
countChildren
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function toArray(children) {
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
return result;
}
|
Flatten a children object (typically specified as `props.children`) and
return an array with appropriately re-keyed children.
|
toArray
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function warnSetProps() {
if (!warnedSetProps) {
warnedSetProps = true;
"development" !== 'production' ? warning(false, 'setProps(...) and replaceProps(...) are deprecated. ' + 'Instead, call render again at the top level.') : undefined;
}
}
|
These methods are similar to DEFINE_MANY, except we assume they return
objects. We try to merge the keys of the return values of all the mixed in
functions. If there is a key conflict we throw.
|
warnSetProps
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
return;
}
!(typeof spec !== 'function') ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
!!ReactElement.isValidElement(spec) ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
var proto = Constructor.prototype;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
validateMethodOverride(proto, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isAlreadyDefined = proto.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
!(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? "development" !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined;
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if ("development" !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
|
Mixin helper which handles policy validation and reserved
specification keys when building React classses.
|
mixSpecIntoComponent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
Constructor = function (props, context, updater) {
// This constructor is overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if ("development" !== 'production') {
"development" !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined;
}
// Wire up auto-binding
if (this.__reactAutoBindMap) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if ("development" !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined;
this.state = initialState;
}
|
Creates a composite component class given a class specification.
@param {object} spec Class specification (which must define `render`).
@return {function} Component constructor function.
@public
|
Constructor
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function createDOMFactory(tag) {
if ("development" !== 'production') {
return ReactElementValidator.createFactory(tag);
}
return ReactElement.createFactory(tag);
}
|
Create a factory that creates HTML tag elements.
@param {string} tag Tag name (e.g. `div`).
@private
|
createDOMFactory
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
// Here we use asap to wait until all updates have propagated, which
// is important when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
ReactUpdates.asap(forceUpdateIfMounted, this);
var name = props.name;
if (props.type === 'radio' && name != null) {
var rootNode = ReactMount.getNode(this._rootNodeID);
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form, let's just use the global
// `querySelectorAll` to ensure we don't miss anything.
var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode === rootNode || otherNode.form !== rootNode.form) {
continue;
}
// This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React with non-React.
var otherID = ReactMount.getID(otherNode);
!otherID ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined;
var otherInstance = instancesByReactID[otherID];
!otherInstance ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined;
// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
}
}
return returnValue;
}
|
Implements an <input> native component that allows setting these optional
props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
If `checked` or `value` are not supplied (or null/undefined), user actions
that affect the checked state or value will trigger updates to the element.
If they are supplied (and not null/undefined), the rendered element will not
trigger updates to the element. Instead, the props must change in order for
the rendered element to be updated.
The rendered element will be initialized as unchecked (or `defaultChecked`)
with an empty value (or `defaultValue`).
@see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
|
_handleChange
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
this._wrapperState.pendingUpdate = true;
ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
return returnValue;
}
|
Implements a <select> native component that allows optionally setting the
props `value` and `defaultValue`. If `multiple` is false, the prop must be a
stringable. If `multiple` is true, the prop must be an array of stringables.
If `value` is not supplied (or null/undefined), user actions that change the
selected option will trigger updates to the rendered options.
If it is supplied (and not null/undefined), the rendered options will not
update in response to user actions. Instead, the `value` prop must change in
order for the rendered options to update.
If `defaultValue` is provided, any options with the supplied values will be
selected.
|
_handleChange
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function setModernOffsets(node, offsets) {
if (!window.getSelection) {
return;
}
var selection = window.getSelection();
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
}
}
|
In modern non-IE browsers, we can support both forward and backward
selections.
Note: IE10+ supports the Selection object, but it does not support
the `extend` method, which means that even in modern IE, it's not possible
to programatically create a backward selection. Thus, for all IE
versions, we use the old IE API to create our selections.
@param {DOMElement|DOMTextNode} node
@param {object} offsets
|
setModernOffsets
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
ReactDOMTextComponent = function (props) {
// This constructor and its argument is currently used by mocks.
}
|
Text nodes violate a couple assumptions that React makes about components:
- When mounting text into the DOM, adjacent text nodes are merged.
- Text nodes cannot be assigned a React root ID.
This component is used to wrap strings in elements so that they can undergo
the same reconciliation that is applied to elements.
TODO: Investigate representing React components in the DOM with text nodes.
@class ReactDOMTextComponent
@extends ReactComponent
@internal
|
ReactDOMTextComponent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
ReactUpdates.asap(forceUpdateIfMounted, this);
return returnValue;
}
|
Implements a <textarea> native component that allows setting `value`, and
`defaultValue`. This differs from the traditional DOM API because value is
usually set as PCDATA children.
If `value` is not supplied (or null/undefined), user actions that affect the
value will trigger updates to the element.
If `value` is supplied (and not null/undefined), the rendered element will
not trigger updates to the element. Instead, the `value` prop must change in
order for the rendered element to be updated.
The rendered element will be initialized with an empty value, the prop
`defaultValue` if specified, or the children content (deprecated).
|
_handleChange
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allow us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
if ("development" !== 'production') {
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
if (canDefineProperty) {
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
});
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
});
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
} else {
element._store.validated = false;
element._self = self;
element._source = source;
}
Object.freeze(element.props);
Object.freeze(element);
}
return element;
}
|
Base constructor for all React elements. This is only used to make this
work with a dynamic instanceof check. Nothing should live on this prototype.
@param {*} type
@param {*} key
@param {string|object} ref
@param {*} self A *temporary* helper to detect places where `this` is
different from the `owner` when React.createElement is called, so that we
can warn. We want to get rid of owner and replace string `ref`s with arrow
functions, and as long as `this` and owner are the same, there will be no
change in behavior.
@param {*} source An annotation object (added by a transpiler or otherwise)
indicating filename, line number, and/or other information.
@param {*} owner
@param {*} props
@internal
|
ReactElement
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var addenda = getAddendaForKeyUse('uniqueKey', element, parentType);
if (addenda === null) {
// we already showed the warning
return;
}
"development" !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined;
}
|
Warn if the element doesn't have an explicit key assigned to it.
This element is in an array. The array could grow and shrink or be
reordered. All children that haven't already been validated are required to
have a "key" property assigned to it.
@internal
@param {ReactElement} element Element that requires a key.
@param {*} parentType element's parent's type.
|
validateExplicitKey
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getAddendaForKeyUse(messageType, element, parentType) {
var addendum = getDeclarationErrorAddendum();
if (!addendum) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
addendum = ' Check the top-level render call using <' + parentName + '>.';
}
}
var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {});
if (memoizer[addendum]) {
return null;
}
memoizer[addendum] = true;
var addenda = {
parentOrOwner: addendum,
url: ' See https://fb.me/react-warning-keys for more information.',
childOwner: null
};
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
}
return addenda;
}
|
Shared warning and monitoring code for the key warnings.
@internal
@param {string} messageType A key used for de-duping warnings.
@param {ReactElement} element Component that requires a key.
@param {*} parentType element's parent's type.
@returns {?object} A set of addenda to use in the warning message, or null
if the warning has already been shown before (and shouldn't be shown again).
|
getAddendaForKeyUse
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function checkPropTypes(componentName, propTypes, props, location) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof propTypes[propName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
"development" !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : undefined;
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var addendum = getDeclarationErrorAddendum();
"development" !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined;
}
}
}
}
|
Assert that the props are valid
@param {string} componentName Name of the component for error messages.
@param {object} propTypes Map of prop name to a ReactPropType
@param {object} props
@param {string} location e.g. "prop", "context", "child context"
@private
|
checkPropTypes
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function isNullComponentID(id) {
return !!nullComponentIDsRegistry[id];
}
|
@param {string} id Component's `_rootNodeID`.
@return {boolean} True if the component is rendered to null.
|
isNullComponentID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function registerNullComponentID(id) {
nullComponentIDsRegistry[id] = true;
}
|
Mark the component as having rendered to null.
@param {string} id Component's `_rootNodeID`.
|
registerNullComponentID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function deregisterNullComponentID(id) {
delete nullComponentIDsRegistry[id];
}
|
Unmark the component as having rendered to null: it renders to something now.
@param {string} id Component's `_rootNodeID`.
|
deregisterNullComponentID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function invokeGuardedCallback(name, func, a, b) {
try {
return func(a, b);
} catch (x) {
if (caughtError === null) {
caughtError = x;
}
return undefined;
}
}
|
Call a function while guarding against errors that happens within it.
@param {?String} name of the guard to use for logging or debugging
@param {Function} func The function to invoke
@param {*} a First argument
@param {*} b Second argument
|
invokeGuardedCallback
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function findParent(node) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
var nodeID = ReactMount.getID(node);
var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
var container = ReactMount.findReactContainerForID(rootID);
var parent = ReactMount.getFirstReactDOM(container);
return parent;
}
|
Finds the parent React component of `node`.
@param {*} node
@return {?DOMEventTarget} Parent container, or `null` if the specified node
is not nested.
|
findParent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getReactRootIDString(index) {
return SEPARATOR + index.toString(36);
}
|
Creates a DOM ID prefix to use when mounting React components.
@param {number} index A unique integer
@return {string} React root ID.
@internal
|
getReactRootIDString
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function isBoundary(id, index) {
return id.charAt(index) === SEPARATOR || index === id.length;
}
|
Checks if a character in the supplied ID is a separator or the end.
@param {string} id A React DOM ID.
@param {number} index Index of the character to check.
@return {boolean} True if the character is a separator or end of the ID.
@private
|
isBoundary
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function isValidID(id) {
return id === '' || id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR;
}
|
Checks if the supplied string is a valid React DOM ID.
@param {string} id A React DOM ID, maybe.
@return {boolean} True if the string is a valid React DOM ID.
@private
|
isValidID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function isAncestorIDOf(ancestorID, descendantID) {
return descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length);
}
|
Checks if the first ID is an ancestor of or equal to the second ID.
@param {string} ancestorID
@param {string} descendantID
@return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
@internal
|
isAncestorIDOf
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getParentID(id) {
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
}
|
Gets the parent ID of the supplied React DOM ID, `id`.
@param {string} id ID of a component.
@return {string} ID of the parent, or an empty string.
@private
|
getParentID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getNextDescendantID(ancestorID, destinationID) {
!(isValidID(ancestorID) && isValidID(destinationID)) ? "development" !== 'production' ? invariant(false, 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID) : invariant(false) : undefined;
!isAncestorIDOf(ancestorID, destinationID) ? "development" !== 'production' ? invariant(false, 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID) : invariant(false) : undefined;
if (ancestorID === destinationID) {
return ancestorID;
}
// Skip over the ancestor and the immediate separator. Traverse until we hit
// another separator or we reach the end of `destinationID`.
var start = ancestorID.length + SEPARATOR_LENGTH;
var i;
for (i = start; i < destinationID.length; i++) {
if (isBoundary(destinationID, i)) {
break;
}
}
return destinationID.substr(0, i);
}
|
Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
supplied `destinationID`. If they are equal, the ID is returned.
@param {string} ancestorID ID of an ancestor node of `destinationID`.
@param {string} destinationID ID of the destination node.
@return {string} Next ID on the path from `ancestorID` to `destinationID`.
@private
|
getNextDescendantID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getFirstCommonAncestorID(oneID, twoID) {
var minLength = Math.min(oneID.length, twoID.length);
if (minLength === 0) {
return '';
}
var lastCommonMarkerIndex = 0;
// Use `<=` to traverse until the "EOL" of the shorter string.
for (var i = 0; i <= minLength; i++) {
if (isBoundary(oneID, i) && isBoundary(twoID, i)) {
lastCommonMarkerIndex = i;
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
break;
}
}
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
!isValidID(longestCommonID) ? "development" !== 'production' ? invariant(false, 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID) : invariant(false) : undefined;
return longestCommonID;
}
|
Gets the nearest common ancestor ID of two IDs.
Using this ID scheme, the nearest common ancestor ID is the longest common
prefix of the two IDs that immediately preceded a "marker" in both strings.
@param {string} oneID
@param {string} twoID
@return {string} Nearest common ancestor ID, or the empty string if none.
@private
|
getFirstCommonAncestorID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
start = start || '';
stop = stop || '';
!(start !== stop) ? "development" !== 'production' ? invariant(false, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start) : invariant(false) : undefined;
var traverseUp = isAncestorIDOf(stop, start);
!(traverseUp || isAncestorIDOf(start, stop)) ? "development" !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop) : invariant(false) : undefined;
// Traverse from `start` to `stop` one depth at a time.
var depth = 0;
var traverse = traverseUp ? getParentID : getNextDescendantID;
for (var id = start;; /* until break */id = traverse(id, stop)) {
var ret;
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
ret = cb(id, traverseUp, arg);
}
if (ret === false || id === stop) {
// Only break //after// visiting `stop`.
break;
}
!(depth++ < MAX_TREE_DEPTH) ? "development" !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop, id) : invariant(false) : undefined;
}
}
|
Traverses the parent path between two IDs (either up or down). The IDs must
not be the same, and there must exist a parent path between them. If the
callback returns `false`, traversal is stopped.
@param {?string} start ID at which to start traversal.
@param {?string} stop ID at which to end traversal.
@param {function} cb Callback to invoke each ID with.
@param {*} arg Argument to invoke the callback with.
@param {?boolean} skipFirst Whether or not to skip the first node.
@param {?boolean} skipLast Whether or not to skip the last node.
@private
|
traverseParentPath
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getReactRootID(container) {
var rootElement = getReactRootElementInContainer(container);
return rootElement && ReactMount.getID(rootElement);
}
|
@param {DOMElement} container DOM element that may contain a React component.
@return {?string} A "reactRoot" ID, if a React component is rendered.
|
getReactRootID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getID(node) {
var id = internalGetID(node);
if (id) {
if (nodeCache.hasOwnProperty(id)) {
var cached = nodeCache[id];
if (cached !== node) {
!!isValid(cached, id) ? "development" !== 'production' ? invariant(false, 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id) : invariant(false) : undefined;
nodeCache[id] = node;
}
} else {
nodeCache[id] = node;
}
}
return id;
}
|
Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form
element can return its control whose name or ID equals ATTR_NAME. All
DOM nodes support `getAttributeNode` but this can also get called on
other objects so just return '' if we're given something other than a
DOM node (such as window).
@param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node.
@return {string} ID of the supplied `domNode`.
|
getID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function setID(node, id) {
var oldID = internalGetID(node);
if (oldID !== id) {
delete nodeCache[oldID];
}
node.setAttribute(ATTR_NAME, id);
nodeCache[id] = node;
}
|
Sets the React-specific ID of the given node.
@param {DOMElement} node The DOM node whose ID will be set.
@param {string} id The value of the ID attribute.
|
setID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getNode(id) {
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
|
Finds the node with the supplied React-generated DOM ID.
@param {string} id A React-generated DOM ID.
@return {DOMElement} DOM node with the suppled `id`.
@internal
|
getNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getNodeFromInstance(instance) {
var id = ReactInstanceMap.get(instance)._rootNodeID;
if (ReactEmptyComponentRegistry.isNullComponentID(id)) {
return null;
}
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
|
Finds the node with the supplied public React instance.
@param {*} instance A public React instance.
@return {?DOMElement} DOM node with the suppled `id`.
@internal
|
getNodeFromInstance
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function isValid(node, id) {
if (node) {
!(internalGetID(node) === id) ? "development" !== 'production' ? invariant(false, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME) : invariant(false) : undefined;
var container = ReactMount.findReactContainerForID(id);
if (container && containsNode(container, node)) {
return true;
}
}
return false;
}
|
A node is "valid" if it is contained by a currently mounted container.
This means that the node does not have to be contained by a document in
order to be considered valid.
@param {?DOMElement} node The candidate DOM node.
@param {string} id The expected ID of the node.
@return {boolean} Whether the node is contained by a mounted container.
|
isValid
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function purgeID(id) {
delete nodeCache[id];
}
|
Causes the cache to forget about one React-specific ID.
@param {string} id The ID to forget.
|
purgeID
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function findDeepestCachedAncestor(targetID) {
deepestNodeSoFar = null;
ReactInstanceHandles.traverseAncestors(targetID, findDeepestCachedAncestorImpl);
var foundNode = deepestNodeSoFar;
deepestNodeSoFar = null;
return foundNode;
}
|
Return the deepest cached node whose ID is a prefix of `targetID`.
|
findDeepestCachedAncestor
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.